CardDavBackendTest.php 32 KB

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