ShareTest.php 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  1. <?php
  2. /**
  3. * ownCloud
  4. *
  5. * @author Michael Gapczynski
  6. * @copyright 2012 Michael Gapczynski mtgap@owncloud.com
  7. *
  8. * This library is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
  10. * License as published by the Free Software Foundation; either
  11. * version 3 of the License, or any later version.
  12. *
  13. * This library is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public
  19. * License along with this library. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. namespace Test\Share;
  22. use OC\Share\Share;
  23. use OCP\IGroup;
  24. use OCP\IGroupManager;
  25. use OCP\ILogger;
  26. use OCP\IUser;
  27. use OCP\IUserManager;
  28. /**
  29. * Class Test_Share
  30. *
  31. * @group DB
  32. */
  33. class ShareTest extends \Test\TestCase {
  34. protected $itemType;
  35. /** @var IUser */
  36. protected $user1;
  37. /** @var IUser */
  38. protected $user2;
  39. /** @var IUser */
  40. protected $user3;
  41. /** @var IUser */
  42. protected $user4;
  43. /** @var IUser */
  44. protected $user5;
  45. /** @var IUser */
  46. protected $user6;
  47. /** @var IUser */
  48. protected $groupAndUser_user;
  49. /** @var IGroup */
  50. protected $group1;
  51. /** @var IGroup */
  52. protected $group2;
  53. /** @var IGroup */
  54. protected $groupAndUser_group;
  55. protected $resharing;
  56. protected $dateInFuture;
  57. protected $dateInPast;
  58. /** @var IGroupManager */
  59. protected $groupManager;
  60. /** @var IUserManager */
  61. protected $userManager;
  62. protected function setUp() {
  63. parent::setUp();
  64. $this->groupManager = \OC::$server->getGroupManager();
  65. $this->userManager = \OC::$server->getUserManager();
  66. $this->userManager->clearBackends();
  67. $this->userManager->registerBackend(new \Test\Util\User\Dummy());
  68. $this->user1 = $this->userManager->createUser($this->getUniqueID('user1_'), 'pass');
  69. $this->user2 = $this->userManager->createUser($this->getUniqueID('user2_'), 'pass');
  70. $this->user3 = $this->userManager->createUser($this->getUniqueID('user3_'), 'pass');
  71. $this->user4 = $this->userManager->createUser($this->getUniqueID('user4_'), 'pass');
  72. $this->user5 = $this->userManager->createUser($this->getUniqueID('user5_'), 'pass');
  73. $this->user6 = $this->userManager->createUser($this->getUniqueID('user6_'), 'pass');
  74. $groupAndUserId = $this->getUniqueID('groupAndUser_');
  75. $this->groupAndUser_user = $this->userManager->createUser($groupAndUserId, 'pass');
  76. \OC_User::setUserId($this->user1->getUID());
  77. $this->groupManager->clearBackends();
  78. $this->groupManager->addBackend(new \Test\Util\Group\Dummy());
  79. $this->group1 = $this->groupManager->createGroup($this->getUniqueID('group1_'));
  80. $this->group2 = $this->groupManager->createGroup($this->getUniqueID('group2_'));
  81. $this->groupAndUser_group = $this->groupManager->createGroup($groupAndUserId);
  82. $this->group1->addUser($this->user1);
  83. $this->group1->addUser($this->user2);
  84. $this->group1->addUser($this->user3);
  85. $this->group2->addUser($this->user2);
  86. $this->group2->addUser($this->user4);
  87. $this->groupAndUser_group->addUser($this->user2);
  88. $this->groupAndUser_group->addUser($this->user3);
  89. \OCP\Share::registerBackend('test', 'Test\Share\Backend');
  90. \OC_Hook::clear('OCP\\Share');
  91. \OC::registerShareHooks();
  92. $this->resharing = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes');
  93. \OC::$server->getAppConfig()->setValue('core', 'shareapi_allow_resharing', 'yes');
  94. // 20 Minutes in the past, 20 minutes in the future.
  95. $now = time();
  96. $dateFormat = 'Y-m-d H:i:s';
  97. $this->dateInPast = date($dateFormat, $now - 20 * 60);
  98. $this->dateInFuture = date($dateFormat, $now + 20 * 60);
  99. }
  100. protected function tearDown() {
  101. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `item_type` = ?');
  102. $query->execute(array('test'));
  103. \OC::$server->getAppConfig()->setValue('core', 'shareapi_allow_resharing', $this->resharing);
  104. $this->user1->delete();
  105. $this->user2->delete();
  106. $this->user3->delete();
  107. $this->user4->delete();
  108. $this->user5->delete();
  109. $this->user6->delete();
  110. $this->groupAndUser_user->delete();
  111. $this->group1->delete();
  112. $this->group2->delete();
  113. $this->groupAndUser_group->delete();
  114. $this->logout();
  115. parent::tearDown();
  116. }
  117. public function testShareInvalidShareType() {
  118. $message = 'Share type foobar is not valid for test.txt';
  119. try {
  120. \OCP\Share::shareItem('test', 'test.txt', 'foobar', $this->user2, \OCP\Constants::PERMISSION_READ);
  121. } catch (\Exception $exception) {
  122. $this->assertEquals($message, $exception->getMessage());
  123. }
  124. }
  125. public function testInvalidItemType() {
  126. $message = 'Sharing backend for foobar not found';
  127. try {
  128. \OCP\Share::shareItem('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_READ);
  129. $this->fail('Exception was expected: '.$message);
  130. } catch (\Exception $exception) {
  131. $this->assertEquals($message, $exception->getMessage());
  132. }
  133. try {
  134. \OCP\Share::getItemsSharedWith('foobar');
  135. $this->fail('Exception was expected: '.$message);
  136. } catch (\Exception $exception) {
  137. $this->assertEquals($message, $exception->getMessage());
  138. }
  139. try {
  140. \OCP\Share::getItemSharedWith('foobar', 'test.txt');
  141. $this->fail('Exception was expected: '.$message);
  142. } catch (\Exception $exception) {
  143. $this->assertEquals($message, $exception->getMessage());
  144. }
  145. try {
  146. \OCP\Share::getItemSharedWithBySource('foobar', 'test.txt');
  147. $this->fail('Exception was expected: '.$message);
  148. } catch (\Exception $exception) {
  149. $this->assertEquals($message, $exception->getMessage());
  150. }
  151. try {
  152. \OCP\Share::getItemShared('foobar', 'test.txt');
  153. $this->fail('Exception was expected: '.$message);
  154. } catch (\Exception $exception) {
  155. $this->assertEquals($message, $exception->getMessage());
  156. }
  157. try {
  158. \OCP\Share::unshare('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2);
  159. $this->fail('Exception was expected: '.$message);
  160. } catch (\Exception $exception) {
  161. $this->assertEquals($message, $exception->getMessage());
  162. }
  163. try {
  164. \OCP\Share::setPermissions('foobar', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2, \OCP\Constants::PERMISSION_UPDATE);
  165. $this->fail('Exception was expected: '.$message);
  166. } catch (\Exception $exception) {
  167. $this->assertEquals($message, $exception->getMessage());
  168. }
  169. }
  170. protected function shareUserOneTestFileWithUserTwo() {
  171. \OC_User::setUserId($this->user1->getUID());
  172. $this->assertTrue(
  173. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ),
  174. 'Failed asserting that user 1 successfully shared text.txt with user 2.'
  175. );
  176. $this->assertContains(
  177. 'test.txt',
  178. \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
  179. 'Failed asserting that test.txt is a shared file of user 1.'
  180. );
  181. \OC_User::setUserId($this->user2->getUID());
  182. $this->assertContains(
  183. 'test.txt',
  184. \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  185. 'Failed asserting that user 2 has access to test.txt after initial sharing.'
  186. );
  187. }
  188. protected function shareUserTestFileAsLink() {
  189. \OC_User::setUserId($this->user1->getUID());
  190. $result = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
  191. $this->assertTrue(is_string($result));
  192. }
  193. /**
  194. * @param string $sharer
  195. * @param string $receiver
  196. */
  197. protected function shareUserTestFileWithUser($sharer, $receiver) {
  198. \OC_User::setUserId($sharer);
  199. $this->assertTrue(
  200. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $receiver, \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE),
  201. 'Failed asserting that ' . $sharer . ' successfully shared text.txt with ' . $receiver . '.'
  202. );
  203. $this->assertContains(
  204. 'test.txt',
  205. \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
  206. 'Failed asserting that test.txt is a shared file of ' . $sharer . '.'
  207. );
  208. \OC_User::setUserId($receiver);
  209. $this->assertContains(
  210. 'test.txt',
  211. \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  212. 'Failed asserting that ' . $receiver . ' has access to test.txt after initial sharing.'
  213. );
  214. }
  215. public function testShareWithUser() {
  216. // Invalid shares
  217. $message = 'Sharing test.txt failed, because you can not share with yourself';
  218. try {
  219. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user1->getUID(), \OCP\Constants::PERMISSION_READ);
  220. $this->fail('Exception was expected: '.$message);
  221. } catch (\Exception $exception) {
  222. $this->assertEquals($message, $exception->getMessage());
  223. }
  224. $message = 'Sharing test.txt failed, because the user foobar does not exist';
  225. try {
  226. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, 'foobar', \OCP\Constants::PERMISSION_READ);
  227. $this->fail('Exception was expected: '.$message);
  228. } catch (\Exception $exception) {
  229. $this->assertEquals($message, $exception->getMessage());
  230. }
  231. $message = 'Sharing foobar failed, because the sharing backend for test could not find its source';
  232. try {
  233. \OCP\Share::shareItem('test', 'foobar', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ);
  234. $this->fail('Exception was expected: '.$message);
  235. } catch (\Exception $exception) {
  236. $this->assertEquals($message, $exception->getMessage());
  237. }
  238. // Valid share
  239. $this->shareUserOneTestFileWithUserTwo();
  240. // Attempt to share again
  241. \OC_User::setUserId($this->user1->getUID());
  242. $message = 'Sharing test.txt failed, because this item is already shared with '.$this->user2->getUID();
  243. try {
  244. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ);
  245. $this->fail('Exception was expected: '.$message);
  246. } catch (\Exception $exception) {
  247. $this->assertEquals($message, $exception->getMessage());
  248. }
  249. // Attempt to share back
  250. \OC_User::setUserId($this->user2->getUID());
  251. $message = 'Sharing failed, because the user '.$this->user1->getUID().' is the original sharer';
  252. try {
  253. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user1->getUID(), \OCP\Constants::PERMISSION_READ);
  254. $this->fail('Exception was expected: '.$message);
  255. } catch (\Exception $exception) {
  256. $this->assertEquals($message, $exception->getMessage());
  257. }
  258. // Unshare
  259. \OC_User::setUserId($this->user1->getUID());
  260. $this->assertTrue(\OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID()));
  261. // Attempt reshare without share permission
  262. $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
  263. \OC_User::setUserId($this->user2->getUID());
  264. $message = 'Sharing test.txt failed, because resharing is not allowed';
  265. try {
  266. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ);
  267. $this->fail('Exception was expected: '.$message);
  268. } catch (\Exception $exception) {
  269. $this->assertEquals($message, $exception->getMessage());
  270. }
  271. // Owner grants share and update permission
  272. \OC_User::setUserId($this->user1->getUID());
  273. $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_SHARE));
  274. // Attempt reshare with escalated permissions
  275. \OC_User::setUserId($this->user2->getUID());
  276. $message = 'Sharing test.txt failed, because the permissions exceed permissions granted to '.$this->user2->getUID();
  277. try {
  278. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE);
  279. $this->fail('Exception was expected: '.$message);
  280. } catch (\Exception $exception) {
  281. $this->assertEquals($message, $exception->getMessage());
  282. }
  283. // Valid reshare
  284. $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE));
  285. $this->assertEquals(array('test.txt'), \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE));
  286. \OC_User::setUserId($this->user3->getUID());
  287. $this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE));
  288. $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
  289. // Attempt to escalate permissions
  290. \OC_User::setUserId($this->user2->getUID());
  291. $message = 'Setting permissions for test.txt failed, because the permissions exceed permissions granted to '.$this->user2->getUID();
  292. try {
  293. \OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_DELETE);
  294. $this->fail('Exception was expected: '.$message);
  295. } catch (\Exception $exception) {
  296. $this->assertEquals($message, $exception->getMessage());
  297. }
  298. // Remove update permission
  299. \OC_User::setUserId($this->user1->getUID());
  300. $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE));
  301. \OC_User::setUserId($this->user2->getUID());
  302. $this->assertEquals(array(\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
  303. \OC_User::setUserId($this->user3->getUID());
  304. $this->assertEquals(array(\OCP\Constants::PERMISSION_READ), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
  305. // Remove share permission
  306. \OC_User::setUserId($this->user1->getUID());
  307. $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
  308. \OC_User::setUserId($this->user2->getUID());
  309. $this->assertEquals(array(\OCP\Constants::PERMISSION_READ), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_PERMISSIONS));
  310. \OC_User::setUserId($this->user3->getUID());
  311. $this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt'));
  312. // Reshare again, and then have owner unshare
  313. \OC_User::setUserId($this->user1->getUID());
  314. $this->assertTrue(\OCP\Share::setPermissions('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_SHARE));
  315. \OC_User::setUserId($this->user2->getUID());
  316. $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_READ));
  317. \OC_User::setUserId($this->user1->getUID());
  318. $this->assertTrue(\OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID()));
  319. \OC_User::setUserId($this->user2->getUID());
  320. $this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt'));
  321. \OC_User::setUserId($this->user3->getUID());
  322. $this->assertSame(array(), \OCP\Share::getItemSharedWith('test', 'test.txt'));
  323. // Attempt target conflict
  324. \OC_User::setUserId($this->user1->getUID());
  325. $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
  326. \OC_User::setUserId($this->user3->getUID());
  327. $this->assertTrue(\OCP\Share::shareItem('test', 'share.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
  328. \OC_User::setUserId($this->user2->getUID());
  329. $to_test = \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET);
  330. $this->assertEquals(2, count($to_test));
  331. $this->assertTrue(in_array('test.txt', $to_test));
  332. $this->assertTrue(in_array('test1.txt', $to_test));
  333. // Unshare from self
  334. $this->assertTrue(\OCP\Share::unshareFromSelf('test', 'test.txt'));
  335. $this->assertEquals(array('test1.txt'), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET));
  336. // Unshare from self via source
  337. $this->assertTrue(\OCP\Share::unshareFromSelf('test', 'share.txt', true));
  338. $this->assertEquals(array(), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET));
  339. \OC_User::setUserId($this->user1->getUID());
  340. $this->assertTrue(\OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
  341. \OC_User::setUserId($this->user3->getUID());
  342. $this->assertTrue(\OCP\Share::shareItem('test', 'share.txt', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ));
  343. \OC_User::setUserId($this->user2->getUID());
  344. $to_test = \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET);
  345. $this->assertEquals(2, count($to_test));
  346. $this->assertTrue(in_array('test.txt', $to_test));
  347. $this->assertTrue(in_array('test1.txt', $to_test));
  348. // Remove user
  349. \OC_User::setUserId($this->user1->getUID());
  350. $user = \OC::$server->getUserManager()->get($this->user1->getUID());
  351. if ($user !== null) { $user->delete(); }
  352. \OC_User::setUserId($this->user2->getUID());
  353. $this->assertEquals(array('test1.txt'), \OCP\Share::getItemsSharedWith('test', Backend::FORMAT_TARGET));
  354. }
  355. public function testShareWithUserExpirationExpired() {
  356. \OC_User::setUserId($this->user1->getUID());
  357. $this->shareUserOneTestFileWithUserTwo();
  358. $this->shareUserTestFileAsLink();
  359. // manipulate share table and set expire date to the past
  360. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ? AND `uid_owner` = ? AND `share_type` = ?');
  361. $query->bindValue(1, new \DateTime($this->dateInPast), 'datetime');
  362. $query->bindValue(2, 'test');
  363. $query->bindValue(3, 'test.txt');
  364. $query->bindValue(4, $this->user1->getUID());
  365. $query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
  366. $query->execute();
  367. $shares = \OCP\Share::getItemsShared('test');
  368. $this->assertSame(1, count($shares));
  369. $share = reset($shares);
  370. $this->assertSame(\OCP\Share::SHARE_TYPE_USER, $share['share_type']);
  371. }
  372. public function testGetShareFromOutsideFilesFolder() {
  373. \OC_User::setUserId($this->user1->getUID());
  374. $view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
  375. $view->mkdir('files/test');
  376. $view->mkdir('files/test/sub');
  377. $view->mkdir('files_trashbin');
  378. $view->mkdir('files_trashbin/files');
  379. $fileInfo = $view->getFileInfo('files/test/sub');
  380. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  381. $fileId = $fileInfo->getId();
  382. $this->assertTrue(
  383. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ),
  384. 'Failed asserting that user 1 successfully shared "test/sub" with user 2.'
  385. );
  386. $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE);
  387. $this->assertNotEmpty($result);
  388. $result = \OCP\Share::getItemSharedWithUser('folder', $fileId, $this->user2->getUID());
  389. $this->assertNotEmpty($result);
  390. $result = \OCP\Share::getItemsSharedWithUser('folder', $this->user2->getUID());
  391. $this->assertNotEmpty($result);
  392. // move to trash (keeps file id)
  393. $view->rename('files/test', 'files_trashbin/files/test');
  394. $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE);
  395. $this->assertEmpty($result, 'Share must not be returned for files outside of "files"');
  396. $result = \OCP\Share::getItemSharedWithUser('folder', $fileId, $this->user2->getUID());
  397. $this->assertEmpty($result, 'Share must not be returned for files outside of "files"');
  398. $result = \OCP\Share::getItemsSharedWithUser('folder', $this->user2->getUID());
  399. $this->assertEmpty($result, 'Share must not be returned for files outside of "files"');
  400. }
  401. public function testSetExpireDateInPast() {
  402. \OC_User::setUserId($this->user1->getUID());
  403. $this->shareUserOneTestFileWithUserTwo();
  404. $this->shareUserTestFileAsLink();
  405. $setExpireDateFailed = false;
  406. try {
  407. $this->assertTrue(
  408. \OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInPast, ''),
  409. 'Failed asserting that user 1 successfully set an expiration date for the test.txt share.'
  410. );
  411. } catch (\Exception $e) {
  412. $setExpireDateFailed = true;
  413. }
  414. $this->assertTrue($setExpireDateFailed);
  415. }
  416. public function testShareWithUserExpirationValid() {
  417. \OC_User::setUserId($this->user1->getUID());
  418. $this->shareUserOneTestFileWithUserTwo();
  419. $this->shareUserTestFileAsLink();
  420. $this->assertTrue(
  421. \OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''),
  422. 'Failed asserting that user 1 successfully set an expiration date for the test.txt share.'
  423. );
  424. $shares = \OCP\Share::getItemsShared('test');
  425. $this->assertSame(2, count($shares));
  426. }
  427. /*
  428. * if user is in a group excluded from resharing, then the share permission should
  429. * be removed
  430. */
  431. public function testShareWithUserAndUserIsExcludedFromResharing() {
  432. \OC_User::setUserId($this->user1->getUID());
  433. $this->assertTrue(
  434. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_USER, $this->user4->getUID(), \OCP\Constants::PERMISSION_ALL),
  435. 'Failed asserting that user 1 successfully shared text.txt with user 4.'
  436. );
  437. $this->assertContains(
  438. 'test.txt',
  439. \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
  440. 'Failed asserting that test.txt is a shared file of user 1.'
  441. );
  442. // exclude group2 from sharing
  443. \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups_list', $this->group2->getGID());
  444. \OC::$server->getAppConfig()->setValue('core', 'shareapi_exclude_groups', "yes");
  445. \OC_User::setUserId($this->user4->getUID());
  446. $share = \OCP\Share::getItemSharedWith('test', 'test.txt');
  447. $this->assertSame(\OCP\Constants::PERMISSION_ALL & ~\OCP\Constants::PERMISSION_SHARE, $share['permissions'],
  448. 'Failed asserting that user 4 is excluded from re-sharing');
  449. \OC::$server->getAppConfig()->deleteKey('core', 'shareapi_exclude_groups_list');
  450. \OC::$server->getAppConfig()->deleteKey('core', 'shareapi_exclude_groups');
  451. }
  452. public function testSharingAFolderThatIsSharedWithAGroupOfTheOwner() {
  453. \OC_User::setUserId($this->user1->getUID());
  454. $view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
  455. $view->mkdir('files/test');
  456. $view->mkdir('files/test/sub1');
  457. $view->mkdir('files/test/sub1/sub2');
  458. $fileInfo = $view->getFileInfo('files/test/sub1');
  459. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  460. $fileId = $fileInfo->getId();
  461. $this->assertTrue(
  462. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_GROUP, $this->group1->getGID(), \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_CREATE),
  463. 'Failed asserting that user 1 successfully shared "test/sub1" with group 1.'
  464. );
  465. $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE);
  466. $this->assertNotEmpty($result);
  467. $this->assertEquals(\OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_CREATE, $result['permissions']);
  468. $fileInfo = $view->getFileInfo('files/test/sub1/sub2');
  469. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  470. $fileId = $fileInfo->getId();
  471. $this->assertTrue(
  472. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user4->getUID(), \OCP\Constants::PERMISSION_READ),
  473. 'Failed asserting that user 1 successfully shared "test/sub1/sub2" with user 4.'
  474. );
  475. $result = \OCP\Share::getItemShared('folder', $fileId, Backend::FORMAT_SOURCE);
  476. $this->assertNotEmpty($result);
  477. $this->assertEquals(\OCP\Constants::PERMISSION_READ, $result['permissions']);
  478. }
  479. public function testSharingAFileInsideAFolderThatIsAlreadyShared() {
  480. \OC_User::setUserId($this->user1->getUID());
  481. $view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
  482. $view->mkdir('files/test');
  483. $view->mkdir('files/test/sub1');
  484. $view->file_put_contents('files/test/sub1/file.txt', 'abc');
  485. $folderInfo = $view->getFileInfo('files/test/sub1');
  486. $this->assertInstanceOf('\OC\Files\FileInfo', $folderInfo);
  487. $folderId = $folderInfo->getId();
  488. $fileInfo = $view->getFileInfo('files/test/sub1/file.txt');
  489. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  490. $fileId = $fileInfo->getId();
  491. $this->assertTrue(
  492. \OCP\Share::shareItem('folder', $folderId, \OCP\Share::SHARE_TYPE_GROUP, $this->group2->getGID(), \OCP\Constants::PERMISSION_READ + \OCP\Constants::PERMISSION_UPDATE),
  493. 'Failed asserting that user 1 successfully shared "test/sub1" with group 2.'
  494. );
  495. $this->assertTrue(
  496. \OCP\Share::shareItem('file', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_READ),
  497. 'Failed asserting that user 1 successfully shared "test/sub1/file.txt" with user 2.'
  498. );
  499. $result = \OCP\Share::getItemsSharedWithUser('file', $this->user2->getUID());
  500. $this->assertCount(2, $result);
  501. foreach ($result as $share) {
  502. $itemName = substr($share['path'], strrpos($share['path'], '/'));
  503. $this->assertSame($itemName, $share['file_target'], 'Asserting that the file_target is the last segment of the path');
  504. $this->assertSame($share['item_target'], '/' . $share['item_source'], 'Asserting that the item is the item that was shared');
  505. }
  506. }
  507. protected function shareUserOneTestFileWithGroupOne() {
  508. \OC_User::setUserId($this->user1->getUID());
  509. $this->assertTrue(
  510. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->group1->getGID(), \OCP\Constants::PERMISSION_READ),
  511. 'Failed asserting that user 1 successfully shared text.txt with group 1.'
  512. );
  513. $this->assertContains(
  514. 'test.txt',
  515. \OCP\Share::getItemShared('test', 'test.txt', Backend::FORMAT_SOURCE),
  516. 'Failed asserting that test.txt is a shared file of user 1.'
  517. );
  518. \OC_User::setUserId($this->user2->getUID());
  519. $this->assertContains(
  520. 'test.txt',
  521. \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  522. 'Failed asserting that user 2 has access to test.txt after initial sharing.'
  523. );
  524. \OC_User::setUserId($this->user3->getUID());
  525. $this->assertContains(
  526. 'test.txt',
  527. \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  528. 'Failed asserting that user 3 has access to test.txt after initial sharing.'
  529. );
  530. }
  531. /**
  532. * Test that unsharing from group will also delete all
  533. * child entries
  534. */
  535. public function testShareWithGroupThenUnshare() {
  536. \OC_User::setUserId($this->user5->getUID());
  537. \OCP\Share::shareItem(
  538. 'test',
  539. 'test.txt',
  540. \OCP\Share::SHARE_TYPE_GROUP,
  541. $this->group1->getGID(),
  542. \OCP\Constants::PERMISSION_ALL
  543. );
  544. $targetUsers = array($this->user1->getUID(), $this->user2->getUID(), $this->user3->getUID());
  545. foreach($targetUsers as $targetUser) {
  546. \OC_User::setUserId($targetUser);
  547. $items = \OCP\Share::getItemsSharedWithUser(
  548. 'test',
  549. $targetUser,
  550. Backend::FORMAT_TARGET
  551. );
  552. $this->assertEquals(1, count($items));
  553. }
  554. \OC_User::setUserId($this->user5->getUID());
  555. \OCP\Share::unshare(
  556. 'test',
  557. 'test.txt',
  558. \OCP\Share::SHARE_TYPE_GROUP,
  559. $this->group1->getGID()
  560. );
  561. // verify that all were deleted
  562. foreach($targetUsers as $targetUser) {
  563. \OC_User::setUserId($targetUser);
  564. $items = \OCP\Share::getItemsSharedWithUser(
  565. 'test',
  566. $targetUser,
  567. Backend::FORMAT_TARGET
  568. );
  569. $this->assertEquals(0, count($items));
  570. }
  571. }
  572. public function testShareWithGroupAndUserBothHaveTheSameId() {
  573. $this->shareUserTestFileWithUser($this->user1->getUID(), $this->groupAndUser_user->getUID());
  574. \OC_User::setUserId($this->groupAndUser_user->getUID());
  575. $this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  576. '"groupAndUser"-User does not see the file but it was shared with him');
  577. \OC_User::setUserId($this->user2->getUID());
  578. $this->assertEquals(array(), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  579. 'User2 sees test.txt but it was only shared with the user "groupAndUser" and not with group');
  580. \OC_User::setUserId($this->user1->getUID());
  581. $this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt'));
  582. $this->assertTrue(
  583. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->groupAndUser_group->getGID(), \OCP\Constants::PERMISSION_READ),
  584. 'Failed asserting that user 1 successfully shared text.txt with group 1.'
  585. );
  586. \OC_User::setUserId($this->groupAndUser_user->getUID());
  587. $this->assertEquals(array(), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  588. '"groupAndUser"-User sees test.txt but it was only shared with the group "groupAndUser" and not with the user');
  589. \OC_User::setUserId($this->user2->getUID());
  590. $this->assertEquals(array('test.txt'), \OCP\Share::getItemSharedWith('test', 'test.txt', Backend::FORMAT_SOURCE),
  591. 'User2 does not see test.txt but it was shared with the group "groupAndUser"');
  592. \OC_User::setUserId($this->user1->getUID());
  593. $this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt'));
  594. }
  595. /**
  596. * @param boolean|string $token
  597. * @return array
  598. */
  599. protected function getShareByValidToken($token) {
  600. $row = \OCP\Share::getShareByToken($token);
  601. $this->assertInternalType(
  602. 'array',
  603. $row,
  604. "Failed asserting that a share for token $token exists."
  605. );
  606. return $row;
  607. }
  608. public function testGetItemSharedWithUser() {
  609. \OC_User::setUserId($this->user1->getUID());
  610. //add dummy values to the share table
  611. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
  612. .' `item_type`, `item_source`, `item_target`, `share_type`,'
  613. .' `share_with`, `uid_owner`) VALUES (?,?,?,?,?,?)');
  614. $args = array('test', 99, 'target1', \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), $this->user1->getUID());
  615. $query->execute($args);
  616. $args = array('test', 99, 'target2', \OCP\Share::SHARE_TYPE_USER, $this->user4->getUID(), $this->user1->getUID());
  617. $query->execute($args);
  618. $args = array('test', 99, 'target3', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), $this->user2->getUID());
  619. $query->execute($args);
  620. $args = array('test', 99, 'target4', \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), $this->user4->getUID());
  621. $query->execute($args);
  622. $args = array('test', 99, 'target4', \OCP\Share::SHARE_TYPE_USER, $this->user6->getUID(), $this->user4->getUID());
  623. $query->execute($args);
  624. $result1 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user2->getUID(), $this->user1->getUID());
  625. $this->assertSame(1, count($result1));
  626. $this->verifyResult($result1, array('target1'));
  627. $result2 = \OCP\Share::getItemSharedWithUser('test', 99, null, $this->user1->getUID());
  628. $this->assertSame(2, count($result2));
  629. $this->verifyResult($result2, array('target1', 'target2'));
  630. $result3 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user3->getUID());
  631. $this->assertSame(2, count($result3));
  632. $this->verifyResult($result3, array('target3', 'target4'));
  633. $result4 = \OCP\Share::getItemSharedWithUser('test', 99, null, null);
  634. $this->assertSame(5, count($result4)); // 5 because target4 appears twice
  635. $this->verifyResult($result4, array('target1', 'target2', 'target3', 'target4'));
  636. $result6 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user6->getUID(), null);
  637. $this->assertSame(1, count($result6));
  638. $this->verifyResult($result6, array('target4'));
  639. }
  640. public function testGetItemSharedWithUserFromGroupShare() {
  641. \OC_User::setUserId($this->user1->getUID());
  642. //add dummy values to the share table
  643. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
  644. .' `item_type`, `item_source`, `item_target`, `share_type`,'
  645. .' `share_with`, `uid_owner`) VALUES (?,?,?,?,?,?)');
  646. $args = array('test', 99, 'target1', \OCP\Share::SHARE_TYPE_GROUP, $this->group1->getGID(), $this->user1->getUID());
  647. $query->execute($args);
  648. $args = array('test', 99, 'target2', \OCP\Share::SHARE_TYPE_GROUP, $this->group2->getGID(), $this->user1->getUID());
  649. $query->execute($args);
  650. $args = array('test', 99, 'target3', \OCP\Share::SHARE_TYPE_GROUP, $this->group1->getGID(), $this->user2->getUID());
  651. $query->execute($args);
  652. $args = array('test', 99, 'target4', \OCP\Share::SHARE_TYPE_GROUP, $this->group1->getGID(), $this->user4->getUID());
  653. $query->execute($args);
  654. // user2 is in group1 and group2
  655. $result1 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user2->getUID(), $this->user1->getUID());
  656. $this->assertSame(2, count($result1));
  657. $this->verifyResult($result1, array('target1', 'target2'));
  658. $result2 = \OCP\Share::getItemSharedWithUser('test', 99, null, $this->user1->getUID());
  659. $this->assertSame(2, count($result2));
  660. $this->verifyResult($result2, array('target1', 'target2'));
  661. // user3 is in group1 and group2
  662. $result3 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user3->getUID());
  663. $this->assertSame(3, count($result3));
  664. $this->verifyResult($result3, array('target1', 'target3', 'target4'));
  665. $result4 = \OCP\Share::getItemSharedWithUser('test', 99, null, null);
  666. $this->assertSame(4, count($result4));
  667. $this->verifyResult($result4, array('target1', 'target2', 'target3', 'target4'));
  668. $result6 = \OCP\Share::getItemSharedWithUser('test', 99, $this->user6->getUID(), null);
  669. $this->assertSame(0, count($result6));
  670. }
  671. public function verifyResult($result, $expected) {
  672. foreach ($result as $r) {
  673. if (in_array($r['item_target'], $expected)) {
  674. $key = array_search($r['item_target'], $expected);
  675. unset($expected[$key]);
  676. }
  677. }
  678. $this->assertEmpty($expected, 'did not found all expected values');
  679. }
  680. public function testGetShareSubItemsWhenUserNotInGroup() {
  681. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_GROUP, $this->group1->getGID(), \OCP\Constants::PERMISSION_READ);
  682. $result = \OCP\Share::getItemsSharedWithUser('test', $this->user2->getUID());
  683. $this->assertCount(1, $result);
  684. $groupShareId = array_keys($result)[0];
  685. // remove user from group
  686. $userObject = \OC::$server->getUserManager()->get($this->user2->getUID());
  687. \OC::$server->getGroupManager()->get($this->group1->getGID())->removeUser($userObject);
  688. $result = \OCP\Share::getItemsSharedWithUser('test', $this->user2->getUID());
  689. $this->assertCount(0, $result);
  690. // test with buggy data
  691. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  692. $qb->insert('share')
  693. ->values([
  694. 'share_type' => $qb->expr()->literal(2), // group sub-share
  695. 'share_with' => $qb->expr()->literal($this->user2->getUID()),
  696. 'parent' => $qb->expr()->literal($groupShareId),
  697. 'uid_owner' => $qb->expr()->literal($this->user1->getUID()),
  698. 'item_type' => $qb->expr()->literal('test'),
  699. 'item_source' => $qb->expr()->literal('test.txt'),
  700. 'item_target' => $qb->expr()->literal('test.txt'),
  701. 'file_target' => $qb->expr()->literal('test2.txt'),
  702. 'permissions' => $qb->expr()->literal(1),
  703. 'stime' => $qb->expr()->literal(time()),
  704. ])->execute();
  705. $result = \OCP\Share::getItemsSharedWithUser('test', $this->user2->getUID());
  706. $this->assertCount(0, $result);
  707. $qb->delete('share')->execute();
  708. }
  709. public function testShareItemWithLink() {
  710. \OC_User::setUserId($this->user1->getUID());
  711. $token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
  712. $this->assertInternalType(
  713. 'string',
  714. $token,
  715. 'Failed asserting that user 1 successfully shared text.txt as link with token.'
  716. );
  717. // testGetShareByTokenNoExpiration
  718. $row = $this->getShareByValidToken($token);
  719. $this->assertEmpty(
  720. $row['expiration'],
  721. 'Failed asserting that the returned row does not have an expiration date.'
  722. );
  723. // testGetShareByTokenExpirationValid
  724. $this->assertTrue(
  725. \OCP\Share::setExpirationDate('test', 'test.txt', $this->dateInFuture, ''),
  726. 'Failed asserting that user 1 successfully set a future expiration date for the test.txt share.'
  727. );
  728. $row = $this->getShareByValidToken($token);
  729. $this->assertNotEmpty(
  730. $row['expiration'],
  731. 'Failed asserting that the returned row has an expiration date.'
  732. );
  733. // manipulate share table and set expire date to the past
  734. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ? AND `uid_owner` = ? AND `share_type` = ?');
  735. $query->bindValue(1, new \DateTime($this->dateInPast), 'datetime');
  736. $query->bindValue(2, 'test');
  737. $query->bindValue(3, 'test.txt');
  738. $query->bindValue(4, $this->user1->getUID());
  739. $query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
  740. $query->execute();
  741. $this->assertFalse(
  742. \OCP\Share::getShareByToken($token),
  743. 'Failed asserting that an expired share could not be found.'
  744. );
  745. }
  746. public function testShareItemWithLinkAndDefaultExpireDate() {
  747. \OC_User::setUserId($this->user1->getUID());
  748. $config = \OC::$server->getConfig();
  749. $config->setAppValue('core', 'shareapi_default_expire_date', 'yes');
  750. $config->setAppValue('core', 'shareapi_expire_after_n_days', '2');
  751. $token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
  752. $this->assertInternalType(
  753. 'string',
  754. $token,
  755. 'Failed asserting that user 1 successfully shared text.txt as link with token.'
  756. );
  757. // share should have default expire date
  758. $row = $this->getShareByValidToken($token);
  759. $this->assertNotEmpty(
  760. $row['expiration'],
  761. 'Failed asserting that the returned row has an default expiration date.'
  762. );
  763. $config->deleteAppValue('core', 'shareapi_default_expire_date');
  764. $config->deleteAppValue('core', 'shareapi_expire_after_n_days');
  765. }
  766. public function dataShareWithRemoteUserAndRemoteIsInvalid() {
  767. return [
  768. // Invalid path
  769. array('user@'),
  770. // Invalid user
  771. array('@server'),
  772. array('us/er@server'),
  773. array('us:er@server'),
  774. // Invalid splitting
  775. array('user'),
  776. array(''),
  777. array('us/erserver'),
  778. array('us:erserver'),
  779. ];
  780. }
  781. /**
  782. * @dataProvider dataShareWithRemoteUserAndRemoteIsInvalid
  783. *
  784. * @param string $remoteId
  785. * @expectedException \OC\HintException
  786. */
  787. public function testShareWithRemoteUserAndRemoteIsInvalid($remoteId) {
  788. \OC_User::setUserId($this->user1->getUID());
  789. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, $remoteId, \OCP\Constants::PERMISSION_ALL);
  790. }
  791. public function testUnshareAll() {
  792. $this->shareUserTestFileWithUser($this->user1->getUID(), $this->user2->getUID());
  793. $this->shareUserTestFileWithUser($this->user2->getUID(), $this->user3->getUID());
  794. $this->shareUserTestFileWithUser($this->user3->getUID(), $this->user4->getUID());
  795. $this->shareUserOneTestFileWithGroupOne();
  796. \OC_User::setUserId($this->user1->getUID());
  797. $this->assertEquals(
  798. array('test.txt', 'test.txt'),
  799. \OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE),
  800. 'Failed asserting that the test.txt file is shared exactly two times by user1.'
  801. );
  802. \OC_User::setUserId($this->user2->getUID());
  803. $this->assertEquals(
  804. array('test.txt'),
  805. \OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE),
  806. 'Failed asserting that the test.txt file is shared exactly once by user2.'
  807. );
  808. \OC_User::setUserId($this->user3->getUID());
  809. $this->assertEquals(
  810. array('test.txt'),
  811. \OCP\Share::getItemsShared('test', Backend::FORMAT_SOURCE),
  812. 'Failed asserting that the test.txt file is shared exactly once by user3.'
  813. );
  814. $this->assertTrue(
  815. \OCP\Share::unshareAll('test', 'test.txt'),
  816. 'Failed asserting that user 3 successfully unshared all shares of the test.txt share.'
  817. );
  818. $this->assertEquals(
  819. array(),
  820. \OCP\Share::getItemsShared('test'),
  821. 'Failed asserting that the share of the test.txt file by user 3 has been removed.'
  822. );
  823. \OC_User::setUserId($this->user1->getUID());
  824. $this->assertEquals(
  825. array(),
  826. \OCP\Share::getItemsShared('test'),
  827. 'Failed asserting that both shares of the test.txt file by user 1 have been removed.'
  828. );
  829. \OC_User::setUserId($this->user2->getUID());
  830. $this->assertEquals(
  831. array(),
  832. \OCP\Share::getItemsShared('test'),
  833. 'Failed asserting that the share of the test.txt file by user 2 has been removed.'
  834. );
  835. }
  836. /**
  837. * @dataProvider checkPasswordProtectedShareDataProvider
  838. * @param $expected
  839. * @param $item
  840. */
  841. public function testCheckPasswordProtectedShare($expected, $item) {
  842. \OC::$server->getSession()->set('public_link_authenticated', '100');
  843. $result = \OCP\Share::checkPasswordProtectedShare($item);
  844. $this->assertEquals($expected, $result);
  845. }
  846. function checkPasswordProtectedShareDataProvider() {
  847. return array(
  848. array(true, array()),
  849. array(true, array('share_with' => null)),
  850. array(true, array('share_with' => '')),
  851. array(true, array('share_with' => '1234567890', 'share_type' => '1')),
  852. array(true, array('share_with' => '1234567890', 'share_type' => 1)),
  853. array(true, array('share_with' => '1234567890', 'share_type' => '3', 'id' => '100')),
  854. array(true, array('share_with' => '1234567890', 'share_type' => 3, 'id' => '100')),
  855. array(true, array('share_with' => '1234567890', 'share_type' => '3', 'id' => 100)),
  856. array(true, array('share_with' => '1234567890', 'share_type' => 3, 'id' => 100)),
  857. array(false, array('share_with' => '1234567890', 'share_type' => '3', 'id' => '101')),
  858. array(false, array('share_with' => '1234567890', 'share_type' => 3, 'id' => '101')),
  859. array(false, array('share_with' => '1234567890', 'share_type' => '3', 'id' => 101)),
  860. array(false, array('share_with' => '1234567890', 'share_type' => 3, 'id' => 101)),
  861. );
  862. }
  863. /**
  864. * @dataProvider urls
  865. * @param string $url
  866. * @param string $expectedResult
  867. */
  868. function testRemoveProtocolFromUrl($url, $expectedResult) {
  869. $share = new \OC\Share\Share();
  870. $result = self::invokePrivate($share, 'removeProtocolFromUrl', array($url));
  871. $this->assertSame($expectedResult, $result);
  872. }
  873. function urls() {
  874. return array(
  875. array('http://owncloud.org', 'owncloud.org'),
  876. array('https://owncloud.org', 'owncloud.org'),
  877. array('owncloud.org', 'owncloud.org'),
  878. );
  879. }
  880. public function dataRemoteShareUrlCalls() {
  881. return [
  882. ['admin@localhost', 'localhost'],
  883. ['admin@https://localhost', 'localhost'],
  884. ['admin@http://localhost', 'localhost'],
  885. ['admin@localhost/subFolder', 'localhost/subFolder'],
  886. ];
  887. }
  888. /**
  889. * @dataProvider dataRemoteShareUrlCalls
  890. *
  891. * @param string $shareWith
  892. * @param string $urlHost
  893. */
  894. public function testRemoteShareUrlCalls($shareWith, $urlHost) {
  895. $httpHelperMock = $this->getMockBuilder('OC\HTTPHelper')
  896. ->disableOriginalConstructor()
  897. ->getMock();
  898. $this->overwriteService('HTTPHelper', $httpHelperMock);
  899. $httpHelperMock->expects($this->at(0))
  900. ->method('post')
  901. ->with($this->stringStartsWith('https://' . $urlHost . '/ocs/v1.php/cloud/shares'), $this->anything())
  902. ->willReturn(['success' => false, 'result' => 'Exception']);
  903. $httpHelperMock->expects($this->at(1))
  904. ->method('post')
  905. ->with($this->stringStartsWith('http://' . $urlHost . '/ocs/v1.php/cloud/shares'), $this->anything())
  906. ->willReturn(['success' => true, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 100]]])]);
  907. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, $shareWith, \OCP\Constants::PERMISSION_READ);
  908. $shares = \OCP\Share::getItemShared('test', 'test.txt');
  909. $share = array_shift($shares);
  910. $httpHelperMock->expects($this->at(0))
  911. ->method('post')
  912. ->with($this->stringStartsWith('https://' . $urlHost . '/ocs/v1.php/cloud/shares/' . $share['id'] . '/unshare'), $this->anything())
  913. ->willReturn(['success' => false, 'result' => 'Exception']);
  914. $httpHelperMock->expects($this->at(1))
  915. ->method('post')
  916. ->with($this->stringStartsWith('http://' . $urlHost . '/ocs/v1.php/cloud/shares/' . $share['id'] . '/unshare'), $this->anything())
  917. ->willReturn(['success' => true, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 100]]])]);
  918. \OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, $shareWith);
  919. $this->restoreService('HTTPHelper');
  920. }
  921. /**
  922. * @dataProvider dataProviderTestGroupItems
  923. * @param array $ungrouped
  924. * @param array $grouped
  925. */
  926. function testGroupItems($ungrouped, $grouped) {
  927. $result = DummyShareClass::groupItemsTest($ungrouped);
  928. $this->compareArrays($grouped, $result);
  929. }
  930. function compareArrays($result, $expectedResult) {
  931. foreach ($expectedResult as $key => $value) {
  932. if (is_array($value)) {
  933. $this->compareArrays($result[$key], $value);
  934. } else {
  935. $this->assertSame($value, $result[$key]);
  936. }
  937. }
  938. }
  939. function dataProviderTestGroupItems() {
  940. return array(
  941. // one array with one share
  942. array(
  943. array( // input
  944. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_ALL, 'item_target' => 't1')),
  945. array( // expected result
  946. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_ALL, 'item_target' => 't1'))),
  947. // two shares both point to the same source
  948. array(
  949. array( // input
  950. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'),
  951. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'),
  952. ),
  953. array( // expected result
  954. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1',
  955. 'grouped' => array(
  956. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'),
  957. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'),
  958. )
  959. ),
  960. )
  961. ),
  962. // two shares both point to the same source but with different targets
  963. array(
  964. array( // input
  965. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'),
  966. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't2'),
  967. ),
  968. array( // expected result
  969. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'),
  970. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't2'),
  971. )
  972. ),
  973. // three shares two point to the same source
  974. array(
  975. array( // input
  976. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'),
  977. array('item_source' => 2, 'permissions' => \OCP\Constants::PERMISSION_CREATE, 'item_target' => 't2'),
  978. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'),
  979. ),
  980. array( // expected result
  981. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1',
  982. 'grouped' => array(
  983. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_READ, 'item_target' => 't1'),
  984. array('item_source' => 1, 'permissions' => \OCP\Constants::PERMISSION_UPDATE, 'item_target' => 't1'),
  985. )
  986. ),
  987. array('item_source' => 2, 'permissions' => \OCP\Constants::PERMISSION_CREATE, 'item_target' => 't2'),
  988. )
  989. ),
  990. );
  991. }
  992. /**
  993. * Ensure that we do not allow removing a an expiration date from a link share if this
  994. * is enforced by the settings.
  995. */
  996. public function testClearExpireDateWhileEnforced() {
  997. \OC_User::setUserId($this->user1->getUID());
  998. \OC::$server->getAppConfig()->setValue('core', 'shareapi_default_expire_date', 'yes');
  999. \OC::$server->getAppConfig()->setValue('core', 'shareapi_expire_after_n_days', '2');
  1000. \OC::$server->getAppConfig()->setValue('core', 'shareapi_enforce_expire_date', 'yes');
  1001. $token = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
  1002. $this->assertInternalType(
  1003. 'string',
  1004. $token,
  1005. 'Failed asserting that user 1 successfully shared text.txt as link with token.'
  1006. );
  1007. $setExpireDateFailed = false;
  1008. try {
  1009. $this->assertTrue(
  1010. \OCP\Share::setExpirationDate('test', 'test.txt', '', ''),
  1011. 'Failed asserting that user 1 successfully set an expiration date for the test.txt share.'
  1012. );
  1013. } catch (\Exception $e) {
  1014. $setExpireDateFailed = true;
  1015. }
  1016. $this->assertTrue($setExpireDateFailed);
  1017. \OC::$server->getAppConfig()->deleteKey('core', 'shareapi_default_expire_date');
  1018. \OC::$server->getAppConfig()->deleteKey('core', 'shareapi_expire_after_n_days');
  1019. \OC::$server->getAppConfig()->deleteKey('core', 'shareapi_enforce_expire_date');
  1020. }
  1021. /**
  1022. * Cannot set password is there is no user
  1023. *
  1024. * @expectedException \Exception
  1025. * @expectedExceptionMessage User not logged in
  1026. */
  1027. public function testSetPasswordNoUser() {
  1028. $userSession = $this->getMockBuilder('\OCP\IUserSession')
  1029. ->disableOriginalConstructor()
  1030. ->getMock();
  1031. $connection = $this->getMockBuilder('\OC\DB\Connection')
  1032. ->disableOriginalConstructor()
  1033. ->getMock();
  1034. $config = $this->getMockBuilder('\OCP\IConfig')
  1035. ->disableOriginalConstructor()
  1036. ->getMock();
  1037. \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
  1038. }
  1039. public function testPasswords() {
  1040. $pass = 'secret';
  1041. $this->shareUserTestFileAsLink();
  1042. $userSession = \OC::$server->getUserSession();
  1043. $connection = \OC::$server->getDatabaseConnection();
  1044. $config = $this->getMockBuilder('\OCP\IConfig')
  1045. ->disableOriginalConstructor()
  1046. ->getMock();
  1047. // Find the share ID in the db
  1048. $qb = $connection->getQueryBuilder();
  1049. $qb->select('id')
  1050. ->from('share')
  1051. ->where($qb->expr()->eq('item_type', $qb->createParameter('type')))
  1052. ->andWhere($qb->expr()->eq('item_source', $qb->createParameter('source')))
  1053. ->andWhere($qb->expr()->eq('uid_owner', $qb->createParameter('owner')))
  1054. ->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
  1055. ->setParameter('type', 'test')
  1056. ->setParameter('source', 'test.txt')
  1057. ->setParameter('owner', $this->user1->getUID())
  1058. ->setParameter('share_type', \OCP\Share::SHARE_TYPE_LINK);
  1059. $res = $qb->execute()->fetchAll();
  1060. $this->assertCount(1, $res);
  1061. $id = $res[0]['id'];
  1062. // Set password on share
  1063. $res = \OC\Share\Share::setPassword($userSession, $connection, $config, $id, $pass);
  1064. $this->assertTrue($res);
  1065. // Fetch the hash from the database
  1066. $qb = $connection->getQueryBuilder();
  1067. $qb->select('share_with')
  1068. ->from('share')
  1069. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  1070. ->setParameter('id', $id);
  1071. $hash = $qb->execute()->fetch()['share_with'];
  1072. $hasher = \OC::$server->getHasher();
  1073. // Verify hash
  1074. $this->assertTrue($hasher->verify($pass, $hash));
  1075. }
  1076. /**
  1077. * Test setting a password when everything is fine
  1078. */
  1079. public function testSetPassword() {
  1080. $user = $this->getMockBuilder('\OCP\IUser')
  1081. ->disableOriginalConstructor()
  1082. ->getMock();
  1083. $user->method('getUID')->willReturn('user');
  1084. $userSession = $this->getMockBuilder('\OCP\IUserSession')
  1085. ->disableOriginalConstructor()
  1086. ->getMock();
  1087. $userSession->method('getUser')->willReturn($user);
  1088. $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
  1089. ->disableOriginalConstructor()
  1090. ->getMock();
  1091. $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
  1092. ->disableOriginalConstructor()
  1093. ->getMock();
  1094. $qb->method('update')->will($this->returnSelf());
  1095. $qb->method('set')->will($this->returnSelf());
  1096. $qb->method('where')->will($this->returnSelf());
  1097. $qb->method('andWhere')->will($this->returnSelf());
  1098. $qb->method('select')->will($this->returnSelf());
  1099. $qb->method('from')->will($this->returnSelf());
  1100. $qb->method('setParameter')->will($this->returnSelf());
  1101. $qb->method('expr')->willReturn($ex);
  1102. $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
  1103. ->disableOriginalConstructor()
  1104. ->getMock();
  1105. $ret->method('fetch')->willReturn(['uid_owner' => 'user']);
  1106. $qb->method('execute')->willReturn($ret);
  1107. $connection = $this->getMockBuilder('\OC\DB\Connection')
  1108. ->disableOriginalConstructor()
  1109. ->getMock();
  1110. $connection->method('getQueryBuilder')->willReturn($qb);
  1111. $config = $this->getMockBuilder('\OCP\IConfig')
  1112. ->disableOriginalConstructor()
  1113. ->getMock();
  1114. $res = \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
  1115. $this->assertTrue($res);
  1116. }
  1117. /**
  1118. * @expectedException \Exception
  1119. * @expectedExceptionMessage Cannot remove password
  1120. *
  1121. * Test removing a password when password is enforced
  1122. */
  1123. public function testSetPasswordRemove() {
  1124. $user = $this->getMockBuilder('\OCP\IUser')
  1125. ->disableOriginalConstructor()
  1126. ->getMock();
  1127. $user->method('getUID')->willReturn('user');
  1128. $userSession = $this->getMockBuilder('\OCP\IUserSession')
  1129. ->disableOriginalConstructor()
  1130. ->getMock();
  1131. $userSession->method('getUser')->willReturn($user);
  1132. $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
  1133. ->disableOriginalConstructor()
  1134. ->getMock();
  1135. $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
  1136. ->disableOriginalConstructor()
  1137. ->getMock();
  1138. $qb->method('update')->will($this->returnSelf());
  1139. $qb->method('select')->will($this->returnSelf());
  1140. $qb->method('from')->will($this->returnSelf());
  1141. $qb->method('set')->will($this->returnSelf());
  1142. $qb->method('where')->will($this->returnSelf());
  1143. $qb->method('andWhere')->will($this->returnSelf());
  1144. $qb->method('setParameter')->will($this->returnSelf());
  1145. $qb->method('expr')->willReturn($ex);
  1146. $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
  1147. ->disableOriginalConstructor()
  1148. ->getMock();
  1149. $ret->method('fetch')->willReturn(['uid_owner' => 'user']);
  1150. $qb->method('execute')->willReturn($ret);
  1151. $connection = $this->getMockBuilder('\OC\DB\Connection')
  1152. ->disableOriginalConstructor()
  1153. ->getMock();
  1154. $connection->method('getQueryBuilder')->willReturn($qb);
  1155. $config = $this->getMockBuilder('\OCP\IConfig')
  1156. ->disableOriginalConstructor()
  1157. ->getMock();
  1158. $config->method('getAppValue')->willReturn('yes');
  1159. \OC\Share\Share::setPassword($userSession, $connection, $config, 1, '');
  1160. }
  1161. /**
  1162. * @expectedException \Exception
  1163. * @expectedExceptionMessage Share not found
  1164. *
  1165. * Test modification of invaid share
  1166. */
  1167. public function testSetPasswordInvalidShare() {
  1168. $user = $this->getMockBuilder('\OCP\IUser')
  1169. ->disableOriginalConstructor()
  1170. ->getMock();
  1171. $user->method('getUID')->willReturn('user');
  1172. $userSession = $this->getMockBuilder('\OCP\IUserSession')
  1173. ->disableOriginalConstructor()
  1174. ->getMock();
  1175. $userSession->method('getUser')->willReturn($user);
  1176. $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
  1177. ->disableOriginalConstructor()
  1178. ->getMock();
  1179. $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
  1180. ->disableOriginalConstructor()
  1181. ->getMock();
  1182. $qb->method('update')->will($this->returnSelf());
  1183. $qb->method('set')->will($this->returnSelf());
  1184. $qb->method('where')->will($this->returnSelf());
  1185. $qb->method('andWhere')->will($this->returnSelf());
  1186. $qb->method('select')->will($this->returnSelf());
  1187. $qb->method('from')->will($this->returnSelf());
  1188. $qb->method('setParameter')->will($this->returnSelf());
  1189. $qb->method('expr')->willReturn($ex);
  1190. $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
  1191. ->disableOriginalConstructor()
  1192. ->getMock();
  1193. $ret->method('fetch')->willReturn([]);
  1194. $qb->method('execute')->willReturn($ret);
  1195. $connection = $this->getMockBuilder('\OC\DB\Connection')
  1196. ->disableOriginalConstructor()
  1197. ->getMock();
  1198. $connection->method('getQueryBuilder')->willReturn($qb);
  1199. $config = $this->getMockBuilder('\OCP\IConfig')
  1200. ->disableOriginalConstructor()
  1201. ->getMock();
  1202. \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
  1203. }
  1204. /**
  1205. * @expectedException \Exception
  1206. * @expectedExceptionMessage Cannot update share of a different user
  1207. *
  1208. * Test modification of share of another user
  1209. */
  1210. public function testSetPasswordShareOtherUser() {
  1211. $user = $this->getMockBuilder('\OCP\IUser')
  1212. ->disableOriginalConstructor()
  1213. ->getMock();
  1214. $user->method('getUID')->willReturn('user');
  1215. $userSession = $this->getMockBuilder('\OCP\IUserSession')
  1216. ->disableOriginalConstructor()
  1217. ->getMock();
  1218. $userSession->method('getUser')->willReturn($user);
  1219. $ex = $this->getMockBuilder('\OC\DB\QueryBuilder\ExpressionBuilder\ExpressionBuilder')
  1220. ->disableOriginalConstructor()
  1221. ->getMock();
  1222. $qb = $this->getMockBuilder('\OC\DB\QueryBuilder\QueryBuilder')
  1223. ->disableOriginalConstructor()
  1224. ->getMock();
  1225. $qb->method('update')->will($this->returnSelf());
  1226. $qb->method('set')->will($this->returnSelf());
  1227. $qb->method('where')->will($this->returnSelf());
  1228. $qb->method('andWhere')->will($this->returnSelf());
  1229. $qb->method('select')->will($this->returnSelf());
  1230. $qb->method('from')->will($this->returnSelf());
  1231. $qb->method('setParameter')->will($this->returnSelf());
  1232. $qb->method('expr')->willReturn($ex);
  1233. $ret = $this->getMockBuilder('\Doctrine\DBAL\Driver\ResultStatement')
  1234. ->disableOriginalConstructor()
  1235. ->getMock();
  1236. $ret->method('fetch')->willReturn(['uid_owner' => 'user2']);
  1237. $qb->method('execute')->willReturn($ret);
  1238. $connection = $this->getMockBuilder('\OC\DB\Connection')
  1239. ->disableOriginalConstructor()
  1240. ->getMock();
  1241. $connection->method('getQueryBuilder')->willReturn($qb);
  1242. $config = $this->getMockBuilder('\OCP\IConfig')
  1243. ->disableOriginalConstructor()
  1244. ->getMock();
  1245. \OC\Share\Share::setPassword($userSession, $connection, $config, 1, 'pass');
  1246. }
  1247. /**
  1248. * Make sure that a user cannot have multiple identical shares to remote users
  1249. */
  1250. public function testOnlyOneRemoteShare() {
  1251. $httpHelperMock = $this->getMockBuilder('OC\HTTPHelper')
  1252. ->disableOriginalConstructor()
  1253. ->getMock();
  1254. $this->overwriteService('HTTPHelper', $httpHelperMock);
  1255. $httpHelperMock->expects($this->at(0))
  1256. ->method('post')
  1257. ->with($this->stringStartsWith('https://localhost/ocs/v1.php/cloud/shares'), $this->anything())
  1258. ->willReturn(['success' => true, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 100]]])]);
  1259. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, 'foo@localhost', \OCP\Constants::PERMISSION_READ);
  1260. $shares = \OCP\Share::getItemShared('test', 'test.txt');
  1261. $share = array_shift($shares);
  1262. //Try share again
  1263. try {
  1264. \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, 'foo@localhost', \OCP\Constants::PERMISSION_READ);
  1265. $this->fail('Identical remote shares are not allowed');
  1266. } catch (\Exception $e) {
  1267. $this->assertEquals('Sharing test.txt failed, because this item is already shared with foo@localhost', $e->getMessage());
  1268. }
  1269. $httpHelperMock->expects($this->at(0))
  1270. ->method('post')
  1271. ->with($this->stringStartsWith('https://localhost/ocs/v1.php/cloud/shares/' . $share['id'] . '/unshare'), $this->anything())
  1272. ->willReturn(['success' => true, 'result' => json_encode(['ocs' => ['meta' => ['statuscode' => 100]]])]);
  1273. \OCP\Share::unshare('test', 'test.txt', \OCP\Share::SHARE_TYPE_REMOTE, 'foo@localhost');
  1274. $this->restoreService('HTTPHelper');
  1275. }
  1276. /**
  1277. * Test case for #19119
  1278. */
  1279. public function testReshareWithLinkDefaultExpirationDate() {
  1280. $config = \OC::$server->getConfig();
  1281. $config->setAppValue('core', 'shareapi_default_expire_date', 'yes');
  1282. $config->setAppValue('core', 'shareapi_expire_after_n_days', '2');
  1283. // Expiration date
  1284. $expireAt = time() + 2 * 24*60*60;
  1285. $date = new \DateTime();
  1286. $date->setTimestamp($expireAt);
  1287. $date->setTime(0, 0, 0);
  1288. //Share a file from user 1 to user 2
  1289. $this->shareUserTestFileWithUser($this->user1->getUID(), $this->user2->getUID());
  1290. //User 2 shares as link
  1291. \OC_User::setUserId($this->user2->getUID());
  1292. $result = \OCP\Share::shareItem('test', 'test.txt', \OCP\Share::SHARE_TYPE_LINK, null, \OCP\Constants::PERMISSION_READ);
  1293. $this->assertTrue(is_string($result));
  1294. //Check if expire date is correct
  1295. $result = \OCP\Share::getItemShared('test', 'test.txt');
  1296. $this->assertCount(1, $result);
  1297. $result = reset($result);
  1298. $this->assertNotEmpty($result['expiration']);
  1299. $expireDate = new \DateTime($result['expiration']);
  1300. $this->assertEquals($date, $expireDate);
  1301. //Unshare
  1302. $this->assertTrue(\OCP\Share::unshareAll('test', 'test.txt'));
  1303. //Reset config
  1304. $config->deleteAppValue('core', 'shareapi_default_expire_date');
  1305. $config->deleteAppValue('core', 'shareapi_expire_after_n_days');
  1306. }
  1307. /**
  1308. * Test case for #17560
  1309. */
  1310. public function testAccesToSharedSubFolder() {
  1311. \OC_User::setUserId($this->user1->getUID());
  1312. $view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
  1313. $view->mkdir('files/folder1');
  1314. $fileInfo = $view->getFileInfo('files/folder1');
  1315. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  1316. $fileId = $fileInfo->getId();
  1317. $this->assertTrue(
  1318. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_ALL),
  1319. 'Failed asserting that user 1 successfully shared "test" with user 2.'
  1320. );
  1321. $this->assertTrue(
  1322. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user3->getUID(), \OCP\Constants::PERMISSION_ALL),
  1323. 'Failed asserting that user 1 successfully shared "test" with user 3.'
  1324. );
  1325. $view->mkdir('files/folder1/folder2');
  1326. $fileInfo = $view->getFileInfo('files/folder1/folder2');
  1327. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  1328. $fileId = $fileInfo->getId();
  1329. $this->assertTrue(
  1330. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user4->getUID(), \OCP\Constants::PERMISSION_ALL),
  1331. 'Failed asserting that user 1 successfully shared "test" with user 4.'
  1332. );
  1333. $res = \OCP\Share::getItemShared(
  1334. 'folder',
  1335. $fileId,
  1336. \OCP\Share::FORMAT_NONE,
  1337. null,
  1338. true
  1339. );
  1340. $this->assertCount(3, $res);
  1341. $this->assertTrue(
  1342. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user5->getUID(), \OCP\Constants::PERMISSION_ALL),
  1343. 'Failed asserting that user 1 successfully shared "test" with user 5.'
  1344. );
  1345. $res = \OCP\Share::getItemShared(
  1346. 'folder',
  1347. $fileId,
  1348. \OCP\Share::FORMAT_NONE,
  1349. null,
  1350. true
  1351. );
  1352. $this->assertCount(4, $res);
  1353. }
  1354. public function testShareWithSelfError() {
  1355. \OC_User::setUserId($this->user1->getUID());
  1356. $view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
  1357. $view->mkdir('files/folder1');
  1358. $fileInfo = $view->getFileInfo('files/folder1');
  1359. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  1360. $fileId = $fileInfo->getId();
  1361. try {
  1362. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user1->getUID(), \OCP\Constants::PERMISSION_ALL);
  1363. $this->fail();
  1364. } catch (\Exception $e) {
  1365. $this->assertEquals('Sharing /folder1 failed, because you can not share with yourself', $e->getMessage());
  1366. }
  1367. }
  1368. public function testShareWithOwnerError() {
  1369. \OC_User::setUserId($this->user1->getUID());
  1370. $view = new \OC\Files\View('/' . $this->user1->getUID() . '/');
  1371. $view->mkdir('files/folder1');
  1372. $fileInfo = $view->getFileInfo('files/folder1');
  1373. $this->assertInstanceOf('\OC\Files\FileInfo', $fileInfo);
  1374. $fileId = $fileInfo->getId();
  1375. $this->assertTrue(
  1376. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user2->getUID(), \OCP\Constants::PERMISSION_ALL),
  1377. 'Failed asserting that user 1 successfully shared "test" with user 2.'
  1378. );
  1379. \OC_User::setUserId($this->user2->getUID());
  1380. try {
  1381. \OCP\Share::shareItem('folder', $fileId, \OCP\Share::SHARE_TYPE_USER, $this->user1->getUID(), \OCP\Constants::PERMISSION_ALL);
  1382. $this->fail();
  1383. } catch (\Exception $e) {
  1384. $this->assertEquals('Sharing failed, because the user ' . $this->user1->getUID() . ' is the original sharer', $e->getMessage());
  1385. }
  1386. }
  1387. /**
  1388. * @expectedException \OC\User\NoUserException
  1389. * @expectedExceptionMessage Backends provided no user object
  1390. */
  1391. public function testGetUsersSharingFileWithException() {
  1392. $userManager = $this->createMock(IUserManager::class);
  1393. $logger = $this->createMock(ILogger::class);
  1394. $userManager
  1395. ->expects($this->once())
  1396. ->method('get')
  1397. ->with('test')
  1398. ->willReturn(null);
  1399. $logger
  1400. ->expects($this->once())
  1401. ->method('error')
  1402. ->with(
  1403. 'Backends provided no user object for test',
  1404. [
  1405. 'app' => 'files',
  1406. ]
  1407. );
  1408. Share::getUsersSharingFile('/my/file/path', 'test', $userManager, $logger);
  1409. }
  1410. }
  1411. class DummyShareClass extends \OC\Share\Share {
  1412. public static function groupItemsTest($items) {
  1413. return parent::groupItems($items, 'test');
  1414. }
  1415. }
  1416. class DummyHookListener {
  1417. static $shareType = null;
  1418. public static function listen($params) {
  1419. self::$shareType = $params['shareType'];
  1420. }
  1421. }