CardDavBackend.php 48 KB

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