1
0

CardDavBackend.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  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->executeQuery();
  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. * @throws Exception
  306. */
  307. public function createAddressBook($principalUri, $url, array $properties) {
  308. if (strlen($url) > 255) {
  309. throw new BadRequest('URI too long. Address book not created');
  310. }
  311. $values = [
  312. 'displayname' => null,
  313. 'description' => null,
  314. 'principaluri' => $principalUri,
  315. 'uri' => $url,
  316. 'synctoken' => 1
  317. ];
  318. foreach ($properties as $property => $newValue) {
  319. switch ($property) {
  320. case '{DAV:}displayname':
  321. $values['displayname'] = $newValue;
  322. break;
  323. case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
  324. $values['description'] = $newValue;
  325. break;
  326. default:
  327. throw new BadRequest('Unknown property: ' . $property);
  328. }
  329. }
  330. // Fallback to make sure the displayname is set. Some clients may refuse
  331. // to work with addressbooks not having a displayname.
  332. if (is_null($values['displayname'])) {
  333. $values['displayname'] = $url;
  334. }
  335. [$addressBookId, $addressBookRow] = $this->atomic(function () use ($values) {
  336. $query = $this->db->getQueryBuilder();
  337. $query->insert('addressbooks')
  338. ->values([
  339. 'uri' => $query->createParameter('uri'),
  340. 'displayname' => $query->createParameter('displayname'),
  341. 'description' => $query->createParameter('description'),
  342. 'principaluri' => $query->createParameter('principaluri'),
  343. 'synctoken' => $query->createParameter('synctoken'),
  344. ])
  345. ->setParameters($values)
  346. ->executeStatement();
  347. $addressBookId = $query->getLastInsertId();
  348. return [
  349. $addressBookId,
  350. $this->getAddressBookById($addressBookId),
  351. ];
  352. }, $this->db);
  353. $this->dispatcher->dispatchTyped(new AddressBookCreatedEvent($addressBookId, $addressBookRow));
  354. return $addressBookId;
  355. }
  356. /**
  357. * Deletes an entire addressbook and all its contents
  358. *
  359. * @param mixed $addressBookId
  360. * @return void
  361. */
  362. public function deleteAddressBook($addressBookId) {
  363. $this->atomic(function () use ($addressBookId): void {
  364. $addressBookId = (int)$addressBookId;
  365. $addressBookData = $this->getAddressBookById($addressBookId);
  366. $shares = $this->getShares($addressBookId);
  367. $query = $this->db->getQueryBuilder();
  368. $query->delete($this->dbCardsTable)
  369. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  370. ->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
  371. ->executeStatement();
  372. $query = $this->db->getQueryBuilder();
  373. $query->delete('addressbookchanges')
  374. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  375. ->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
  376. ->executeStatement();
  377. $query = $this->db->getQueryBuilder();
  378. $query->delete('addressbooks')
  379. ->where($query->expr()->eq('id', $query->createParameter('id')))
  380. ->setParameter('id', $addressBookId, IQueryBuilder::PARAM_INT)
  381. ->executeStatement();
  382. $this->sharingBackend->deleteAllShares($addressBookId);
  383. $query = $this->db->getQueryBuilder();
  384. $query->delete($this->dbCardsPropertiesTable)
  385. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId, IQueryBuilder::PARAM_INT)))
  386. ->executeStatement();
  387. if ($addressBookData) {
  388. $this->dispatcher->dispatchTyped(new AddressBookDeletedEvent($addressBookId, $addressBookData, $shares));
  389. }
  390. }, $this->db);
  391. }
  392. /**
  393. * Returns all cards for a specific addressbook id.
  394. *
  395. * This method should return the following properties for each card:
  396. * * carddata - raw vcard data
  397. * * uri - Some unique url
  398. * * lastmodified - A unix timestamp
  399. *
  400. * It's recommended to also return the following properties:
  401. * * etag - A unique etag. This must change every time the card changes.
  402. * * size - The size of the card in bytes.
  403. *
  404. * If these last two properties are provided, less time will be spent
  405. * calculating them. If they are specified, you can also omit carddata.
  406. * This may speed up certain requests, especially with large cards.
  407. *
  408. * @param mixed $addressbookId
  409. * @return array
  410. */
  411. public function getCards($addressbookId) {
  412. $query = $this->db->getQueryBuilder();
  413. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
  414. ->from($this->dbCardsTable)
  415. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressbookId)));
  416. $cards = [];
  417. $result = $query->executeQuery();
  418. while ($row = $result->fetch()) {
  419. $row['etag'] = '"' . $row['etag'] . '"';
  420. $modified = false;
  421. $row['carddata'] = $this->readBlob($row['carddata'], $modified);
  422. if ($modified) {
  423. $row['size'] = strlen($row['carddata']);
  424. }
  425. $cards[] = $row;
  426. }
  427. $result->closeCursor();
  428. return $cards;
  429. }
  430. /**
  431. * Returns a specific card.
  432. *
  433. * The same set of properties must be returned as with getCards. The only
  434. * exception is that 'carddata' is absolutely required.
  435. *
  436. * If the card does not exist, you must return false.
  437. *
  438. * @param mixed $addressBookId
  439. * @param string $cardUri
  440. * @return array
  441. */
  442. public function getCard($addressBookId, $cardUri) {
  443. $query = $this->db->getQueryBuilder();
  444. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
  445. ->from($this->dbCardsTable)
  446. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  447. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  448. ->setMaxResults(1);
  449. $result = $query->executeQuery();
  450. $row = $result->fetch();
  451. if (!$row) {
  452. return false;
  453. }
  454. $row['etag'] = '"' . $row['etag'] . '"';
  455. $modified = false;
  456. $row['carddata'] = $this->readBlob($row['carddata'], $modified);
  457. if ($modified) {
  458. $row['size'] = strlen($row['carddata']);
  459. }
  460. return $row;
  461. }
  462. /**
  463. * Returns a list of cards.
  464. *
  465. * This method should work identical to getCard, but instead return all the
  466. * cards in the list as an array.
  467. *
  468. * If the backend supports this, it may allow for some speed-ups.
  469. *
  470. * @param mixed $addressBookId
  471. * @param array $uris
  472. * @return array
  473. */
  474. public function getMultipleCards($addressBookId, array $uris) {
  475. if (empty($uris)) {
  476. return [];
  477. }
  478. $chunks = array_chunk($uris, 100);
  479. $cards = [];
  480. $query = $this->db->getQueryBuilder();
  481. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
  482. ->from($this->dbCardsTable)
  483. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  484. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
  485. foreach ($chunks as $uris) {
  486. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  487. $result = $query->executeQuery();
  488. while ($row = $result->fetch()) {
  489. $row['etag'] = '"' . $row['etag'] . '"';
  490. $modified = false;
  491. $row['carddata'] = $this->readBlob($row['carddata'], $modified);
  492. if ($modified) {
  493. $row['size'] = strlen($row['carddata']);
  494. }
  495. $cards[] = $row;
  496. }
  497. $result->closeCursor();
  498. }
  499. return $cards;
  500. }
  501. /**
  502. * Creates a new card.
  503. *
  504. * The addressbook id will be passed as the first argument. This is the
  505. * same id as it is returned from the getAddressBooksForUser method.
  506. *
  507. * The cardUri is a base uri, and doesn't include the full path. The
  508. * cardData argument is the vcard body, and is passed as a string.
  509. *
  510. * It is possible to return an ETag from this method. This ETag is for the
  511. * newly created resource, and must be enclosed with double quotes (that
  512. * is, the string itself must contain the double quotes).
  513. *
  514. * You should only return the ETag if you store the carddata as-is. If a
  515. * subsequent GET request on the same card does not have the same body,
  516. * byte-by-byte and you did return an ETag here, clients tend to get
  517. * confused.
  518. *
  519. * If you don't return an ETag, you can just return null.
  520. *
  521. * @param mixed $addressBookId
  522. * @param string $cardUri
  523. * @param string $cardData
  524. * @param bool $checkAlreadyExists
  525. * @return string
  526. */
  527. public function createCard($addressBookId, $cardUri, $cardData, bool $checkAlreadyExists = true) {
  528. $etag = md5($cardData);
  529. $uid = $this->getUID($cardData);
  530. return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $checkAlreadyExists, $etag, $uid) {
  531. if ($checkAlreadyExists) {
  532. $q = $this->db->getQueryBuilder();
  533. $q->select('uid')
  534. ->from($this->dbCardsTable)
  535. ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
  536. ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
  537. ->setMaxResults(1);
  538. $result = $q->executeQuery();
  539. $count = (bool)$result->fetchOne();
  540. $result->closeCursor();
  541. if ($count) {
  542. throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
  543. }
  544. }
  545. $query = $this->db->getQueryBuilder();
  546. $query->insert('cards')
  547. ->values([
  548. 'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
  549. 'uri' => $query->createNamedParameter($cardUri),
  550. 'lastmodified' => $query->createNamedParameter(time()),
  551. 'addressbookid' => $query->createNamedParameter($addressBookId),
  552. 'size' => $query->createNamedParameter(strlen($cardData)),
  553. 'etag' => $query->createNamedParameter($etag),
  554. 'uid' => $query->createNamedParameter($uid),
  555. ])
  556. ->executeStatement();
  557. $etagCacheKey = "$addressBookId#$cardUri";
  558. $this->etagCache[$etagCacheKey] = $etag;
  559. $this->addChange($addressBookId, $cardUri, 1);
  560. $this->updateProperties($addressBookId, $cardUri, $cardData);
  561. $addressBookData = $this->getAddressBookById($addressBookId);
  562. $shares = $this->getShares($addressBookId);
  563. $objectRow = $this->getCard($addressBookId, $cardUri);
  564. $this->dispatcher->dispatchTyped(new CardCreatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
  565. return '"' . $etag . '"';
  566. }, $this->db);
  567. }
  568. /**
  569. * Updates a card.
  570. *
  571. * The addressbook id will be passed as the first argument. This is the
  572. * same id as it is returned from the getAddressBooksForUser method.
  573. *
  574. * The cardUri is a base uri, and doesn't include the full path. The
  575. * cardData argument is the vcard body, and is passed as a string.
  576. *
  577. * It is possible to return an ETag from this method. This ETag should
  578. * match that of the updated resource, and must be enclosed with double
  579. * quotes (that is: the string itself must contain the actual quotes).
  580. *
  581. * You should only return the ETag if you store the carddata as-is. If a
  582. * subsequent GET request on the same card does not have the same body,
  583. * byte-by-byte and you did return an ETag here, clients tend to get
  584. * confused.
  585. *
  586. * If you don't return an ETag, you can just return null.
  587. *
  588. * @param mixed $addressBookId
  589. * @param string $cardUri
  590. * @param string $cardData
  591. * @return string
  592. */
  593. public function updateCard($addressBookId, $cardUri, $cardData) {
  594. $uid = $this->getUID($cardData);
  595. $etag = md5($cardData);
  596. return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $uid, $etag) {
  597. $query = $this->db->getQueryBuilder();
  598. // check for recently stored etag and stop if it is the same
  599. $etagCacheKey = "$addressBookId#$cardUri";
  600. if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
  601. return '"' . $etag . '"';
  602. }
  603. $query->update($this->dbCardsTable)
  604. ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
  605. ->set('lastmodified', $query->createNamedParameter(time()))
  606. ->set('size', $query->createNamedParameter(strlen($cardData)))
  607. ->set('etag', $query->createNamedParameter($etag))
  608. ->set('uid', $query->createNamedParameter($uid))
  609. ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  610. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  611. ->executeStatement();
  612. $this->etagCache[$etagCacheKey] = $etag;
  613. $this->addChange($addressBookId, $cardUri, 2);
  614. $this->updateProperties($addressBookId, $cardUri, $cardData);
  615. $addressBookData = $this->getAddressBookById($addressBookId);
  616. $shares = $this->getShares($addressBookId);
  617. $objectRow = $this->getCard($addressBookId, $cardUri);
  618. $this->dispatcher->dispatchTyped(new CardUpdatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
  619. return '"' . $etag . '"';
  620. }, $this->db);
  621. }
  622. /**
  623. * @throws Exception
  624. */
  625. public function moveCard(int $sourceAddressBookId, int $targetAddressBookId, string $cardUri, string $oldPrincipalUri): bool {
  626. return $this->atomic(function () use ($sourceAddressBookId, $targetAddressBookId, $cardUri, $oldPrincipalUri) {
  627. $card = $this->getCard($sourceAddressBookId, $cardUri);
  628. if (empty($card)) {
  629. return false;
  630. }
  631. $query = $this->db->getQueryBuilder();
  632. $query->update('cards')
  633. ->set('addressbookid', $query->createNamedParameter($targetAddressBookId, IQueryBuilder::PARAM_INT))
  634. ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
  635. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($sourceAddressBookId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
  636. ->executeStatement();
  637. $this->purgeProperties($sourceAddressBookId, (int)$card['id']);
  638. $this->updateProperties($sourceAddressBookId, $card['uri'], $card['carddata']);
  639. $this->addChange($sourceAddressBookId, $card['uri'], 3);
  640. $this->addChange($targetAddressBookId, $card['uri'], 1);
  641. $card = $this->getCard($targetAddressBookId, $cardUri);
  642. // Card wasn't found - possibly because it was deleted in the meantime by a different client
  643. if (empty($card)) {
  644. return false;
  645. }
  646. $targetAddressBookRow = $this->getAddressBookById($targetAddressBookId);
  647. // the address book this card is being moved to does not exist any longer
  648. if (empty($targetAddressBookRow)) {
  649. return false;
  650. }
  651. $sourceShares = $this->getShares($sourceAddressBookId);
  652. $targetShares = $this->getShares($targetAddressBookId);
  653. $sourceAddressBookRow = $this->getAddressBookById($sourceAddressBookId);
  654. $this->dispatcher->dispatchTyped(new CardMovedEvent($sourceAddressBookId, $sourceAddressBookRow, $targetAddressBookId, $targetAddressBookRow, $sourceShares, $targetShares, $card));
  655. return true;
  656. }, $this->db);
  657. }
  658. /**
  659. * Deletes a card
  660. *
  661. * @param mixed $addressBookId
  662. * @param string $cardUri
  663. * @return bool
  664. */
  665. public function deleteCard($addressBookId, $cardUri) {
  666. return $this->atomic(function () use ($addressBookId, $cardUri) {
  667. $addressBookData = $this->getAddressBookById($addressBookId);
  668. $shares = $this->getShares($addressBookId);
  669. $objectRow = $this->getCard($addressBookId, $cardUri);
  670. try {
  671. $cardId = $this->getCardId($addressBookId, $cardUri);
  672. } catch (\InvalidArgumentException $e) {
  673. $cardId = null;
  674. }
  675. $query = $this->db->getQueryBuilder();
  676. $ret = $query->delete($this->dbCardsTable)
  677. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  678. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  679. ->executeStatement();
  680. $this->addChange($addressBookId, $cardUri, 3);
  681. if ($ret === 1) {
  682. if ($cardId !== null) {
  683. $this->dispatcher->dispatchTyped(new CardDeletedEvent($addressBookId, $addressBookData, $shares, $objectRow));
  684. $this->purgeProperties($addressBookId, $cardId);
  685. }
  686. return true;
  687. }
  688. return false;
  689. }, $this->db);
  690. }
  691. /**
  692. * The getChanges method returns all the changes that have happened, since
  693. * the specified syncToken in the specified address book.
  694. *
  695. * This function should return an array, such as the following:
  696. *
  697. * [
  698. * 'syncToken' => 'The current synctoken',
  699. * 'added' => [
  700. * 'new.txt',
  701. * ],
  702. * 'modified' => [
  703. * 'modified.txt',
  704. * ],
  705. * 'deleted' => [
  706. * 'foo.php.bak',
  707. * 'old.txt'
  708. * ]
  709. * ];
  710. *
  711. * The returned syncToken property should reflect the *current* syncToken
  712. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  713. * property. This is needed here too, to ensure the operation is atomic.
  714. *
  715. * If the $syncToken argument is specified as null, this is an initial
  716. * sync, and all members should be reported.
  717. *
  718. * The modified property is an array of nodenames that have changed since
  719. * the last token.
  720. *
  721. * The deleted property is an array with nodenames, that have been deleted
  722. * from collection.
  723. *
  724. * The $syncLevel argument is basically the 'depth' of the report. If it's
  725. * 1, you only have to report changes that happened only directly in
  726. * immediate descendants. If it's 2, it should also include changes from
  727. * the nodes below the child collections. (grandchildren)
  728. *
  729. * The $limit argument allows a client to specify how many results should
  730. * be returned at most. If the limit is not specified, it should be treated
  731. * as infinite.
  732. *
  733. * If the limit (infinite or not) is higher than you're willing to return,
  734. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  735. *
  736. * If the syncToken is expired (due to data cleanup) or unknown, you must
  737. * return null.
  738. *
  739. * The limit is 'suggestive'. You are free to ignore it.
  740. *
  741. * @param string $addressBookId
  742. * @param string $syncToken
  743. * @param int $syncLevel
  744. * @param int|null $limit
  745. * @return array
  746. */
  747. public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
  748. // Current synctoken
  749. return $this->atomic(function () use ($addressBookId, $syncToken, $syncLevel, $limit) {
  750. $qb = $this->db->getQueryBuilder();
  751. $qb->select('synctoken')
  752. ->from('addressbooks')
  753. ->where(
  754. $qb->expr()->eq('id', $qb->createNamedParameter($addressBookId))
  755. );
  756. $stmt = $qb->executeQuery();
  757. $currentToken = $stmt->fetchOne();
  758. $stmt->closeCursor();
  759. if (is_null($currentToken)) {
  760. return [];
  761. }
  762. $result = [
  763. 'syncToken' => $currentToken,
  764. 'added' => [],
  765. 'modified' => [],
  766. 'deleted' => [],
  767. ];
  768. if ($syncToken) {
  769. $qb = $this->db->getQueryBuilder();
  770. $qb->select('uri', 'operation')
  771. ->from('addressbookchanges')
  772. ->where(
  773. $qb->expr()->andX(
  774. $qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
  775. $qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
  776. $qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
  777. )
  778. )->orderBy('synctoken');
  779. if (is_int($limit) && $limit > 0) {
  780. $qb->setMaxResults($limit);
  781. }
  782. // Fetching all changes
  783. $stmt = $qb->executeQuery();
  784. $changes = [];
  785. // This loop ensures that any duplicates are overwritten, only the
  786. // last change on a node is relevant.
  787. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  788. $changes[$row['uri']] = $row['operation'];
  789. }
  790. $stmt->closeCursor();
  791. foreach ($changes as $uri => $operation) {
  792. switch ($operation) {
  793. case 1:
  794. $result['added'][] = $uri;
  795. break;
  796. case 2:
  797. $result['modified'][] = $uri;
  798. break;
  799. case 3:
  800. $result['deleted'][] = $uri;
  801. break;
  802. }
  803. }
  804. } else {
  805. $qb = $this->db->getQueryBuilder();
  806. $qb->select('uri')
  807. ->from('cards')
  808. ->where(
  809. $qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
  810. );
  811. // No synctoken supplied, this is the initial sync.
  812. $stmt = $qb->executeQuery();
  813. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  814. $stmt->closeCursor();
  815. }
  816. return $result;
  817. }, $this->db);
  818. }
  819. /**
  820. * Adds a change record to the addressbookchanges table.
  821. *
  822. * @param mixed $addressBookId
  823. * @param string $objectUri
  824. * @param int $operation 1 = add, 2 = modify, 3 = delete
  825. * @return void
  826. */
  827. protected function addChange(int $addressBookId, string $objectUri, int $operation): void {
  828. $this->atomic(function () use ($addressBookId, $objectUri, $operation): void {
  829. $query = $this->db->getQueryBuilder();
  830. $query->select('synctoken')
  831. ->from('addressbooks')
  832. ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)));
  833. $result = $query->executeQuery();
  834. $syncToken = (int)$result->fetchOne();
  835. $result->closeCursor();
  836. $query = $this->db->getQueryBuilder();
  837. $query->insert('addressbookchanges')
  838. ->values([
  839. 'uri' => $query->createNamedParameter($objectUri),
  840. 'synctoken' => $query->createNamedParameter($syncToken),
  841. 'addressbookid' => $query->createNamedParameter($addressBookId),
  842. 'operation' => $query->createNamedParameter($operation),
  843. 'created_at' => time(),
  844. ])
  845. ->executeStatement();
  846. $query = $this->db->getQueryBuilder();
  847. $query->update('addressbooks')
  848. ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
  849. ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
  850. ->executeStatement();
  851. }, $this->db);
  852. }
  853. /**
  854. * @param resource|string $cardData
  855. * @param bool $modified
  856. * @return string
  857. */
  858. private function readBlob($cardData, &$modified = false) {
  859. if (is_resource($cardData)) {
  860. $cardData = stream_get_contents($cardData);
  861. }
  862. // Micro optimisation
  863. // don't loop through
  864. if (str_starts_with($cardData, 'PHOTO:data:')) {
  865. return $cardData;
  866. }
  867. $cardDataArray = explode("\r\n", $cardData);
  868. $cardDataFiltered = [];
  869. $removingPhoto = false;
  870. foreach ($cardDataArray as $line) {
  871. if (str_starts_with($line, 'PHOTO:data:')
  872. && !str_starts_with($line, 'PHOTO:data:image/')) {
  873. // Filter out PHOTO data of non-images
  874. $removingPhoto = true;
  875. $modified = true;
  876. continue;
  877. }
  878. if ($removingPhoto) {
  879. if (str_starts_with($line, ' ')) {
  880. continue;
  881. }
  882. // No leading space means this is a new property
  883. $removingPhoto = false;
  884. }
  885. $cardDataFiltered[] = $line;
  886. }
  887. return implode("\r\n", $cardDataFiltered);
  888. }
  889. /**
  890. * @param list<array{href: string, commonName: string, readOnly: bool}> $add
  891. * @param list<string> $remove
  892. */
  893. public function updateShares(IShareable $shareable, array $add, array $remove): void {
  894. $this->atomic(function () use ($shareable, $add, $remove): void {
  895. $addressBookId = $shareable->getResourceId();
  896. $addressBookData = $this->getAddressBookById($addressBookId);
  897. $oldShares = $this->getShares($addressBookId);
  898. $this->sharingBackend->updateShares($shareable, $add, $remove, $oldShares);
  899. $this->dispatcher->dispatchTyped(new AddressBookShareUpdatedEvent($addressBookId, $addressBookData, $oldShares, $add, $remove));
  900. }, $this->db);
  901. }
  902. /**
  903. * Search contacts in a specific address-book
  904. *
  905. * @param int $addressBookId
  906. * @param string $pattern which should match within the $searchProperties
  907. * @param array $searchProperties defines the properties within the query pattern should match
  908. * @param array $options = array() to define the search behavior
  909. * - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
  910. * - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
  911. * - 'limit' - Set a numeric limit for the search results
  912. * - 'offset' - Set the offset for the limited search results
  913. * - 'wildcard' - Whether the search should use wildcards
  914. * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options
  915. * @return array an array of contacts which are arrays of key-value-pairs
  916. */
  917. public function search($addressBookId, $pattern, $searchProperties, $options = []): array {
  918. return $this->atomic(function () use ($addressBookId, $pattern, $searchProperties, $options) {
  919. return $this->searchByAddressBookIds([$addressBookId], $pattern, $searchProperties, $options);
  920. }, $this->db);
  921. }
  922. /**
  923. * Search contacts in all address-books accessible by a user
  924. *
  925. * @param string $principalUri
  926. * @param string $pattern
  927. * @param array $searchProperties
  928. * @param array $options
  929. * @return array
  930. */
  931. public function searchPrincipalUri(string $principalUri,
  932. string $pattern,
  933. array $searchProperties,
  934. array $options = []): array {
  935. return $this->atomic(function () use ($principalUri, $pattern, $searchProperties, $options) {
  936. $addressBookIds = array_map(static function ($row):int {
  937. return (int)$row['id'];
  938. }, $this->getAddressBooksForUser($principalUri));
  939. return $this->searchByAddressBookIds($addressBookIds, $pattern, $searchProperties, $options);
  940. }, $this->db);
  941. }
  942. /**
  943. * @param int[] $addressBookIds
  944. * @param string $pattern
  945. * @param array $searchProperties
  946. * @param array $options
  947. * @psalm-param array{
  948. * types?: bool,
  949. * escape_like_param?: bool,
  950. * limit?: int,
  951. * offset?: int,
  952. * wildcard?: bool,
  953. * since?: DateTimeFilter|null,
  954. * until?: DateTimeFilter|null,
  955. * person?: string
  956. * } $options
  957. * @return array
  958. */
  959. private function searchByAddressBookIds(array $addressBookIds,
  960. string $pattern,
  961. array $searchProperties,
  962. array $options = []): array {
  963. if (empty($addressBookIds)) {
  964. return [];
  965. }
  966. $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
  967. $useWildcards = !\array_key_exists('wildcard', $options) || $options['wildcard'] !== false;
  968. if ($escapePattern) {
  969. $searchProperties = array_filter($searchProperties, function ($property) use ($pattern) {
  970. if ($property === 'EMAIL' && str_contains($pattern, ' ')) {
  971. // There can be no spaces in emails
  972. return false;
  973. }
  974. if ($property === 'CLOUD' && preg_match('/[^a-zA-Z0-9 :_.@\/\-\']/', $pattern) === 1) {
  975. // There can be no chars in cloud ids which are not valid for user ids plus :/
  976. // worst case: CA61590A-BBBC-423E-84AF-E6DF01455A53@https://my.nxt/srv/
  977. return false;
  978. }
  979. return true;
  980. });
  981. }
  982. if (empty($searchProperties)) {
  983. return [];
  984. }
  985. $query2 = $this->db->getQueryBuilder();
  986. $query2->selectDistinct('cp.cardid')
  987. ->from($this->dbCardsPropertiesTable, 'cp')
  988. ->where($query2->expr()->in('cp.addressbookid', $query2->createNamedParameter($addressBookIds, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
  989. ->andWhere($query2->expr()->in('cp.name', $query2->createNamedParameter($searchProperties, IQueryBuilder::PARAM_STR_ARRAY)));
  990. // No need for like when the pattern is empty
  991. if ($pattern !== '') {
  992. if (!$useWildcards) {
  993. $query2->andWhere($query2->expr()->eq('cp.value', $query2->createNamedParameter($pattern)));
  994. } elseif (!$escapePattern) {
  995. $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
  996. } else {
  997. $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
  998. }
  999. }
  1000. if (isset($options['limit'])) {
  1001. $query2->setMaxResults($options['limit']);
  1002. }
  1003. if (isset($options['offset'])) {
  1004. $query2->setFirstResult($options['offset']);
  1005. }
  1006. if (isset($options['person'])) {
  1007. $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($options['person']) . '%')));
  1008. }
  1009. if (isset($options['since']) || isset($options['until'])) {
  1010. $query2->join('cp', $this->dbCardsPropertiesTable, 'cp_bday', 'cp.cardid = cp_bday.cardid');
  1011. $query2->andWhere($query2->expr()->eq('cp_bday.name', $query2->createNamedParameter('BDAY')));
  1012. /**
  1013. * FIXME Find a way to match only 4 last digits
  1014. * BDAY can be --1018 without year or 20001019 with it
  1015. * $bDayOr = [];
  1016. * if ($options['since'] instanceof DateTimeFilter) {
  1017. * $bDayOr[] =
  1018. * $query2->expr()->gte('SUBSTR(cp_bday.value, -4)',
  1019. * $query2->createNamedParameter($options['since']->get()->format('md'))
  1020. * );
  1021. * }
  1022. * if ($options['until'] instanceof DateTimeFilter) {
  1023. * $bDayOr[] =
  1024. * $query2->expr()->lte('SUBSTR(cp_bday.value, -4)',
  1025. * $query2->createNamedParameter($options['until']->get()->format('md'))
  1026. * );
  1027. * }
  1028. * $query2->andWhere($query2->expr()->orX(...$bDayOr));
  1029. */
  1030. }
  1031. $result = $query2->executeQuery();
  1032. $matches = $result->fetchAll();
  1033. $result->closeCursor();
  1034. $matches = array_map(function ($match) {
  1035. return (int)$match['cardid'];
  1036. }, $matches);
  1037. $cards = [];
  1038. $query = $this->db->getQueryBuilder();
  1039. $query->select('c.addressbookid', 'c.carddata', 'c.uri')
  1040. ->from($this->dbCardsTable, 'c')
  1041. ->where($query->expr()->in('c.id', $query->createParameter('matches')));
  1042. foreach (array_chunk($matches, 1000) as $matchesChunk) {
  1043. $query->setParameter('matches', $matchesChunk, IQueryBuilder::PARAM_INT_ARRAY);
  1044. $result = $query->executeQuery();
  1045. $cards = array_merge($cards, $result->fetchAll());
  1046. $result->closeCursor();
  1047. }
  1048. return array_map(function ($array) {
  1049. $array['addressbookid'] = (int)$array['addressbookid'];
  1050. $modified = false;
  1051. $array['carddata'] = $this->readBlob($array['carddata'], $modified);
  1052. if ($modified) {
  1053. $array['size'] = strlen($array['carddata']);
  1054. }
  1055. return $array;
  1056. }, $cards);
  1057. }
  1058. /**
  1059. * @param int $bookId
  1060. * @param string $name
  1061. * @return array
  1062. */
  1063. public function collectCardProperties($bookId, $name) {
  1064. $query = $this->db->getQueryBuilder();
  1065. $result = $query->selectDistinct('value')
  1066. ->from($this->dbCardsPropertiesTable)
  1067. ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
  1068. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
  1069. ->executeQuery();
  1070. $all = $result->fetchAll(PDO::FETCH_COLUMN);
  1071. $result->closeCursor();
  1072. return $all;
  1073. }
  1074. /**
  1075. * get URI from a given contact
  1076. *
  1077. * @param int $id
  1078. * @return string
  1079. */
  1080. public function getCardUri($id) {
  1081. $query = $this->db->getQueryBuilder();
  1082. $query->select('uri')->from($this->dbCardsTable)
  1083. ->where($query->expr()->eq('id', $query->createParameter('id')))
  1084. ->setParameter('id', $id);
  1085. $result = $query->executeQuery();
  1086. $uri = $result->fetch();
  1087. $result->closeCursor();
  1088. if (!isset($uri['uri'])) {
  1089. throw new \InvalidArgumentException('Card does not exists: ' . $id);
  1090. }
  1091. return $uri['uri'];
  1092. }
  1093. /**
  1094. * return contact with the given URI
  1095. *
  1096. * @param int $addressBookId
  1097. * @param string $uri
  1098. * @returns array
  1099. */
  1100. public function getContact($addressBookId, $uri) {
  1101. $result = [];
  1102. $query = $this->db->getQueryBuilder();
  1103. $query->select('*')->from($this->dbCardsTable)
  1104. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  1105. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1106. $queryResult = $query->executeQuery();
  1107. $contact = $queryResult->fetch();
  1108. $queryResult->closeCursor();
  1109. if (is_array($contact)) {
  1110. $modified = false;
  1111. $contact['etag'] = '"' . $contact['etag'] . '"';
  1112. $contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
  1113. if ($modified) {
  1114. $contact['size'] = strlen($contact['carddata']);
  1115. }
  1116. $result = $contact;
  1117. }
  1118. return $result;
  1119. }
  1120. /**
  1121. * Returns the list of people whom this address book is shared with.
  1122. *
  1123. * Every element in this array should have the following properties:
  1124. * * href - Often a mailto: address
  1125. * * commonName - Optional, for example a first + last name
  1126. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  1127. * * readOnly - boolean
  1128. *
  1129. * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
  1130. */
  1131. public function getShares(int $addressBookId): array {
  1132. return $this->sharingBackend->getShares($addressBookId);
  1133. }
  1134. /**
  1135. * update properties table
  1136. *
  1137. * @param int $addressBookId
  1138. * @param string $cardUri
  1139. * @param string $vCardSerialized
  1140. */
  1141. protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
  1142. $this->atomic(function () use ($addressBookId, $cardUri, $vCardSerialized): void {
  1143. $cardId = $this->getCardId($addressBookId, $cardUri);
  1144. $vCard = $this->readCard($vCardSerialized);
  1145. $this->purgeProperties($addressBookId, $cardId);
  1146. $query = $this->db->getQueryBuilder();
  1147. $query->insert($this->dbCardsPropertiesTable)
  1148. ->values(
  1149. [
  1150. 'addressbookid' => $query->createNamedParameter($addressBookId),
  1151. 'cardid' => $query->createNamedParameter($cardId),
  1152. 'name' => $query->createParameter('name'),
  1153. 'value' => $query->createParameter('value'),
  1154. 'preferred' => $query->createParameter('preferred')
  1155. ]
  1156. );
  1157. foreach ($vCard->children() as $property) {
  1158. if (!in_array($property->name, self::$indexProperties)) {
  1159. continue;
  1160. }
  1161. $preferred = 0;
  1162. foreach ($property->parameters as $parameter) {
  1163. if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
  1164. $preferred = 1;
  1165. break;
  1166. }
  1167. }
  1168. $query->setParameter('name', $property->name);
  1169. $query->setParameter('value', mb_strcut($property->getValue(), 0, 254));
  1170. $query->setParameter('preferred', $preferred);
  1171. $query->executeStatement();
  1172. }
  1173. }, $this->db);
  1174. }
  1175. /**
  1176. * read vCard data into a vCard object
  1177. *
  1178. * @param string $cardData
  1179. * @return VCard
  1180. */
  1181. protected function readCard($cardData) {
  1182. return Reader::read($cardData);
  1183. }
  1184. /**
  1185. * delete all properties from a given card
  1186. *
  1187. * @param int $addressBookId
  1188. * @param int $cardId
  1189. */
  1190. protected function purgeProperties($addressBookId, $cardId) {
  1191. $query = $this->db->getQueryBuilder();
  1192. $query->delete($this->dbCardsPropertiesTable)
  1193. ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
  1194. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1195. $query->executeStatement();
  1196. }
  1197. /**
  1198. * Get ID from a given contact
  1199. */
  1200. protected function getCardId(int $addressBookId, string $uri): int {
  1201. $query = $this->db->getQueryBuilder();
  1202. $query->select('id')->from($this->dbCardsTable)
  1203. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  1204. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1205. $result = $query->executeQuery();
  1206. $cardIds = $result->fetch();
  1207. $result->closeCursor();
  1208. if (!isset($cardIds['id'])) {
  1209. throw new \InvalidArgumentException('Card does not exists: ' . $uri);
  1210. }
  1211. return (int)$cardIds['id'];
  1212. }
  1213. /**
  1214. * For shared address books the sharee is set in the ACL of the address book
  1215. *
  1216. * @param int $addressBookId
  1217. * @param list<array{privilege: string, principal: string, protected: bool}> $acl
  1218. * @return list<array{privilege: string, principal: string, protected: bool}>
  1219. */
  1220. public function applyShareAcl(int $addressBookId, array $acl): array {
  1221. $shares = $this->sharingBackend->getShares($addressBookId);
  1222. return $this->sharingBackend->applyShareAcl($shares, $acl);
  1223. }
  1224. /**
  1225. * @throws \InvalidArgumentException
  1226. */
  1227. public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
  1228. if ($keep < 0) {
  1229. throw new \InvalidArgumentException();
  1230. }
  1231. $query = $this->db->getQueryBuilder();
  1232. $query->select($query->func()->max('id'))
  1233. ->from('addressbookchanges');
  1234. $result = $query->executeQuery();
  1235. $maxId = (int)$result->fetchOne();
  1236. $result->closeCursor();
  1237. if (!$maxId || $maxId < $keep) {
  1238. return 0;
  1239. }
  1240. $query = $this->db->getQueryBuilder();
  1241. $query->delete('addressbookchanges')
  1242. ->where(
  1243. $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
  1244. $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
  1245. );
  1246. return $query->executeStatement();
  1247. }
  1248. private function convertPrincipal(string $principalUri, bool $toV2): string {
  1249. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  1250. [, $name] = \Sabre\Uri\split($principalUri);
  1251. if ($toV2 === true) {
  1252. return "principals/users/$name";
  1253. }
  1254. return "principals/$name";
  1255. }
  1256. return $principalUri;
  1257. }
  1258. private function addOwnerPrincipal(array &$addressbookInfo): void {
  1259. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  1260. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  1261. if (isset($addressbookInfo[$ownerPrincipalKey])) {
  1262. $uri = $addressbookInfo[$ownerPrincipalKey];
  1263. } else {
  1264. $uri = $addressbookInfo['principaluri'];
  1265. }
  1266. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  1267. if (isset($principalInformation['{DAV:}displayname'])) {
  1268. $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  1269. }
  1270. }
  1271. /**
  1272. * Extract UID from vcard
  1273. *
  1274. * @param string $cardData the vcard raw data
  1275. * @return string the uid
  1276. * @throws BadRequest if no UID is available or vcard is empty
  1277. */
  1278. private function getUID(string $cardData): string {
  1279. if ($cardData !== '') {
  1280. $vCard = Reader::read($cardData);
  1281. if ($vCard->UID) {
  1282. $uid = $vCard->UID->getValue();
  1283. return $uid;
  1284. }
  1285. // should already be handled, but just in case
  1286. throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
  1287. }
  1288. // should already be handled, but just in case
  1289. throw new BadRequest('vCard can not be empty');
  1290. }
  1291. }