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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Georg Ehrke <georg@owncloud.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Robin Appelman <robin@icewind.nl>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. * @author Stefan Weil <sw@weilnetz.de>
  15. * @author Thomas Citharel <tcit@tcit.fr>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. *
  18. * @license AGPL-3.0
  19. *
  20. * This code is free software: you can redistribute it and/or modify
  21. * it under the terms of the GNU Affero General Public License, version 3,
  22. * as published by the Free Software Foundation.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU Affero General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU Affero General Public License, version 3,
  30. * along with this program. If not, see <http://www.gnu.org/licenses/>
  31. *
  32. */
  33. namespace OCA\DAV\CardDAV;
  34. use OCA\DAV\Connector\Sabre\Principal;
  35. use OCP\DB\QueryBuilder\IQueryBuilder;
  36. use OCA\DAV\DAV\Sharing\Backend;
  37. use OCA\DAV\DAV\Sharing\IShareable;
  38. use OCP\IDBConnection;
  39. use OCP\IGroupManager;
  40. use OCP\IUser;
  41. use OCP\IUserManager;
  42. use PDO;
  43. use Sabre\CardDAV\Backend\BackendInterface;
  44. use Sabre\CardDAV\Backend\SyncSupport;
  45. use Sabre\CardDAV\Plugin;
  46. use Sabre\DAV\Exception\BadRequest;
  47. use Sabre\HTTP\URLUtil;
  48. use Sabre\VObject\Component\VCard;
  49. use Sabre\VObject\Reader;
  50. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  51. use Symfony\Component\EventDispatcher\GenericEvent;
  52. class CardDavBackend implements BackendInterface, SyncSupport {
  53. const PERSONAL_ADDRESSBOOK_URI = 'contacts';
  54. const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
  55. /** @var Principal */
  56. private $principalBackend;
  57. /** @var string */
  58. private $dbCardsTable = 'cards';
  59. /** @var string */
  60. private $dbCardsPropertiesTable = 'cards_properties';
  61. /** @var IDBConnection */
  62. private $db;
  63. /** @var Backend */
  64. private $sharingBackend;
  65. /** @var array properties to index */
  66. public static $indexProperties = array(
  67. 'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
  68. 'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
  69. /**
  70. * @var string[] Map of uid => display name
  71. */
  72. protected $userDisplayNames;
  73. /** @var IUserManager */
  74. private $userManager;
  75. /** @var EventDispatcherInterface */
  76. private $dispatcher;
  77. /**
  78. * CardDavBackend constructor.
  79. *
  80. * @param IDBConnection $db
  81. * @param Principal $principalBackend
  82. * @param IUserManager $userManager
  83. * @param IGroupManager $groupManager
  84. * @param EventDispatcherInterface $dispatcher
  85. */
  86. public function __construct(IDBConnection $db,
  87. Principal $principalBackend,
  88. IUserManager $userManager,
  89. IGroupManager $groupManager,
  90. EventDispatcherInterface $dispatcher) {
  91. $this->db = $db;
  92. $this->principalBackend = $principalBackend;
  93. $this->userManager = $userManager;
  94. $this->dispatcher = $dispatcher;
  95. $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
  96. }
  97. /**
  98. * Return the number of address books for a principal
  99. *
  100. * @param $principalUri
  101. * @return int
  102. */
  103. public function getAddressBooksForUserCount($principalUri) {
  104. $principalUri = $this->convertPrincipal($principalUri, true);
  105. $query = $this->db->getQueryBuilder();
  106. $query->select($query->createFunction('COUNT(*)'))
  107. ->from('addressbooks')
  108. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  109. return (int)$query->execute()->fetchColumn();
  110. }
  111. /**
  112. * Returns the list of address books for a specific user.
  113. *
  114. * Every addressbook should have the following properties:
  115. * id - an arbitrary unique id
  116. * uri - the 'basename' part of the url
  117. * principaluri - Same as the passed parameter
  118. *
  119. * Any additional clark-notation property may be passed besides this. Some
  120. * common ones are :
  121. * {DAV:}displayname
  122. * {urn:ietf:params:xml:ns:carddav}addressbook-description
  123. * {http://calendarserver.org/ns/}getctag
  124. *
  125. * @param string $principalUri
  126. * @return array
  127. */
  128. function getAddressBooksForUser($principalUri) {
  129. $principalUriOriginal = $principalUri;
  130. $principalUri = $this->convertPrincipal($principalUri, true);
  131. $query = $this->db->getQueryBuilder();
  132. $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  133. ->from('addressbooks')
  134. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  135. $addressBooks = [];
  136. $result = $query->execute();
  137. while($row = $result->fetch()) {
  138. $addressBooks[$row['id']] = [
  139. 'id' => $row['id'],
  140. 'uri' => $row['uri'],
  141. 'principaluri' => $this->convertPrincipal($row['principaluri'], false),
  142. '{DAV:}displayname' => $row['displayname'],
  143. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  144. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  145. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  146. ];
  147. $this->addOwnerPrincipal($addressBooks[$row['id']]);
  148. }
  149. $result->closeCursor();
  150. // query for shared calendars
  151. $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
  152. $principals = array_map(function($principal) {
  153. return urldecode($principal);
  154. }, $principals);
  155. $principals[]= $principalUri;
  156. $query = $this->db->getQueryBuilder();
  157. $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
  158. ->from('dav_shares', 's')
  159. ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
  160. ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
  161. ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
  162. ->setParameter('type', 'addressbook')
  163. ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
  164. ->execute();
  165. $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
  166. while($row = $result->fetch()) {
  167. if ($row['principaluri'] === $principalUri) {
  168. continue;
  169. }
  170. $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
  171. if (isset($addressBooks[$row['id']])) {
  172. if ($readOnly) {
  173. // New share can not have more permissions then the old one.
  174. continue;
  175. }
  176. if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
  177. $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
  178. // Old share is already read-write, no more permissions can be gained
  179. continue;
  180. }
  181. }
  182. list(, $name) = \Sabre\Uri\split($row['principaluri']);
  183. $uri = $row['uri'] . '_shared_by_' . $name;
  184. $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
  185. $addressBooks[$row['id']] = [
  186. 'id' => $row['id'],
  187. 'uri' => $uri,
  188. 'principaluri' => $principalUriOriginal,
  189. '{DAV:}displayname' => $displayName,
  190. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  191. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  192. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  193. '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
  194. $readOnlyPropertyName => $readOnly,
  195. ];
  196. $this->addOwnerPrincipal($addressBooks[$row['id']]);
  197. }
  198. $result->closeCursor();
  199. return array_values($addressBooks);
  200. }
  201. public function getUsersOwnAddressBooks($principalUri) {
  202. $principalUri = $this->convertPrincipal($principalUri, true);
  203. $query = $this->db->getQueryBuilder();
  204. $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  205. ->from('addressbooks')
  206. ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
  207. $addressBooks = [];
  208. $result = $query->execute();
  209. while($row = $result->fetch()) {
  210. $addressBooks[$row['id']] = [
  211. 'id' => $row['id'],
  212. 'uri' => $row['uri'],
  213. 'principaluri' => $this->convertPrincipal($row['principaluri'], false),
  214. '{DAV:}displayname' => $row['displayname'],
  215. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  216. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  217. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  218. ];
  219. $this->addOwnerPrincipal($addressBooks[$row['id']]);
  220. }
  221. $result->closeCursor();
  222. return array_values($addressBooks);
  223. }
  224. private function getUserDisplayName($uid) {
  225. if (!isset($this->userDisplayNames[$uid])) {
  226. $user = $this->userManager->get($uid);
  227. if ($user instanceof IUser) {
  228. $this->userDisplayNames[$uid] = $user->getDisplayName();
  229. } else {
  230. $this->userDisplayNames[$uid] = $uid;
  231. }
  232. }
  233. return $this->userDisplayNames[$uid];
  234. }
  235. /**
  236. * @param int $addressBookId
  237. */
  238. public function getAddressBookById($addressBookId) {
  239. $query = $this->db->getQueryBuilder();
  240. $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  241. ->from('addressbooks')
  242. ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
  243. ->execute();
  244. $row = $result->fetch();
  245. $result->closeCursor();
  246. if ($row === false) {
  247. return null;
  248. }
  249. $addressBook = [
  250. 'id' => $row['id'],
  251. 'uri' => $row['uri'],
  252. 'principaluri' => $row['principaluri'],
  253. '{DAV:}displayname' => $row['displayname'],
  254. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  255. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  256. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  257. ];
  258. $this->addOwnerPrincipal($addressBook);
  259. return $addressBook;
  260. }
  261. /**
  262. * @param $addressBookUri
  263. * @return array|null
  264. */
  265. public function getAddressBooksByUri($principal, $addressBookUri) {
  266. $query = $this->db->getQueryBuilder();
  267. $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
  268. ->from('addressbooks')
  269. ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
  270. ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
  271. ->setMaxResults(1)
  272. ->execute();
  273. $row = $result->fetch();
  274. $result->closeCursor();
  275. if ($row === false) {
  276. return null;
  277. }
  278. $addressBook = [
  279. 'id' => $row['id'],
  280. 'uri' => $row['uri'],
  281. 'principaluri' => $row['principaluri'],
  282. '{DAV:}displayname' => $row['displayname'],
  283. '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
  284. '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
  285. '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
  286. ];
  287. $this->addOwnerPrincipal($addressBook);
  288. return $addressBook;
  289. }
  290. /**
  291. * Updates properties for an address book.
  292. *
  293. * The list of mutations is stored in a Sabre\DAV\PropPatch object.
  294. * To do the actual updates, you must tell this object which properties
  295. * you're going to process with the handle() method.
  296. *
  297. * Calling the handle method is like telling the PropPatch object "I
  298. * promise I can handle updating this property".
  299. *
  300. * Read the PropPatch documentation for more info and examples.
  301. *
  302. * @param string $addressBookId
  303. * @param \Sabre\DAV\PropPatch $propPatch
  304. * @return void
  305. */
  306. function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
  307. $supportedProperties = [
  308. '{DAV:}displayname',
  309. '{' . Plugin::NS_CARDDAV . '}addressbook-description',
  310. ];
  311. /**
  312. * @suppress SqlInjectionChecker
  313. */
  314. $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
  315. $updates = [];
  316. foreach($mutations as $property=>$newValue) {
  317. switch($property) {
  318. case '{DAV:}displayname' :
  319. $updates['displayname'] = $newValue;
  320. break;
  321. case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
  322. $updates['description'] = $newValue;
  323. break;
  324. }
  325. }
  326. $query = $this->db->getQueryBuilder();
  327. $query->update('addressbooks');
  328. foreach($updates as $key=>$value) {
  329. $query->set($key, $query->createNamedParameter($value));
  330. }
  331. $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
  332. ->execute();
  333. $this->addChange($addressBookId, "", 2);
  334. return true;
  335. });
  336. }
  337. /**
  338. * Creates a new address book
  339. *
  340. * @param string $principalUri
  341. * @param string $url Just the 'basename' of the url.
  342. * @param array $properties
  343. * @return int
  344. * @throws BadRequest
  345. */
  346. function createAddressBook($principalUri, $url, array $properties) {
  347. $values = [
  348. 'displayname' => null,
  349. 'description' => null,
  350. 'principaluri' => $principalUri,
  351. 'uri' => $url,
  352. 'synctoken' => 1
  353. ];
  354. foreach($properties as $property=>$newValue) {
  355. switch($property) {
  356. case '{DAV:}displayname' :
  357. $values['displayname'] = $newValue;
  358. break;
  359. case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
  360. $values['description'] = $newValue;
  361. break;
  362. default :
  363. throw new BadRequest('Unknown property: ' . $property);
  364. }
  365. }
  366. // Fallback to make sure the displayname is set. Some clients may refuse
  367. // to work with addressbooks not having a displayname.
  368. if(is_null($values['displayname'])) {
  369. $values['displayname'] = $url;
  370. }
  371. $query = $this->db->getQueryBuilder();
  372. $query->insert('addressbooks')
  373. ->values([
  374. 'uri' => $query->createParameter('uri'),
  375. 'displayname' => $query->createParameter('displayname'),
  376. 'description' => $query->createParameter('description'),
  377. 'principaluri' => $query->createParameter('principaluri'),
  378. 'synctoken' => $query->createParameter('synctoken'),
  379. ])
  380. ->setParameters($values)
  381. ->execute();
  382. return $query->getLastInsertId();
  383. }
  384. /**
  385. * Deletes an entire addressbook and all its contents
  386. *
  387. * @param mixed $addressBookId
  388. * @return void
  389. */
  390. function deleteAddressBook($addressBookId) {
  391. $query = $this->db->getQueryBuilder();
  392. $query->delete('cards')
  393. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  394. ->setParameter('addressbookid', $addressBookId)
  395. ->execute();
  396. $query->delete('addressbookchanges')
  397. ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
  398. ->setParameter('addressbookid', $addressBookId)
  399. ->execute();
  400. $query->delete('addressbooks')
  401. ->where($query->expr()->eq('id', $query->createParameter('id')))
  402. ->setParameter('id', $addressBookId)
  403. ->execute();
  404. $this->sharingBackend->deleteAllShares($addressBookId);
  405. $query->delete($this->dbCardsPropertiesTable)
  406. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  407. ->execute();
  408. }
  409. /**
  410. * Returns all cards for a specific addressbook id.
  411. *
  412. * This method should return the following properties for each card:
  413. * * carddata - raw vcard data
  414. * * uri - Some unique url
  415. * * lastmodified - A unix timestamp
  416. *
  417. * It's recommended to also return the following properties:
  418. * * etag - A unique etag. This must change every time the card changes.
  419. * * size - The size of the card in bytes.
  420. *
  421. * If these last two properties are provided, less time will be spent
  422. * calculating them. If they are specified, you can also ommit carddata.
  423. * This may speed up certain requests, especially with large cards.
  424. *
  425. * @param mixed $addressBookId
  426. * @return array
  427. */
  428. function getCards($addressBookId) {
  429. $query = $this->db->getQueryBuilder();
  430. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
  431. ->from('cards')
  432. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  433. $cards = [];
  434. $result = $query->execute();
  435. while($row = $result->fetch()) {
  436. $row['etag'] = '"' . $row['etag'] . '"';
  437. $row['carddata'] = $this->readBlob($row['carddata']);
  438. $cards[] = $row;
  439. }
  440. $result->closeCursor();
  441. return $cards;
  442. }
  443. /**
  444. * Returns a specific card.
  445. *
  446. * The same set of properties must be returned as with getCards. The only
  447. * exception is that 'carddata' is absolutely required.
  448. *
  449. * If the card does not exist, you must return false.
  450. *
  451. * @param mixed $addressBookId
  452. * @param string $cardUri
  453. * @return array
  454. */
  455. function getCard($addressBookId, $cardUri) {
  456. $query = $this->db->getQueryBuilder();
  457. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
  458. ->from('cards')
  459. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  460. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  461. ->setMaxResults(1);
  462. $result = $query->execute();
  463. $row = $result->fetch();
  464. if (!$row) {
  465. return false;
  466. }
  467. $row['etag'] = '"' . $row['etag'] . '"';
  468. $row['carddata'] = $this->readBlob($row['carddata']);
  469. return $row;
  470. }
  471. /**
  472. * Returns a list of cards.
  473. *
  474. * This method should work identical to getCard, but instead return all the
  475. * cards in the list as an array.
  476. *
  477. * If the backend supports this, it may allow for some speed-ups.
  478. *
  479. * @param mixed $addressBookId
  480. * @param string[] $uris
  481. * @return array
  482. */
  483. function getMultipleCards($addressBookId, array $uris) {
  484. if (empty($uris)) {
  485. return [];
  486. }
  487. $chunks = array_chunk($uris, 100);
  488. $cards = [];
  489. $query = $this->db->getQueryBuilder();
  490. $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata'])
  491. ->from('cards')
  492. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  493. ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
  494. foreach ($chunks as $uris) {
  495. $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
  496. $result = $query->execute();
  497. while ($row = $result->fetch()) {
  498. $row['etag'] = '"' . $row['etag'] . '"';
  499. $row['carddata'] = $this->readBlob($row['carddata']);
  500. $cards[] = $row;
  501. }
  502. $result->closeCursor();
  503. }
  504. return $cards;
  505. }
  506. /**
  507. * Creates a new card.
  508. *
  509. * The addressbook id will be passed as the first argument. This is the
  510. * same id as it is returned from the getAddressBooksForUser method.
  511. *
  512. * The cardUri is a base uri, and doesn't include the full path. The
  513. * cardData argument is the vcard body, and is passed as a string.
  514. *
  515. * It is possible to return an ETag from this method. This ETag is for the
  516. * newly created resource, and must be enclosed with double quotes (that
  517. * is, the string itself must contain the double quotes).
  518. *
  519. * You should only return the ETag if you store the carddata as-is. If a
  520. * subsequent GET request on the same card does not have the same body,
  521. * byte-by-byte and you did return an ETag here, clients tend to get
  522. * confused.
  523. *
  524. * If you don't return an ETag, you can just return null.
  525. *
  526. * @param mixed $addressBookId
  527. * @param string $cardUri
  528. * @param string $cardData
  529. * @return string
  530. */
  531. function createCard($addressBookId, $cardUri, $cardData) {
  532. $etag = md5($cardData);
  533. $query = $this->db->getQueryBuilder();
  534. $query->insert('cards')
  535. ->values([
  536. 'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
  537. 'uri' => $query->createNamedParameter($cardUri),
  538. 'lastmodified' => $query->createNamedParameter(time()),
  539. 'addressbookid' => $query->createNamedParameter($addressBookId),
  540. 'size' => $query->createNamedParameter(strlen($cardData)),
  541. 'etag' => $query->createNamedParameter($etag),
  542. ])
  543. ->execute();
  544. $this->addChange($addressBookId, $cardUri, 1);
  545. $this->updateProperties($addressBookId, $cardUri, $cardData);
  546. $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
  547. new GenericEvent(null, [
  548. 'addressBookId' => $addressBookId,
  549. 'cardUri' => $cardUri,
  550. 'cardData' => $cardData]));
  551. return '"' . $etag . '"';
  552. }
  553. /**
  554. * Updates a card.
  555. *
  556. * The addressbook id will be passed as the first argument. This is the
  557. * same id as it is returned from the getAddressBooksForUser method.
  558. *
  559. * The cardUri is a base uri, and doesn't include the full path. The
  560. * cardData argument is the vcard body, and is passed as a string.
  561. *
  562. * It is possible to return an ETag from this method. This ETag should
  563. * match that of the updated resource, and must be enclosed with double
  564. * quotes (that is: the string itself must contain the actual quotes).
  565. *
  566. * You should only return the ETag if you store the carddata as-is. If a
  567. * subsequent GET request on the same card does not have the same body,
  568. * byte-by-byte and you did return an ETag here, clients tend to get
  569. * confused.
  570. *
  571. * If you don't return an ETag, you can just return null.
  572. *
  573. * @param mixed $addressBookId
  574. * @param string $cardUri
  575. * @param string $cardData
  576. * @return string
  577. */
  578. function updateCard($addressBookId, $cardUri, $cardData) {
  579. $etag = md5($cardData);
  580. $query = $this->db->getQueryBuilder();
  581. $query->update('cards')
  582. ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
  583. ->set('lastmodified', $query->createNamedParameter(time()))
  584. ->set('size', $query->createNamedParameter(strlen($cardData)))
  585. ->set('etag', $query->createNamedParameter($etag))
  586. ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  587. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  588. ->execute();
  589. $this->addChange($addressBookId, $cardUri, 2);
  590. $this->updateProperties($addressBookId, $cardUri, $cardData);
  591. $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
  592. new GenericEvent(null, [
  593. 'addressBookId' => $addressBookId,
  594. 'cardUri' => $cardUri,
  595. 'cardData' => $cardData]));
  596. return '"' . $etag . '"';
  597. }
  598. /**
  599. * Deletes a card
  600. *
  601. * @param mixed $addressBookId
  602. * @param string $cardUri
  603. * @return bool
  604. */
  605. function deleteCard($addressBookId, $cardUri) {
  606. try {
  607. $cardId = $this->getCardId($addressBookId, $cardUri);
  608. } catch (\InvalidArgumentException $e) {
  609. $cardId = null;
  610. }
  611. $query = $this->db->getQueryBuilder();
  612. $ret = $query->delete('cards')
  613. ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
  614. ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
  615. ->execute();
  616. $this->addChange($addressBookId, $cardUri, 3);
  617. $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
  618. new GenericEvent(null, [
  619. 'addressBookId' => $addressBookId,
  620. 'cardUri' => $cardUri]));
  621. if ($ret === 1) {
  622. if ($cardId !== null) {
  623. $this->purgeProperties($addressBookId, $cardId);
  624. }
  625. return true;
  626. }
  627. return false;
  628. }
  629. /**
  630. * The getChanges method returns all the changes that have happened, since
  631. * the specified syncToken in the specified address book.
  632. *
  633. * This function should return an array, such as the following:
  634. *
  635. * [
  636. * 'syncToken' => 'The current synctoken',
  637. * 'added' => [
  638. * 'new.txt',
  639. * ],
  640. * 'modified' => [
  641. * 'modified.txt',
  642. * ],
  643. * 'deleted' => [
  644. * 'foo.php.bak',
  645. * 'old.txt'
  646. * ]
  647. * ];
  648. *
  649. * The returned syncToken property should reflect the *current* syncToken
  650. * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
  651. * property. This is needed here too, to ensure the operation is atomic.
  652. *
  653. * If the $syncToken argument is specified as null, this is an initial
  654. * sync, and all members should be reported.
  655. *
  656. * The modified property is an array of nodenames that have changed since
  657. * the last token.
  658. *
  659. * The deleted property is an array with nodenames, that have been deleted
  660. * from collection.
  661. *
  662. * The $syncLevel argument is basically the 'depth' of the report. If it's
  663. * 1, you only have to report changes that happened only directly in
  664. * immediate descendants. If it's 2, it should also include changes from
  665. * the nodes below the child collections. (grandchildren)
  666. *
  667. * The $limit argument allows a client to specify how many results should
  668. * be returned at most. If the limit is not specified, it should be treated
  669. * as infinite.
  670. *
  671. * If the limit (infinite or not) is higher than you're willing to return,
  672. * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
  673. *
  674. * If the syncToken is expired (due to data cleanup) or unknown, you must
  675. * return null.
  676. *
  677. * The limit is 'suggestive'. You are free to ignore it.
  678. *
  679. * @param string $addressBookId
  680. * @param string $syncToken
  681. * @param int $syncLevel
  682. * @param int $limit
  683. * @return array
  684. */
  685. function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
  686. // Current synctoken
  687. $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
  688. $stmt->execute([ $addressBookId ]);
  689. $currentToken = $stmt->fetchColumn(0);
  690. if (is_null($currentToken)) return null;
  691. $result = [
  692. 'syncToken' => $currentToken,
  693. 'added' => [],
  694. 'modified' => [],
  695. 'deleted' => [],
  696. ];
  697. if ($syncToken) {
  698. $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
  699. if ($limit>0) {
  700. $query .= " `LIMIT` " . (int)$limit;
  701. }
  702. // Fetching all changes
  703. $stmt = $this->db->prepare($query);
  704. $stmt->execute([$syncToken, $currentToken, $addressBookId]);
  705. $changes = [];
  706. // This loop ensures that any duplicates are overwritten, only the
  707. // last change on a node is relevant.
  708. while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
  709. $changes[$row['uri']] = $row['operation'];
  710. }
  711. foreach($changes as $uri => $operation) {
  712. switch($operation) {
  713. case 1:
  714. $result['added'][] = $uri;
  715. break;
  716. case 2:
  717. $result['modified'][] = $uri;
  718. break;
  719. case 3:
  720. $result['deleted'][] = $uri;
  721. break;
  722. }
  723. }
  724. } else {
  725. // No synctoken supplied, this is the initial sync.
  726. $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
  727. $stmt = $this->db->prepare($query);
  728. $stmt->execute([$addressBookId]);
  729. $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
  730. }
  731. return $result;
  732. }
  733. /**
  734. * Adds a change record to the addressbookchanges table.
  735. *
  736. * @param mixed $addressBookId
  737. * @param string $objectUri
  738. * @param int $operation 1 = add, 2 = modify, 3 = delete
  739. * @return void
  740. */
  741. protected function addChange($addressBookId, $objectUri, $operation) {
  742. $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
  743. $stmt = $this->db->prepare($sql);
  744. $stmt->execute([
  745. $objectUri,
  746. $addressBookId,
  747. $operation,
  748. $addressBookId
  749. ]);
  750. $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
  751. $stmt->execute([
  752. $addressBookId
  753. ]);
  754. }
  755. private function readBlob($cardData) {
  756. if (is_resource($cardData)) {
  757. return stream_get_contents($cardData);
  758. }
  759. return $cardData;
  760. }
  761. /**
  762. * @param IShareable $shareable
  763. * @param string[] $add
  764. * @param string[] $remove
  765. */
  766. public function updateShares(IShareable $shareable, $add, $remove) {
  767. $this->sharingBackend->updateShares($shareable, $add, $remove);
  768. }
  769. /**
  770. * search contact
  771. *
  772. * @param int $addressBookId
  773. * @param string $pattern which should match within the $searchProperties
  774. * @param array $searchProperties defines the properties within the query pattern should match
  775. * @return array an array of contacts which are arrays of key-value-pairs
  776. */
  777. public function search($addressBookId, $pattern, $searchProperties) {
  778. $query = $this->db->getQueryBuilder();
  779. $query2 = $this->db->getQueryBuilder();
  780. $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
  781. $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
  782. $or = $query2->expr()->orX();
  783. foreach ($searchProperties as $property) {
  784. $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
  785. }
  786. $query2->andWhere($or);
  787. // No need for like when the pattern is empty
  788. if ('' !== $pattern) {
  789. $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
  790. }
  791. $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
  792. ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
  793. $result = $query->execute();
  794. $cards = $result->fetchAll();
  795. $result->closeCursor();
  796. return array_map(function($array) {
  797. $array['carddata'] = $this->readBlob($array['carddata']);
  798. return $array;
  799. }, $cards);
  800. }
  801. /**
  802. * @param int $bookId
  803. * @param string $name
  804. * @return array
  805. */
  806. public function collectCardProperties($bookId, $name) {
  807. $query = $this->db->getQueryBuilder();
  808. $result = $query->selectDistinct('value')
  809. ->from($this->dbCardsPropertiesTable)
  810. ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
  811. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
  812. ->execute();
  813. $all = $result->fetchAll(PDO::FETCH_COLUMN);
  814. $result->closeCursor();
  815. return $all;
  816. }
  817. /**
  818. * get URI from a given contact
  819. *
  820. * @param int $id
  821. * @return string
  822. */
  823. public function getCardUri($id) {
  824. $query = $this->db->getQueryBuilder();
  825. $query->select('uri')->from($this->dbCardsTable)
  826. ->where($query->expr()->eq('id', $query->createParameter('id')))
  827. ->setParameter('id', $id);
  828. $result = $query->execute();
  829. $uri = $result->fetch();
  830. $result->closeCursor();
  831. if (!isset($uri['uri'])) {
  832. throw new \InvalidArgumentException('Card does not exists: ' . $id);
  833. }
  834. return $uri['uri'];
  835. }
  836. /**
  837. * return contact with the given URI
  838. *
  839. * @param int $addressBookId
  840. * @param string $uri
  841. * @returns array
  842. */
  843. public function getContact($addressBookId, $uri) {
  844. $result = [];
  845. $query = $this->db->getQueryBuilder();
  846. $query->select('*')->from($this->dbCardsTable)
  847. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  848. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  849. $queryResult = $query->execute();
  850. $contact = $queryResult->fetch();
  851. $queryResult->closeCursor();
  852. if (is_array($contact)) {
  853. $result = $contact;
  854. }
  855. return $result;
  856. }
  857. /**
  858. * Returns the list of people whom this address book is shared with.
  859. *
  860. * Every element in this array should have the following properties:
  861. * * href - Often a mailto: address
  862. * * commonName - Optional, for example a first + last name
  863. * * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
  864. * * readOnly - boolean
  865. * * summary - Optional, a description for the share
  866. *
  867. * @return array
  868. */
  869. public function getShares($addressBookId) {
  870. return $this->sharingBackend->getShares($addressBookId);
  871. }
  872. /**
  873. * update properties table
  874. *
  875. * @param int $addressBookId
  876. * @param string $cardUri
  877. * @param string $vCardSerialized
  878. */
  879. protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
  880. $cardId = $this->getCardId($addressBookId, $cardUri);
  881. $vCard = $this->readCard($vCardSerialized);
  882. $this->purgeProperties($addressBookId, $cardId);
  883. $query = $this->db->getQueryBuilder();
  884. $query->insert($this->dbCardsPropertiesTable)
  885. ->values(
  886. [
  887. 'addressbookid' => $query->createNamedParameter($addressBookId),
  888. 'cardid' => $query->createNamedParameter($cardId),
  889. 'name' => $query->createParameter('name'),
  890. 'value' => $query->createParameter('value'),
  891. 'preferred' => $query->createParameter('preferred')
  892. ]
  893. );
  894. foreach ($vCard->children() as $property) {
  895. if(!in_array($property->name, self::$indexProperties)) {
  896. continue;
  897. }
  898. $preferred = 0;
  899. foreach($property->parameters as $parameter) {
  900. if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
  901. $preferred = 1;
  902. break;
  903. }
  904. }
  905. $query->setParameter('name', $property->name);
  906. $query->setParameter('value', substr($property->getValue(), 0, 254));
  907. $query->setParameter('preferred', $preferred);
  908. $query->execute();
  909. }
  910. }
  911. /**
  912. * read vCard data into a vCard object
  913. *
  914. * @param string $cardData
  915. * @return VCard
  916. */
  917. protected function readCard($cardData) {
  918. return Reader::read($cardData);
  919. }
  920. /**
  921. * delete all properties from a given card
  922. *
  923. * @param int $addressBookId
  924. * @param int $cardId
  925. */
  926. protected function purgeProperties($addressBookId, $cardId) {
  927. $query = $this->db->getQueryBuilder();
  928. $query->delete($this->dbCardsPropertiesTable)
  929. ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
  930. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  931. $query->execute();
  932. }
  933. /**
  934. * get ID from a given contact
  935. *
  936. * @param int $addressBookId
  937. * @param string $uri
  938. * @return int
  939. */
  940. protected function getCardId($addressBookId, $uri) {
  941. $query = $this->db->getQueryBuilder();
  942. $query->select('id')->from($this->dbCardsTable)
  943. ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
  944. ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
  945. $result = $query->execute();
  946. $cardIds = $result->fetch();
  947. $result->closeCursor();
  948. if (!isset($cardIds['id'])) {
  949. throw new \InvalidArgumentException('Card does not exists: ' . $uri);
  950. }
  951. return (int)$cardIds['id'];
  952. }
  953. /**
  954. * For shared address books the sharee is set in the ACL of the address book
  955. * @param $addressBookId
  956. * @param $acl
  957. * @return array
  958. */
  959. public function applyShareAcl($addressBookId, $acl) {
  960. return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
  961. }
  962. private function convertPrincipal($principalUri, $toV2) {
  963. if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
  964. list(, $name) = \Sabre\Uri\split($principalUri);
  965. if ($toV2 === true) {
  966. return "principals/users/$name";
  967. }
  968. return "principals/$name";
  969. }
  970. return $principalUri;
  971. }
  972. private function addOwnerPrincipal(&$addressbookInfo) {
  973. $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
  974. $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
  975. if (isset($addressbookInfo[$ownerPrincipalKey])) {
  976. $uri = $addressbookInfo[$ownerPrincipalKey];
  977. } else {
  978. $uri = $addressbookInfo['principaluri'];
  979. }
  980. $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
  981. if (isset($principalInformation['{DAV:}displayname'])) {
  982. $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
  983. }
  984. }
  985. }