CardDavBackendTest.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\DAV\Tests\unit\CardDAV;
  8. use OC\KnownUser\KnownUserService;
  9. use OCA\DAV\CalDAV\Proxy\ProxyMapper;
  10. use OCA\DAV\CardDAV\AddressBook;
  11. use OCA\DAV\CardDAV\CardDavBackend;
  12. use OCA\DAV\CardDAV\Sharing\Backend;
  13. use OCA\DAV\CardDAV\Sharing\Service;
  14. use OCA\DAV\Connector\Sabre\Principal;
  15. use OCA\DAV\DAV\Sharing\SharingMapper;
  16. use OCP\Accounts\IAccountManager;
  17. use OCP\App\IAppManager;
  18. use OCP\DB\QueryBuilder\IQueryBuilder;
  19. use OCP\EventDispatcher\IEventDispatcher;
  20. use OCP\ICacheFactory;
  21. use OCP\IConfig;
  22. use OCP\IDBConnection;
  23. use OCP\IGroupManager;
  24. use OCP\IL10N;
  25. use OCP\IUserManager;
  26. use OCP\IUserSession;
  27. use OCP\L10N\IFactory;
  28. use OCP\Share\IManager as ShareManager;
  29. use Psr\Log\LoggerInterface;
  30. use Sabre\DAV\Exception\BadRequest;
  31. use Sabre\DAV\PropPatch;
  32. use Sabre\VObject\Component\VCard;
  33. use Sabre\VObject\Property\Text;
  34. use Test\TestCase;
  35. use function time;
  36. /**
  37. * Class CardDavBackendTest
  38. *
  39. * @group DB
  40. *
  41. * @package OCA\DAV\Tests\unit\CardDAV
  42. */
  43. class CardDavBackendTest extends TestCase {
  44. /** @var CardDavBackend */
  45. private $backend;
  46. /** @var Principal | \PHPUnit\Framework\MockObject\MockObject */
  47. private $principal;
  48. /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */
  49. private $userManager;
  50. /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */
  51. private $groupManager;
  52. /** @var IEventDispatcher|MockObject */
  53. private $dispatcher;
  54. private Backend $sharingBackend;
  55. /** @var IDBConnection */
  56. private $db;
  57. /** @var string */
  58. private $dbCardsTable = 'cards';
  59. /** @var string */
  60. private $dbCardsPropertiesTable = 'cards_properties';
  61. public const UNIT_TEST_USER = 'principals/users/carddav-unit-test';
  62. public const UNIT_TEST_USER1 = 'principals/users/carddav-unit-test1';
  63. public const UNIT_TEST_GROUP = 'principals/groups/carddav-unit-test-group';
  64. private $vcardTest0 = 'BEGIN:VCARD'.PHP_EOL.
  65. 'VERSION:3.0'.PHP_EOL.
  66. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  67. 'UID:Test'.PHP_EOL.
  68. 'FN:Test'.PHP_EOL.
  69. 'N:Test;;;;'.PHP_EOL.
  70. 'END:VCARD';
  71. private $vcardTest1 = 'BEGIN:VCARD'.PHP_EOL.
  72. 'VERSION:3.0'.PHP_EOL.
  73. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  74. 'UID:Test2'.PHP_EOL.
  75. 'FN:Test2'.PHP_EOL.
  76. 'N:Test2;;;;'.PHP_EOL.
  77. 'END:VCARD';
  78. private $vcardTest2 = 'BEGIN:VCARD'.PHP_EOL.
  79. 'VERSION:3.0'.PHP_EOL.
  80. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  81. 'UID:Test3'.PHP_EOL.
  82. 'FN:Test3'.PHP_EOL.
  83. 'N:Test3;;;;'.PHP_EOL.
  84. 'END:VCARD';
  85. private $vcardTestNoUID = 'BEGIN:VCARD'.PHP_EOL.
  86. 'VERSION:3.0'.PHP_EOL.
  87. 'PRODID:-//Sabre//Sabre VObject 4.1.2//EN'.PHP_EOL.
  88. 'FN:TestNoUID'.PHP_EOL.
  89. 'N:TestNoUID;;;;'.PHP_EOL.
  90. 'END:VCARD';
  91. protected function setUp(): void {
  92. parent::setUp();
  93. $this->userManager = $this->createMock(IUserManager::class);
  94. $this->groupManager = $this->createMock(IGroupManager::class);
  95. $this->principal = $this->getMockBuilder(Principal::class)
  96. ->setConstructorArgs([
  97. $this->userManager,
  98. $this->groupManager,
  99. $this->createMock(IAccountManager::class),
  100. $this->createMock(ShareManager::class),
  101. $this->createMock(IUserSession::class),
  102. $this->createMock(IAppManager::class),
  103. $this->createMock(ProxyMapper::class),
  104. $this->createMock(KnownUserService::class),
  105. $this->createMock(IConfig::class),
  106. $this->createMock(IFactory::class)
  107. ])
  108. ->setMethods(['getPrincipalByPath', 'getGroupMembership', 'findByUri'])
  109. ->getMock();
  110. $this->principal->method('getPrincipalByPath')
  111. ->willReturn([
  112. 'uri' => 'principals/best-friend',
  113. '{DAV:}displayname' => 'User\'s displayname',
  114. ]);
  115. $this->principal->method('getGroupMembership')
  116. ->withAnyParameters()
  117. ->willReturn([self::UNIT_TEST_GROUP]);
  118. $this->dispatcher = $this->createMock(IEventDispatcher::class);
  119. $this->db = \OC::$server->getDatabaseConnection();
  120. $this->sharingBackend = new Backend($this->userManager,
  121. $this->groupManager,
  122. $this->principal,
  123. $this->createMock(ICacheFactory::class),
  124. new Service(new SharingMapper($this->db)),
  125. $this->createMock(LoggerInterface::class)
  126. );
  127. $this->backend = new CardDavBackend($this->db,
  128. $this->principal,
  129. $this->userManager,
  130. $this->dispatcher,
  131. $this->sharingBackend,
  132. );
  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(): void {
  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 its 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(): void {
  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->principal->expects(self::atLeastOnce())
  185. ->method('findByUri')
  186. ->willReturnOnConsecutiveCalls(self::UNIT_TEST_USER1, self::UNIT_TEST_GROUP);
  187. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  188. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  189. $this->assertEquals(1, count($books));
  190. $l = $this->createMock(IL10N::class);
  191. $addressBook = new AddressBook($this->backend, $books[0], $l);
  192. $this->backend->updateShares($addressBook, [
  193. [
  194. 'href' => 'principal:' . self::UNIT_TEST_USER1,
  195. ],
  196. [
  197. 'href' => 'principal:' . self::UNIT_TEST_GROUP,
  198. ]
  199. ], []);
  200. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1);
  201. $this->assertEquals(1, count($books));
  202. // delete the address book
  203. $this->backend->deleteAddressBook($books[0]['id']);
  204. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  205. $this->assertEquals(0, count($books));
  206. }
  207. public function testCardOperations(): void {
  208. /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backend */
  209. $backend = $this->getMockBuilder(CardDavBackend::class)
  210. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  211. ->onlyMethods(['updateProperties', 'purgeProperties'])->getMock();
  212. // create a new address book
  213. $backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  214. $books = $backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  215. $this->assertEquals(1, count($books));
  216. $bookId = $books[0]['id'];
  217. $uri = $this->getUniqueID('card');
  218. // updateProperties is expected twice, once for createCard and once for updateCard
  219. $backend->expects($this->exactly(2))
  220. ->method('updateProperties')
  221. ->withConsecutive(
  222. [$bookId, $uri, $this->vcardTest0],
  223. [$bookId, $uri, $this->vcardTest1],
  224. );
  225. // Expect event
  226. $this->dispatcher
  227. ->expects($this->exactly(3))
  228. ->method('dispatchTyped');
  229. // create a card
  230. $backend->createCard($bookId, $uri, $this->vcardTest0);
  231. // get all the cards
  232. $cards = $backend->getCards($bookId);
  233. $this->assertEquals(1, count($cards));
  234. $this->assertEquals($this->vcardTest0, $cards[0]['carddata']);
  235. // get the cards
  236. $card = $backend->getCard($bookId, $uri);
  237. $this->assertNotNull($card);
  238. $this->assertArrayHasKey('id', $card);
  239. $this->assertArrayHasKey('uri', $card);
  240. $this->assertArrayHasKey('lastmodified', $card);
  241. $this->assertArrayHasKey('etag', $card);
  242. $this->assertArrayHasKey('size', $card);
  243. $this->assertEquals($this->vcardTest0, $card['carddata']);
  244. // update the card
  245. $backend->updateCard($bookId, $uri, $this->vcardTest1);
  246. $card = $backend->getCard($bookId, $uri);
  247. $this->assertEquals($this->vcardTest1, $card['carddata']);
  248. // delete the card
  249. $backend->expects($this->once())->method('purgeProperties')->with($bookId, $card['id']);
  250. $backend->deleteCard($bookId, $uri);
  251. $cards = $backend->getCards($bookId);
  252. $this->assertEquals(0, count($cards));
  253. }
  254. public function testMultiCard(): void {
  255. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  256. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  257. ->setMethods(['updateProperties'])->getMock();
  258. // create a new address book
  259. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  260. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  261. $this->assertEquals(1, count($books));
  262. $bookId = $books[0]['id'];
  263. // create a card
  264. $uri0 = self::getUniqueID('card');
  265. $this->backend->createCard($bookId, $uri0, $this->vcardTest0);
  266. $uri1 = self::getUniqueID('card');
  267. $this->backend->createCard($bookId, $uri1, $this->vcardTest1);
  268. $uri2 = self::getUniqueID('card');
  269. $this->backend->createCard($bookId, $uri2, $this->vcardTest2);
  270. // get all the cards
  271. $cards = $this->backend->getCards($bookId);
  272. $this->assertEquals(3, count($cards));
  273. usort($cards, function ($a, $b) {
  274. return $a['id'] < $b['id'] ? -1 : 1;
  275. });
  276. $this->assertEquals($this->vcardTest0, $cards[0]['carddata']);
  277. $this->assertEquals($this->vcardTest1, $cards[1]['carddata']);
  278. $this->assertEquals($this->vcardTest2, $cards[2]['carddata']);
  279. // get the cards 1 & 2 (not 0)
  280. $cards = $this->backend->getMultipleCards($bookId, [$uri1, $uri2]);
  281. $this->assertEquals(2, count($cards));
  282. usort($cards, function ($a, $b) {
  283. return $a['id'] < $b['id'] ? -1 : 1;
  284. });
  285. foreach ($cards as $index => $card) {
  286. $this->assertArrayHasKey('id', $card);
  287. $this->assertArrayHasKey('uri', $card);
  288. $this->assertArrayHasKey('lastmodified', $card);
  289. $this->assertArrayHasKey('etag', $card);
  290. $this->assertArrayHasKey('size', $card);
  291. $this->assertEquals($this->{ 'vcardTest'.($index + 1) }, $card['carddata']);
  292. }
  293. // delete the card
  294. $this->backend->deleteCard($bookId, $uri0);
  295. $this->backend->deleteCard($bookId, $uri1);
  296. $this->backend->deleteCard($bookId, $uri2);
  297. $cards = $this->backend->getCards($bookId);
  298. $this->assertEquals(0, count($cards));
  299. }
  300. public function testMultipleUIDOnDifferentAddressbooks(): void {
  301. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  302. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  303. ->onlyMethods(['updateProperties'])->getMock();
  304. // create 2 new address books
  305. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  306. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example2', []);
  307. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  308. $this->assertEquals(2, count($books));
  309. $bookId0 = $books[0]['id'];
  310. $bookId1 = $books[1]['id'];
  311. // create a card
  312. $uri0 = $this->getUniqueID('card');
  313. $this->backend->createCard($bookId0, $uri0, $this->vcardTest0);
  314. // create another card with same uid but in second address book
  315. $uri1 = $this->getUniqueID('card');
  316. $this->backend->createCard($bookId1, $uri1, $this->vcardTest0);
  317. }
  318. public function testMultipleUIDDenied(): void {
  319. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  320. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  321. ->setMethods(['updateProperties'])->getMock();
  322. // create a new address book
  323. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  324. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  325. $this->assertEquals(1, count($books));
  326. $bookId = $books[0]['id'];
  327. // create a card
  328. $uri0 = $this->getUniqueID('card');
  329. $this->backend->createCard($bookId, $uri0, $this->vcardTest0);
  330. // create another card with same uid
  331. $uri1 = $this->getUniqueID('card');
  332. $this->expectException(BadRequest::class);
  333. $test = $this->backend->createCard($bookId, $uri1, $this->vcardTest0);
  334. }
  335. public function testNoValidUID(): void {
  336. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  337. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  338. ->setMethods(['updateProperties'])->getMock();
  339. // create a new address book
  340. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  341. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  342. $this->assertEquals(1, count($books));
  343. $bookId = $books[0]['id'];
  344. // create a card without uid
  345. $uri1 = $this->getUniqueID('card');
  346. $this->expectException(BadRequest::class);
  347. $test = $this->backend->createCard($bookId, $uri1, $this->vcardTestNoUID);
  348. }
  349. public function testDeleteWithoutCard(): void {
  350. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  351. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  352. ->onlyMethods([
  353. 'getCardId',
  354. 'addChange',
  355. 'purgeProperties',
  356. 'updateProperties',
  357. ])
  358. ->getMock();
  359. // create a new address book
  360. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  361. $books = $this->backend->getUsersOwnAddressBooks(self::UNIT_TEST_USER);
  362. $this->assertEquals(1, count($books));
  363. $bookId = $books[0]['id'];
  364. $uri = $this->getUniqueID('card');
  365. // create a new address book
  366. $this->backend->expects($this->once())
  367. ->method('getCardId')
  368. ->with($bookId, $uri)
  369. ->willThrowException(new \InvalidArgumentException());
  370. $this->backend->expects($this->exactly(2))
  371. ->method('addChange')
  372. ->withConsecutive(
  373. [$bookId, $uri, 1],
  374. [$bookId, $uri, 3]
  375. );
  376. $this->backend->expects($this->never())
  377. ->method('purgeProperties');
  378. // create a card
  379. $this->backend->createCard($bookId, $uri, $this->vcardTest0);
  380. // delete the card
  381. $this->assertTrue($this->backend->deleteCard($bookId, $uri));
  382. }
  383. public function testSyncSupport(): void {
  384. $this->backend = $this->getMockBuilder(CardDavBackend::class)
  385. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  386. ->setMethods(['updateProperties'])->getMock();
  387. // create a new address book
  388. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  389. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  390. $this->assertEquals(1, count($books));
  391. $bookId = $books[0]['id'];
  392. // fist call without synctoken
  393. $changes = $this->backend->getChangesForAddressBook($bookId, '', 1);
  394. $syncToken = $changes['syncToken'];
  395. // add a change
  396. $uri0 = $this->getUniqueID('card');
  397. $this->backend->createCard($bookId, $uri0, $this->vcardTest0);
  398. // look for changes
  399. $changes = $this->backend->getChangesForAddressBook($bookId, $syncToken, 1);
  400. $this->assertEquals($uri0, $changes['added'][0]);
  401. }
  402. public function testSharing(): void {
  403. $this->userManager->expects($this->any())
  404. ->method('userExists')
  405. ->willReturn(true);
  406. $this->groupManager->expects($this->any())
  407. ->method('groupExists')
  408. ->willReturn(true);
  409. $this->principal->expects(self::any())
  410. ->method('findByUri')
  411. ->willReturn(self::UNIT_TEST_USER1);
  412. $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  413. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER);
  414. $this->assertEquals(1, count($books));
  415. $l = $this->createMock(IL10N::class);
  416. $exampleBook = new AddressBook($this->backend, $books[0], $l);
  417. $this->backend->updateShares($exampleBook, [['href' => 'principal:' . self::UNIT_TEST_USER1]], []);
  418. $shares = $this->backend->getShares($exampleBook->getResourceId());
  419. $this->assertEquals(1, count($shares));
  420. // adding the same sharee again has no effect
  421. $this->backend->updateShares($exampleBook, [['href' => 'principal:' . self::UNIT_TEST_USER1]], []);
  422. $shares = $this->backend->getShares($exampleBook->getResourceId());
  423. $this->assertEquals(1, count($shares));
  424. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1);
  425. $this->assertEquals(1, count($books));
  426. $this->backend->updateShares($exampleBook, [], ['principal:' . self::UNIT_TEST_USER1]);
  427. $shares = $this->backend->getShares($exampleBook->getResourceId());
  428. $this->assertEquals(0, count($shares));
  429. $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1);
  430. $this->assertEquals(0, count($books));
  431. }
  432. public function testUpdateProperties(): void {
  433. $bookId = 42;
  434. $cardUri = 'card-uri';
  435. $cardId = 2;
  436. $backend = $this->getMockBuilder(CardDavBackend::class)
  437. ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->dispatcher, $this->sharingBackend])
  438. ->onlyMethods(['getCardId'])->getMock();
  439. $backend->expects($this->any())->method('getCardId')->willReturn($cardId);
  440. // add properties for new vCard
  441. $vCard = new VCard();
  442. $vCard->UID = $cardUri;
  443. $vCard->FN = 'John Doe';
  444. $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]);
  445. $query = $this->db->getQueryBuilder();
  446. $query->select('*')
  447. ->from('cards_properties');
  448. $qResult = $query->execute();
  449. $result = $qResult->fetchAll();
  450. $qResult->closeCursor();
  451. $this->assertSame(2, count($result));
  452. $this->assertSame('UID', $result[0]['name']);
  453. $this->assertSame($cardUri, $result[0]['value']);
  454. $this->assertSame($bookId, (int)$result[0]['addressbookid']);
  455. $this->assertSame($cardId, (int)$result[0]['cardid']);
  456. $this->assertSame('FN', $result[1]['name']);
  457. $this->assertSame('John Doe', $result[1]['value']);
  458. $this->assertSame($bookId, (int)$result[1]['addressbookid']);
  459. $this->assertSame($cardId, (int)$result[1]['cardid']);
  460. // update properties for existing vCard
  461. $vCard = new VCard();
  462. $vCard->UID = $cardUri;
  463. $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]);
  464. $query = $this->db->getQueryBuilder();
  465. $query->select('*')
  466. ->from('cards_properties');
  467. $qResult = $query->execute();
  468. $result = $qResult->fetchAll();
  469. $qResult->closeCursor();
  470. $this->assertSame(1, count($result));
  471. $this->assertSame('UID', $result[0]['name']);
  472. $this->assertSame($cardUri, $result[0]['value']);
  473. $this->assertSame($bookId, (int)$result[0]['addressbookid']);
  474. $this->assertSame($cardId, (int)$result[0]['cardid']);
  475. }
  476. public function testPurgeProperties(): void {
  477. $query = $this->db->getQueryBuilder();
  478. $query->insert('cards_properties')
  479. ->values(
  480. [
  481. 'addressbookid' => $query->createNamedParameter(1),
  482. 'cardid' => $query->createNamedParameter(1),
  483. 'name' => $query->createNamedParameter('name1'),
  484. 'value' => $query->createNamedParameter('value1'),
  485. 'preferred' => $query->createNamedParameter(0)
  486. ]
  487. );
  488. $query->execute();
  489. $query = $this->db->getQueryBuilder();
  490. $query->insert('cards_properties')
  491. ->values(
  492. [
  493. 'addressbookid' => $query->createNamedParameter(1),
  494. 'cardid' => $query->createNamedParameter(2),
  495. 'name' => $query->createNamedParameter('name2'),
  496. 'value' => $query->createNamedParameter('value2'),
  497. 'preferred' => $query->createNamedParameter(0)
  498. ]
  499. );
  500. $query->execute();
  501. $this->invokePrivate($this->backend, 'purgeProperties', [1, 1]);
  502. $query = $this->db->getQueryBuilder();
  503. $query->select('*')
  504. ->from('cards_properties');
  505. $qResult = $query->execute();
  506. $result = $qResult->fetchAll();
  507. $qResult->closeCursor();
  508. $this->assertSame(1, count($result));
  509. $this->assertSame(1, (int)$result[0]['addressbookid']);
  510. $this->assertSame(2, (int)$result[0]['cardid']);
  511. }
  512. public function testGetCardId(): void {
  513. $query = $this->db->getQueryBuilder();
  514. $query->insert('cards')
  515. ->values(
  516. [
  517. 'addressbookid' => $query->createNamedParameter(1),
  518. 'carddata' => $query->createNamedParameter(''),
  519. 'uri' => $query->createNamedParameter('uri'),
  520. 'lastmodified' => $query->createNamedParameter(4738743),
  521. 'etag' => $query->createNamedParameter('etag'),
  522. 'size' => $query->createNamedParameter(120)
  523. ]
  524. );
  525. $query->execute();
  526. $id = $query->getLastInsertId();
  527. $this->assertSame($id,
  528. $this->invokePrivate($this->backend, 'getCardId', [1, 'uri']));
  529. }
  530. public function testGetCardIdFailed(): void {
  531. $this->expectException(\InvalidArgumentException::class);
  532. $this->invokePrivate($this->backend, 'getCardId', [1, 'uri']);
  533. }
  534. /**
  535. * @dataProvider dataTestSearch
  536. *
  537. * @param string $pattern
  538. * @param array $properties
  539. * @param array $options
  540. * @param array $expected
  541. */
  542. public function testSearch($pattern, $properties, $options, $expected): void {
  543. /** @var VCard $vCards */
  544. $vCards = [];
  545. $vCards[0] = new VCard();
  546. $vCards[0]->add(new Text($vCards[0], 'UID', 'uid'));
  547. $vCards[0]->add(new Text($vCards[0], 'FN', 'John Doe'));
  548. $vCards[0]->add(new Text($vCards[0], 'CLOUD', 'john@nextcloud.com'));
  549. $vCards[1] = new VCard();
  550. $vCards[1]->add(new Text($vCards[1], 'UID', 'uid'));
  551. $vCards[1]->add(new Text($vCards[1], 'FN', 'John M. Doe'));
  552. $vCards[2] = new VCard();
  553. $vCards[2]->add(new Text($vCards[2], 'UID', 'uid'));
  554. $vCards[2]->add(new Text($vCards[2], 'FN', 'find without options'));
  555. $vCards[2]->add(new Text($vCards[2], 'CLOUD', 'peter_pan@nextcloud.com'));
  556. $vCardIds = [];
  557. $query = $this->db->getQueryBuilder();
  558. for ($i = 0; $i < 3; $i++) {
  559. $query->insert($this->dbCardsTable)
  560. ->values(
  561. [
  562. 'addressbookid' => $query->createNamedParameter(0),
  563. 'carddata' => $query->createNamedParameter($vCards[$i]->serialize(), IQueryBuilder::PARAM_LOB),
  564. 'uri' => $query->createNamedParameter('uri' . $i),
  565. 'lastmodified' => $query->createNamedParameter(time()),
  566. 'etag' => $query->createNamedParameter('etag' . $i),
  567. 'size' => $query->createNamedParameter(120),
  568. ]
  569. );
  570. $query->execute();
  571. $vCardIds[] = $query->getLastInsertId();
  572. }
  573. $query = $this->db->getQueryBuilder();
  574. $query->insert($this->dbCardsPropertiesTable)
  575. ->values(
  576. [
  577. 'addressbookid' => $query->createNamedParameter(0),
  578. 'cardid' => $query->createNamedParameter($vCardIds[0]),
  579. 'name' => $query->createNamedParameter('FN'),
  580. 'value' => $query->createNamedParameter('John Doe'),
  581. 'preferred' => $query->createNamedParameter(0)
  582. ]
  583. );
  584. $query->execute();
  585. $query = $this->db->getQueryBuilder();
  586. $query->insert($this->dbCardsPropertiesTable)
  587. ->values(
  588. [
  589. 'addressbookid' => $query->createNamedParameter(0),
  590. 'cardid' => $query->createNamedParameter($vCardIds[0]),
  591. 'name' => $query->createNamedParameter('CLOUD'),
  592. 'value' => $query->createNamedParameter('John@nextcloud.com'),
  593. 'preferred' => $query->createNamedParameter(0)
  594. ]
  595. );
  596. $query->execute();
  597. $query = $this->db->getQueryBuilder();
  598. $query->insert($this->dbCardsPropertiesTable)
  599. ->values(
  600. [
  601. 'addressbookid' => $query->createNamedParameter(0),
  602. 'cardid' => $query->createNamedParameter($vCardIds[1]),
  603. 'name' => $query->createNamedParameter('FN'),
  604. 'value' => $query->createNamedParameter('John M. Doe'),
  605. 'preferred' => $query->createNamedParameter(0)
  606. ]
  607. );
  608. $query->execute();
  609. $query = $this->db->getQueryBuilder();
  610. $query->insert($this->dbCardsPropertiesTable)
  611. ->values(
  612. [
  613. 'addressbookid' => $query->createNamedParameter(0),
  614. 'cardid' => $query->createNamedParameter($vCardIds[2]),
  615. 'name' => $query->createNamedParameter('FN'),
  616. 'value' => $query->createNamedParameter('find without options'),
  617. 'preferred' => $query->createNamedParameter(0)
  618. ]
  619. );
  620. $query->execute();
  621. $query = $this->db->getQueryBuilder();
  622. $query->insert($this->dbCardsPropertiesTable)
  623. ->values(
  624. [
  625. 'addressbookid' => $query->createNamedParameter(0),
  626. 'cardid' => $query->createNamedParameter($vCardIds[2]),
  627. 'name' => $query->createNamedParameter('CLOUD'),
  628. 'value' => $query->createNamedParameter('peter_pan@nextcloud.com'),
  629. 'preferred' => $query->createNamedParameter(0)
  630. ]
  631. );
  632. $query->execute();
  633. $result = $this->backend->search(0, $pattern, $properties, $options);
  634. // check result
  635. $this->assertSame(count($expected), count($result));
  636. $found = [];
  637. foreach ($result as $r) {
  638. foreach ($expected as $exp) {
  639. if ($r['uri'] === $exp[0] && strpos($r['carddata'], $exp[1]) > 0) {
  640. $found[$exp[1]] = true;
  641. break;
  642. }
  643. }
  644. }
  645. $this->assertSame(count($expected), count($found));
  646. }
  647. public function dataTestSearch() {
  648. return [
  649. ['John', ['FN'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  650. ['M. Doe', ['FN'], [], [['uri1', 'John M. Doe']]],
  651. ['Do', ['FN'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  652. 'check if duplicates are handled correctly' => ['John', ['FN', 'CLOUD'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  653. 'case insensitive' => ['john', ['FN'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]],
  654. 'limit' => ['john', ['FN'], ['limit' => 1], [['uri0', 'John Doe']]],
  655. 'limit and offset' => ['john', ['FN'], ['limit' => 1, 'offset' => 1], [['uri1', 'John M. Doe']]],
  656. 'find "_" escaped' => ['_', ['CLOUD'], [], [['uri2', 'find without options']]],
  657. 'find not empty CLOUD' => ['%_%', ['CLOUD'], ['escape_like_param' => false], [['uri0', 'John Doe'], ['uri2', 'find without options']]],
  658. ];
  659. }
  660. public function testGetCardUri(): void {
  661. $query = $this->db->getQueryBuilder();
  662. $query->insert($this->dbCardsTable)
  663. ->values(
  664. [
  665. 'addressbookid' => $query->createNamedParameter(1),
  666. 'carddata' => $query->createNamedParameter('carddata', IQueryBuilder::PARAM_LOB),
  667. 'uri' => $query->createNamedParameter('uri'),
  668. 'lastmodified' => $query->createNamedParameter(5489543),
  669. 'etag' => $query->createNamedParameter('etag'),
  670. 'size' => $query->createNamedParameter(120),
  671. ]
  672. );
  673. $query->execute();
  674. $id = $query->getLastInsertId();
  675. $this->assertSame('uri', $this->backend->getCardUri($id));
  676. }
  677. public function testGetCardUriFailed(): void {
  678. $this->expectException(\InvalidArgumentException::class);
  679. $this->backend->getCardUri(1);
  680. }
  681. public function testGetContact(): void {
  682. $query = $this->db->getQueryBuilder();
  683. for ($i = 0; $i < 2; $i++) {
  684. $query->insert($this->dbCardsTable)
  685. ->values(
  686. [
  687. 'addressbookid' => $query->createNamedParameter($i),
  688. 'carddata' => $query->createNamedParameter('carddata' . $i, IQueryBuilder::PARAM_LOB),
  689. 'uri' => $query->createNamedParameter('uri' . $i),
  690. 'lastmodified' => $query->createNamedParameter(5489543),
  691. 'etag' => $query->createNamedParameter('etag' . $i),
  692. 'size' => $query->createNamedParameter(120),
  693. ]
  694. );
  695. $query->execute();
  696. }
  697. $result = $this->backend->getContact(0, 'uri0');
  698. $this->assertSame(8, count($result));
  699. $this->assertSame(0, (int)$result['addressbookid']);
  700. $this->assertSame('uri0', $result['uri']);
  701. $this->assertSame(5489543, (int)$result['lastmodified']);
  702. $this->assertSame('"etag0"', $result['etag']);
  703. $this->assertSame(120, (int)$result['size']);
  704. // this shouldn't return any result because 'uri1' is in address book 1
  705. // see https://github.com/nextcloud/server/issues/229
  706. $result = $this->backend->getContact(0, 'uri1');
  707. $this->assertEmpty($result);
  708. }
  709. public function testGetContactFail(): void {
  710. $this->assertEmpty($this->backend->getContact(0, 'uri'));
  711. }
  712. public function testCollectCardProperties(): void {
  713. $query = $this->db->getQueryBuilder();
  714. $query->insert($this->dbCardsPropertiesTable)
  715. ->values(
  716. [
  717. 'addressbookid' => $query->createNamedParameter(666),
  718. 'cardid' => $query->createNamedParameter(777),
  719. 'name' => $query->createNamedParameter('FN'),
  720. 'value' => $query->createNamedParameter('John Doe'),
  721. 'preferred' => $query->createNamedParameter(0)
  722. ]
  723. )
  724. ->execute();
  725. $result = $this->backend->collectCardProperties(666, 'FN');
  726. $this->assertEquals(['John Doe'], $result);
  727. }
  728. /**
  729. * @throws \OCP\DB\Exception
  730. * @throws \Sabre\DAV\Exception\BadRequest
  731. */
  732. public function testPruneOutdatedSyncTokens(): void {
  733. $addressBookId = $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []);
  734. $changes = $this->backend->getChangesForAddressBook($addressBookId, '', 1);
  735. $syncToken = $changes['syncToken'];
  736. $uri = $this->getUniqueID('card');
  737. $this->backend->createCard($addressBookId, $uri, $this->vcardTest0);
  738. $this->backend->updateCard($addressBookId, $uri, $this->vcardTest1);
  739. // Do not delete anything if week data as old as ts=0
  740. $deleted = $this->backend->pruneOutdatedSyncTokens(0, 0);
  741. self::assertSame(0, $deleted);
  742. $deleted = $this->backend->pruneOutdatedSyncTokens(0, time());
  743. // At least one from the object creation and one from the object update
  744. $this->assertGreaterThanOrEqual(2, $deleted);
  745. $changes = $this->backend->getChangesForAddressBook($addressBookId, $syncToken, 1);
  746. $this->assertEmpty($changes['added']);
  747. $this->assertEmpty($changes['modified']);
  748. $this->assertEmpty($changes['deleted']);
  749. // Test that objects remain
  750. // Currently changes are empty
  751. $changes = $this->backend->getChangesForAddressBook($addressBookId, $syncToken, 100);
  752. $this->assertEquals(0, count($changes['added'] + $changes['modified'] + $changes['deleted']));
  753. // Create card
  754. $uri = $this->getUniqueID('card');
  755. $this->backend->createCard($addressBookId, $uri, $this->vcardTest0);
  756. // We now have one add
  757. $changes = $this->backend->getChangesForAddressBook($addressBookId, $syncToken, 100);
  758. $this->assertEquals(1, count($changes['added']));
  759. $this->assertEmpty($changes['modified']);
  760. $this->assertEmpty($changes['deleted']);
  761. // Update card
  762. $this->backend->updateCard($addressBookId, $uri, $this->vcardTest1);
  763. // One add, one modify, but shortened to modify
  764. $changes = $this->backend->getChangesForAddressBook($addressBookId, $syncToken, 100);
  765. $this->assertEmpty($changes['added']);
  766. $this->assertEquals(1, count($changes['modified']));
  767. $this->assertEmpty($changes['deleted']);
  768. // Delete all but last change
  769. $deleted = $this->backend->pruneOutdatedSyncTokens(1, time());
  770. $this->assertEquals(1, $deleted); // We had two changes before, now one
  771. // Only update should remain
  772. $changes = $this->backend->getChangesForAddressBook($addressBookId, $syncToken, 100);
  773. $this->assertEmpty($changes['added']);
  774. $this->assertEquals(1, count($changes['modified']));
  775. $this->assertEmpty($changes['deleted']);
  776. // Check that no crash occurs when prune is called without current changes
  777. $deleted = $this->backend->pruneOutdatedSyncTokens(1, time());
  778. }
  779. }