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

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