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

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