3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Module;
24 use Friendica\BaseModule;
25 use Friendica\Content\ContactSelector;
26 use Friendica\Content\Nav;
27 use Friendica\Content\Pager;
28 use Friendica\Content\Widget;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\System;
33 use Friendica\Core\Theme;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
38 use Friendica\Model\User;
39 use Friendica\Module\Security\Login;
40 use Friendica\Network\HTTPException\InternalServerErrorException;
41 use Friendica\Network\HTTPException\NotFoundException;
42 use Friendica\Worker\UpdateContact;
45 * Manages and show Contacts and their content
47 class Contact extends BaseModule
49 const TAB_CONVERSATIONS = 1;
51 const TAB_PROFILE = 3;
52 const TAB_CONTACTS = 4;
53 const TAB_ADVANCED = 5;
56 private static function batchActions()
58 if (empty($_POST['contact_batch']) || !is_array($_POST['contact_batch'])) {
62 $redirectUrl = $_POST['redirect_url'] ?? 'contact';
64 self::checkFormSecurityTokenRedirectOnError($redirectUrl, 'contact_batch_actions');
66 $orig_records = Model\Contact::selectToArray(['id', 'uid'], ['id' => $_POST['contact_batch'], 'uid' => [0, DI::userSession()->getLocalUserId()], 'self' => false, 'deleted' => false]);
69 foreach ($orig_records as $orig_record) {
70 $cdata = Model\Contact::getPublicAndUserContactID($orig_record['id'], DI::userSession()->getLocalUserId());
71 if (empty($cdata) || DI::userSession()->getPublicContactId() === $cdata['public']) {
72 // No action available on your own contact
76 if (!empty($_POST['contacts_batch_update']) && $cdata['user']) {
77 self::updateContactFromPoll($cdata['user']);
81 if (!empty($_POST['contacts_batch_block'])) {
82 self::toggleBlockContact($cdata['public'], DI::userSession()->getLocalUserId());
86 if (!empty($_POST['contacts_batch_ignore'])) {
87 self::toggleIgnoreContact($cdata['public']);
91 if (!empty($_POST['contacts_batch_collapse'])) {
92 self::toggleCollapseContact($cdata['public']);
96 if ($count_actions > 0) {
97 DI::sysmsg()->addInfo(DI::l10n()->tt('%d contact edited.', '%d contacts edited.', $count_actions));
100 DI::baseUrl()->redirect($redirectUrl);
103 protected function post(array $request = [])
105 if (!DI::userSession()->getLocalUserId()) {
109 // @TODO: Replace with parameter from router
110 if (DI::args()->getArgv()[1] === 'batch') {
111 self::batchActions();
115 /* contact actions */
118 * @param int $contact_id Id of contact with uid != 0
119 * @throws NotFoundException
120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121 * @throws \ImagickException
123 public static function updateContactFromPoll(int $contact_id)
125 $contact = DBA::selectFirst('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => DI::userSession()->getLocalUserId(), 'deleted' => false]);
126 if (!DBA::isResult($contact)) {
130 if ($contact['network'] == Protocol::OSTATUS) {
131 $result = Model\Contact::createFromProbeForUser($contact['uid'], $contact['url'], $contact['network']);
133 if ($result['success']) {
134 Model\Contact::update(['subhub' => 1], ['id' => $contact_id]);
137 // pull feed and consume it, which should subscribe to the hub.
138 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
141 UpdateContact::add(Worker::PRIORITY_HIGH, $contact_id);
142 } catch (\InvalidArgumentException $e) {
143 Logger::notice($e->getMessage(), ['contact' => $contact, 'callstack' => System::callstack()]);
149 * Toggles the blocked status of a contact identified by id.
151 * @param int $contact_id Id of the contact with uid = 0
152 * @param int $owner_id Id of the user we want to block the contact for
155 private static function toggleBlockContact(int $contact_id, int $owner_id)
157 $blocked = !Model\Contact\User::isBlocked($contact_id, $owner_id);
158 Model\Contact\User::setBlocked($contact_id, $owner_id, $blocked);
162 * Toggles the ignored status of a contact identified by id.
164 * @param int $contact_id Id of the contact with uid = 0
167 private static function toggleIgnoreContact(int $contact_id)
169 $ignored = !Model\Contact\User::isIgnored($contact_id, DI::userSession()->getLocalUserId());
170 Model\Contact\User::setIgnored($contact_id, DI::userSession()->getLocalUserId(), $ignored);
174 * Toggles the collapsed status of a contact identified by id.
176 * @param int $contact_id Id of the contact with uid = 0
179 private static function toggleCollapseContact(int $contact_id)
181 $collapsed = !Model\Contact\User::isCollapsed($contact_id, DI::userSession()->getLocalUserId());
182 Model\Contact\User::setCollapsed($contact_id, DI::userSession()->getLocalUserId(), $collapsed);
185 protected function content(array $request = []): string
187 if (!DI::userSession()->getLocalUserId()) {
188 return Login::form($_SERVER['REQUEST_URI']);
191 $search = trim($_GET['search'] ?? '');
192 $nets = trim($_GET['nets'] ?? '');
193 $rel = trim($_GET['rel'] ?? '');
194 $group = trim($_GET['group'] ?? '');
196 $accounttype = $_GET['accounttype'] ?? '';
197 $accounttypeid = User::getAccountTypeByString($accounttype);
201 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
202 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
203 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
204 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
207 $findpeople_widget = Widget::findPeople();
208 if (isset($_GET['add'])) {
209 $follow_widget = Widget::follow($_GET['add']);
211 $follow_widget = Widget::follow();
214 $account_widget = Widget::accountTypes($_SERVER['REQUEST_URI'], $accounttype);
215 $networks_widget = Widget::networks($_SERVER['REQUEST_URI'], $nets);
216 $rel_widget = Widget::contactRels($_SERVER['REQUEST_URI'], $rel);
217 $groups_widget = Widget::groups($_SERVER['REQUEST_URI'], $group);
219 DI::page()['aside'] .= $vcard_widget . $findpeople_widget . $follow_widget . $rel_widget . $groups_widget . $networks_widget . $account_widget;
221 $tpl = Renderer::getMarkupTemplate('contacts-head.tpl');
222 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
226 Nav::setSelected('contact');
228 $_SESSION['return_path'] = DI::args()->getQueryString();
230 $sql_values = [DI::userSession()->getLocalUserId()];
232 // @TODO: Replace with parameter from router
233 $type = DI::args()->getArgv()[1] ?? '';
237 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`blocked`)";
238 // This makes the query look for contact.uid = 0
239 array_unshift($sql_values, 0);
242 $sql_extra = " AND `hidden` AND NOT `blocked` AND NOT `pending`";
245 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`ignored`)";
246 // This makes the query look for contact.uid = 0
247 array_unshift($sql_values, 0);
250 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`collapsed`)";
251 // This makes the query look for contact.uid = 0
252 array_unshift($sql_values, 0);
255 $sql_extra = " AND `archive` AND NOT `blocked` AND NOT `pending`";
258 $sql_extra = " AND `pending` AND NOT `archive` AND NOT `failed` AND ((`rel` = ?)
259 OR `id` IN (SELECT `contact-id` FROM `intro` WHERE `intro`.`uid` = ? AND NOT `ignore`))";
260 $sql_values[] = Model\Contact::SHARING;
261 $sql_values[] = DI::userSession()->getLocalUserId();
264 $sql_extra = " AND NOT `archive` AND NOT `blocked` AND NOT `pending`";
268 if (isset($accounttypeid)) {
269 $sql_extra .= " AND `contact-type` = ?";
270 $sql_values[] = $accounttypeid;
277 $search_hdr = $search;
278 $search_txt = preg_quote(trim($search, ' @!'));
279 $sql_extra .= " AND (`name` REGEXP ? OR `url` REGEXP ? OR `nick` REGEXP ? OR `addr` REGEXP ? OR `alias` REGEXP ?)";
280 $sql_values[] = $search_txt;
281 $sql_values[] = $search_txt;
282 $sql_values[] = $search_txt;
283 $sql_values[] = $search_txt;
284 $sql_values[] = $search_txt;
288 $sql_extra .= " AND network = ? ";
289 $sql_values[] = $nets;
294 $sql_extra .= " AND `rel` IN (?, ?)";
295 $sql_values[] = Model\Contact::FOLLOWER;
296 $sql_values[] = Model\Contact::FRIEND;
299 $sql_extra .= " AND `rel` IN (?, ?)";
300 $sql_values[] = Model\Contact::SHARING;
301 $sql_values[] = Model\Contact::FRIEND;
304 $sql_extra .= " AND `rel` = ?";
305 $sql_values[] = Model\Contact::FRIEND;
310 $sql_extra .= " AND `id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)";
311 $sql_values[] = $group;
314 $networks = Widget::unavailableNetworks();
315 $sql_extra .= " AND NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")";
316 $sql_values = array_merge($sql_values, $networks);
318 $condition = ["`uid` = ? AND NOT `self` AND NOT `deleted`" . $sql_extra];
319 $condition = array_merge($condition, $sql_values);
321 $total = DBA::count('contact', $condition);
323 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
327 $stmt = DBA::select('contact', [], $condition, ['order' => ['name'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
329 while ($contact = DBA::fetch($stmt)) {
330 $contact['blocked'] = Model\Contact\User::isBlocked($contact['id'], DI::userSession()->getLocalUserId());
331 $contact['readonly'] = Model\Contact\User::isIgnored($contact['id'], DI::userSession()->getLocalUserId());
332 $contacts[] = self::getContactTemplateVars($contact);
338 'label' => DI::l10n()->t('All Contacts'),
340 'sel' => !$type ? 'active' : '',
341 'title' => DI::l10n()->t('Show all contacts'),
342 'id' => 'showall-tab',
346 'label' => DI::l10n()->t('Pending'),
347 'url' => 'contact/pending',
348 'sel' => $type == 'pending' ? 'active' : '',
349 'title' => DI::l10n()->t('Only show pending contacts'),
350 'id' => 'showpending-tab',
354 'label' => DI::l10n()->t('Blocked'),
355 'url' => 'contact/blocked',
356 'sel' => $type == 'blocked' ? 'active' : '',
357 'title' => DI::l10n()->t('Only show blocked contacts'),
358 'id' => 'showblocked-tab',
362 'label' => DI::l10n()->t('Ignored'),
363 'url' => 'contact/ignored',
364 'sel' => $type == 'ignored' ? 'active' : '',
365 'title' => DI::l10n()->t('Only show ignored contacts'),
366 'id' => 'showignored-tab',
370 'label' => DI::l10n()->t('Collapsed'),
371 'url' => 'contact/collapsed',
372 'sel' => $type == 'collapsed' ? 'active' : '',
373 'title' => DI::l10n()->t('Only show collapsed contacts'),
374 'id' => 'showcollapsed-tab',
378 'label' => DI::l10n()->t('Archived'),
379 'url' => 'contact/archived',
380 'sel' => $type == 'archived' ? 'active' : '',
381 'title' => DI::l10n()->t('Only show archived contacts'),
382 'id' => 'showarchived-tab',
386 'label' => DI::l10n()->t('Hidden'),
387 'url' => 'contact/hidden',
388 'sel' => $type == 'hidden' ? 'active' : '',
389 'title' => DI::l10n()->t('Only show hidden contacts'),
390 'id' => 'showhidden-tab',
394 'label' => DI::l10n()->t('Groups'),
397 'title' => DI::l10n()->t('Organize your contact groups'),
398 'id' => 'contactgroups-tab',
403 $tabs_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
404 $tabs_html = Renderer::replaceMacros($tabs_tpl, ['$tabs' => $tabs]);
407 case 'followers': $header = DI::l10n()->t('Followers'); break;
408 case 'following': $header = DI::l10n()->t('Following'); break;
409 case 'mutuals': $header = DI::l10n()->t('Mutual friends'); break;
410 default: $header = DI::l10n()->t('Contacts');
414 case 'pending': $header .= ' - ' . DI::l10n()->t('Pending'); break;
415 case 'blocked': $header .= ' - ' . DI::l10n()->t('Blocked'); break;
416 case 'hidden': $header .= ' - ' . DI::l10n()->t('Hidden'); break;
417 case 'ignored': $header .= ' - ' . DI::l10n()->t('Ignored'); break;
418 case 'collapsed': $header .= ' - ' . DI::l10n()->t('Collapsed'); break;
419 case 'archived': $header .= ' - ' . DI::l10n()->t('Archived'); break;
422 $header .= $nets ? ' - ' . ContactSelector::networkToName($nets) : '';
424 $tpl = Renderer::getMarkupTemplate('contacts-template.tpl');
425 $o .= Renderer::replaceMacros($tpl, [
426 '$header' => $header,
427 '$tabs' => $tabs_html,
429 '$search' => $search_hdr,
430 '$desc' => DI::l10n()->t('Search your contacts'),
431 '$finding' => $searching ? DI::l10n()->t('Results for: %s', $search) : '',
432 '$submit' => DI::l10n()->t('Find'),
433 '$cmd' => DI::args()->getCommand(),
434 '$contacts' => $contacts,
435 '$form_security_token' => BaseModule::getFormSecurityToken('contact_batch_actions'),
437 '$batch_actions' => [
438 'contacts_batch_update' => DI::l10n()->t('Update'),
439 'contacts_batch_block' => DI::l10n()->t('Block') . '/' . DI::l10n()->t('Unblock'),
440 'contacts_batch_ignore' => DI::l10n()->t('Ignore') . '/' . DI::l10n()->t('Unignore'),
441 'contacts_batch_collapse' => DI::l10n()->t('Collapse') . '/' . DI::l10n()->t('Uncollapse'),
443 '$h_batch_actions' => DI::l10n()->t('Batch Actions'),
444 '$paginate' => $pager->renderFull($total),
451 * List of pages for the Contact TabBar
453 * Available Pages are 'Conversations', 'Profile', 'Contacts' and 'Common Friends'
455 * @param array $contact The contact array
456 * @param int $active_tab 1 if tab should be marked as active
458 * @return string HTML string of the contact page tabs buttons.
459 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
460 * @throws \ImagickException
462 public static function getTabsHTML(array $contact, int $active_tab)
464 $cid = $pcid = $contact['id'];
465 $data = Model\Contact::getPublicAndUserContactID($contact['id'], DI::userSession()->getLocalUserId());
466 if (!empty($data['user']) && ($contact['id'] == $data['public'])) {
467 $cid = $data['user'];
468 } elseif (!empty($data['public'])) {
469 $pcid = $data['public'];
475 'label' => DI::l10n()->t('Profile'),
476 'url' => 'contact/' . $cid,
477 'sel' => (($active_tab == self::TAB_PROFILE) ? 'active' : ''),
478 'title' => DI::l10n()->t('Profile Details'),
479 'id' => 'profile-tab',
483 'label' => DI::l10n()->t('Conversations'),
484 'url' => 'contact/' . $pcid . '/conversations',
485 'sel' => (($active_tab == self::TAB_CONVERSATIONS) ? 'active' : ''),
486 'title' => DI::l10n()->t('Conversations started by this contact'),
487 'id' => 'status-tab',
491 'label' => DI::l10n()->t('Posts and Comments'),
492 'url' => 'contact/' . $pcid . '/posts',
493 'sel' => (($active_tab == self::TAB_POSTS) ? 'active' : ''),
494 'title' => DI::l10n()->t('Individual Posts and Replies'),
499 'label' => DI::l10n()->t('Media'),
500 'url' => 'contact/' . $pcid . '/media',
501 'sel' => (($active_tab == self::TAB_MEDIA) ? 'active' : ''),
502 'title' => DI::l10n()->t('Posts containing media objects'),
506 ['label' => DI::l10n()->t('Contacts'),
507 'url' => 'contact/' . $pcid . '/contacts',
508 'sel' => (($active_tab == self::TAB_CONTACTS) ? 'active' : ''),
509 'title' => DI::l10n()->t('View all known contacts'),
510 'id' => 'contacts-tab',
515 if (!empty($contact['network']) && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && ($cid != $pcid)) {
516 $tabs[] = ['label' => DI::l10n()->t('Advanced'),
517 'url' => 'contact/' . $cid . '/advanced/',
518 'sel' => (($active_tab == self::TAB_ADVANCED) ? 'active' : ''),
519 'title' => DI::l10n()->t('Advanced Contact Settings'),
520 'id' => 'advanced-tab',
525 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
526 $tab_str = Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
532 * Return the fields for the contact template
534 * @param array $contact Contact array
535 * @return array Template fields
536 * @throws InternalServerErrorException
537 * @throws \ImagickException
539 public static function getContactTemplateVars(array $contact): array
543 if (!empty($contact['url']) && isset($contact['uid']) && ($contact['uid'] == 0) && DI::userSession()->getLocalUserId()) {
544 $personal = Model\Contact::getByURL($contact['url'], false, ['uid', 'rel', 'self'], DI::userSession()->getLocalUserId());
545 if (!empty($personal)) {
546 $contact['uid'] = $personal['uid'];
547 $contact['rel'] = $personal['rel'];
548 $contact['self'] = $personal['self'];
552 if (!empty($contact['uid']) && !empty($contact['rel']) && DI::userSession()->getLocalUserId() == $contact['uid']) {
553 switch ($contact['rel']) {
554 case Model\Contact::FRIEND:
555 $alt_text = DI::l10n()->t('Mutual Friendship');
558 case Model\Contact::FOLLOWER;
559 $alt_text = DI::l10n()->t('is a fan of yours');
562 case Model\Contact::SHARING;
563 $alt_text = DI::l10n()->t('you are a fan of');
571 $url = Model\Contact::magicLinkByContact($contact);
573 if (strpos($url, 'contact/redir/') === 0) {
574 $sparkle = ' class="sparkle" ';
579 if ($contact['pending']) {
580 if (in_array($contact['rel'], [Model\Contact::FRIEND, Model\Contact::SHARING])) {
581 $alt_text = DI::l10n()->t('Pending outgoing contact request');
583 $alt_text = DI::l10n()->t('Pending incoming contact request');
587 if ($contact['self']) {
588 $alt_text = DI::l10n()->t('This is you');
589 $url = $contact['url'];
594 'id' => $contact['id'],
596 'img_hover' => DI::l10n()->t('Visit %s\'s profile [%s]', $contact['name'], $contact['url']),
597 'photo_menu' => Model\Contact::photoMenu($contact, DI::userSession()->getLocalUserId()),
598 'thumb' => Model\Contact::getThumb($contact, true),
599 'alt_text' => $alt_text,
600 'name' => $contact['name'],
601 'nick' => $contact['nick'],
602 'details' => $contact['location'],
603 'tags' => $contact['keywords'],
604 'about' => $contact['about'],
605 'account_type' => Model\Contact::getAccountType($contact['contact-type']),
606 'sparkle' => $sparkle,
607 'itemurl' => ($contact['addr'] ?? '') ?: $contact['url'],
608 'network' => ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol'], $contact['gsid']),