CardDavBackendTest.php 32 KB

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