CardDavBackend.php 50 KB

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