CardDavBackendTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arne Hamann <kontakt+github@arne.email>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Björn Schießle <bjoern@schiessle.org>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Georg Ehrke <oc.list@georgehrke.com>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\DAV\Tests\unit\CardDAV;
  34. use OCA\DAV\CalDAV\Proxy\ProxyMapper;
  35. use OCA\DAV\CardDAV\AddressBook;
  36. use OCA\DAV\CardDAV\CardDavBackend;
  37. use OCA\DAV\Connector\Sabre\Principal;
  38. use OCP\App\IAppManager;
  39. use OCP\DB\QueryBuilder\IQueryBuilder;
  40. use OCP\IConfig;
  41. use OCP\IDBConnection;
  42. use OCP\IGroupManager;
  43. use OCP\IL10N;
  44. use OCP\IUserManager;
  45. use OCP\IUserSession;
  46. use OCP\Share\IManager as ShareManager;
  47. use Sabre\DAV\Exception\BadRequest;
  48. use Sabre\DAV\PropPatch;
  49. use Sabre\VObject\Component\VCard;
  50. use Sabre\VObject\Property\Text;
  51. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  52. use Symfony\Component\EventDispatcher\GenericEvent;
  53. use Test\TestCase;
  54. /**
  55. * Class CardDavBackendTest
  56. *
  57. * @group DB
  58. *
  59. * @package OCA\DAV\Tests\unit\CardDAV
  60. */
  61. class CardDavBackendTest extends TestCase {
  62. /** @var CardDavBackend */
  63. private $backend;
  64. /** @var Principal | \PHPUnit_Framework_MockObject_MockObject */
  65. private $principal;
  66. /** @var IUserManager|\PHPUnit_Framework_MockObject_MockObject */
  67. private $userManager;
  68. /** @var IGroupManager|\PHPUnit_Framework_MockObject_MockObject */
  69. private $groupManager;
  70. /** @var EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject */
  71. private $dispatcher;
  72. /** @var IDBConnection */
  73. private $db;
  74. /** @var string */
  75. private $dbCardsTable = 'cards';
  76. /** @var string */
  77. private $dbCardsPropertiesTable = 'cards_properties';
  78. public const UNIT_TEST_USER = 'principals/users/carddav-unit-test';
  79. public const UNIT_TEST_USER1 = 'principals/users/carddav-unit-test1';
  80. public const UNIT_TEST_GROUP = 'principals/groups/carddav-unit-test-group';
  81. private $vcardTest0 = 'BEGIN:VCARD'.PHP_EOL.
  82. 'VERSION:3.0'.PHP_EOL.
  83. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  84. 'UID:Test'.PHP_EOL.
  85. 'FN:Test'.PHP_EOL.
  86. 'N:Test;;;;'.PHP_EOL.
  87. 'END:VCARD';
  88. private $vcardTest1 = 'BEGIN:VCARD'.PHP_EOL.
  89. 'VERSION:3.0'.PHP_EOL.
  90. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  91. 'UID:Test2'.PHP_EOL.
  92. 'FN:Test2'.PHP_EOL.
  93. 'N:Test2;;;;'.PHP_EOL.
  94. 'END:VCARD';
  95. private $vcardTest2 = 'BEGIN:VCARD'.PHP_EOL.
  96. 'VERSION:3.0'.PHP_EOL.
  97. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  98. 'UID:Test3'.PHP_EOL.
  99. 'FN:Test3'.PHP_EOL.
  100. 'N:Test3;;;;'.PHP_EOL.
  101. 'END:VCARD';
  102. private $vcardTestNoUID = 'BEGIN:VCARD'.PHP_EOL.
  103. 'VERSION:3.0'.PHP_EOL.
  104. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  105. 'FN:TestNoUID'.PHP_EOL.
  106. 'N:TestNoUID;;;;'.PHP_EOL.
  107. 'END:VCARD';
  108. protected function setUp(): void {
  109. parent::setUp();
  110. $this->userManager = $this->createMock(IUserManager::class);
  111. $this->groupManager = $this->createMock(IGroupManager::class);
  112. $this->principal = $this->getMockBuilder(Principal::class)
  113. ->setConstructorArgs([
  114. $this->userManager,
  115. $this->groupManager,
  116. $this->createMock(ShareManager::class),
  117. $this->createMock(IUserSession::class),
  118. $this->createMock(IAppManager::class),
  119. $this->createMock(ProxyMapper::class),
  120. $this->createMock(IConfig::class),
  121. ])
  122. ->setMethods(['getPrincipalByPath', 'getGroupMembership'])
  123. ->getMock();
  124. $this->principal->method('getPrincipalByPath')
  125. ->willReturn([
  126. 'uri' => 'principals/best-friend',
  127. '{DAV:}displayname' => 'User\'s displayname',
  128. ]);
  129. $this->principal->method('getGroupMembership')
  130. ->withAnyParameters()
  131. ->willReturn([self::UNIT_TEST_GROUP]);
  132. $this->dispatcher = $this->createMock(EventDispatcherInterface::class);
  133. $this->db = \OC::$server->getDatabaseConnection();
  134. $this->backend = new CardDavBackend($this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher);
  135. // start every test with a empty cards_properties and cards table
  136. $query = $this->db->getQueryBuilder();
  137. $query->delete('cards_properties')->execute();
  138. $query = $this->db->getQueryBuilder();
  139. $query->delete('cards')->execute();
  140. $this->tearDown();
  141. }
  142. protected function tearDown(): void {
  143. parent::tearDown();
  144. if (is_null($this->backend)) {
  145. return;
  146. }
  147. $this->principal->method('getGroupMembership')
  148. ->withAnyParameters()
  149. ->willReturn([self::UNIT_TEST_GROUP]);
  150. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  151. foreach ($books as $book) {
  152. $this->backend->deleteAddressBook($book['id']);
  153. }
  154. }
  155. public function testAddressBookOperations() {
  156. // create a new address book
  157. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  158. $this->assertEquals(1, $this->backend->getAddressBooksForUserCount(self::UNIT_TEST_USER));
  159. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  160. $this->assertEquals(1, count($books));
  161. $this->assertEquals('Example', $books[0]['{DAV:}displayname']);
  162. $this->assertEquals('User\'s displayname', $books[0]['{http://nextcloud.com/ns}owner-displayname']);
  163. // update it's display name
  164. $patch = new PropPatch([
  165. '{DAV:}displayname' => 'Unit test',
  166. '{urn:ietf:params:xml:ns:carddav}addressbook-description' => 'Addressbook used for unit testing'
  167. ]);
  168. $this->backend->updateAddressBook($books[0]['id'], $patch);
  169. $patch->commit();
  170. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  171. $this->assertEquals(1, count($books));
  172. $this->assertEquals('Unit test', $books[0]['{DAV:}displayname']);
  173. $this->assertEquals('Addressbook used for unit testing', $books[0]['{urn:ietf:params:xml:ns:carddav}addressbook-description']);
  174. // delete the address book
  175. $this->backend->deleteAddressBook($books[0]['id']);
  176. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  177. $this->assertEquals(0, count($books));
  178. }
  179. public function testAddressBookSharing() {
  180. $this->userManager->expects($this->any())
  181. ->method('userExists')
  182. ->willReturn(true);
  183. $this->groupManager->expects($this->any())
  184. ->method('groupExists')
  185. ->willReturn(true);
  186. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  187. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  188. $this->assertEquals(1, count($books));
  189. $l = $this->createMock(IL10N::class);
  190. $addressBook = new AddressBook($this->backend, $books[0], $l);
  191. $this->backend->updateShares($addressBook, [
  192. [
  193. 'href' => 'principal:' . self::UNIT_TEST_USER1,
  194. ],
  195. [
  196. 'href' => 'principal:' . self::UNIT_TEST_GROUP,
  197. ]
  198. ], []);
  199. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1);
  200. $this->assertEquals(1, count($books));
  201. // delete the address book
  202. $this->backend->deleteAddressBook($books[0]['id']);
  203. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  204. $this->assertEquals(0, count($books));
  205. }
  206. public function testCardOperations() {
  207. /** @var CardDavBackend | \PHPUnit_Framework_MockObject_MockObject $backend */
  208. $backend = $this->getMockBuilder(CardDavBackend::class)
  209. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  210. ->setMethods(['updateProperties', 'purgeProperties'])->getMock();
  211. // create a new address book
  212. $backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  213. $books = $backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  214. $this->assertEquals(1, count($books));
  215. $bookId = $books[0]['id'];
  216. $uri = $this->getUniqueID('card');
  217. // updateProperties is expected twice, once for createCard and once for updateCard
  218. $backend->expects($this->at(0))->method('updateProperties')->with($bookId, $uri, $this->vcardTest0);
  219. $backend->expects($this->at(1))->method('updateProperties')->with($bookId, $uri, $this->vcardTest0);
  220. // Expect event
  221. $this->dispatcher->expects($this->at(0))
  222. ->method('dispatch')
  223. ->with('\OCA\DAV\CardDAV\CardDavBackend::createCard', $this->callback(function (GenericEvent $e) use ($bookId, $uri) {
  224. return $e->getArgument('addressBookId') === $bookId &&
  225. $e->getArgument('cardUri') === $uri &&
  226. $e->getArgument('cardData') === $this->vcardTest0;
  227. }));
  228. // create a card
  229. $backend->createCard($bookId, $uri, $this->vcardTest0);
  230. // get all the cards
  231. $cards = $backend->getCards($bookId);
  232. $this->assertEquals(1, count($cards));
  233. $this->assertEquals($this->vcardTest0, $cards[0]['carddata']);
  234. // get the cards
  235. $card = $backend->getCard($bookId, $uri);
  236. $this->assertNotNull($card);
  237. $this->assertArrayHasKey('id', $card);
  238. $this->assertArrayHasKey('uri', $card);
  239. $this->assertArrayHasKey('lastmodified', $card);
  240. $this->assertArrayHasKey('etag', $card);
  241. $this->assertArrayHasKey('size', $card);
  242. $this->assertEquals($this->vcardTest0, $card['carddata']);
  243. // Expect event
  244. $this->dispatcher->expects($this->at(0))
  245. ->method('dispatch')
  246. ->with('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $this->callback(function (GenericEvent $e) use ($bookId, $uri) {
  247. return $e->getArgument('addressBookId') === $bookId &&
  248. $e->getArgument('cardUri') === $uri &&
  249. $e->getArgument('cardData') === $this->vcardTest0;
  250. }));
  251. // update the card
  252. $backend->updateCard($bookId, $uri, $this->vcardTest0);
  253. $card = $backend->getCard($bookId, $uri);
  254. $this->assertEquals($this->vcardTest0, $card['carddata']);
  255. // Expect event
  256. $this->dispatcher->expects($this->at(0))
  257. ->method('dispatch')
  258. ->with('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', $this->callback(function (GenericEvent $e) use ($bookId, $uri) {
  259. return $e->getArgument('addressBookId') === $bookId &&
  260. $e->getArgument('cardUri') === $uri;
  261. }));
  262. // delete the card
  263. $backend->expects($this->once())->method('purgeProperties')->with($bookId, $card['id']);
  264. $backend->deleteCard($bookId, $uri);
  265. $cards = $backend->getCards($bookId);
  266. $this->assertEquals(0, count($cards));
  267. }
  268. public function testMultiCard() {
  269. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  270. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  271. ->setMethods(['updateProperties'])->getMock();
  272. // create a new address book
  273. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  274. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  275. $this->assertEquals(1, count($books));
  276. $bookId = $books[0]['id'];
  277. // create a card
  278. $uri0 = self::getUniqueID('card');
  279. $this->backend->createCard($bookId, $uri0, $this->vcardTest0);
  280. $uri1 = self::getUniqueID('card');
  281. $this->backend->createCard($bookId, $uri1, $this->vcardTest1);
  282. $uri2 = self::getUniqueID('card');
  283. $this->backend->createCard($bookId, $uri2, $this->vcardTest2);
  284. // get all the cards
  285. $cards = $this->backend->getCards($bookId);
  286. $this->assertEquals(3, count($cards));
  287. usort($cards, function ($a, $b) {
  288. return $a['id'] < $b['id'] ? -1 : 1;
  289. });
  290. $this->assertEquals($this->vcardTest0, $cards[0]['carddata']);
  291. $this->assertEquals($this->vcardTest1, $cards[1]['carddata']);
  292. $this->assertEquals($this->vcardTest2, $cards[2]['carddata']);
  293. // get the cards 1 & 2 (not 0)
  294. $cards = $this->backend->getMultipleCards($bookId, [$uri1, $uri2]);
  295. $this->assertEquals(2, count($cards));
  296. usort($cards, function ($a, $b) {
  297. return $a['id'] < $b['id'] ? -1 : 1;
  298. });
  299. foreach ($cards as $index => $card) {
  300. $this->assertArrayHasKey('id', $card);
  301. $this->assertArrayHasKey('uri', $card);
  302. $this->assertArrayHasKey('lastmodified', $card);
  303. $this->assertArrayHasKey('etag', $card);
  304. $this->assertArrayHasKey('size', $card);
  305. $this->assertEquals($this->{ 'vcardTest'.($index+1) }, $card['carddata']);
  306. }
  307. // delete the card
  308. $this->backend->deleteCard($bookId, $uri0);
  309. $this->backend->deleteCard($bookId, $uri1);
  310. $this->backend->deleteCard($bookId, $uri2);
  311. $cards = $this->backend->getCards($bookId);
  312. $this->assertEquals(0, count($cards));
  313. }
  314. public function testMultipleUIDOnDifferentAddressbooks() {
  315. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  316. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  317. ->setMethods(['updateProperties'])->getMock();
  318. // create 2 new address books
  319. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  320. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example2', []);
  321. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  322. $this->assertEquals(2, count($books));
  323. $bookId0 = $books[0]['id'];
  324. $bookId1 = $books[1]['id'];
  325. // create a card
  326. $uri0 = $this->getUniqueID('card');
  327. $this->backend->createCard($bookId0, $uri0, $this->vcardTest0);
  328. // create another card with same uid but in second address book
  329. $uri1 = $this->getUniqueID('card');
  330. $this->backend->createCard($bookId1, $uri1, $this->vcardTest0);
  331. }
  332. public function testMultipleUIDDenied() {
  333. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  334. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  335. ->setMethods(['updateProperties'])->getMock();
  336. // create a new address book
  337. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  338. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  339. $this->assertEquals(1, count($books));
  340. $bookId = $books[0]['id'];
  341. // create a card
  342. $uri0 = $this->getUniqueID('card');
  343. $this->backend->createCard($bookId, $uri0, $this->vcardTest0);
  344. // create another card with same uid
  345. $uri1 = $this->getUniqueID('card');
  346. $this->expectException(BadRequest::class);
  347. $test = $this->backend->createCard($bookId, $uri1, $this->vcardTest0);
  348. }
  349. public function testNoValidUID() {
  350. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  351. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  352. ->setMethods(['updateProperties'])->getMock();
  353. // create a new address book
  354. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  355. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  356. $this->assertEquals(1, count($books));
  357. $bookId = $books[0]['id'];
  358. // create a card without uid
  359. $uri1 = $this->getUniqueID('card');
  360. $this->expectException(BadRequest::class);
  361. $test = $this->backend->createCard($bookId, $uri1, $this->vcardTestNoUID);
  362. }
  363. public function testDeleteWithoutCard() {
  364. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  365. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  366. ->setMethods([
  367. 'getCardId',
  368. 'addChange',
  369. 'purgeProperties',
  370. 'updateProperties',
  371. ])
  372. ->getMock();
  373. // create a new address book
  374. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  375. $books = $this->backend->getUsersOwnAddressBooks(self::UNIT_TEST_USER);
  376. $this->assertEquals(1, count($books));
  377. $bookId = $books[0]['id'];
  378. $uri = $this->getUniqueID('card');
  379. // create a new address book
  380. $this->backend->expects($this->once())
  381. ->method('getCardId')
  382. ->with($bookId, $uri)
  383. ->willThrowException(new \InvalidArgumentException());
  384. $this->backend->expects($this->exactly(2))
  385. ->method('addChange')
  386. ->withConsecutive(
  387. [$bookId, $uri, 1],
  388. [$bookId, $uri, 3]
  389. );
  390. $this->backend->expects($this->never())
  391. ->method('purgeProperties');
  392. // create a card
  393. $this->backend->createCard($bookId, $uri, $this->vcardTest0);
  394. // delete the card
  395. $this->assertTrue($this->backend->deleteCard($bookId, $uri));
  396. }
  397. public function testSyncSupport() {
  398. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  399. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  400. ->setMethods(['updateProperties'])->getMock();
  401. // create a new address book
  402. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  403. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  404. $this->assertEquals(1, count($books));
  405. $bookId = $books[0]['id'];
  406. // fist call without synctoken
  407. $changes = $this->backend->getChangesForAddressBook($bookId, '', 1);
  408. $syncToken = $changes['syncToken'];
  409. // add a change
  410. $uri0 = $this->getUniqueID('card');
  411. $this->backend->createCard($bookId, $uri0, $this->vcardTest0);
  412. // look for changes
  413. $changes = $this->backend->getChangesForAddressBook($bookId, $syncToken, 1);
  414. $this->assertEquals($uri0, $changes['added'][0]);
  415. }
  416. public function testSharing() {
  417. $this->userManager->expects($this->any())
  418. ->method('userExists')
  419. ->willReturn(true);
  420. $this->groupManager->expects($this->any())
  421. ->method('groupExists')
  422. ->willReturn(true);
  423. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  424. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  425. $this->assertEquals(1, count($books));
  426. $l = $this->createMock(IL10N::class);
  427. $exampleBook = new AddressBook($this->backend, $books[0], $l);
  428. $this->backend->updateShares($exampleBook, [['href' => 'principal:' . self::UNIT_TEST_USER1]], []);
  429. $shares = $this->backend->getShares($exampleBook->getResourceId());
  430. $this->assertEquals(1, count($shares));
  431. // adding the same sharee again has no effect
  432. $this->backend->updateShares($exampleBook, [['href' => 'principal:' . self::UNIT_TEST_USER1]], []);
  433. $shares = $this->backend->getShares($exampleBook->getResourceId());
  434. $this->assertEquals(1, count($shares));
  435. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1);
  436. $this->assertEquals(1, count($books));
  437. $this->backend->updateShares($exampleBook, [], ['principal:' . self::UNIT_TEST_USER1]);
  438. $shares = $this->backend->getShares($exampleBook->getResourceId());
  439. $this->assertEquals(0, count($shares));
  440. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1);
  441. $this->assertEquals(0, count($books));
  442. }
  443. public function testUpdateProperties() {
  444. $bookId = 42;
  445. $cardUri = 'card-uri';
  446. $cardId = 2;
  447. $backend = $this->getMockBuilder(CardDavBackend::class)
  448. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher])
  449. ->setMethods(['getCardId'])->getMock();
  450. $backend->expects($this->any())->method('getCardId')->willReturn($cardId);
  451. // add properties for new vCard
  452. $vCard = new VCard();
  453. $vCard->UID = $cardUri;
  454. $vCard->FN = 'John Doe';
  455. $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]);
  456. $query = $this->db->getQueryBuilder();
  457. $result = $query->select('*')->from('cards_properties')->execute()->fetchAll();
  458. $this->assertSame(2, count($result));
  459. $this->assertSame('UID', $result[0]['name']);
  460. $this->assertSame($cardUri, $result[0]['value']);
  461. $this->assertSame($bookId, (int)$result[0]['addressbookid']);
  462. $this->assertSame($cardId, (int)$result[0]['cardid']);
  463. $this->assertSame('FN', $result[1]['name']);
  464. $this->assertSame('John Doe', $result[1]['value']);
  465. $this->assertSame($bookId, (int)$result[1]['addressbookid']);
  466. $this->assertSame($cardId, (int)$result[1]['cardid']);
  467. // update properties for existing vCard
  468. $vCard = new VCard();
  469. $vCard->UID = $cardUri;
  470. $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]);
  471. $query = $this->db->getQueryBuilder();
  472. $result = $query->select('*')->from('cards_properties')->execute()->fetchAll();
  473. $this->assertSame(1, count($result));
  474. $this->assertSame('UID', $result[0]['name']);
  475. $this->assertSame($cardUri, $result[0]['value']);
  476. $this->assertSame($bookId, (int)$result[0]['addressbookid']);
  477. $this->assertSame($cardId, (int)$result[0]['cardid']);
  478. }
  479. public function testPurgeProperties() {
  480. $query = $this->db->getQueryBuilder();
  481. $query->insert('cards_properties')
  482. ->values(
  483. [
  484. 'addressbookid' => $query->createNamedParameter(1),
  485. 'cardid' => $query->createNamedParameter(1),
  486. 'name' => $query->createNamedParameter('name1'),
  487. 'value' => $query->createNamedParameter('value1'),
  488. 'preferred' => $query->createNamedParameter(0)
  489. ]
  490. );
  491. $query->execute();
  492. $query = $this->db->getQueryBuilder();
  493. $query->insert('cards_properties')
  494. ->values(
  495. [
  496. 'addressbookid' => $query->createNamedParameter(1),
  497. 'cardid' => $query->createNamedParameter(2),
  498. 'name' => $query->createNamedParameter('name2'),
  499. 'value' => $query->createNamedParameter('value2'),
  500. 'preferred' => $query->createNamedParameter(0)
  501. ]
  502. );
  503. $query->execute();
  504. $this->invokePrivate($this->backend, 'purgeProperties', [1, 1]);
  505. $query = $this->db->getQueryBuilder();
  506. $result = $query->select('*')->from('cards_properties')->execute()->fetchAll();
  507. $this->assertSame(1, count($result));
  508. $this->assertSame(1 ,(int)$result[0]['addressbookid']);
  509. $this->assertSame(2 ,(int)$result[0]['cardid']);
  510. }
  511. public function testGetCardId() {
  512. $query = $this->db->getQueryBuilder();
  513. $query->insert('cards')
  514. ->values(
  515. [
  516. 'addressbookid' => $query->createNamedParameter(1),
  517. 'carddata' => $query->createNamedParameter(''),
  518. 'uri' => $query->createNamedParameter('uri'),
  519. 'lastmodified' => $query->createNamedParameter(4738743),
  520. 'etag' => $query->createNamedParameter('etag'),
  521. 'size' => $query->createNamedParameter(120)
  522. ]
  523. );
  524. $query->execute();
  525. $id = $query->getLastInsertId();
  526. $this->assertSame($id,
  527. $this->invokePrivate($this->backend, 'getCardId', [1, 'uri']));
  528. }
  529. public function testGetCardIdFailed() {
  530. $this->expectException(\InvalidArgumentException::class);
  531. $this->invokePrivate($this->backend, 'getCardId', [1, 'uri']);
  532. }
  533. /**
  534. * @dataProvider dataTestSearch
  535. *
  536. * @param string $pattern
  537. * @param array $properties
  538. * @param array $options
  539. * @param array $expected
  540. */
  541. public function testSearch($pattern, $properties, $options, $expected) {
  542. /** @var VCard $vCards */
  543. $vCards = [];
  544. $vCards[0] = new VCard();
  545. $vCards[0]->add(new Text($vCards[0], 'UID', 'uid'));
  546. $vCards[0]->add(new Text($vCards[0], 'FN', 'John Doe'));
  547. $vCards[0]->add(new Text($vCards[0], 'CLOUD', 'john@nextcloud.com'));
  548. $vCards[1] = new VCard();
  549. $vCards[1]->add(new Text($vCards[1], 'UID', 'uid'));
  550. $vCards[1]->add(new Text($vCards[1], 'FN', 'John M. Doe'));
  551. $vCards[2] = new VCard();
  552. $vCards[2]->add(new Text($vCards[2], 'UID', 'uid'));
  553. $vCards[2]->add(new Text($vCards[2], 'FN', 'find without options'));
  554. $vCards[2]->add(new Text($vCards[2], 'CLOUD', 'peter_pan@nextcloud.com'));
  555. $vCardIds = [];
  556. $query = $this->db->getQueryBuilder();
  557. for ($i=0; $i < 3; $i++) {
  558. $query->insert($this->dbCardsTable)
  559. ->values(
  560. [
  561. 'addressbookid' => $query->createNamedParameter(0),
  562. 'carddata' => $query->createNamedParameter($vCards[$i]->serialize(), IQueryBuilder::PARAM_LOB),
  563. 'uri' => $query->createNamedParameter('uri' . $i),
  564. 'lastmodified' => $query->createNamedParameter(time()),
  565. 'etag' => $query->createNamedParameter('etag' . $i),
  566. 'size' => $query->createNamedParameter(120),
  567. ]
  568. );
  569. $query->execute();
  570. $vCardIds[] = $query->getLastInsertId();
  571. }
  572. $query->insert($this->dbCardsPropertiesTable)
  573. ->values(
  574. [
  575. 'addressbookid' => $query->createNamedParameter(0),
  576. 'cardid' => $query->createNamedParameter($vCardIds[0]),
  577. 'name' => $query->createNamedParameter('FN'),
  578. 'value' => $query->createNamedParameter('John Doe'),
  579. 'preferred' => $query->createNamedParameter(0)
  580. ]
  581. );
  582. $query->execute();
  583. $query->insert($this->dbCardsPropertiesTable)
  584. ->values(
  585. [
  586. 'addressbookid' => $query->createNamedParameter(0),
  587. 'cardid' => $query->createNamedParameter($vCardIds[0]),
  588. 'name' => $query->createNamedParameter('CLOUD'),
  589. 'value' => $query->createNamedParameter('John@nextcloud.com'),
  590. 'preferred' => $query->createNamedParameter(0)
  591. ]
  592. );
  593. $query->execute();
  594. $query->insert($this->dbCardsPropertiesTable)
  595. ->values(
  596. [
  597. 'addressbookid' => $query->createNamedParameter(0),
  598. 'cardid' => $query->createNamedParameter($vCardIds[1]),
  599. 'name' => $query->createNamedParameter('FN'),
  600. 'value' => $query->createNamedParameter('John M. Doe'),
  601. 'preferred' => $query->createNamedParameter(0)
  602. ]
  603. );
  604. $query->execute();
  605. $query->insert($this->dbCardsPropertiesTable)
  606. ->values(
  607. [
  608. 'addressbookid' => $query->createNamedParameter(0),
  609. 'cardid' => $query->createNamedParameter($vCardIds[2]),
  610. 'name' => $query->createNamedParameter('FN'),
  611. 'value' => $query->createNamedParameter('find without options'),
  612. 'preferred' => $query->createNamedParameter(0)
  613. ]
  614. );
  615. $query->execute();
  616. $query->insert($this->dbCardsPropertiesTable)
  617. ->values(
  618. [
  619. 'addressbookid' => $query->createNamedParameter(0),
  620. 'cardid' => $query->createNamedParameter($vCardIds[2]),
  621. 'name' => $query->createNamedParameter('CLOUD'),
  622. 'value' => $query->createNamedParameter('peter_pan@nextcloud.com'),
  623. 'preferred' => $query->createNamedParameter(0)
  624. ]
  625. );
  626. $query->execute();
  627. $result = $this->backend->search(0, $pattern, $properties, $options);
  628. // check result
  629. $this->assertSame(count($expected), count($result));
  630. $found = [];
  631. foreach ($result as $r) {
  632. foreach ($expected as $exp) {
  633. if ($r['uri'] === $exp[0] && strpos($r['carddata'], $exp[1]) > 0) {
  634. $found[$exp[1]] = true;
  635. break;
  636. }
  637. }
  638. }
  639. $this->assertSame(count($expected), count($found));
  640. }
  641. public function dataTestSearch() {
  642. return [
  643. ['John', ['FN'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  644. ['M. Doe', ['FN'], [], [['uri1', 'John M. Doe']]],
  645. ['Do', ['FN'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  646. 'check if duplicates are handled correctly' => ['John', ['FN', 'CLOUD'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  647. 'case insensitive' => ['john', ['FN'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  648. 'find "_" escaped' => ['_', ['CLOUD'], [], [['uri2', 'find without options']]],
  649. 'find not empty ClOUD' => ['%_%', ['CLOUD'], ['escape_like_param'=>false], [['uri0', 'John Doe'], ['uri2', 'find without options']]],
  650. ];
  651. }
  652. public function testGetCardUri() {
  653. $query = $this->db->getQueryBuilder();
  654. $query->insert($this->dbCardsTable)
  655. ->values(
  656. [
  657. 'addressbookid' => $query->createNamedParameter(1),
  658. 'carddata' => $query->createNamedParameter('carddata', IQueryBuilder::PARAM_LOB),
  659. 'uri' => $query->createNamedParameter('uri'),
  660. 'lastmodified' => $query->createNamedParameter(5489543),
  661. 'etag' => $query->createNamedParameter('etag'),
  662. 'size' => $query->createNamedParameter(120),
  663. ]
  664. );
  665. $query->execute();
  666. $id = $query->getLastInsertId();
  667. $this->assertSame('uri', $this->backend->getCardUri($id));
  668. }
  669. public function testGetCardUriFailed() {
  670. $this->expectException(\InvalidArgumentException::class);
  671. $this->backend->getCardUri(1);
  672. }
  673. public function testGetContact() {
  674. $query = $this->db->getQueryBuilder();
  675. for ($i=0; $i<2; $i++) {
  676. $query->insert($this->dbCardsTable)
  677. ->values(
  678. [
  679. 'addressbookid' => $query->createNamedParameter($i),
  680. 'carddata' => $query->createNamedParameter('carddata' . $i, IQueryBuilder::PARAM_LOB),
  681. 'uri' => $query->createNamedParameter('uri' . $i),
  682. 'lastmodified' => $query->createNamedParameter(5489543),
  683. 'etag' => $query->createNamedParameter('etag' . $i),
  684. 'size' => $query->createNamedParameter(120),
  685. ]
  686. );
  687. $query->execute();
  688. }
  689. $result = $this->backend->getContact(0, 'uri0');
  690. $this->assertSame(8, count($result));
  691. $this->assertSame(0, (int)$result['addressbookid']);
  692. $this->assertSame('uri0', $result['uri']);
  693. $this->assertSame(5489543, (int)$result['lastmodified']);
  694. $this->assertSame('"etag0"', $result['etag']);
  695. $this->assertSame(120, (int)$result['size']);
  696. // this shouldn't return any result because 'uri1' is in address book 1
  697. // see https://github.com/nextcloud/server/issues/229
  698. $result = $this->backend->getContact(0, 'uri1');
  699. $this->assertEmpty($result);
  700. }
  701. public function testGetContactFail() {
  702. $this->assertEmpty($this->backend->getContact(0, 'uri'));
  703. }
  704. public function testCollectCardProperties() {
  705. $query = $this->db->getQueryBuilder();
  706. $query->insert($this->dbCardsPropertiesTable)
  707. ->values(
  708. [
  709. 'addressbookid' => $query->createNamedParameter(666),
  710. 'cardid' => $query->createNamedParameter(777),
  711. 'name' => $query->createNamedParameter('FN'),
  712. 'value' => $query->createNamedParameter('John Doe'),
  713. 'preferred' => $query->createNamedParameter(0)
  714. ]
  715. )
  716. ->execute();
  717. $result = $this->backend->collectCardProperties(666, 'FN');
  718. $this->assertEquals(['John Doe'], $result);
  719. }
  720. }