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

CardDavBackend.php 44KB

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