CardDavBackendTest.php 29 KB

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