3 * @copyright Copyright (C) 2010-2022, 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\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Theme;
32 use Friendica\Core\Worker;
33 use Friendica\Database\DBA;
36 use Friendica\Model\User;
37 use Friendica\Module\Security\Login;
38 use Friendica\Network\HTTPException\NotFoundException;
41 * Manages and show Contacts and their content
43 class Contact extends BaseModule
45 const TAB_CONVERSATIONS = 1;
47 const TAB_PROFILE = 3;
48 const TAB_CONTACTS = 4;
49 const TAB_ADVANCED = 5;
52 private static function batchActions()
54 if (empty($_POST['contact_batch']) || !is_array($_POST['contact_batch'])) {
58 $redirectUrl = $_POST['redirect_url'] ?? 'contact';
60 self::checkFormSecurityTokenRedirectOnError($redirectUrl, 'contact_batch_actions');
62 $orig_records = Model\Contact::selectToArray(['id', 'uid'], ['id' => $_POST['contact_batch'], 'uid' => [0, DI::userSession()->getLocalUserId()], 'self' => false, 'deleted' => false]);
65 foreach ($orig_records as $orig_record) {
66 $cdata = Model\Contact::getPublicAndUserContactID($orig_record['id'], DI::userSession()->getLocalUserId());
67 if (empty($cdata) || DI::userSession()->getPublicContactId() === $cdata['public']) {
68 // No action available on your own contact
72 if (!empty($_POST['contacts_batch_update']) && $cdata['user']) {
73 self::updateContactFromPoll($cdata['user']);
77 if (!empty($_POST['contacts_batch_block'])) {
78 self::toggleBlockContact($cdata['public'], DI::userSession()->getLocalUserId());
82 if (!empty($_POST['contacts_batch_ignore'])) {
83 self::toggleIgnoreContact($cdata['public']);
87 if ($count_actions > 0) {
88 DI::sysmsg()->addInfo(DI::l10n()->tt('%d contact edited.', '%d contacts edited.', $count_actions));
91 DI::baseUrl()->redirect($redirectUrl);
94 protected function post(array $request = [])
96 if (!DI::userSession()->getLocalUserId()) {
100 // @TODO: Replace with parameter from router
101 if (DI::args()->getArgv()[1] === 'batch') {
102 self::batchActions();
106 /* contact actions */
109 * @param int $contact_id Id of contact with uid != 0
110 * @throws NotFoundException
111 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
112 * @throws \ImagickException
114 public static function updateContactFromPoll(int $contact_id)
116 $contact = DBA::selectFirst('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => DI::userSession()->getLocalUserId(), 'deleted' => false]);
117 if (!DBA::isResult($contact)) {
121 if ($contact['network'] == Protocol::OSTATUS) {
122 $result = Model\Contact::createFromProbeForUser($contact['uid'], $contact['url'], $contact['network']);
124 if ($result['success']) {
125 Model\Contact::update(['subhub' => 1], ['id' => $contact_id]);
128 // pull feed and consume it, which should subscribe to the hub.
129 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
131 Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
136 * Toggles the blocked status of a contact identified by id.
138 * @param int $contact_id Id of the contact with uid = 0
139 * @param int $owner_id Id of the user we want to block the contact for
142 private static function toggleBlockContact(int $contact_id, int $owner_id)
144 $blocked = !Model\Contact\User::isBlocked($contact_id, $owner_id);
145 Model\Contact\User::setBlocked($contact_id, $owner_id, $blocked);
149 * Toggles the ignored status of a contact identified by id.
151 * @param int $contact_id Id of the contact with uid = 0
154 private static function toggleIgnoreContact(int $contact_id)
156 $ignored = !Model\Contact\User::isIgnored($contact_id, DI::userSession()->getLocalUserId());
157 Model\Contact\User::setIgnored($contact_id, DI::userSession()->getLocalUserId(), $ignored);
160 protected function content(array $request = []): string
162 if (!DI::userSession()->getLocalUserId()) {
163 return Login::form($_SERVER['REQUEST_URI']);
166 $search = trim($_GET['search'] ?? '');
167 $nets = trim($_GET['nets'] ?? '');
168 $rel = trim($_GET['rel'] ?? '');
169 $group = trim($_GET['group'] ?? '');
171 $accounttype = $_GET['accounttype'] ?? '';
172 $accounttypeid = User::getAccountTypeByString($accounttype);
176 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
177 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
178 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
179 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
182 $findpeople_widget = Widget::findPeople();
183 if (isset($_GET['add'])) {
184 $follow_widget = Widget::follow($_GET['add']);
186 $follow_widget = Widget::follow();
189 $account_widget = Widget::accountTypes($_SERVER['REQUEST_URI'], $accounttype);
190 $networks_widget = Widget::networks($_SERVER['REQUEST_URI'], $nets);
191 $rel_widget = Widget::contactRels($_SERVER['REQUEST_URI'], $rel);
192 $groups_widget = Widget::groups($_SERVER['REQUEST_URI'], $group);
194 DI::page()['aside'] .= $vcard_widget . $findpeople_widget . $follow_widget . $account_widget . $groups_widget . $networks_widget . $rel_widget;
196 $tpl = Renderer::getMarkupTemplate('contacts-head.tpl');
197 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
198 '$baseurl' => DI::baseUrl()->get(true),
202 Nav::setSelected('contact');
204 $_SESSION['return_path'] = DI::args()->getQueryString();
206 $sql_values = [DI::userSession()->getLocalUserId()];
208 // @TODO: Replace with parameter from router
209 $type = DI::args()->getArgv()[1] ?? '';
213 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`blocked`)";
214 // This makes the query look for contact.uid = 0
215 array_unshift($sql_values, 0);
218 $sql_extra = " AND `hidden` AND NOT `blocked` AND NOT `pending`";
221 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`ignored`)";
222 // This makes the query look for contact.uid = 0
223 array_unshift($sql_values, 0);
226 $sql_extra = " AND `archive` AND NOT `blocked` AND NOT `pending`";
229 $sql_extra = " AND `pending` AND NOT `archive` AND NOT `failed` AND ((`rel` = ?)
230 OR `id` IN (SELECT `contact-id` FROM `intro` WHERE `intro`.`uid` = ? AND NOT `ignore`))";
231 $sql_values[] = Model\Contact::SHARING;
232 $sql_values[] = DI::userSession()->getLocalUserId();
235 $sql_extra = " AND NOT `archive` AND NOT `blocked` AND NOT `pending`";
239 if (isset($accounttypeid)) {
240 $sql_extra .= " AND `contact-type` = ?";
241 $sql_values[] = $accounttypeid;
248 $search_hdr = $search;
249 $search_txt = preg_quote(trim($search, ' @!'));
250 $sql_extra .= " AND (`name` REGEXP ? OR `url` REGEXP ? OR `nick` REGEXP ? OR `addr` REGEXP ? OR `alias` REGEXP ?)";
251 $sql_values[] = $search_txt;
252 $sql_values[] = $search_txt;
253 $sql_values[] = $search_txt;
254 $sql_values[] = $search_txt;
255 $sql_values[] = $search_txt;
259 $sql_extra .= " AND network = ? ";
260 $sql_values[] = $nets;
265 $sql_extra .= " AND `rel` IN (?, ?)";
266 $sql_values[] = Model\Contact::FOLLOWER;
267 $sql_values[] = Model\Contact::FRIEND;
270 $sql_extra .= " AND `rel` IN (?, ?)";
271 $sql_values[] = Model\Contact::SHARING;
272 $sql_values[] = Model\Contact::FRIEND;
275 $sql_extra .= " AND `rel` = ?";
276 $sql_values[] = Model\Contact::FRIEND;
281 $sql_extra .= " AND `id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)";
282 $sql_values[] = $group;
285 $networks = Widget::unavailableNetworks();
286 $sql_extra .= " AND NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")";
287 $sql_values = array_merge($sql_values, $networks);
289 $condition = ["`uid` = ? AND NOT `self` AND NOT `deleted`" . $sql_extra];
290 $condition = array_merge($condition, $sql_values);
292 $total = DBA::count('contact', $condition);
294 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
298 $stmt = DBA::select('contact', [], $condition, ['order' => ['name'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
300 while ($contact = DBA::fetch($stmt)) {
301 $contact['blocked'] = Model\Contact\User::isBlocked($contact['id'], DI::userSession()->getLocalUserId());
302 $contact['readonly'] = Model\Contact\User::isIgnored($contact['id'], DI::userSession()->getLocalUserId());
303 $contacts[] = self::getContactTemplateVars($contact);
309 'label' => DI::l10n()->t('All Contacts'),
311 'sel' => !$type ? 'active' : '',
312 'title' => DI::l10n()->t('Show all contacts'),
313 'id' => 'showall-tab',
317 'label' => DI::l10n()->t('Pending'),
318 'url' => 'contact/pending',
319 'sel' => $type == 'pending' ? 'active' : '',
320 'title' => DI::l10n()->t('Only show pending contacts'),
321 'id' => 'showpending-tab',
325 'label' => DI::l10n()->t('Blocked'),
326 'url' => 'contact/blocked',
327 'sel' => $type == 'blocked' ? 'active' : '',
328 'title' => DI::l10n()->t('Only show blocked contacts'),
329 'id' => 'showblocked-tab',
333 'label' => DI::l10n()->t('Ignored'),
334 'url' => 'contact/ignored',
335 'sel' => $type == 'ignored' ? 'active' : '',
336 'title' => DI::l10n()->t('Only show ignored contacts'),
337 'id' => 'showignored-tab',
341 'label' => DI::l10n()->t('Archived'),
342 'url' => 'contact/archived',
343 'sel' => $type == 'archived' ? 'active' : '',
344 'title' => DI::l10n()->t('Only show archived contacts'),
345 'id' => 'showarchived-tab',
349 'label' => DI::l10n()->t('Hidden'),
350 'url' => 'contact/hidden',
351 'sel' => $type == 'hidden' ? 'active' : '',
352 'title' => DI::l10n()->t('Only show hidden contacts'),
353 'id' => 'showhidden-tab',
357 'label' => DI::l10n()->t('Groups'),
360 'title' => DI::l10n()->t('Organize your contact groups'),
361 'id' => 'contactgroups-tab',
366 $tabs_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
367 $tabs_html = Renderer::replaceMacros($tabs_tpl, ['$tabs' => $tabs]);
370 case 'followers': $header = DI::l10n()->t('Followers'); break;
371 case 'following': $header = DI::l10n()->t('Following'); break;
372 case 'mutuals': $header = DI::l10n()->t('Mutual friends'); break;
373 default: $header = DI::l10n()->t('Contacts');
377 case 'pending': $header .= ' - ' . DI::l10n()->t('Pending'); break;
378 case 'blocked': $header .= ' - ' . DI::l10n()->t('Blocked'); break;
379 case 'hidden': $header .= ' - ' . DI::l10n()->t('Hidden'); break;
380 case 'ignored': $header .= ' - ' . DI::l10n()->t('Ignored'); break;
381 case 'archived': $header .= ' - ' . DI::l10n()->t('Archived'); break;
384 $header .= $nets ? ' - ' . ContactSelector::networkToName($nets) : '';
386 $tpl = Renderer::getMarkupTemplate('contacts-template.tpl');
387 $o .= Renderer::replaceMacros($tpl, [
388 '$header' => $header,
389 '$tabs' => $tabs_html,
391 '$search' => $search_hdr,
392 '$desc' => DI::l10n()->t('Search your contacts'),
393 '$finding' => $searching ? DI::l10n()->t('Results for: %s', $search) : '',
394 '$submit' => DI::l10n()->t('Find'),
395 '$cmd' => DI::args()->getCommand(),
396 '$contacts' => $contacts,
397 '$form_security_token' => BaseModule::getFormSecurityToken('contact_batch_actions'),
399 '$batch_actions' => [
400 'contacts_batch_update' => DI::l10n()->t('Update'),
401 'contacts_batch_block' => DI::l10n()->t('Block') . '/' . DI::l10n()->t('Unblock'),
402 'contacts_batch_ignore' => DI::l10n()->t('Ignore') . '/' . DI::l10n()->t('Unignore'),
404 '$h_batch_actions' => DI::l10n()->t('Batch Actions'),
405 '$paginate' => $pager->renderFull($total),
412 * List of pages for the Contact TabBar
414 * Available Pages are 'Status', 'Profile', 'Contacts' and 'Common Friends'
416 * @param array $contact The contact array
417 * @param int $active_tab 1 if tab should be marked as active
419 * @return string HTML string of the contact page tabs buttons.
420 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
421 * @throws \ImagickException
423 public static function getTabsHTML(array $contact, int $active_tab)
425 $cid = $pcid = $contact['id'];
426 $data = Model\Contact::getPublicAndUserContactID($contact['id'], DI::userSession()->getLocalUserId());
427 if (!empty($data['user']) && ($contact['id'] == $data['public'])) {
428 $cid = $data['user'];
429 } elseif (!empty($data['public'])) {
430 $pcid = $data['public'];
436 'label' => DI::l10n()->t('Status'),
437 'url' => 'contact/' . $pcid . '/conversations',
438 'sel' => (($active_tab == self::TAB_CONVERSATIONS) ? 'active' : ''),
439 'title' => DI::l10n()->t('Conversations started by this contact'),
440 'id' => 'status-tab',
444 'label' => DI::l10n()->t('Posts and Comments'),
445 'url' => 'contact/' . $pcid . '/posts',
446 'sel' => (($active_tab == self::TAB_POSTS) ? 'active' : ''),
447 'title' => DI::l10n()->t('Status Messages and Posts'),
452 'label' => DI::l10n()->t('Media'),
453 'url' => 'contact/' . $pcid . '/media',
454 'sel' => (($active_tab == self::TAB_MEDIA) ? 'active' : ''),
455 'title' => DI::l10n()->t('Posts containing media objects'),
460 'label' => DI::l10n()->t('Profile'),
461 'url' => 'contact/' . $cid,
462 'sel' => (($active_tab == self::TAB_PROFILE) ? 'active' : ''),
463 'title' => DI::l10n()->t('Profile Details'),
464 'id' => 'profile-tab',
467 ['label' => DI::l10n()->t('Contacts'),
468 'url' => 'contact/' . $pcid . '/contacts',
469 'sel' => (($active_tab == self::TAB_CONTACTS) ? 'active' : ''),
470 'title' => DI::l10n()->t('View all known contacts'),
471 'id' => 'contacts-tab',
476 if (!empty($contact['network']) && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && ($cid != $pcid)) {
477 $tabs[] = ['label' => DI::l10n()->t('Advanced'),
478 'url' => 'contact/' . $cid . '/advanced/',
479 'sel' => (($active_tab == self::TAB_ADVANCED) ? 'active' : ''),
480 'title' => DI::l10n()->t('Advanced Contact Settings'),
481 'id' => 'advanced-tab',
486 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
487 $tab_str = Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
493 * Return the fields for the contact template
495 * @param array $contact Contact array
496 * @return array Template fields
498 public static function getContactTemplateVars(array $contact)
502 if (!empty($contact['url']) && isset($contact['uid']) && ($contact['uid'] == 0) && DI::userSession()->getLocalUserId()) {
503 $personal = Model\Contact::getByURL($contact['url'], false, ['uid', 'rel', 'self'], DI::userSession()->getLocalUserId());
504 if (!empty($personal)) {
505 $contact['uid'] = $personal['uid'];
506 $contact['rel'] = $personal['rel'];
507 $contact['self'] = $personal['self'];
511 if (!empty($contact['uid']) && !empty($contact['rel']) && DI::userSession()->getLocalUserId() == $contact['uid']) {
512 switch ($contact['rel']) {
513 case Model\Contact::FRIEND:
514 $alt_text = DI::l10n()->t('Mutual Friendship');
517 case Model\Contact::FOLLOWER;
518 $alt_text = DI::l10n()->t('is a fan of yours');
521 case Model\Contact::SHARING;
522 $alt_text = DI::l10n()->t('you are a fan of');
530 $url = Model\Contact::magicLinkByContact($contact);
532 if (strpos($url, 'contact/redir/') === 0) {
533 $sparkle = ' class="sparkle" ';
538 if ($contact['pending']) {
539 if (in_array($contact['rel'], [Model\Contact::FRIEND, Model\Contact::SHARING])) {
540 $alt_text = DI::l10n()->t('Pending outgoing contact request');
542 $alt_text = DI::l10n()->t('Pending incoming contact request');
546 if ($contact['self']) {
547 $alt_text = DI::l10n()->t('This is you');
548 $url = $contact['url'];
553 'id' => $contact['id'],
555 'img_hover' => DI::l10n()->t('Visit %s\'s profile [%s]', $contact['name'], $contact['url']),
556 'photo_menu' => Model\Contact::photoMenu($contact),
557 'thumb' => Model\Contact::getThumb($contact, true),
558 'alt_text' => $alt_text,
559 'name' => $contact['name'],
560 'nick' => $contact['nick'],
561 'details' => $contact['location'],
562 'tags' => $contact['keywords'],
563 'about' => $contact['about'],
564 'account_type' => Model\Contact::getAccountType($contact['contact-type']),
565 'sparkle' => $sparkle,
566 'itemurl' => ($contact['addr'] ?? '') ?: $contact['url'],
567 'network' => ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol'], $contact['gsid']),