1
0

CardDavBackend.php 49 KB

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