You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1468 lines
49 KiB

9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
  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 Björn Schießle <bjoern@schiessle.org>
  8. * @author Chih-Hsuan Yen <yan12125@gmail.com>
  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 matt <34400929+call-me-matt@users.noreply.github.com>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Stefan Weil <sw@weilnetz.de>
  18. * @author Thomas Citharel <nextcloud@tcit.fr>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. *
  21. * @license AGPL-3.0
  22. *
  23. * This code is free software: you can redistribute it and/or modify
  24. * it under the terms of the GNU Affero General Public License, version 3,
  25. * as published by the Free Software Foundation.
  26. *
  27. * This program is distributed in the hope that it will be useful,
  28. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  29. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  30. * GNU Affero General Public License for more details.
  31. *
  32. * You should have received a copy of the GNU Affero General Public License, version 3,
  33. * along with this program. If not, see <http://www.gnu.org/licenses/>
  34. *
  35. */
  36. namespace OCA\DAV\CardDAV;
  37. use OCA\DAV\Connector\Sabre\Principal;
  38. use OCA\DAV\DAV\Sharing\Backend;
  39. use OCA\DAV\DAV\Sharing\IShareable;
  40. use OCA\DAV\Events\AddressBookCreatedEvent;
  41. use OCA\DAV\Events\AddressBookDeletedEvent;
  42. use OCA\DAV\Events\AddressBookShareUpdatedEvent;
  43. use OCA\DAV\Events\AddressBookUpdatedEvent;
  44. use OCA\DAV\Events\CardCreatedEvent;
  45. use OCA\DAV\Events\CardDeletedEvent;
  46. use OCA\DAV\Events\CardMovedEvent;
  47. use OCA\DAV\Events\CardUpdatedEvent;
  48. use OCP\AppFramework\Db\TTransactional;
  49. use OCP\DB\Exception;
  50. use OCP\DB\QueryBuilder\IQueryBuilder;
  51. use OCP\EventDispatcher\IEventDispatcher;
  52. use OCP\IDBConnection;
  53. use OCP\IGroupManager;
  54. use OCP\IUserManager;
  55. use PDO;
  56. use Sabre\CardDAV\Backend\BackendInterface;
  57. use Sabre\CardDAV\Backend\SyncSupport;
  58. use Sabre\CardDAV\Plugin;
  59. use Sabre\DAV\Exception\BadRequest;
  60. use Sabre\VObject\Component\VCard;
  61. use Sabre\VObject\Reader;
  62. class CardDavBackend implements BackendInterface, SyncSupport {
  63. use TTransactional;
  64. public const PERSONAL_ADDRESSBOOK_URI = 'contacts';
  65. public const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
  66. private Principal $principalBackend;
  67. private string $dbCardsTable = 'cards';
  68. private string $dbCardsPropertiesTable = 'cards_properties';
  69. private IDBConnection $db;
  70. private Backend $sharingBackend;
  71. /** @var array properties to index */
  72. public static array $indexProperties = [
  73. 'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
  74. 'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO',
  75. 'CLOUD', 'X-SOCIALPROFILE'];
  76. /**
  77. * @var string[] Map of uid => display name
  78. */
  79. protected array $userDisplayNames;
  80. private IUserManager $userManager;
  81. private IEventDispatcher $dispatcher;
  82. private array $etagCache = [];
  83. /**
  84. * CardDavBackend constructor.
  85. *
  86. * @param IDBConnection $db
  87. * @param Principal $principalBackend
  88. * @param IUserManager $userManager
  89. * @param IGroupManager $groupManager
  90. * @param IEventDispatcher $dispatcher
  91. */
  92. public function __construct(IDBConnection $db,
  93. Principal $principalBackend,
  94. IUserManager $userManager,
  95. IGroupManager $groupManager,
  96. IEventDispatcher $dispatcher) {
  97. $this->db = $db;
  98. $this->principalBackend = $principalBackend;
  99. $this->userManager = $userManager;
  100. $this->dispatcher = $dispatcher;
  101. $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
  102. }
  103. /**
  104. * Return the number of address books for a principal
  105. *
  106. * @param $principalUri
  107. * @return int
  108. */
  109. public function getAddressBooksForUserCount($principalUri) {
  110. $principalUri = $this->convertPrincipal($principalUri, true);
  111. $query = $this->db->getQueryBuilder();
  112. $query->select($query->func()->count('*'))
  113. ->from('addressbooks')
  114. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  115. $result = $query->executeQuery();
  116. $column = (int) $result->fetchOne();
  117. $result->closeCursor();
  118. return $column;
  119. }
  120. /**
  121. * Returns the list of address books for a specific user.
  122. *
  123. * Every addressbook should have the following properties:
  124. * id - an arbitrary unique id
  125. * uri - the 'basename' part of the url
  126. * principaluri - Same as the passed parameter
  127. *
  128. * Any additional clark-notation property may be passed besides this. Some
  129. * common ones are :
  130. * {DAV:}displayname
  131. * {urn:ietf:params:xml:ns:carddav}addressbook-description
  132. * {http://calendarserver.org/ns/}getctag
  133. *
  134. * @param string $principalUri
  135. * @return array
  136. */
  137. public function getAddressBooksForUser($principalUri) {
  138. return $this->atomic(function () use ($principalUri) {
  139. $principalUriOriginal = $principalUri;
  140. $principalUri = $this->convertPrincipal($principalUri, true);
  141. $query = $this->db->getQueryBuilder();
  142. $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  143. ->from('addressbooks')
  144. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  145. $addressBooks = [];
  146. $result = $query->execute();
  147. while ($row = $result->fetch()) {
  148. $addressBooks[$row['id']] = [
  149. 'id' => $row['id'],
  150. 'uri' => $row['uri'],
  151. 'principaluri' => $this->convertPrincipal($row['principaluri'], false),
  152. '{DAV:}displayname' => $row['displayname'],
  153. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  154. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  155. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
  156. ];
  157. $this->addOwnerPrincipal($addressBooks[$row['id']]);
  158. }
  159. $result->closeCursor();
  160. // query for shared addressbooks
  161. $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
  162. $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
  163. $principals[] = $principalUri;
  164. $query = $this->db->getQueryBuilder();
  165. $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
  166. ->from('dav_shares', 's')
  167. ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  168. ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
  169. ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
  170. ->setParameter('type', 'addressbook')
  171. ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
  172. ->execute();
  173. $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
  174. while ($row = $result->fetch()) {
  175. if ($row['principaluri'] === $principalUri) {
  176. continue;
  177. }
  178. $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
  179. if (isset($addressBooks[$row['id']])) {
  180. if ($readOnly) {
  181. // New share can not have more permissions then the old one.
  182. continue;
  183. }
  184. if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
  185. $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
  186. // Old share is already read-write, no more permissions can be gained
  187. continue;
  188. }
  189. }
  190. [, $name] = \Sabre\Uri\split($row['principaluri']);
  191. $uri = $row['uri'] . '_shared_by_' . $name;
  192. $displayName = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? $name ?? '') . ')';
  193. $addressBooks[$row['id']] = [
  194. 'id' => $row['id'],
  195. 'uri' => $uri,
  196. 'principaluri' => $principalUriOriginal,
  197. '{DAV:}displayname' => $displayName,
  198. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  199. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  200. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
  201. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
  202. $readOnlyPropertyName => $readOnly,
  203. ];
  204. $this->addOwnerPrincipal($addressBooks[$row['id']]);
  205. }
  206. $result->closeCursor();
  207. return array_values($addressBooks);
  208. }, $this->db);
  209. }
  210. public function getUsersOwnAddressBooks($principalUri) {
  211. $principalUri = $this->convertPrincipal($principalUri, true);
  212. $query = $this->db->getQueryBuilder();
  213. $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  214. ->from('addressbooks')
  215. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  216. $addressBooks = [];
  217. $result = $query->execute();
  218. while ($row = $result->fetch()) {
  219. $addressBooks[$row['id']] = [
  220. 'id' => $row['id'],
  221. 'uri' => $row['uri'],
  222. 'principaluri' => $this->convertPrincipal($row['principaluri'], false),
  223. '{DAV:}displayname' => $row['displayname'],
  224. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  225. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  226. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
  227. ];
  228. $this->addOwnerPrincipal($addressBooks[$row['id']]);
  229. }
  230. $result->closeCursor();
  231. return array_values($addressBooks);
  232. }
  233. /**
  234. * @param int $addressBookId
  235. */
  236. public function getAddressBookById(int $addressBookId): ?array {
  237. $query = $this->db->getQueryBuilder();
  238. $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  239. ->from('addressbooks')
  240. ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId, IQueryBuilder::PARAM_INT)))
  241. ->executeQuery();
  242. $row = $result->fetch();
  243. $result->closeCursor();
  244. if (!$row) {
  245. return null;
  246. }
  247. $addressBook = [
  248. 'id' => $row['id'],
  249. 'uri' => $row['uri'],
  250. 'principaluri' => $row['principaluri'],
  251. '{DAV:}displayname' => $row['displayname'],
  252. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  253. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  254. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
  255. ];
  256. $this->addOwnerPrincipal($addressBook);
  257. return $addressBook;
  258. }
  259. public function getAddressBooksByUri(string $principal, string $addressBookUri): ?array {
  260. $query = $this->db->getQueryBuilder();
  261. $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  262. ->from('addressbooks')
  263. ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
  264. ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
  265. ->setMaxResults(1)
  266. ->executeQuery();
  267. $row = $result->fetch();
  268. $result->closeCursor();
  269. if ($row === false) {
  270. return null;
  271. }
  272. $addressBook = [
  273. 'id' => $row['id'],
  274. 'uri' => $row['uri'],
  275. 'principaluri' => $row['principaluri'],
  276. '{DAV:}displayname' => $row['displayname'],
  277. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  278. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  279. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
  280. ];
  281. // system address books are always read only
  282. if ($principal === 'principals/system/system') {
  283. $addressBook['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal'] = $row['principaluri'];
  284. $addressBook['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only'] = true;
  285. }
  286. $this->addOwnerPrincipal($addressBook);
  287. return $addressBook;
  288. }
  289. /**
  290. * Updates properties for an address book.
  291. *
  292. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  293. * To do the actual updates, you must tell this object which properties
  294. * you're going to process with the handle() method.
  295. *
  296. * Calling the handle method is like telling the PropPatch object "I
  297. * promise I can handle updating this property".
  298. *
  299. * Read the PropPatch documentation for more info and examples.
  300. *
  301. * @param string $addressBookId
  302. * @param \Sabre\DAV\PropPatch $propPatch
  303. * @return void
  304. */
  305. public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
  306. $this->atomic(function () use ($addressBookId, $propPatch) {
  307. $supportedProperties = [
  308. '{DAV:}displayname',
  309. '{' . Plugin::NS_CARDDAV . '}addressbook-description',
  310. ];
  311. $propPatch->handle($supportedProperties, function ($mutations) use ($addressBookId) {
  312. $updates = [];
  313. foreach ($mutations as $property => $newValue) {
  314. switch ($property) {
  315. case '{DAV:}displayname':
  316. $updates['displayname'] = $newValue;
  317. break;
  318. case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
  319. $updates['description'] = $newValue;
  320. break;
  321. }
  322. }
  323. $query = $this->db->getQueryBuilder();
  324. $query->update('addressbooks');
  325. foreach ($updates as $key => $value) {
  326. $query->set($key, $query->createNamedParameter($value));
  327. }
  328. $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
  329. ->executeStatement();
  330. $this->addChange($addressBookId, "", 2);
  331. $addressBookRow = $this->getAddressBookById((int)$addressBookId);
  332. $shares = $this->getShares((int)$addressBookId);
  333. $this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations));
  334. return true;
  335. });
  336. }, $this->db);
  337. }
  338. /**
  339. * Creates a new address book
  340. *
  341. * @param string $principalUri
  342. * @param string $url Just the 'basename' of the url.
  343. * @param array $properties
  344. * @return int
  345. * @throws BadRequest
  346. */
  347. public function createAddressBook($principalUri, $url, array $properties) {
  348. if (strlen($url) > 255) {
  349. throw new BadRequest('URI too long. Address book not created');
  350. }
  351. $values = [
  352. 'displayname' => null,
  353. 'description' => null,
  354. 'principaluri' => $principalUri,
  355. 'uri' => $url,
  356. 'synctoken' => 1
  357. ];
  358. foreach ($properties as $property => $newValue) {
  359. switch ($property) {
  360. case '{DAV:}displayname':
  361. $values['displayname'] = $newValue;
  362. break;
  363. case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
  364. $values['description'] = $newValue;
  365. break;
  366. default:
  367. throw new BadRequest('Unknown property: ' . $property);
  368. }
  369. }
  370. // Fallback to make sure the displayname is set. Some clients may refuse
  371. // to work with addressbooks not having a displayname.
  372. if (is_null($values['displayname'])) {
  373. $values['displayname'] = $url;
  374. }
  375. [$addressBookId, $addressBookRow] = $this->atomic(function () use ($values) {
  376. $query = $this->db->getQueryBuilder();
  377. $query->insert('addressbooks')
  378. ->values([
  379. 'uri' => $query->createParameter('uri'),
  380. 'displayname' => $query->createParameter('displayname'),
  381. 'description' => $query->createParameter('description'),
  382. 'principaluri' => $query->createParameter('principaluri'),
  383. 'synctoken' => $query->createParameter('synctoken'),
  384. ])
  385. ->setParameters($values)
  386. ->execute();
  387. $addressBookId = $query->getLastInsertId();
  388. return [
  389. $addressBookId,
  390. $this->getAddressBookById($addressBookId),
  391. ];
  392. }, $this->db);
  393. $this->dispatcher->dispatchTyped(new AddressBookCreatedEvent($addressBookId, $addressBookRow));
  394. return $addressBookId;
  395. }
  396. /**
  397. * Deletes an entire addressbook and all its contents
  398. *
  399. * @param mixed $addressBookId
  400. * @return void
  401. */
  402. public function deleteAddressBook($addressBookId) {
  403. $this->atomic(function () use ($addressBookId) {
  404. $addressBookId = (int)$addressBookId;
  405. $addressBookData = $this->getAddressBookById($addressBookId);
  406. $shares = $this->getShares($addressBookId);
  407. $query = $this->db->getQueryBuilder();
  408. $query->delete($this->dbCardsTable)
  409. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  410. ->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
  411. ->executeStatement();
  412. $query = $this->db->getQueryBuilder();
  413. $query->delete('addressbookchanges')
  414. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  415. ->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
  416. ->executeStatement();
  417. $query = $this->db->getQueryBuilder();
  418. $query->delete('addressbooks')
  419. ->where($query->expr()->eq('id', $query->createParameter('id')))
  420. ->setParameter('id', $addressBookId, IQueryBuilder::PARAM_INT)
  421. ->executeStatement();
  422. $this->sharingBackend->deleteAllShares($addressBookId);
  423. $query = $this->db->getQueryBuilder();
  424. $query->delete($this->dbCardsPropertiesTable)
  425. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId, IQueryBuilder::PARAM_INT)))
  426. ->executeStatement();
  427. if ($addressBookData) {
  428. $this->dispatcher->dispatchTyped(new AddressBookDeletedEvent($addressBookId, $addressBookData, $shares));
  429. }
  430. }, $this->db);
  431. }
  432. /**
  433. * Returns all cards for a specific addressbook id.
  434. *
  435. * This method should return the following properties for each card:
  436. * * carddata - raw vcard data
  437. * * uri - Some unique url
  438. * * lastmodified - A unix timestamp
  439. *
  440. * It's recommended to also return the following properties:
  441. * * etag - A unique etag. This must change every time the card changes.
  442. * * size - The size of the card in bytes.
  443. *
  444. * If these last two properties are provided, less time will be spent
  445. * calculating them. If they are specified, you can also omit carddata.
  446. * This may speed up certain requests, especially with large cards.
  447. *
  448. * @param mixed $addressbookId
  449. * @return array
  450. */
  451. public function getCards($addressbookId) {
  452. $query = $this->db->getQueryBuilder();
  453. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
  454. ->from($this->dbCardsTable)
  455. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressbookId)));
  456. $cards = [];
  457. $result = $query->execute();
  458. while ($row = $result->fetch()) {
  459. $row['etag'] = '"' . $row['etag'] . '"';
  460. $modified = false;
  461. $row['carddata'] = $this->readBlob($row['carddata'], $modified);
  462. if ($modified) {
  463. $row['size'] = strlen($row['carddata']);
  464. }
  465. $cards[] = $row;
  466. }
  467. $result->closeCursor();
  468. return $cards;
  469. }
  470. /**
  471. * Returns a specific card.
  472. *
  473. * The same set of properties must be returned as with getCards. The only
  474. * exception is that 'carddata' is absolutely required.
  475. *
  476. * If the card does not exist, you must return false.
  477. *
  478. * @param mixed $addressBookId
  479. * @param string $cardUri
  480. * @return array
  481. */
  482. public function getCard($addressBookId, $cardUri) {
  483. $query = $this->db->getQueryBuilder();
  484. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
  485. ->from($this->dbCardsTable)
  486. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  487. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  488. ->setMaxResults(1);
  489. $result = $query->execute();
  490. $row = $result->fetch();
  491. if (!$row) {
  492. return false;
  493. }
  494. $row['etag'] = '"' . $row['etag'] . '"';
  495. $modified = false;
  496. $row['carddata'] = $this->readBlob($row['carddata'], $modified);
  497. if ($modified) {
  498. $row['size'] = strlen($row['carddata']);
  499. }
  500. return $row;
  501. }
  502. /**
  503. * Returns a list of cards.
  504. *
  505. * This method should work identical to getCard, but instead return all the
  506. * cards in the list as an array.
  507. *
  508. * If the backend supports this, it may allow for some speed-ups.
  509. *
  510. * @param mixed $addressBookId
  511. * @param array $uris
  512. * @return array
  513. */
  514. public function getMultipleCards($addressBookId, array $uris) {
  515. if (empty($uris)) {
  516. return [];
  517. }
  518. $chunks = array_chunk($uris, 100);
  519. $cards = [];
  520. $query = $this->db->getQueryBuilder();
  521. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
  522. ->from($this->dbCardsTable)
  523. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  524. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
  525. foreach ($chunks as $uris) {
  526. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  527. $result = $query->execute();
  528. while ($row = $result->fetch()) {
  529. $row['etag'] = '"' . $row['etag'] . '"';
  530. $modified = false;
  531. $row['carddata'] = $this->readBlob($row['carddata'], $modified);
  532. if ($modified) {
  533. $row['size'] = strlen($row['carddata']);
  534. }
  535. $cards[] = $row;
  536. }
  537. $result->closeCursor();
  538. }
  539. return $cards;
  540. }
  541. /**
  542. * Creates a new card.
  543. *
  544. * The addressbook id will be passed as the first argument. This is the
  545. * same id as it is returned from the getAddressBooksForUser method.
  546. *
  547. * The cardUri is a base uri, and doesn't include the full path. The
  548. * cardData argument is the vcard body, and is passed as a string.
  549. *
  550. * It is possible to return an ETag from this method. This ETag is for the
  551. * newly created resource, and must be enclosed with double quotes (that
  552. * is, the string itself must contain the double quotes).
  553. *
  554. * You should only return the ETag if you store the carddata as-is. If a
  555. * subsequent GET request on the same card does not have the same body,
  556. * byte-by-byte and you did return an ETag here, clients tend to get
  557. * confused.
  558. *
  559. * If you don't return an ETag, you can just return null.
  560. *
  561. * @param mixed $addressBookId
  562. * @param string $cardUri
  563. * @param string $cardData
  564. * @param bool $checkAlreadyExists
  565. * @return string
  566. */
  567. public function createCard($addressBookId, $cardUri, $cardData, bool $checkAlreadyExists = true) {
  568. $etag = md5($cardData);
  569. $uid = $this->getUID($cardData);
  570. return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $checkAlreadyExists, $etag, $uid) {
  571. if ($checkAlreadyExists) {
  572. $q = $this->db->getQueryBuilder();
  573. $q->select('uid')
  574. ->from($this->dbCardsTable)
  575. ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
  576. ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
  577. ->setMaxResults(1);
  578. $result = $q->executeQuery();
  579. $count = (bool)$result->fetchOne();
  580. $result->closeCursor();
  581. if ($count) {
  582. throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
  583. }
  584. }
  585. $query = $this->db->getQueryBuilder();
  586. $query->insert('cards')
  587. ->values([
  588. 'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
  589. 'uri' => $query->createNamedParameter($cardUri),
  590. 'lastmodified' => $query->createNamedParameter(time()),
  591. 'addressbookid' => $query->createNamedParameter($addressBookId),
  592. 'size' => $query->createNamedParameter(strlen($cardData)),
  593. 'etag' => $query->createNamedParameter($etag),
  594. 'uid' => $query->createNamedParameter($uid),
  595. ])
  596. ->execute();
  597. $etagCacheKey = "$addressBookId#$cardUri";
  598. $this->etagCache[$etagCacheKey] = $etag;
  599. $this->addChange($addressBookId, $cardUri, 1);
  600. $this->updateProperties($addressBookId, $cardUri, $cardData);
  601. $addressBookData = $this->getAddressBookById($addressBookId);
  602. $shares = $this->getShares($addressBookId);
  603. $objectRow = $this->getCard($addressBookId, $cardUri);
  604. $this->dispatcher->dispatchTyped(new CardCreatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
  605. return '"' . $etag . '"';
  606. }, $this->db);
  607. }
  608. /**
  609. * Updates a card.
  610. *
  611. * The addressbook id will be passed as the first argument. This is the
  612. * same id as it is returned from the getAddressBooksForUser method.
  613. *
  614. * The cardUri is a base uri, and doesn't include the full path. The
  615. * cardData argument is the vcard body, and is passed as a string.
  616. *
  617. * It is possible to return an ETag from this method. This ETag should
  618. * match that of the updated resource, and must be enclosed with double
  619. * quotes (that is: the string itself must contain the actual quotes).
  620. *
  621. * You should only return the ETag if you store the carddata as-is. If a
  622. * subsequent GET request on the same card does not have the same body,
  623. * byte-by-byte and you did return an ETag here, clients tend to get
  624. * confused.
  625. *
  626. * If you don't return an ETag, you can just return null.
  627. *
  628. * @param mixed $addressBookId
  629. * @param string $cardUri
  630. * @param string $cardData
  631. * @return string
  632. */
  633. public function updateCard($addressBookId, $cardUri, $cardData) {
  634. $uid = $this->getUID($cardData);
  635. $etag = md5($cardData);
  636. return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $uid, $etag) {
  637. $query = $this->db->getQueryBuilder();
  638. // check for recently stored etag and stop if it is the same
  639. $etagCacheKey = "$addressBookId#$cardUri";
  640. if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
  641. return '"' . $etag . '"';
  642. }
  643. $query->update($this->dbCardsTable)
  644. ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
  645. ->set('lastmodified', $query->createNamedParameter(time()))
  646. ->set('size', $query->createNamedParameter(strlen($cardData)))
  647. ->set('etag', $query->createNamedParameter($etag))
  648. ->set('uid', $query->createNamedParameter($uid))
  649. ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  650. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  651. ->execute();
  652. $this->etagCache[$etagCacheKey] = $etag;
  653. $this->addChange($addressBookId, $cardUri, 2);
  654. $this->updateProperties($addressBookId, $cardUri, $cardData);
  655. $addressBookData = $this->getAddressBookById($addressBookId);
  656. $shares = $this->getShares($addressBookId);
  657. $objectRow = $this->getCard($addressBookId, $cardUri);
  658. $this->dispatcher->dispatchTyped(new CardUpdatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
  659. return '"' . $etag . '"';
  660. }, $this->db);
  661. }
  662. /**
  663. * @throws Exception
  664. */
  665. public function moveCard(int $sourceAddressBookId, int $targetAddressBookId, string $cardUri, string $oldPrincipalUri): bool {
  666. return $this->atomic(function () use ($sourceAddressBookId, $targetAddressBookId, $cardUri, $oldPrincipalUri) {
  667. $card = $this->getCard($sourceAddressBookId, $cardUri);
  668. if (empty($card)) {
  669. return false;
  670. }
  671. $query = $this->db->getQueryBuilder();
  672. $query->update('cards')
  673. ->set('addressbookid', $query->createNamedParameter($targetAddressBookId, IQueryBuilder::PARAM_INT))
  674. ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
  675. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($sourceAddressBookId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
  676. ->executeStatement();
  677. $this->purgeProperties($sourceAddressBookId, (int)$card['id']);
  678. $this->updateProperties($sourceAddressBookId, $card['uri'], $card['carddata']);
  679. $this->addChange($sourceAddressBookId, $card['uri'], 3);
  680. $this->addChange($targetAddressBookId, $card['uri'], 1);
  681. $card = $this->getCard($targetAddressBookId, $cardUri);
  682. // Card wasn't found - possibly because it was deleted in the meantime by a different client
  683. if (empty($card)) {
  684. return false;
  685. }
  686. $targetAddressBookRow = $this->getAddressBookById($targetAddressBookId);
  687. // the address book this card is being moved to does not exist any longer
  688. if (empty($targetAddressBookRow)) {
  689. return false;
  690. }
  691. $sourceShares = $this->getShares($sourceAddressBookId);
  692. $targetShares = $this->getShares($targetAddressBookId);
  693. $sourceAddressBookRow = $this->getAddressBookById($sourceAddressBookId);
  694. $this->dispatcher->dispatchTyped(new CardMovedEvent($sourceAddressBookId, $sourceAddressBookRow, $targetAddressBookId, $targetAddressBookRow, $sourceShares, $targetShares, $card));
  695. return true;
  696. }, $this->db);
  697. }
  698. /**
  699. * Deletes a card
  700. *
  701. * @param mixed $addressBookId
  702. * @param string $cardUri
  703. * @return bool
  704. */
  705. public function deleteCard($addressBookId, $cardUri) {
  706. return $this->atomic(function () use ($addressBookId, $cardUri) {
  707. $addressBookData = $this->getAddressBookById($addressBookId);
  708. $shares = $this->getShares($addressBookId);
  709. $objectRow = $this->getCard($addressBookId, $cardUri);
  710. try {
  711. $cardId = $this->getCardId($addressBookId, $cardUri);
  712. } catch (\InvalidArgumentException $e) {
  713. $cardId = null;
  714. }
  715. $query = $this->db->getQueryBuilder();
  716. $ret = $query->delete($this->dbCardsTable)
  717. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  718. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  719. ->executeStatement();
  720. $this->addChange($addressBookId, $cardUri, 3);
  721. if ($ret === 1) {
  722. if ($cardId !== null) {
  723. $this->dispatcher->dispatchTyped(new CardDeletedEvent($addressBookId, $addressBookData, $shares, $objectRow));
  724. $this->purgeProperties($addressBookId, $cardId);
  725. }
  726. return true;
  727. }
  728. return false;
  729. }, $this->db);
  730. }
  731. /**
  732. * The getChanges method returns all the changes that have happened, since
  733. * the specified syncToken in the specified address book.
  734. *
  735. * This function should return an array, such as the following:
  736. *
  737. * [
  738. * 'syncToken' => 'The current synctoken',
  739. * 'added' => [
  740. * 'new.txt',
  741. * ],
  742. * 'modified' => [
  743. * 'modified.txt',
  744. * ],
  745. * 'deleted' => [
  746. * 'foo.php.bak',
  747. * 'old.txt'
  748. * ]
  749. * ];
  750. *
  751. * The returned syncToken property should reflect the *current* syncToken
  752. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  753. * property. This is needed here too, to ensure the operation is atomic.
  754. *
  755. * If the $syncToken argument is specified as null, this is an initial
  756. * sync, and all members should be reported.
  757. *
  758. * The modified property is an array of nodenames that have changed since
  759. * the last token.
  760. *
  761. * The deleted property is an array with nodenames, that have been deleted
  762. * from collection.
  763. *
  764. * The $syncLevel argument is basically the 'depth' of the report. If it's
  765. * 1, you only have to report changes that happened only directly in
  766. * immediate descendants. If it's 2, it should also include changes from
  767. * the nodes below the child collections. (grandchildren)
  768. *
  769. * The $limit argument allows a client to specify how many results should
  770. * be returned at most. If the limit is not specified, it should be treated
  771. * as infinite.
  772. *
  773. * If the limit (infinite or not) is higher than you're willing to return,
  774. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  775. *
  776. * If the syncToken is expired (due to data cleanup) or unknown, you must
  777. * return null.
  778. *
  779. * The limit is 'suggestive'. You are free to ignore it.
  780. *
  781. * @param string $addressBookId
  782. * @param string $syncToken
  783. * @param int $syncLevel
  784. * @param int|null $limit
  785. * @return array
  786. */
  787. public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
  788. // Current synctoken
  789. return $this->atomic(function () use ($addressBookId, $syncToken, $syncLevel, $limit) {
  790. $qb = $this->db->getQueryBuilder();
  791. $qb->select('synctoken')
  792. ->from('addressbooks')
  793. ->where(
  794. $qb->expr()->eq('id', $qb->createNamedParameter($addressBookId))
  795. );
  796. $stmt = $qb->executeQuery();
  797. $currentToken = $stmt->fetchOne();
  798. $stmt->closeCursor();
  799. if (is_null($currentToken)) {
  800. return [];
  801. }
  802. $result = [
  803. 'syncToken' => $currentToken,
  804. 'added' => [],
  805. 'modified' => [],
  806. 'deleted' => [],
  807. ];
  808. if ($syncToken) {
  809. $qb = $this->db->getQueryBuilder();
  810. $qb->select('uri', 'operation')
  811. ->from('addressbookchanges')
  812. ->where(
  813. $qb->expr()->andX(
  814. $qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
  815. $qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
  816. $qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
  817. )
  818. )->orderBy('synctoken');
  819. if (is_int($limit) && $limit > 0) {
  820. $qb->setMaxResults($limit);
  821. }
  822. // Fetching all changes
  823. $stmt = $qb->executeQuery();
  824. $changes = [];
  825. // This loop ensures that any duplicates are overwritten, only the
  826. // last change on a node is relevant.
  827. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  828. $changes[$row['uri']] = $row['operation'];
  829. }
  830. $stmt->closeCursor();
  831. foreach ($changes as $uri => $operation) {
  832. switch ($operation) {
  833. case 1:
  834. $result['added'][] = $uri;
  835. break;
  836. case 2:
  837. $result['modified'][] = $uri;
  838. break;
  839. case 3:
  840. $result['deleted'][] = $uri;
  841. break;
  842. }
  843. }
  844. } else {
  845. $qb = $this->db->getQueryBuilder();
  846. $qb->select('uri')
  847. ->from('cards')
  848. ->where(
  849. $qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
  850. );
  851. // No synctoken supplied, this is the initial sync.
  852. $stmt = $qb->executeQuery();
  853. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  854. $stmt->closeCursor();
  855. }
  856. return $result;
  857. }, $this->db);
  858. }
  859. /**
  860. * Adds a change record to the addressbookchanges table.
  861. *
  862. * @param mixed $addressBookId
  863. * @param string $objectUri
  864. * @param int $operation 1 = add, 2 = modify, 3 = delete
  865. * @return void
  866. */
  867. protected function addChange(int $addressBookId, string $objectUri, int $operation): void {
  868. $this->atomic(function () use ($addressBookId, $objectUri, $operation) {
  869. $query = $this->db->getQueryBuilder();
  870. $query->select('synctoken')
  871. ->from('addressbooks')
  872. ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)));
  873. $result = $query->executeQuery();
  874. $syncToken = (int)$result->fetchOne();
  875. $result->closeCursor();
  876. $query = $this->db->getQueryBuilder();
  877. $query->insert('addressbookchanges')
  878. ->values([
  879. 'uri' => $query->createNamedParameter($objectUri),
  880. 'synctoken' => $query->createNamedParameter($syncToken),
  881. 'addressbookid' => $query->createNamedParameter($addressBookId),
  882. 'operation' => $query->createNamedParameter($operation),
  883. ])
  884. ->executeStatement();
  885. $query = $this->db->getQueryBuilder();
  886. $query->update('addressbooks')
  887. ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
  888. ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
  889. ->executeStatement();
  890. }, $this->db);
  891. }
  892. /**
  893. * @param resource|string $cardData
  894. * @param bool $modified
  895. * @return string
  896. */
  897. private function readBlob($cardData, &$modified = false) {
  898. if (is_resource($cardData)) {
  899. $cardData = stream_get_contents($cardData);
  900. }
  901. // Micro optimisation
  902. // don't loop through
  903. if (str_starts_with($cardData, 'PHOTO:data:')) {
  904. return $cardData;
  905. }
  906. $cardDataArray = explode("\r\n", $cardData);
  907. $cardDataFiltered = [];
  908. $removingPhoto = false;
  909. foreach ($cardDataArray as $line) {
  910. if (str_starts_with($line, 'PHOTO:data:')
  911. && !str_starts_with($line, 'PHOTO:data:image/')) {
  912. // Filter out PHOTO data of non-images
  913. $removingPhoto = true;
  914. $modified = true;
  915. continue;
  916. }
  917. if ($removingPhoto) {
  918. if (str_starts_with($line, ' ')) {
  919. continue;
  920. }
  921. // No leading space means this is a new property
  922. $removingPhoto = false;
  923. }
  924. $cardDataFiltered[] = $line;
  925. }
  926. return implode("\r\n", $cardDataFiltered);
  927. }
  928. /**
  929. * @param list<array{href: string, commonName: string, readOnly: bool}> $add
  930. * @param list<string> $remove
  931. */
  932. public function updateShares(IShareable $shareable, array $add, array $remove): void {
  933. $this->atomic(function () use ($shareable, $add, $remove) {
  934. $addressBookId = $shareable->getResourceId();
  935. $addressBookData = $this->getAddressBookById($addressBookId);
  936. $oldShares = $this->getShares($addressBookId);
  937. $this->sharingBackend->updateShares($shareable, $add, $remove);
  938. $this->dispatcher->dispatchTyped(new AddressBookShareUpdatedEvent($addressBookId, $addressBookData, $oldShares, $add, $remove));
  939. }, $this->db);
  940. }
  941. /**
  942. * Search contacts in a specific address-book
  943. *
  944. * @param int $addressBookId
  945. * @param string $pattern which should match within the $searchProperties
  946. * @param array $searchProperties defines the properties within the query pattern should match
  947. * @param array $options = array() to define the search behavior
  948. * - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
  949. * - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
  950. * - 'limit' - Set a numeric limit for the search results
  951. * - 'offset' - Set the offset for the limited search results
  952. * - 'wildcard' - Whether the search should use wildcards
  953. * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options
  954. * @return array an array of contacts which are arrays of key-value-pairs
  955. */
  956. public function search($addressBookId, $pattern, $searchProperties, $options = []): array {
  957. return $this->atomic(function () use ($addressBookId, $pattern, $searchProperties, $options) {
  958. return $this->searchByAddressBookIds([$addressBookId], $pattern, $searchProperties, $options);
  959. }, $this->db);
  960. }
  961. /**
  962. * Search contacts in all address-books accessible by a user
  963. *
  964. * @param string $principalUri
  965. * @param string $pattern
  966. * @param array $searchProperties
  967. * @param array $options
  968. * @return array
  969. */
  970. public function searchPrincipalUri(string $principalUri,
  971. string $pattern,
  972. array $searchProperties,
  973. array $options = []): array {
  974. return $this->atomic(function () use ($principalUri, $pattern, $searchProperties, $options) {
  975. $addressBookIds = array_map(static function ($row):int {
  976. return (int) $row['id'];
  977. }, $this->getAddressBooksForUser($principalUri));
  978. return $this->searchByAddressBookIds($addressBookIds, $pattern, $searchProperties, $options);
  979. }, $this->db);
  980. }
  981. /**
  982. * @param array $addressBookIds
  983. * @param string $pattern
  984. * @param array $searchProperties
  985. * @param array $options
  986. * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options
  987. * @return array
  988. */
  989. private function searchByAddressBookIds(array $addressBookIds,
  990. string $pattern,
  991. array $searchProperties,
  992. array $options = []): array {
  993. $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
  994. $useWildcards = !\array_key_exists('wildcard', $options) || $options['wildcard'] !== false;
  995. $query2 = $this->db->getQueryBuilder();
  996. $addressBookOr = $query2->expr()->orX();
  997. foreach ($addressBookIds as $addressBookId) {
  998. $addressBookOr->add($query2->expr()->eq('cp.addressbookid', $query2->createNamedParameter($addressBookId)));
  999. }
  1000. if ($addressBookOr->count() === 0) {
  1001. return [];
  1002. }
  1003. $propertyOr = $query2->expr()->orX();
  1004. foreach ($searchProperties as $property) {
  1005. if ($escapePattern) {
  1006. if ($property === 'EMAIL' && str_contains($pattern, ' ')) {
  1007. // There can be no spaces in emails
  1008. continue;
  1009. }
  1010. if ($property === 'CLOUD' && preg_match('/[^a-zA-Z0-9 :_.@\/\-\']/', $pattern) === 1) {
  1011. // There can be no chars in cloud ids which are not valid for user ids plus :/
  1012. // worst case: CA61590A-BBBC-423E-84AF-E6DF01455A53@https://my.nxt/srv/
  1013. continue;
  1014. }
  1015. }
  1016. $propertyOr->add($query2->expr()->eq('cp.name', $query2->createNamedParameter($property)));
  1017. }
  1018. if ($propertyOr->count() === 0) {
  1019. return [];
  1020. }
  1021. $query2->selectDistinct('cp.cardid')
  1022. ->from($this->dbCardsPropertiesTable, 'cp')
  1023. ->andWhere($addressBookOr)
  1024. ->andWhere($propertyOr);
  1025. // No need for like when the pattern is empty
  1026. if ('' !== $pattern) {
  1027. if (!$useWildcards) {
  1028. $query2->andWhere($query2->expr()->eq('cp.value', $query2->createNamedParameter($pattern)));
  1029. } elseif (!$escapePattern) {
  1030. $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
  1031. } else {
  1032. $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
  1033. }
  1034. }
  1035. if (isset($options['limit'])) {
  1036. $query2->setMaxResults($options['limit']);
  1037. }
  1038. if (isset($options['offset'])) {
  1039. $query2->setFirstResult($options['offset']);
  1040. }
  1041. $result = $query2->execute();
  1042. $matches = $result->fetchAll();
  1043. $result->closeCursor();
  1044. $matches = array_map(function ($match) {
  1045. return (int)$match['cardid'];
  1046. }, $matches);
  1047. $cards = [];
  1048. $query = $this->db->getQueryBuilder();
  1049. $query->select('c.addressbookid', 'c.carddata', 'c.uri')
  1050. ->from($this->dbCardsTable, 'c')
  1051. ->where($query->expr()->in('c.id', $query->createParameter('matches')));
  1052. foreach (array_chunk($matches, 1000) as $matchesChunk) {
  1053. $query->setParameter('matches', $matchesChunk, IQueryBuilder::PARAM_INT_ARRAY);
  1054. $result = $query->executeQuery();
  1055. $cards = array_merge($cards, $result->fetchAll());
  1056. $result->closeCursor();
  1057. }
  1058. return array_map(function ($array) {
  1059. $array['addressbookid'] = (int) $array['addressbookid'];
  1060. $modified = false;
  1061. $array['carddata'] = $this->readBlob($array['carddata'], $modified);
  1062. if ($modified) {
  1063. $array['size'] = strlen($array['carddata']);
  1064. }
  1065. return $array;
  1066. }, $cards);
  1067. }
  1068. /**
  1069. * @param int $bookId
  1070. * @param string $name
  1071. * @return array
  1072. */
  1073. public function collectCardProperties($bookId, $name) {
  1074. $query = $this->db->getQueryBuilder();
  1075. $result = $query->selectDistinct('value')
  1076. ->from($this->dbCardsPropertiesTable)
  1077. ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
  1078. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
  1079. ->execute();
  1080. $all = $result->fetchAll(PDO::FETCH_COLUMN);
  1081. $result->closeCursor();
  1082. return $all;
  1083. }
  1084. /**
  1085. * get URI from a given contact
  1086. *
  1087. * @param int $id
  1088. * @return string
  1089. */
  1090. public function getCardUri($id) {
  1091. $query = $this->db->getQueryBuilder();
  1092. $query->select('uri')->from($this->dbCardsTable)
  1093. ->where($query->expr()->eq('id', $query->createParameter('id')))
  1094. ->setParameter('id', $id);
  1095. $result = $query->execute();
  1096. $uri = $result->fetch();
  1097. $result->closeCursor();
  1098. if (!isset($uri['uri'])) {
  1099. throw new \InvalidArgumentException('Card does not exists: ' . $id);
  1100. }
  1101. return $uri['uri'];
  1102. }
  1103. /**
  1104. * return contact with the given URI
  1105. *
  1106. * @param int $addressBookId
  1107. * @param string $uri
  1108. * @returns array
  1109. */
  1110. public function getContact($addressBookId, $uri) {
  1111. $result = [];
  1112. $query = $this->db->getQueryBuilder();
  1113. $query->select('*')->from($this->dbCardsTable)
  1114. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  1115. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1116. $queryResult = $query->execute();
  1117. $contact = $queryResult->fetch();
  1118. $queryResult->closeCursor();
  1119. if (is_array($contact)) {
  1120. $modified = false;
  1121. $contact['etag'] = '"' . $contact['etag'] . '"';
  1122. $contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
  1123. if ($modified) {
  1124. $contact['size'] = strlen($contact['carddata']);
  1125. }
  1126. $result = $contact;
  1127. }
  1128. return $result;
  1129. }
  1130. /**
  1131. * Returns the list of people whom this address book is shared with.
  1132. *
  1133. * Every element in this array should have the following properties:
  1134. * * href - Often a mailto: address
  1135. * * commonName - Optional, for example a first + last name
  1136. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  1137. * * readOnly - boolean
  1138. *
  1139. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  1140. */
  1141. public function getShares(int $addressBookId): array {
  1142. return $this->sharingBackend->getShares($addressBookId);
  1143. }
  1144. /**
  1145. * update properties table
  1146. *
  1147. * @param int $addressBookId
  1148. * @param string $cardUri
  1149. * @param string $vCardSerialized
  1150. */
  1151. protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
  1152. $this->atomic(function () use ($addressBookId, $cardUri, $vCardSerialized) {
  1153. $cardId = $this->getCardId($addressBookId, $cardUri);
  1154. $vCard = $this->readCard($vCardSerialized);
  1155. $this->purgeProperties($addressBookId, $cardId);
  1156. $query = $this->db->getQueryBuilder();
  1157. $query->insert($this->dbCardsPropertiesTable)
  1158. ->values(
  1159. [
  1160. 'addressbookid' => $query->createNamedParameter($addressBookId),
  1161. 'cardid' => $query->createNamedParameter($cardId),
  1162. 'name' => $query->createParameter('name'),
  1163. 'value' => $query->createParameter('value'),
  1164. 'preferred' => $query->createParameter('preferred')
  1165. ]
  1166. );
  1167. foreach ($vCard->children() as $property) {
  1168. if (!in_array($property->name, self::$indexProperties)) {
  1169. continue;
  1170. }
  1171. $preferred = 0;
  1172. foreach ($property->parameters as $parameter) {
  1173. if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
  1174. $preferred = 1;
  1175. break;
  1176. }
  1177. }
  1178. $query->setParameter('name', $property->name);
  1179. $query->setParameter('value', mb_strcut($property->getValue(), 0, 254));
  1180. $query->setParameter('preferred', $preferred);
  1181. $query->execute();
  1182. }
  1183. }, $this->db);
  1184. }
  1185. /**
  1186. * read vCard data into a vCard object
  1187. *
  1188. * @param string $cardData
  1189. * @return VCard
  1190. */
  1191. protected function readCard($cardData) {
  1192. return Reader::read($cardData);
  1193. }
  1194. /**
  1195. * delete all properties from a given card
  1196. *
  1197. * @param int $addressBookId
  1198. * @param int $cardId
  1199. */
  1200. protected function purgeProperties($addressBookId, $cardId) {
  1201. $query = $this->db->getQueryBuilder();
  1202. $query->delete($this->dbCardsPropertiesTable)
  1203. ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
  1204. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1205. $query->execute();
  1206. }
  1207. /**
  1208. * Get ID from a given contact
  1209. */
  1210. protected function getCardId(int $addressBookId, string $uri): int {
  1211. $query = $this->db->getQueryBuilder();
  1212. $query->select('id')->from($this->dbCardsTable)
  1213. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  1214. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1215. $result = $query->execute();
  1216. $cardIds = $result->fetch();
  1217. $result->closeCursor();
  1218. if (!isset($cardIds['id'])) {
  1219. throw new \InvalidArgumentException('Card does not exists: ' . $uri);
  1220. }
  1221. return (int)$cardIds['id'];
  1222. }
  1223. /**
  1224. * For shared address books the sharee is set in the ACL of the address book
  1225. *
  1226. * @param int $addressBookId
  1227. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  1228. * @return list<array{privilege: string, principal: string, protected: bool}>
  1229. */
  1230. public function applyShareAcl(int $addressBookId, array $acl): array {
  1231. return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
  1232. }
  1233. /**
  1234. * @throws \InvalidArgumentException
  1235. */
  1236. public function pruneOutdatedSyncTokens(int $keep = 10_000): int {
  1237. if ($keep < 0) {
  1238. throw new \InvalidArgumentException();
  1239. }
  1240. $query = $this->db->getQueryBuilder();
  1241. $query->select($query->func()->max('id'))
  1242. ->from('addressbookchanges');
  1243. $result = $query->executeQuery();
  1244. $maxId = (int) $result->fetchOne();
  1245. $result->closeCursor();
  1246. if (!$maxId || $maxId < $keep) {
  1247. return 0;
  1248. }
  1249. $query = $this->db->getQueryBuilder();
  1250. $query->delete('addressbookchanges')
  1251. ->where($query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
  1252. return $query->executeStatement();
  1253. }
  1254. private function convertPrincipal(string $principalUri, bool $toV2): string {
  1255. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  1256. [, $name] = \Sabre\Uri\split($principalUri);
  1257. if ($toV2 === true) {
  1258. return "principals/users/$name";
  1259. }
  1260. return "principals/$name";
  1261. }
  1262. return $principalUri;
  1263. }
  1264. private function addOwnerPrincipal(array &$addressbookInfo): void {
  1265. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  1266. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  1267. if (isset($addressbookInfo[$ownerPrincipalKey])) {
  1268. $uri = $addressbookInfo[$ownerPrincipalKey];
  1269. } else {
  1270. $uri = $addressbookInfo['principaluri'];
  1271. }
  1272. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  1273. if (isset($principalInformation['{DAV:}displayname'])) {
  1274. $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  1275. }
  1276. }
  1277. /**
  1278. * Extract UID from vcard
  1279. *
  1280. * @param string $cardData the vcard raw data
  1281. * @return string the uid
  1282. * @throws BadRequest if no UID is available or vcard is empty
  1283. */
  1284. private function getUID(string $cardData): string {
  1285. if ($cardData !== '') {
  1286. $vCard = Reader::read($cardData);
  1287. if ($vCard->UID) {
  1288. $uid = $vCard->UID->getValue();
  1289. return $uid;
  1290. }
  1291. // should already be handled, but just in case
  1292. throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
  1293. }
  1294. // should already be handled, but just in case
  1295. throw new BadRequest('vCard can not be empty');
  1296. }
  1297. }