CardDavBackendTest.php 32 KB

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