ContactsStore.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. /**
  3. * @copyright 2017 Christoph Wurst <christoph@winzerhof-wurst.at>
  4. * @copyright 2017 Lukas Reschke <lukas@statuscode.ch>
  5. *
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Georg Ehrke <oc.list@georgehrke.com>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Lukas Reschke <lukas@statuscode.ch>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Tobia De Koninck <tobia@ledfan.be>
  13. *
  14. * @license GNU AGPL version 3 or any later version
  15. *
  16. * This program is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License as
  18. * published by the Free Software Foundation, either version 3 of the
  19. * License, or (at your option) any later version.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. *
  29. */
  30. namespace OC\Contacts\ContactsMenu;
  31. use OC\KnownUser\KnownUserService;
  32. use OC\Profile\ProfileManager;
  33. use OCA\UserStatus\Db\UserStatus;
  34. use OCA\UserStatus\Service\StatusService;
  35. use OCP\Contacts\ContactsMenu\IContactsStore;
  36. use OCP\Contacts\ContactsMenu\IEntry;
  37. use OCP\Contacts\IManager;
  38. use OCP\IConfig;
  39. use OCP\IGroupManager;
  40. use OCP\IURLGenerator;
  41. use OCP\IUser;
  42. use OCP\IUserManager;
  43. use OCP\L10N\IFactory as IL10NFactory;
  44. use function array_column;
  45. use function array_fill_keys;
  46. use function array_filter;
  47. use function array_key_exists;
  48. use function array_merge;
  49. use function count;
  50. class ContactsStore implements IContactsStore {
  51. public function __construct(
  52. private IManager $contactsManager,
  53. private ?StatusService $userStatusService,
  54. private IConfig $config,
  55. private ProfileManager $profileManager,
  56. private IUserManager $userManager,
  57. private IURLGenerator $urlGenerator,
  58. private IGroupManager $groupManager,
  59. private KnownUserService $knownUserService,
  60. private IL10NFactory $l10nFactory,
  61. ) {
  62. }
  63. /**
  64. * @return IEntry[]
  65. */
  66. public function getContacts(IUser $user, ?string $filter, ?int $limit = null, ?int $offset = null): array {
  67. $options = [
  68. 'enumeration' => $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes',
  69. 'fullmatch' => $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match', 'yes') === 'yes',
  70. ];
  71. if ($limit !== null) {
  72. $options['limit'] = $limit;
  73. }
  74. if ($offset !== null) {
  75. $options['offset'] = $offset;
  76. }
  77. // Status integration only works without pagination and filters
  78. if ($offset === null && ($filter === null || $filter === '')) {
  79. $recentStatuses = $this->userStatusService?->findAllRecentStatusChanges($limit, $offset) ?? [];
  80. } else {
  81. $recentStatuses = [];
  82. }
  83. // Search by status if there is no filter and statuses are available
  84. if (!empty($recentStatuses)) {
  85. $allContacts = array_filter(array_map(function (UserStatus $userStatus) use ($options) {
  86. // UID is ambiguous with federation. We have to use the federated cloud ID to an exact match of
  87. // A local user
  88. $user = $this->userManager->get($userStatus->getUserId());
  89. if ($user === null) {
  90. return null;
  91. }
  92. $contact = $this->contactsManager->search(
  93. $user->getCloudId(),
  94. [
  95. 'CLOUD',
  96. ],
  97. array_merge(
  98. $options,
  99. [
  100. 'limit' => 1,
  101. 'offset' => 0,
  102. ],
  103. ),
  104. )[0] ?? null;
  105. if ($contact !== null) {
  106. $contact[Entry::PROPERTY_STATUS_MESSAGE_TIMESTAMP] = $userStatus->getStatusMessageTimestamp();
  107. }
  108. return $contact;
  109. }, $recentStatuses));
  110. if ($limit !== null && count($allContacts) < $limit) {
  111. // More contacts were requested
  112. $fromContacts = $this->contactsManager->search(
  113. $filter ?? '',
  114. [
  115. 'FN',
  116. 'EMAIL'
  117. ],
  118. array_merge(
  119. $options,
  120. [
  121. 'limit' => $limit - count($allContacts),
  122. ],
  123. ),
  124. );
  125. // Create hash map of all status contacts
  126. $existing = array_fill_keys(array_column($allContacts, 'URI'), null);
  127. // Append the ones that are new
  128. $allContacts = array_merge(
  129. $allContacts,
  130. array_filter($fromContacts, fn (array $contact): bool => !array_key_exists($contact['URI'], $existing))
  131. );
  132. }
  133. } else {
  134. $allContacts = $this->contactsManager->search(
  135. $filter ?? '',
  136. [
  137. 'FN',
  138. 'EMAIL'
  139. ],
  140. $options
  141. );
  142. }
  143. $userId = $user->getUID();
  144. $contacts = array_filter($allContacts, function ($contact) use ($userId) {
  145. // When searching for multiple results, we strip out the current user
  146. if (array_key_exists('UID', $contact)) {
  147. return $contact['UID'] !== $userId;
  148. }
  149. return true;
  150. });
  151. $entries = array_map(function (array $contact) {
  152. return $this->contactArrayToEntry($contact);
  153. }, $contacts);
  154. return $this->filterContacts(
  155. $user,
  156. $entries,
  157. $filter
  158. );
  159. }
  160. /**
  161. * Filters the contacts. Applied filters:
  162. * 1. if the `shareapi_allow_share_dialog_user_enumeration` config option is
  163. * enabled it will filter all local users
  164. * 2. if the `shareapi_exclude_groups` config option is enabled and the
  165. * current user is in an excluded group it will filter all local users.
  166. * 3. if the `shareapi_only_share_with_group_members` config option is
  167. * enabled it will filter all users which doesn't have a common group
  168. * with the current user.
  169. *
  170. * @param Entry[] $entries
  171. * @return Entry[] the filtered contacts
  172. */
  173. private function filterContacts(
  174. IUser $self,
  175. array $entries,
  176. ?string $filter
  177. ): array {
  178. $disallowEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') !== 'yes';
  179. $restrictEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
  180. $restrictEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes';
  181. $allowEnumerationFullMatch = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_full_match', 'yes') === 'yes';
  182. $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes';
  183. // whether to filter out local users
  184. $skipLocal = false;
  185. // whether to filter out all users which don't have a common group as the current user
  186. $ownGroupsOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
  187. $selfGroups = $this->groupManager->getUserGroupIds($self);
  188. if ($excludedGroups) {
  189. $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  190. $decodedExcludeGroups = json_decode($excludedGroups, true);
  191. $excludeGroupsList = $decodedExcludeGroups ?? [];
  192. if (count(array_intersect($excludeGroupsList, $selfGroups)) !== 0) {
  193. // a group of the current user is excluded -> filter all local users
  194. $skipLocal = true;
  195. }
  196. }
  197. $selfUID = $self->getUID();
  198. return array_values(array_filter($entries, function (IEntry $entry) use ($skipLocal, $ownGroupsOnly, $selfGroups, $selfUID, $disallowEnumeration, $restrictEnumerationGroup, $restrictEnumerationPhone, $allowEnumerationFullMatch, $filter) {
  199. if ($entry->getProperty('isLocalSystemBook')) {
  200. if ($skipLocal) {
  201. return false;
  202. }
  203. $checkedCommonGroupAlready = false;
  204. // Prevent enumerating local users
  205. if ($disallowEnumeration) {
  206. if (!$allowEnumerationFullMatch) {
  207. return false;
  208. }
  209. $filterOutUser = true;
  210. $mailAddresses = $entry->getEMailAddresses();
  211. foreach ($mailAddresses as $mailAddress) {
  212. if ($mailAddress === $filter) {
  213. $filterOutUser = false;
  214. break;
  215. }
  216. }
  217. if ($entry->getProperty('UID') && $entry->getProperty('UID') === $filter) {
  218. $filterOutUser = false;
  219. }
  220. if ($filterOutUser) {
  221. return false;
  222. }
  223. } elseif ($restrictEnumerationPhone || $restrictEnumerationGroup) {
  224. $canEnumerate = false;
  225. if ($restrictEnumerationPhone) {
  226. $canEnumerate = $this->knownUserService->isKnownToUser($selfUID, $entry->getProperty('UID'));
  227. }
  228. if (!$canEnumerate && $restrictEnumerationGroup) {
  229. $user = $this->userManager->get($entry->getProperty('UID'));
  230. if ($user === null) {
  231. return false;
  232. }
  233. $contactGroups = $this->groupManager->getUserGroupIds($user);
  234. $canEnumerate = !empty(array_intersect($contactGroups, $selfGroups));
  235. $checkedCommonGroupAlready = true;
  236. }
  237. if (!$canEnumerate) {
  238. return false;
  239. }
  240. }
  241. if ($ownGroupsOnly && !$checkedCommonGroupAlready) {
  242. $user = $this->userManager->get($entry->getProperty('UID'));
  243. if (!$user instanceof IUser) {
  244. return false;
  245. }
  246. $contactGroups = $this->groupManager->getUserGroupIds($user);
  247. if (empty(array_intersect($contactGroups, $selfGroups))) {
  248. // no groups in common, so shouldn't see the contact
  249. return false;
  250. }
  251. }
  252. }
  253. return true;
  254. }));
  255. }
  256. public function findOne(IUser $user, int $shareType, string $shareWith): ?IEntry {
  257. switch ($shareType) {
  258. case 0:
  259. case 6:
  260. $filter = ['UID'];
  261. break;
  262. case 4:
  263. $filter = ['EMAIL'];
  264. break;
  265. default:
  266. return null;
  267. }
  268. $contacts = $this->contactsManager->search($shareWith, $filter, [
  269. 'strict_search' => true,
  270. ]);
  271. $match = null;
  272. foreach ($contacts as $contact) {
  273. if ($shareType === 4 && isset($contact['EMAIL'])) {
  274. if (in_array($shareWith, $contact['EMAIL'])) {
  275. $match = $contact;
  276. break;
  277. }
  278. }
  279. if ($shareType === 0 || $shareType === 6) {
  280. $isLocal = $contact['isLocalSystemBook'] ?? false;
  281. if ($contact['UID'] === $shareWith && $isLocal === true) {
  282. $match = $contact;
  283. break;
  284. }
  285. }
  286. }
  287. if ($match) {
  288. $match = $this->filterContacts($user, [$this->contactArrayToEntry($match)], $shareWith);
  289. if (count($match) === 1) {
  290. $match = $match[0];
  291. } else {
  292. $match = null;
  293. }
  294. }
  295. return $match;
  296. }
  297. private function contactArrayToEntry(array $contact): Entry {
  298. $entry = new Entry();
  299. if (!empty($contact['UID'])) {
  300. $uid = $contact['UID'];
  301. $entry->setId($uid);
  302. $entry->setProperty('isUser', false);
  303. // overloaded usage so leaving as-is for now
  304. if (isset($contact['isLocalSystemBook'])) {
  305. $avatar = $this->urlGenerator->linkToRouteAbsolute('core.avatar.getAvatar', ['userId' => $uid, 'size' => 64]);
  306. $entry->setProperty('isUser', true);
  307. } elseif (!empty($contact['FN'])) {
  308. $avatar = $this->urlGenerator->linkToRouteAbsolute('core.GuestAvatar.getAvatar', ['guestName' => str_replace('/', ' ', $contact['FN']), 'size' => 64]);
  309. } else {
  310. $avatar = $this->urlGenerator->linkToRouteAbsolute('core.GuestAvatar.getAvatar', ['guestName' => str_replace('/', ' ', $uid), 'size' => 64]);
  311. }
  312. $entry->setAvatar($avatar);
  313. }
  314. if (!empty($contact['FN'])) {
  315. $entry->setFullName($contact['FN']);
  316. }
  317. $avatarPrefix = "VALUE=uri:";
  318. if (!empty($contact['PHOTO']) && str_starts_with($contact['PHOTO'], $avatarPrefix)) {
  319. $entry->setAvatar(substr($contact['PHOTO'], strlen($avatarPrefix)));
  320. }
  321. if (!empty($contact['EMAIL'])) {
  322. foreach ($contact['EMAIL'] as $email) {
  323. $entry->addEMailAddress($email);
  324. }
  325. }
  326. // Provide profile parameters for core/src/OC/contactsmenu/contact.handlebars template
  327. if (!empty($contact['UID']) && !empty($contact['FN'])) {
  328. $targetUserId = $contact['UID'];
  329. $targetUser = $this->userManager->get($targetUserId);
  330. if (!empty($targetUser)) {
  331. if ($this->profileManager->isProfileEnabled($targetUser)) {
  332. $entry->setProfileTitle($this->l10nFactory->get('lib')->t('View profile'));
  333. $entry->setProfileUrl($this->urlGenerator->linkToRouteAbsolute('core.ProfilePage.index', ['targetUserId' => $targetUserId]));
  334. }
  335. }
  336. }
  337. // Attach all other properties to the entry too because some
  338. // providers might make use of it.
  339. $entry->setProperties($contact);
  340. return $entry;
  341. }
  342. }