CardDavBackend.php 50 KB

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