CardDavBackend.php 45 KB

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