1
0

CardSearchDao.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\ContactsInteraction\Db;
  8. use OCP\DB\QueryBuilder\IQueryBuilder;
  9. use OCP\IDBConnection;
  10. use OCP\IUser;
  11. use function is_resource;
  12. use function stream_get_contents;
  13. class CardSearchDao {
  14. private IDBConnection $db;
  15. public function __construct(IDBConnection $db) {
  16. $this->db = $db;
  17. }
  18. public function findExisting(IUser $user,
  19. ?string $uid,
  20. ?string $email,
  21. ?string $cloudId): ?string {
  22. $addressbooksQuery = $this->db->getQueryBuilder();
  23. $cardQuery = $this->db->getQueryBuilder();
  24. $propQuery = $this->db->getQueryBuilder();
  25. $propOr = $propQuery->expr()->orX();
  26. if ($uid !== null) {
  27. $propOr->add($propQuery->expr()->andX(
  28. $propQuery->expr()->eq('name', $cardQuery->createNamedParameter('UID')),
  29. $propQuery->expr()->eq('value', $cardQuery->createNamedParameter($uid))
  30. ));
  31. }
  32. if ($email !== null) {
  33. $propOr->add($propQuery->expr()->andX(
  34. $propQuery->expr()->eq('name', $cardQuery->createNamedParameter('EMAIL')),
  35. $propQuery->expr()->eq('value', $cardQuery->createNamedParameter($email))
  36. ));
  37. }
  38. if ($cloudId !== null) {
  39. $propOr->add($propQuery->expr()->andX(
  40. $propQuery->expr()->eq('name', $cardQuery->createNamedParameter('CLOUD')),
  41. $propQuery->expr()->eq('value', $cardQuery->createNamedParameter($cloudId))
  42. ));
  43. }
  44. $addressbooksQuery->selectDistinct('id')
  45. ->from('addressbooks')
  46. ->where($addressbooksQuery->expr()->eq('principaluri', $cardQuery->createNamedParameter("principals/users/" . $user->getUID())));
  47. $propQuery->selectDistinct('cardid')
  48. ->from('cards_properties')
  49. ->where($propQuery->expr()->in('addressbookid', $propQuery->createFunction($addressbooksQuery->getSQL()), IQueryBuilder::PARAM_INT_ARRAY))
  50. ->andWhere($propOr)
  51. ->groupBy('cardid');
  52. $cardQuery->select('carddata')
  53. ->from('cards')
  54. ->where($cardQuery->expr()->in('id', $cardQuery->createFunction($propQuery->getSQL()), IQueryBuilder::PARAM_INT_ARRAY))
  55. ->andWhere($cardQuery->expr()->in('addressbookid', $cardQuery->createFunction($addressbooksQuery->getSQL()), IQueryBuilder::PARAM_INT_ARRAY))
  56. ->setMaxResults(1);
  57. $result = $cardQuery->execute();
  58. /** @var string|resource|false $card */
  59. $card = $result->fetchOne();
  60. if ($card === false) {
  61. return null;
  62. }
  63. if (is_resource($card)) {
  64. return stream_get_contents($card);
  65. }
  66. return $card;
  67. }
  68. }