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

CardDavBackend.php 50KB

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