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 43KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  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 Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Georg Ehrke <oc.list@georgehrke.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Robin Appelman <robin@icewind.nl>
  14. * @author Roeland Jago Douma <roeland@famdouma.nl>
  15. * @author Stefan Weil <sw@weilnetz.de>
  16. * @author Thomas Citharel <nextcloud@tcit.fr>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OCA\DAV\CardDAV;
  35. use OCA\DAV\Connector\Sabre\Principal;
  36. use OCA\DAV\DAV\Sharing\Backend;
  37. use OCA\DAV\DAV\Sharing\IShareable;
  38. use OCA\DAV\Events\AddressBookCreatedEvent;
  39. use OCA\DAV\Events\AddressBookDeletedEvent;
  40. use OCA\DAV\Events\AddressBookShareUpdatedEvent;
  41. use OCA\DAV\Events\AddressBookUpdatedEvent;
  42. use OCA\DAV\Events\CardCreatedEvent;
  43. use OCA\DAV\Events\CardDeletedEvent;
  44. use OCA\DAV\Events\CardUpdatedEvent;
  45. use OCP\DB\QueryBuilder\IQueryBuilder;
  46. use OCP\EventDispatcher\IEventDispatcher;
  47. use OCP\IDBConnection;
  48. use OCP\IGroupManager;
  49. use OCP\IUser;
  50. use OCP\IUserManager;
  51. use PDO;
  52. use Sabre\CardDAV\Backend\BackendInterface;
  53. use Sabre\CardDAV\Backend\SyncSupport;
  54. use Sabre\CardDAV\Plugin;
  55. use Sabre\DAV\Exception\BadRequest;
  56. use Sabre\VObject\Component\VCard;
  57. use Sabre\VObject\Reader;
  58. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  59. use Symfony\Component\EventDispatcher\GenericEvent;
  60. class CardDavBackend implements BackendInterface, SyncSupport {
  61. public const PERSONAL_ADDRESSBOOK_URI = 'contacts';
  62. public const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
  63. /** @var Principal */
  64. private $principalBackend;
  65. /** @var string */
  66. private $dbCardsTable = 'cards';
  67. /** @var string */
  68. private $dbCardsPropertiesTable = 'cards_properties';
  69. /** @var IDBConnection */
  70. private $db;
  71. /** @var Backend */
  72. private $sharingBackend;
  73. /** @var array properties to index */
  74. public static $indexProperties = [
  75. 'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
  76. 'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD'];
  77. /**
  78. * @var string[] Map of uid => display name
  79. */
  80. protected $userDisplayNames;
  81. /** @var IUserManager */
  82. private $userManager;
  83. /** @var IEventDispatcher */
  84. private $dispatcher;
  85. /** @var EventDispatcherInterface */
  86. private $legacyDispatcher;
  87. private $etagCache = [];
  88. /**
  89. * CardDavBackend constructor.
  90. *
  91. * @param IDBConnection $db
  92. * @param Principal $principalBackend
  93. * @param IUserManager $userManager
  94. * @param IGroupManager $groupManager
  95. * @param IEventDispatcher $dispatcher
  96. * @param EventDispatcherInterface $legacyDispatcher
  97. */
  98. public function __construct(IDBConnection $db,
  99. Principal $principalBackend,
  100. IUserManager $userManager,
  101. IGroupManager $groupManager,
  102. IEventDispatcher $dispatcher,
  103. EventDispatcherInterface $legacyDispatcher) {
  104. $this->db = $db;
  105. $this->principalBackend = $principalBackend;
  106. $this->userManager = $userManager;
  107. $this->dispatcher = $dispatcher;
  108. $this->legacyDispatcher = $legacyDispatcher;
  109. $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
  110. }
  111. /**
  112. * Return the number of address books for a principal
  113. *
  114. * @param $principalUri
  115. * @return int
  116. */
  117. public function getAddressBooksForUserCount($principalUri) {
  118. $principalUri = $this->convertPrincipal($principalUri, true);
  119. $query = $this->db->getQueryBuilder();
  120. $query->select($query->func()->count('*'))
  121. ->from('addressbooks')
  122. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  123. $result = $query->execute();
  124. $column = (int) $result->fetchColumn();
  125. $result->closeCursor();
  126. return $column;
  127. }
  128. /**
  129. * Returns the list of address books for a specific user.
  130. *
  131. * Every addressbook should have the following properties:
  132. * id - an arbitrary unique id
  133. * uri - the 'basename' part of the url
  134. * principaluri - Same as the passed parameter
  135. *
  136. * Any additional clark-notation property may be passed besides this. Some
  137. * common ones are :
  138. * {DAV:}displayname
  139. * {urn:ietf:params:xml:ns:carddav}addressbook-description
  140. * {http://calendarserver.org/ns/}getctag
  141. *
  142. * @param string $principalUri
  143. * @return array
  144. */
  145. public function getAddressBooksForUser($principalUri) {
  146. $principalUriOriginal = $principalUri;
  147. $principalUri = $this->convertPrincipal($principalUri, true);
  148. $query = $this->db->getQueryBuilder();
  149. $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  150. ->from('addressbooks')
  151. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  152. $addressBooks = [];
  153. $result = $query->execute();
  154. while ($row = $result->fetch()) {
  155. $addressBooks[$row['id']] = [
  156. 'id' => $row['id'],
  157. 'uri' => $row['uri'],
  158. 'principaluri' => $this->convertPrincipal($row['principaluri'], false),
  159. '{DAV:}displayname' => $row['displayname'],
  160. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  161. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  162. '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
  163. ];
  164. $this->addOwnerPrincipal($addressBooks[$row['id']]);
  165. }
  166. $result->closeCursor();
  167. // query for shared addressbooks
  168. $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
  169. $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
  170. $principals = array_map(function ($principal) {
  171. return urldecode($principal);
  172. }, $principals);
  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. list(, $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($addressBookId) {
  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)))
  261. ->execute();
  262. $row = $result->fetch();
  263. $result->closeCursor();
  264. if ($row === false) {
  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((int)$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((int) $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 string[] $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. * @return string
  568. */
  569. public function createCard($addressBookId, $cardUri, $cardData) {
  570. $etag = md5($cardData);
  571. $uid = $this->getUID($cardData);
  572. $q = $this->db->getQueryBuilder();
  573. $q->select('uid')
  574. ->from($this->dbCardsTable)
  575. ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
  576. ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
  577. ->setMaxResults(1);
  578. $result = $q->execute();
  579. $count = (bool)$result->fetchColumn();
  580. $result->closeCursor();
  581. if ($count) {
  582. throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
  583. }
  584. $query = $this->db->getQueryBuilder();
  585. $query->insert('cards')
  586. ->values([
  587. 'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
  588. 'uri' => $query->createNamedParameter($cardUri),
  589. 'lastmodified' => $query->createNamedParameter(time()),
  590. 'addressbookid' => $query->createNamedParameter($addressBookId),
  591. 'size' => $query->createNamedParameter(strlen($cardData)),
  592. 'etag' => $query->createNamedParameter($etag),
  593. 'uid' => $query->createNamedParameter($uid),
  594. ])
  595. ->execute();
  596. $etagCacheKey = "$addressBookId#$cardUri";
  597. $this->etagCache[$etagCacheKey] = $etag;
  598. $this->addChange($addressBookId, $cardUri, 1);
  599. $this->updateProperties($addressBookId, $cardUri, $cardData);
  600. $addressBookData = $this->getAddressBookById($addressBookId);
  601. $shares = $this->getShares($addressBookId);
  602. $objectRow = $this->getCard($addressBookId, $cardUri);
  603. $this->dispatcher->dispatchTyped(new CardCreatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
  604. $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
  605. new GenericEvent(null, [
  606. 'addressBookId' => $addressBookId,
  607. 'cardUri' => $cardUri,
  608. 'cardData' => $cardData]));
  609. return '"' . $etag . '"';
  610. }
  611. /**
  612. * Updates a card.
  613. *
  614. * The addressbook id will be passed as the first argument. This is the
  615. * same id as it is returned from the getAddressBooksForUser method.
  616. *
  617. * The cardUri is a base uri, and doesn't include the full path. The
  618. * cardData argument is the vcard body, and is passed as a string.
  619. *
  620. * It is possible to return an ETag from this method. This ETag should
  621. * match that of the updated resource, and must be enclosed with double
  622. * quotes (that is: the string itself must contain the actual quotes).
  623. *
  624. * You should only return the ETag if you store the carddata as-is. If a
  625. * subsequent GET request on the same card does not have the same body,
  626. * byte-by-byte and you did return an ETag here, clients tend to get
  627. * confused.
  628. *
  629. * If you don't return an ETag, you can just return null.
  630. *
  631. * @param mixed $addressBookId
  632. * @param string $cardUri
  633. * @param string $cardData
  634. * @return string
  635. */
  636. public function updateCard($addressBookId, $cardUri, $cardData) {
  637. $uid = $this->getUID($cardData);
  638. $etag = md5($cardData);
  639. $query = $this->db->getQueryBuilder();
  640. // check for recently stored etag and stop if it is the same
  641. $etagCacheKey = "$addressBookId#$cardUri";
  642. if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
  643. return '"' . $etag . '"';
  644. }
  645. $query->update($this->dbCardsTable)
  646. ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
  647. ->set('lastmodified', $query->createNamedParameter(time()))
  648. ->set('size', $query->createNamedParameter(strlen($cardData)))
  649. ->set('etag', $query->createNamedParameter($etag))
  650. ->set('uid', $query->createNamedParameter($uid))
  651. ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  652. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  653. ->execute();
  654. $this->etagCache[$etagCacheKey] = $etag;
  655. $this->addChange($addressBookId, $cardUri, 2);
  656. $this->updateProperties($addressBookId, $cardUri, $cardData);
  657. $addressBookData = $this->getAddressBookById($addressBookId);
  658. $shares = $this->getShares($addressBookId);
  659. $objectRow = $this->getCard($addressBookId, $cardUri);
  660. $this->dispatcher->dispatchTyped(new CardUpdatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
  661. $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
  662. new GenericEvent(null, [
  663. 'addressBookId' => $addressBookId,
  664. 'cardUri' => $cardUri,
  665. 'cardData' => $cardData]));
  666. return '"' . $etag . '"';
  667. }
  668. /**
  669. * Deletes a card
  670. *
  671. * @param mixed $addressBookId
  672. * @param string $cardUri
  673. * @return bool
  674. */
  675. public function deleteCard($addressBookId, $cardUri) {
  676. $addressBookData = $this->getAddressBookById($addressBookId);
  677. $shares = $this->getShares($addressBookId);
  678. $objectRow = $this->getCard($addressBookId, $cardUri);
  679. try {
  680. $cardId = $this->getCardId($addressBookId, $cardUri);
  681. } catch (\InvalidArgumentException $e) {
  682. $cardId = null;
  683. }
  684. $query = $this->db->getQueryBuilder();
  685. $ret = $query->delete($this->dbCardsTable)
  686. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  687. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  688. ->execute();
  689. $this->addChange($addressBookId, $cardUri, 3);
  690. if ($ret === 1) {
  691. if ($cardId !== null) {
  692. $this->dispatcher->dispatchTyped(new CardDeletedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow));
  693. $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
  694. new GenericEvent(null, [
  695. 'addressBookId' => $addressBookId,
  696. 'cardUri' => $cardUri]));
  697. $this->purgeProperties($addressBookId, $cardId);
  698. }
  699. return true;
  700. }
  701. return false;
  702. }
  703. /**
  704. * The getChanges method returns all the changes that have happened, since
  705. * the specified syncToken in the specified address book.
  706. *
  707. * This function should return an array, such as the following:
  708. *
  709. * [
  710. * 'syncToken' => 'The current synctoken',
  711. * 'added' => [
  712. * 'new.txt',
  713. * ],
  714. * 'modified' => [
  715. * 'modified.txt',
  716. * ],
  717. * 'deleted' => [
  718. * 'foo.php.bak',
  719. * 'old.txt'
  720. * ]
  721. * ];
  722. *
  723. * The returned syncToken property should reflect the *current* syncToken
  724. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  725. * property. This is needed here too, to ensure the operation is atomic.
  726. *
  727. * If the $syncToken argument is specified as null, this is an initial
  728. * sync, and all members should be reported.
  729. *
  730. * The modified property is an array of nodenames that have changed since
  731. * the last token.
  732. *
  733. * The deleted property is an array with nodenames, that have been deleted
  734. * from collection.
  735. *
  736. * The $syncLevel argument is basically the 'depth' of the report. If it's
  737. * 1, you only have to report changes that happened only directly in
  738. * immediate descendants. If it's 2, it should also include changes from
  739. * the nodes below the child collections. (grandchildren)
  740. *
  741. * The $limit argument allows a client to specify how many results should
  742. * be returned at most. If the limit is not specified, it should be treated
  743. * as infinite.
  744. *
  745. * If the limit (infinite or not) is higher than you're willing to return,
  746. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  747. *
  748. * If the syncToken is expired (due to data cleanup) or unknown, you must
  749. * return null.
  750. *
  751. * The limit is 'suggestive'. You are free to ignore it.
  752. *
  753. * @param string $addressBookId
  754. * @param string $syncToken
  755. * @param int $syncLevel
  756. * @param int $limit
  757. * @return array
  758. */
  759. public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
  760. // Current synctoken
  761. $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
  762. $stmt->execute([$addressBookId]);
  763. $currentToken = $stmt->fetchColumn(0);
  764. if (is_null($currentToken)) {
  765. return null;
  766. }
  767. $result = [
  768. 'syncToken' => $currentToken,
  769. 'added' => [],
  770. 'modified' => [],
  771. 'deleted' => [],
  772. ];
  773. if ($syncToken) {
  774. $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
  775. if ($limit > 0) {
  776. $query .= " LIMIT " . (int)$limit;
  777. }
  778. // Fetching all changes
  779. $stmt = $this->db->prepare($query);
  780. $stmt->execute([$syncToken, $currentToken, $addressBookId]);
  781. $changes = [];
  782. // This loop ensures that any duplicates are overwritten, only the
  783. // last change on a node is relevant.
  784. while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  785. $changes[$row['uri']] = $row['operation'];
  786. }
  787. foreach ($changes as $uri => $operation) {
  788. switch ($operation) {
  789. case 1:
  790. $result['added'][] = $uri;
  791. break;
  792. case 2:
  793. $result['modified'][] = $uri;
  794. break;
  795. case 3:
  796. $result['deleted'][] = $uri;
  797. break;
  798. }
  799. }
  800. } else {
  801. // No synctoken supplied, this is the initial sync.
  802. $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
  803. $stmt = $this->db->prepare($query);
  804. $stmt->execute([$addressBookId]);
  805. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  806. }
  807. return $result;
  808. }
  809. /**
  810. * Adds a change record to the addressbookchanges table.
  811. *
  812. * @param mixed $addressBookId
  813. * @param string $objectUri
  814. * @param int $operation 1 = add, 2 = modify, 3 = delete
  815. * @return void
  816. */
  817. protected function addChange($addressBookId, $objectUri, $operation) {
  818. $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
  819. $stmt = $this->db->prepare($sql);
  820. $stmt->execute([
  821. $objectUri,
  822. $addressBookId,
  823. $operation,
  824. $addressBookId
  825. ]);
  826. $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
  827. $stmt->execute([
  828. $addressBookId
  829. ]);
  830. }
  831. /**
  832. * @param resource|string $cardData
  833. * @param bool $modified
  834. * @return string
  835. */
  836. private function readBlob($cardData, &$modified = false) {
  837. if (is_resource($cardData)) {
  838. $cardData = stream_get_contents($cardData);
  839. }
  840. $cardDataArray = explode("\r\n", $cardData);
  841. $cardDataFiltered = [];
  842. $removingPhoto = false;
  843. foreach ($cardDataArray as $line) {
  844. if (strpos($line, 'PHOTO:data:') === 0
  845. && strpos($line, 'PHOTO:data:image/') !== 0) {
  846. // Filter out PHOTO data of non-images
  847. $removingPhoto = true;
  848. $modified = true;
  849. continue;
  850. }
  851. if ($removingPhoto) {
  852. if (strpos($line, ' ') === 0) {
  853. continue;
  854. }
  855. // No leading space means this is a new property
  856. $removingPhoto = false;
  857. }
  858. $cardDataFiltered[] = $line;
  859. }
  860. return implode("\r\n", $cardDataFiltered);
  861. }
  862. /**
  863. * @param IShareable $shareable
  864. * @param string[] $add
  865. * @param string[] $remove
  866. */
  867. public function updateShares(IShareable $shareable, $add, $remove) {
  868. $addressBookId = $shareable->getResourceId();
  869. $addressBookData = $this->getAddressBookById($addressBookId);
  870. $oldShares = $this->getShares($addressBookId);
  871. $this->sharingBackend->updateShares($shareable, $add, $remove);
  872. $this->dispatcher->dispatchTyped(new AddressBookShareUpdatedEvent($addressBookId, $addressBookData, $oldShares, $add, $remove));
  873. }
  874. /**
  875. * Search contacts in a specific address-book
  876. *
  877. * @param int $addressBookId
  878. * @param string $pattern which should match within the $searchProperties
  879. * @param array $searchProperties defines the properties within the query pattern should match
  880. * @param array $options = array() to define the search behavior
  881. * - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
  882. * - 'limit' - Set a numeric limit for the search results
  883. * - 'offset' - Set the offset for the limited search results
  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. * @return array
  913. */
  914. private function searchByAddressBookIds(array $addressBookIds,
  915. string $pattern,
  916. array $searchProperties,
  917. array $options = []): array {
  918. $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
  919. $query2 = $this->db->getQueryBuilder();
  920. $addressBookOr = $query2->expr()->orX();
  921. foreach ($addressBookIds as $addressBookId) {
  922. $addressBookOr->add($query2->expr()->eq('cp.addressbookid', $query2->createNamedParameter($addressBookId)));
  923. }
  924. if ($addressBookOr->count() === 0) {
  925. return [];
  926. }
  927. $propertyOr = $query2->expr()->orX();
  928. foreach ($searchProperties as $property) {
  929. if ($escapePattern) {
  930. if ($property === 'EMAIL' && strpos($pattern, ' ') !== false) {
  931. // There can be no spaces in emails
  932. continue;
  933. }
  934. if ($property === 'CLOUD' && preg_match('/[^a-zA-Z0-9 :_.@\/\-\']/', $pattern) === 1) {
  935. // There can be no chars in cloud ids which are not valid for user ids plus :/
  936. // worst case: CA61590A-BBBC-423E-84AF-E6DF01455A53@https://my.nxt/srv/
  937. continue;
  938. }
  939. }
  940. $propertyOr->add($query2->expr()->eq('cp.name', $query2->createNamedParameter($property)));
  941. }
  942. if ($propertyOr->count() === 0) {
  943. return [];
  944. }
  945. $query2->selectDistinct('cp.cardid')
  946. ->from($this->dbCardsPropertiesTable, 'cp')
  947. ->andWhere($addressBookOr)
  948. ->andWhere($propertyOr);
  949. // No need for like when the pattern is empty
  950. if ('' !== $pattern) {
  951. if (!$escapePattern) {
  952. $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
  953. } else {
  954. $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
  955. }
  956. }
  957. if (isset($options['limit'])) {
  958. $query2->setMaxResults($options['limit']);
  959. }
  960. if (isset($options['offset'])) {
  961. $query2->setFirstResult($options['offset']);
  962. }
  963. $result = $query2->execute();
  964. $matches = $result->fetchAll();
  965. $result->closeCursor();
  966. $matches = array_map(function ($match) {
  967. return (int)$match['cardid'];
  968. }, $matches);
  969. $query = $this->db->getQueryBuilder();
  970. $query->select('c.addressbookid', 'c.carddata', 'c.uri')
  971. ->from($this->dbCardsTable, 'c')
  972. ->where($query->expr()->in('c.id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
  973. $result = $query->execute();
  974. $cards = $result->fetchAll();
  975. $result->closeCursor();
  976. return array_map(function ($array) {
  977. $array['addressbookid'] = (int) $array['addressbookid'];
  978. $modified = false;
  979. $array['carddata'] = $this->readBlob($array['carddata'], $modified);
  980. if ($modified) {
  981. $array['size'] = strlen($array['carddata']);
  982. }
  983. return $array;
  984. }, $cards);
  985. }
  986. /**
  987. * @param int $bookId
  988. * @param string $name
  989. * @return array
  990. */
  991. public function collectCardProperties($bookId, $name) {
  992. $query = $this->db->getQueryBuilder();
  993. $result = $query->selectDistinct('value')
  994. ->from($this->dbCardsPropertiesTable)
  995. ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
  996. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
  997. ->execute();
  998. $all = $result->fetchAll(PDO::FETCH_COLUMN);
  999. $result->closeCursor();
  1000. return $all;
  1001. }
  1002. /**
  1003. * get URI from a given contact
  1004. *
  1005. * @param int $id
  1006. * @return string
  1007. */
  1008. public function getCardUri($id) {
  1009. $query = $this->db->getQueryBuilder();
  1010. $query->select('uri')->from($this->dbCardsTable)
  1011. ->where($query->expr()->eq('id', $query->createParameter('id')))
  1012. ->setParameter('id', $id);
  1013. $result = $query->execute();
  1014. $uri = $result->fetch();
  1015. $result->closeCursor();
  1016. if (!isset($uri['uri'])) {
  1017. throw new \InvalidArgumentException('Card does not exists: ' . $id);
  1018. }
  1019. return $uri['uri'];
  1020. }
  1021. /**
  1022. * return contact with the given URI
  1023. *
  1024. * @param int $addressBookId
  1025. * @param string $uri
  1026. * @returns array
  1027. */
  1028. public function getContact($addressBookId, $uri) {
  1029. $result = [];
  1030. $query = $this->db->getQueryBuilder();
  1031. $query->select('*')->from($this->dbCardsTable)
  1032. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  1033. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1034. $queryResult = $query->execute();
  1035. $contact = $queryResult->fetch();
  1036. $queryResult->closeCursor();
  1037. if (is_array($contact)) {
  1038. $modified = false;
  1039. $contact['etag'] = '"' . $contact['etag'] . '"';
  1040. $contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
  1041. if ($modified) {
  1042. $contact['size'] = strlen($contact['carddata']);
  1043. }
  1044. $result = $contact;
  1045. }
  1046. return $result;
  1047. }
  1048. /**
  1049. * Returns the list of people whom this address book is shared with.
  1050. *
  1051. * Every element in this array should have the following properties:
  1052. * * href - Often a mailto: address
  1053. * * commonName - Optional, for example a first + last name
  1054. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  1055. * * readOnly - boolean
  1056. * * summary - Optional, a description for the share
  1057. *
  1058. * @return array
  1059. */
  1060. public function getShares($addressBookId) {
  1061. return $this->sharingBackend->getShares($addressBookId);
  1062. }
  1063. /**
  1064. * update properties table
  1065. *
  1066. * @param int $addressBookId
  1067. * @param string $cardUri
  1068. * @param string $vCardSerialized
  1069. */
  1070. protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
  1071. $cardId = $this->getCardId($addressBookId, $cardUri);
  1072. $vCard = $this->readCard($vCardSerialized);
  1073. $this->purgeProperties($addressBookId, $cardId);
  1074. $query = $this->db->getQueryBuilder();
  1075. $query->insert($this->dbCardsPropertiesTable)
  1076. ->values(
  1077. [
  1078. 'addressbookid' => $query->createNamedParameter($addressBookId),
  1079. 'cardid' => $query->createNamedParameter($cardId),
  1080. 'name' => $query->createParameter('name'),
  1081. 'value' => $query->createParameter('value'),
  1082. 'preferred' => $query->createParameter('preferred')
  1083. ]
  1084. );
  1085. foreach ($vCard->children() as $property) {
  1086. if (!in_array($property->name, self::$indexProperties)) {
  1087. continue;
  1088. }
  1089. $preferred = 0;
  1090. foreach ($property->parameters as $parameter) {
  1091. if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
  1092. $preferred = 1;
  1093. break;
  1094. }
  1095. }
  1096. $query->setParameter('name', $property->name);
  1097. $query->setParameter('value', mb_substr($property->getValue(), 0, 254));
  1098. $query->setParameter('preferred', $preferred);
  1099. $query->execute();
  1100. }
  1101. }
  1102. /**
  1103. * read vCard data into a vCard object
  1104. *
  1105. * @param string $cardData
  1106. * @return VCard
  1107. */
  1108. protected function readCard($cardData) {
  1109. return Reader::read($cardData);
  1110. }
  1111. /**
  1112. * delete all properties from a given card
  1113. *
  1114. * @param int $addressBookId
  1115. * @param int $cardId
  1116. */
  1117. protected function purgeProperties($addressBookId, $cardId) {
  1118. $query = $this->db->getQueryBuilder();
  1119. $query->delete($this->dbCardsPropertiesTable)
  1120. ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
  1121. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1122. $query->execute();
  1123. }
  1124. /**
  1125. * get ID from a given contact
  1126. *
  1127. * @param int $addressBookId
  1128. * @param string $uri
  1129. * @return int
  1130. */
  1131. protected function getCardId($addressBookId, $uri) {
  1132. $query = $this->db->getQueryBuilder();
  1133. $query->select('id')->from($this->dbCardsTable)
  1134. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  1135. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  1136. $result = $query->execute();
  1137. $cardIds = $result->fetch();
  1138. $result->closeCursor();
  1139. if (!isset($cardIds['id'])) {
  1140. throw new \InvalidArgumentException('Card does not exists: ' . $uri);
  1141. }
  1142. return (int)$cardIds['id'];
  1143. }
  1144. /**
  1145. * For shared address books the sharee is set in the ACL of the address book
  1146. *
  1147. * @param $addressBookId
  1148. * @param $acl
  1149. * @return array
  1150. */
  1151. public function applyShareAcl($addressBookId, $acl) {
  1152. return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
  1153. }
  1154. private function convertPrincipal($principalUri, $toV2) {
  1155. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  1156. list(, $name) = \Sabre\Uri\split($principalUri);
  1157. if ($toV2 === true) {
  1158. return "principals/users/$name";
  1159. }
  1160. return "principals/$name";
  1161. }
  1162. return $principalUri;
  1163. }
  1164. private function addOwnerPrincipal(&$addressbookInfo) {
  1165. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  1166. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  1167. if (isset($addressbookInfo[$ownerPrincipalKey])) {
  1168. $uri = $addressbookInfo[$ownerPrincipalKey];
  1169. } else {
  1170. $uri = $addressbookInfo['principaluri'];
  1171. }
  1172. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  1173. if (isset($principalInformation['{DAV:}displayname'])) {
  1174. $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  1175. }
  1176. }
  1177. /**
  1178. * Extract UID from vcard
  1179. *
  1180. * @param string $cardData the vcard raw data
  1181. * @return string the uid
  1182. * @throws BadRequest if no UID is available
  1183. */
  1184. private function getUID($cardData) {
  1185. if ($cardData != '') {
  1186. $vCard = Reader::read($cardData);
  1187. if ($vCard->UID) {
  1188. $uid = $vCard->UID->getValue();
  1189. return $uid;
  1190. }
  1191. // should already be handled, but just in case
  1192. throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
  1193. }
  1194. // should already be handled, but just in case
  1195. throw new BadRequest('vCard can not be empty');
  1196. }
  1197. }