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 ($count_actions > 0) {
92 DI::sysmsg()->addInfo(DI::l10n()->tt('%d contact edited.', '%d contacts edited.', $count_actions));
95 DI::baseUrl()->redirect($redirectUrl);
98 protected function post(array $request = [])
100 if (!DI::userSession()->getLocalUserId()) {
104 // @TODO: Replace with parameter from router
105 if (DI::args()->getArgv()[1] === 'batch') {
106 self::batchActions();
110 /* contact actions */
113 * @param int $contact_id Id of contact with uid != 0
114 * @throws NotFoundException
115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
116 * @throws \ImagickException
118 public static function updateContactFromPoll(int $contact_id)
120 $contact = DBA::selectFirst('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => DI::userSession()->getLocalUserId(), 'deleted' => false]);
121 if (!DBA::isResult($contact)) {
125 if ($contact['network'] == Protocol::OSTATUS) {
126 $result = Model\Contact::createFromProbeForUser($contact['uid'], $contact['url'], $contact['network']);
128 if ($result['success']) {
129 Model\Contact::update(['subhub' => 1], ['id' => $contact_id]);
132 // pull feed and consume it, which should subscribe to the hub.
133 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
136 UpdateContact::add(Worker::PRIORITY_HIGH, $contact_id);
137 } catch (\InvalidArgumentException $e) {
138 Logger::notice($e->getMessage(), ['contact' => $contact, 'callstack' => System::callstack()]);
144 * Toggles the blocked status of a contact identified by id.
146 * @param int $contact_id Id of the contact with uid = 0
147 * @param int $owner_id Id of the user we want to block the contact for
150 private static function toggleBlockContact(int $contact_id, int $owner_id)
152 $blocked = !Model\Contact\User::isBlocked($contact_id, $owner_id);
153 Model\Contact\User::setBlocked($contact_id, $owner_id, $blocked);
157 * Toggles the ignored status of a contact identified by id.
159 * @param int $contact_id Id of the contact with uid = 0
162 private static function toggleIgnoreContact(int $contact_id)
164 $ignored = !Model\Contact\User::isIgnored($contact_id, DI::userSession()->getLocalUserId());
165 Model\Contact\User::setIgnored($contact_id, DI::userSession()->getLocalUserId(), $ignored);
168 protected function content(array $request = []): string
170 if (!DI::userSession()->getLocalUserId()) {
171 return Login::form($_SERVER['REQUEST_URI']);
174 $search = trim($_GET['search'] ?? '');
175 $nets = trim($_GET['nets'] ?? '');
176 $rel = trim($_GET['rel'] ?? '');
177 $group = trim($_GET['group'] ?? '');
179 $accounttype = $_GET['accounttype'] ?? '';
180 $accounttypeid = User::getAccountTypeByString($accounttype);
184 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
185 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
186 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
187 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
190 $findpeople_widget = Widget::findPeople();
191 if (isset($_GET['add'])) {
192 $follow_widget = Widget::follow($_GET['add']);
194 $follow_widget = Widget::follow();
197 $account_widget = Widget::accountTypes($_SERVER['REQUEST_URI'], $accounttype);
198 $networks_widget = Widget::networks($_SERVER['REQUEST_URI'], $nets);
199 $rel_widget = Widget::contactRels($_SERVER['REQUEST_URI'], $rel);
200 $groups_widget = Widget::groups($_SERVER['REQUEST_URI'], $group);
202 DI::page()['aside'] .= $vcard_widget . $findpeople_widget . $follow_widget . $rel_widget . $groups_widget . $networks_widget . $account_widget;
204 $tpl = Renderer::getMarkupTemplate('contacts-head.tpl');
205 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
206 '$baseurl' => DI::baseUrl()->get(true),
210 Nav::setSelected('contact');
212 $_SESSION['return_path'] = DI::args()->getQueryString();
214 $sql_values = [DI::userSession()->getLocalUserId()];
216 // @TODO: Replace with parameter from router
217 $type = DI::args()->getArgv()[1] ?? '';
221 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`blocked`)";
222 // This makes the query look for contact.uid = 0
223 array_unshift($sql_values, 0);
226 $sql_extra = " AND `hidden` AND NOT `blocked` AND NOT `pending`";
229 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`ignored`)";
230 // This makes the query look for contact.uid = 0
231 array_unshift($sql_values, 0);
234 $sql_extra = " AND `archive` AND NOT `blocked` AND NOT `pending`";
237 $sql_extra = " AND `pending` AND NOT `archive` AND NOT `failed` AND ((`rel` = ?)
238 OR `id` IN (SELECT `contact-id` FROM `intro` WHERE `intro`.`uid` = ? AND NOT `ignore`))";
239 $sql_values[] = Model\Contact::SHARING;
240 $sql_values[] = DI::userSession()->getLocalUserId();
243 $sql_extra = " AND NOT `archive` AND NOT `blocked` AND NOT `pending`";
247 if (isset($accounttypeid)) {
248 $sql_extra .= " AND `contact-type` = ?";
249 $sql_values[] = $accounttypeid;
256 $search_hdr = $search;
257 $search_txt = preg_quote(trim($search, ' @!'));
258 $sql_extra .= " AND (`name` REGEXP ? OR `url` REGEXP ? OR `nick` REGEXP ? OR `addr` REGEXP ? OR `alias` REGEXP ?)";
259 $sql_values[] = $search_txt;
260 $sql_values[] = $search_txt;
261 $sql_values[] = $search_txt;
262 $sql_values[] = $search_txt;
263 $sql_values[] = $search_txt;
267 $sql_extra .= " AND network = ? ";
268 $sql_values[] = $nets;
273 $sql_extra .= " AND `rel` IN (?, ?)";
274 $sql_values[] = Model\Contact::FOLLOWER;
275 $sql_values[] = Model\Contact::FRIEND;
278 $sql_extra .= " AND `rel` IN (?, ?)";
279 $sql_values[] = Model\Contact::SHARING;
280 $sql_values[] = Model\Contact::FRIEND;
283 $sql_extra .= " AND `rel` = ?";
284 $sql_values[] = Model\Contact::FRIEND;
289 $sql_extra .= " AND `id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)";
290 $sql_values[] = $group;
293 $networks = Widget::unavailableNetworks();
294 $sql_extra .= " AND NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")";
295 $sql_values = array_merge($sql_values, $networks);
297 $condition = ["`uid` = ? AND NOT `self` AND NOT `deleted`" . $sql_extra];
298 $condition = array_merge($condition, $sql_values);
300 $total = DBA::count('contact', $condition);
302 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
306 $stmt = DBA::select('contact', [], $condition, ['order' => ['name'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
308 while ($contact = DBA::fetch($stmt)) {
309 $contact['blocked'] = Model\Contact\User::isBlocked($contact['id'], DI::userSession()->getLocalUserId());
310 $contact['readonly'] = Model\Contact\User::isIgnored($contact['id'], DI::userSession()->getLocalUserId());
311 $contacts[] = self::getContactTemplateVars($contact);
317 'label' => DI::l10n()->t('All Contacts'),
319 'sel' => !$type ? 'active' : '',
320 'title' => DI::l10n()->t('Show all contacts'),
321 'id' => 'showall-tab',
325 'label' => DI::l10n()->t('Pending'),
326 'url' => 'contact/pending',
327 'sel' => $type == 'pending' ? 'active' : '',
328 'title' => DI::l10n()->t('Only show pending contacts'),
329 'id' => 'showpending-tab',
333 'label' => DI::l10n()->t('Blocked'),
334 'url' => 'contact/blocked',
335 'sel' => $type == 'blocked' ? 'active' : '',
336 'title' => DI::l10n()->t('Only show blocked contacts'),
337 'id' => 'showblocked-tab',
341 'label' => DI::l10n()->t('Ignored'),
342 'url' => 'contact/ignored',
343 'sel' => $type == 'ignored' ? 'active' : '',
344 'title' => DI::l10n()->t('Only show ignored contacts'),
345 'id' => 'showignored-tab',
349 'label' => DI::l10n()->t('Archived'),
350 'url' => 'contact/archived',
351 'sel' => $type == 'archived' ? 'active' : '',
352 'title' => DI::l10n()->t('Only show archived contacts'),
353 'id' => 'showarchived-tab',
357 'label' => DI::l10n()->t('Hidden'),
358 'url' => 'contact/hidden',
359 'sel' => $type == 'hidden' ? 'active' : '',
360 'title' => DI::l10n()->t('Only show hidden contacts'),
361 'id' => 'showhidden-tab',
365 'label' => DI::l10n()->t('Groups'),
368 'title' => DI::l10n()->t('Organize your contact groups'),
369 'id' => 'contactgroups-tab',
374 $tabs_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
375 $tabs_html = Renderer::replaceMacros($tabs_tpl, ['$tabs' => $tabs]);
378 case 'followers': $header = DI::l10n()->t('Followers'); break;
379 case 'following': $header = DI::l10n()->t('Following'); break;
380 case 'mutuals': $header = DI::l10n()->t('Mutual friends'); break;
381 default: $header = DI::l10n()->t('Contacts');
385 case 'pending': $header .= ' - ' . DI::l10n()->t('Pending'); break;
386 case 'blocked': $header .= ' - ' . DI::l10n()->t('Blocked'); break;
387 case 'hidden': $header .= ' - ' . DI::l10n()->t('Hidden'); break;
388 case 'ignored': $header .= ' - ' . DI::l10n()->t('Ignored'); break;
389 case 'archived': $header .= ' - ' . DI::l10n()->t('Archived'); break;
392 $header .= $nets ? ' - ' . ContactSelector::networkToName($nets) : '';
394 $tpl = Renderer::getMarkupTemplate('contacts-template.tpl');
395 $o .= Renderer::replaceMacros($tpl, [
396 '$header' => $header,
397 '$tabs' => $tabs_html,
399 '$search' => $search_hdr,
400 '$desc' => DI::l10n()->t('Search your contacts'),
401 '$finding' => $searching ? DI::l10n()->t('Results for: %s', $search) : '',
402 '$submit' => DI::l10n()->t('Find'),
403 '$cmd' => DI::args()->getCommand(),
404 '$contacts' => $contacts,
405 '$form_security_token' => BaseModule::getFormSecurityToken('contact_batch_actions'),
407 '$batch_actions' => [
408 'contacts_batch_update' => DI::l10n()->t('Update'),
409 'contacts_batch_block' => DI::l10n()->t('Block') . '/' . DI::l10n()->t('Unblock'),
410 'contacts_batch_ignore' => DI::l10n()->t('Ignore') . '/' . DI::l10n()->t('Unignore'),
412 '$h_batch_actions' => DI::l10n()->t('Batch Actions'),
413 '$paginate' => $pager->renderFull($total),
420 * List of pages for the Contact TabBar
422 * Available Pages are 'Status', 'Profile', 'Contacts' and 'Common Friends'
424 * @param array $contact The contact array
425 * @param int $active_tab 1 if tab should be marked as active
427 * @return string HTML string of the contact page tabs buttons.
428 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
429 * @throws \ImagickException
431 public static function getTabsHTML(array $contact, int $active_tab)
433 $cid = $pcid = $contact['id'];
434 $data = Model\Contact::getPublicAndUserContactID($contact['id'], DI::userSession()->getLocalUserId());
435 if (!empty($data['user']) && ($contact['id'] == $data['public'])) {
436 $cid = $data['user'];
437 } elseif (!empty($data['public'])) {
438 $pcid = $data['public'];
444 'label' => DI::l10n()->t('Status'),
445 'url' => 'contact/' . $pcid . '/conversations',
446 'sel' => (($active_tab == self::TAB_CONVERSATIONS) ? 'active' : ''),
447 'title' => DI::l10n()->t('Conversations started by this contact'),
448 'id' => 'status-tab',
452 'label' => DI::l10n()->t('Posts and Comments'),
453 'url' => 'contact/' . $pcid . '/posts',
454 'sel' => (($active_tab == self::TAB_POSTS) ? 'active' : ''),
455 'title' => DI::l10n()->t('Status Messages and Posts'),
460 'label' => DI::l10n()->t('Media'),
461 'url' => 'contact/' . $pcid . '/media',
462 'sel' => (($active_tab == self::TAB_MEDIA) ? 'active' : ''),
463 'title' => DI::l10n()->t('Posts containing media objects'),
468 'label' => DI::l10n()->t('Profile'),
469 'url' => 'contact/' . $cid,
470 'sel' => (($active_tab == self::TAB_PROFILE) ? 'active' : ''),
471 'title' => DI::l10n()->t('Profile Details'),
472 'id' => 'profile-tab',
475 ['label' => DI::l10n()->t('Contacts'),
476 'url' => 'contact/' . $pcid . '/contacts',
477 'sel' => (($active_tab == self::TAB_CONTACTS) ? 'active' : ''),
478 'title' => DI::l10n()->t('View all known contacts'),
479 'id' => 'contacts-tab',
484 if (!empty($contact['network']) && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && ($cid != $pcid)) {
485 $tabs[] = ['label' => DI::l10n()->t('Advanced'),
486 'url' => 'contact/' . $cid . '/advanced/',
487 'sel' => (($active_tab == self::TAB_ADVANCED) ? 'active' : ''),
488 'title' => DI::l10n()->t('Advanced Contact Settings'),
489 'id' => 'advanced-tab',
494 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
495 $tab_str = Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
501 * Return the fields for the contact template
503 * @param array $contact Contact array
504 * @return array Template fields
505 * @throws InternalServerErrorException
506 * @throws \ImagickException
508 public static function getContactTemplateVars(array $contact): array
512 if (!empty($contact['url']) && isset($contact['uid']) && ($contact['uid'] == 0) && DI::userSession()->getLocalUserId()) {
513 $personal = Model\Contact::getByURL($contact['url'], false, ['uid', 'rel', 'self'], DI::userSession()->getLocalUserId());
514 if (!empty($personal)) {
515 $contact['uid'] = $personal['uid'];
516 $contact['rel'] = $personal['rel'];
517 $contact['self'] = $personal['self'];
521 if (!empty($contact['uid']) && !empty($contact['rel']) && DI::userSession()->getLocalUserId() == $contact['uid']) {
522 switch ($contact['rel']) {
523 case Model\Contact::FRIEND:
524 $alt_text = DI::l10n()->t('Mutual Friendship');
527 case Model\Contact::FOLLOWER;
528 $alt_text = DI::l10n()->t('is a fan of yours');
531 case Model\Contact::SHARING;
532 $alt_text = DI::l10n()->t('you are a fan of');
540 $url = Model\Contact::magicLinkByContact($contact);
542 if (strpos($url, 'contact/redir/') === 0) {
543 $sparkle = ' class="sparkle" ';
548 if ($contact['pending']) {
549 if (in_array($contact['rel'], [Model\Contact::FRIEND, Model\Contact::SHARING])) {
550 $alt_text = DI::l10n()->t('Pending outgoing contact request');
552 $alt_text = DI::l10n()->t('Pending incoming contact request');
556 if ($contact['self']) {
557 $alt_text = DI::l10n()->t('This is you');
558 $url = $contact['url'];
563 'id' => $contact['id'],
565 'img_hover' => DI::l10n()->t('Visit %s\'s profile [%s]', $contact['name'], $contact['url']),
566 'photo_menu' => Model\Contact::photoMenu($contact, DI::userSession()->getLocalUserId()),
567 'thumb' => Model\Contact::getThumb($contact, true),
568 'alt_text' => $alt_text,
569 'name' => $contact['name'],
570 'nick' => $contact['nick'],
571 'details' => $contact['location'],
572 'tags' => $contact['keywords'],
573 'about' => $contact['about'],
574 'account_type' => Model\Contact::getAccountType($contact['contact-type']),
575 'sparkle' => $sparkle,
576 'itemurl' => ($contact['addr'] ?? '') ?: $contact['url'],
577 'network' => ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol'], $contact['gsid']),