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\Session;
32 use Friendica\Core\Theme;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
37 use Friendica\Model\User;
38 use Friendica\Module\Security\Login;
39 use Friendica\Network\HTTPException\NotFoundException;
42 * Manages and show Contacts and their content
44 class Contact extends BaseModule
46 const TAB_CONVERSATIONS = 1;
48 const TAB_PROFILE = 3;
49 const TAB_CONTACTS = 4;
50 const TAB_ADVANCED = 5;
53 private static function batchActions()
55 if (empty($_POST['contact_batch']) || !is_array($_POST['contact_batch'])) {
59 $redirectUrl = $_POST['redirect_url'] ?? 'contact';
61 self::checkFormSecurityTokenRedirectOnError($redirectUrl, 'contact_batch_actions');
63 $orig_records = Model\Contact::selectToArray(['id', 'uid'], ['id' => $_POST['contact_batch'], 'uid' => [0, Session::getLocalUser()], 'self' => false, 'deleted' => false]);
66 foreach ($orig_records as $orig_record) {
67 $cdata = Model\Contact::getPublicAndUserContactID($orig_record['id'], Session::getLocalUser());
68 if (empty($cdata) || Session::getPublicContact() === $cdata['public']) {
69 // No action available on your own contact
73 if (!empty($_POST['contacts_batch_update']) && $cdata['user']) {
74 self::updateContactFromPoll($cdata['user']);
78 if (!empty($_POST['contacts_batch_block'])) {
79 self::toggleBlockContact($cdata['public'], Session::getLocalUser());
83 if (!empty($_POST['contacts_batch_ignore'])) {
84 self::toggleIgnoreContact($cdata['public']);
88 if ($count_actions > 0) {
89 DI::sysmsg()->addInfo(DI::l10n()->tt('%d contact edited.', '%d contacts edited.', $count_actions));
92 DI::baseUrl()->redirect($redirectUrl);
95 protected function post(array $request = [])
97 if (!Session::getLocalUser()) {
101 // @TODO: Replace with parameter from router
102 if (DI::args()->getArgv()[1] === 'batch') {
103 self::batchActions();
107 /* contact actions */
110 * @param int $contact_id Id of contact with uid != 0
111 * @throws NotFoundException
112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
113 * @throws \ImagickException
115 public static function updateContactFromPoll(int $contact_id)
117 $contact = DBA::selectFirst('contact', ['uid', 'url', 'network'], ['id' => $contact_id, 'uid' => Session::getLocalUser(), 'deleted' => false]);
118 if (!DBA::isResult($contact)) {
122 if ($contact['network'] == Protocol::OSTATUS) {
123 $result = Model\Contact::createFromProbeForUser($contact['uid'], $contact['url'], $contact['network']);
125 if ($result['success']) {
126 Model\Contact::update(['subhub' => 1], ['id' => $contact_id]);
129 // pull feed and consume it, which should subscribe to the hub.
130 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
132 Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
137 * Toggles the blocked status of a contact identified by id.
139 * @param int $contact_id Id of the contact with uid = 0
140 * @param int $owner_id Id of the user we want to block the contact for
143 private static function toggleBlockContact(int $contact_id, int $owner_id)
145 $blocked = !Model\Contact\User::isBlocked($contact_id, $owner_id);
146 Model\Contact\User::setBlocked($contact_id, $owner_id, $blocked);
150 * Toggles the ignored status of a contact identified by id.
152 * @param int $contact_id Id of the contact with uid = 0
155 private static function toggleIgnoreContact(int $contact_id)
157 $ignored = !Model\Contact\User::isIgnored($contact_id, Session::getLocalUser());
158 Model\Contact\User::setIgnored($contact_id, Session::getLocalUser(), $ignored);
161 protected function content(array $request = []): string
163 if (!Session::getLocalUser()) {
164 return Login::form($_SERVER['REQUEST_URI']);
167 $search = trim($_GET['search'] ?? '');
168 $nets = trim($_GET['nets'] ?? '');
169 $rel = trim($_GET['rel'] ?? '');
170 $group = trim($_GET['group'] ?? '');
172 $accounttype = $_GET['accounttype'] ?? '';
173 $accounttypeid = User::getAccountTypeByString($accounttype);
177 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
178 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
179 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
180 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
183 $findpeople_widget = Widget::findPeople();
184 if (isset($_GET['add'])) {
185 $follow_widget = Widget::follow($_GET['add']);
187 $follow_widget = Widget::follow();
190 $account_widget = Widget::accountTypes($_SERVER['REQUEST_URI'], $accounttype);
191 $networks_widget = Widget::networks($_SERVER['REQUEST_URI'], $nets);
192 $rel_widget = Widget::contactRels($_SERVER['REQUEST_URI'], $rel);
193 $groups_widget = Widget::groups($_SERVER['REQUEST_URI'], $group);
195 DI::page()['aside'] .= $vcard_widget . $findpeople_widget . $follow_widget . $account_widget . $groups_widget . $networks_widget . $rel_widget;
197 $tpl = Renderer::getMarkupTemplate('contacts-head.tpl');
198 DI::page()['htmlhead'] .= Renderer::replaceMacros($tpl, [
199 '$baseurl' => DI::baseUrl()->get(true),
203 Nav::setSelected('contact');
205 $_SESSION['return_path'] = DI::args()->getQueryString();
207 $sql_values = [Session::getLocalUser()];
209 // @TODO: Replace with parameter from router
210 $type = DI::args()->getArgv()[1] ?? '';
214 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`blocked`)";
215 // This makes the query look for contact.uid = 0
216 array_unshift($sql_values, 0);
219 $sql_extra = " AND `hidden` AND NOT `blocked` AND NOT `pending`";
222 $sql_extra = " AND `id` IN (SELECT `cid` FROM `user-contact` WHERE `user-contact`.`uid` = ? AND `user-contact`.`ignored`)";
223 // This makes the query look for contact.uid = 0
224 array_unshift($sql_values, 0);
227 $sql_extra = " AND `archive` AND NOT `blocked` AND NOT `pending`";
230 $sql_extra = " AND `pending` AND NOT `archive` AND NOT `failed` AND ((`rel` = ?)
231 OR `id` IN (SELECT `contact-id` FROM `intro` WHERE `intro`.`uid` = ? AND NOT `ignore`))";
232 $sql_values[] = Model\Contact::SHARING;
233 $sql_values[] = Session::getLocalUser();
236 $sql_extra = " AND NOT `archive` AND NOT `blocked` AND NOT `pending`";
240 if (isset($accounttypeid)) {
241 $sql_extra .= " AND `contact-type` = ?";
242 $sql_values[] = $accounttypeid;
249 $search_hdr = $search;
250 $search_txt = preg_quote(trim($search, ' @!'));
251 $sql_extra .= " AND (`name` REGEXP ? OR `url` REGEXP ? OR `nick` REGEXP ? OR `addr` REGEXP ? OR `alias` REGEXP ?)";
252 $sql_values[] = $search_txt;
253 $sql_values[] = $search_txt;
254 $sql_values[] = $search_txt;
255 $sql_values[] = $search_txt;
256 $sql_values[] = $search_txt;
260 $sql_extra .= " AND network = ? ";
261 $sql_values[] = $nets;
266 $sql_extra .= " AND `rel` IN (?, ?)";
267 $sql_values[] = Model\Contact::FOLLOWER;
268 $sql_values[] = Model\Contact::FRIEND;
271 $sql_extra .= " AND `rel` IN (?, ?)";
272 $sql_values[] = Model\Contact::SHARING;
273 $sql_values[] = Model\Contact::FRIEND;
276 $sql_extra .= " AND `rel` = ?";
277 $sql_values[] = Model\Contact::FRIEND;
282 $sql_extra .= " AND `id` IN (SELECT `contact-id` FROM `group_member` WHERE `gid` = ?)";
283 $sql_values[] = $group;
286 $networks = Widget::unavailableNetworks();
287 $sql_extra .= " AND NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")";
288 $sql_values = array_merge($sql_values, $networks);
290 $condition = ["`uid` = ? AND NOT `self` AND NOT `deleted`" . $sql_extra];
291 $condition = array_merge($condition, $sql_values);
293 $total = DBA::count('contact', $condition);
295 $pager = new Pager(DI::l10n(), DI::args()->getQueryString());
299 $stmt = DBA::select('contact', [], $condition, ['order' => ['name'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]]);
301 while ($contact = DBA::fetch($stmt)) {
302 $contact['blocked'] = Model\Contact\User::isBlocked($contact['id'], Session::getLocalUser());
303 $contact['readonly'] = Model\Contact\User::isIgnored($contact['id'], Session::getLocalUser());
304 $contacts[] = self::getContactTemplateVars($contact);
310 'label' => DI::l10n()->t('All Contacts'),
312 'sel' => !$type ? 'active' : '',
313 'title' => DI::l10n()->t('Show all contacts'),
314 'id' => 'showall-tab',
318 'label' => DI::l10n()->t('Pending'),
319 'url' => 'contact/pending',
320 'sel' => $type == 'pending' ? 'active' : '',
321 'title' => DI::l10n()->t('Only show pending contacts'),
322 'id' => 'showpending-tab',
326 'label' => DI::l10n()->t('Blocked'),
327 'url' => 'contact/blocked',
328 'sel' => $type == 'blocked' ? 'active' : '',
329 'title' => DI::l10n()->t('Only show blocked contacts'),
330 'id' => 'showblocked-tab',
334 'label' => DI::l10n()->t('Ignored'),
335 'url' => 'contact/ignored',
336 'sel' => $type == 'ignored' ? 'active' : '',
337 'title' => DI::l10n()->t('Only show ignored contacts'),
338 'id' => 'showignored-tab',
342 'label' => DI::l10n()->t('Archived'),
343 'url' => 'contact/archived',
344 'sel' => $type == 'archived' ? 'active' : '',
345 'title' => DI::l10n()->t('Only show archived contacts'),
346 'id' => 'showarchived-tab',
350 'label' => DI::l10n()->t('Hidden'),
351 'url' => 'contact/hidden',
352 'sel' => $type == 'hidden' ? 'active' : '',
353 'title' => DI::l10n()->t('Only show hidden contacts'),
354 'id' => 'showhidden-tab',
358 'label' => DI::l10n()->t('Groups'),
361 'title' => DI::l10n()->t('Organize your contact groups'),
362 'id' => 'contactgroups-tab',
367 $tabs_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
368 $tabs_html = Renderer::replaceMacros($tabs_tpl, ['$tabs' => $tabs]);
371 case 'followers': $header = DI::l10n()->t('Followers'); break;
372 case 'following': $header = DI::l10n()->t('Following'); break;
373 case 'mutuals': $header = DI::l10n()->t('Mutual friends'); break;
374 default: $header = DI::l10n()->t('Contacts');
378 case 'pending': $header .= ' - ' . DI::l10n()->t('Pending'); break;
379 case 'blocked': $header .= ' - ' . DI::l10n()->t('Blocked'); break;
380 case 'hidden': $header .= ' - ' . DI::l10n()->t('Hidden'); break;
381 case 'ignored': $header .= ' - ' . DI::l10n()->t('Ignored'); break;
382 case 'archived': $header .= ' - ' . DI::l10n()->t('Archived'); break;
385 $header .= $nets ? ' - ' . ContactSelector::networkToName($nets) : '';
387 $tpl = Renderer::getMarkupTemplate('contacts-template.tpl');
388 $o .= Renderer::replaceMacros($tpl, [
389 '$header' => $header,
390 '$tabs' => $tabs_html,
392 '$search' => $search_hdr,
393 '$desc' => DI::l10n()->t('Search your contacts'),
394 '$finding' => $searching ? DI::l10n()->t('Results for: %s', $search) : '',
395 '$submit' => DI::l10n()->t('Find'),
396 '$cmd' => DI::args()->getCommand(),
397 '$contacts' => $contacts,
398 '$form_security_token' => BaseModule::getFormSecurityToken('contact_batch_actions'),
400 '$batch_actions' => [
401 'contacts_batch_update' => DI::l10n()->t('Update'),
402 'contacts_batch_block' => DI::l10n()->t('Block') . '/' . DI::l10n()->t('Unblock'),
403 'contacts_batch_ignore' => DI::l10n()->t('Ignore') . '/' . DI::l10n()->t('Unignore'),
405 '$h_batch_actions' => DI::l10n()->t('Batch Actions'),
406 '$paginate' => $pager->renderFull($total),
413 * List of pages for the Contact TabBar
415 * Available Pages are 'Status', 'Profile', 'Contacts' and 'Common Friends'
417 * @param array $contact The contact array
418 * @param int $active_tab 1 if tab should be marked as active
420 * @return string HTML string of the contact page tabs buttons.
421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
422 * @throws \ImagickException
424 public static function getTabsHTML(array $contact, int $active_tab)
426 $cid = $pcid = $contact['id'];
427 $data = Model\Contact::getPublicAndUserContactID($contact['id'], Session::getLocalUser());
428 if (!empty($data['user']) && ($contact['id'] == $data['public'])) {
429 $cid = $data['user'];
430 } elseif (!empty($data['public'])) {
431 $pcid = $data['public'];
437 'label' => DI::l10n()->t('Status'),
438 'url' => 'contact/' . $pcid . '/conversations',
439 'sel' => (($active_tab == self::TAB_CONVERSATIONS) ? 'active' : ''),
440 'title' => DI::l10n()->t('Conversations started by this contact'),
441 'id' => 'status-tab',
445 'label' => DI::l10n()->t('Posts and Comments'),
446 'url' => 'contact/' . $pcid . '/posts',
447 'sel' => (($active_tab == self::TAB_POSTS) ? 'active' : ''),
448 'title' => DI::l10n()->t('Status Messages and Posts'),
453 'label' => DI::l10n()->t('Media'),
454 'url' => 'contact/' . $pcid . '/media',
455 'sel' => (($active_tab == self::TAB_MEDIA) ? 'active' : ''),
456 'title' => DI::l10n()->t('Posts containing media objects'),
461 'label' => DI::l10n()->t('Profile'),
462 'url' => 'contact/' . $cid,
463 'sel' => (($active_tab == self::TAB_PROFILE) ? 'active' : ''),
464 'title' => DI::l10n()->t('Profile Details'),
465 'id' => 'profile-tab',
468 ['label' => DI::l10n()->t('Contacts'),
469 'url' => 'contact/' . $pcid . '/contacts',
470 'sel' => (($active_tab == self::TAB_CONTACTS) ? 'active' : ''),
471 'title' => DI::l10n()->t('View all known contacts'),
472 'id' => 'contacts-tab',
477 if (!empty($contact['network']) && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && ($cid != $pcid)) {
478 $tabs[] = ['label' => DI::l10n()->t('Advanced'),
479 'url' => 'contact/' . $cid . '/advanced/',
480 'sel' => (($active_tab == self::TAB_ADVANCED) ? 'active' : ''),
481 'title' => DI::l10n()->t('Advanced Contact Settings'),
482 'id' => 'advanced-tab',
487 $tab_tpl = Renderer::getMarkupTemplate('common_tabs.tpl');
488 $tab_str = Renderer::replaceMacros($tab_tpl, ['$tabs' => $tabs]);
494 * Return the fields for the contact template
496 * @param array $contact Contact array
497 * @return array Template fields
499 public static function getContactTemplateVars(array $contact)
503 if (!empty($contact['url']) && isset($contact['uid']) && ($contact['uid'] == 0) && Session::getLocalUser()) {
504 $personal = Model\Contact::getByURL($contact['url'], false, ['uid', 'rel', 'self'], Session::getLocalUser());
505 if (!empty($personal)) {
506 $contact['uid'] = $personal['uid'];
507 $contact['rel'] = $personal['rel'];
508 $contact['self'] = $personal['self'];
512 if (!empty($contact['uid']) && !empty($contact['rel']) && Session::getLocalUser() == $contact['uid']) {
513 switch ($contact['rel']) {
514 case Model\Contact::FRIEND:
515 $alt_text = DI::l10n()->t('Mutual Friendship');
518 case Model\Contact::FOLLOWER;
519 $alt_text = DI::l10n()->t('is a fan of yours');
522 case Model\Contact::SHARING;
523 $alt_text = DI::l10n()->t('you are a fan of');
531 $url = Model\Contact::magicLinkByContact($contact);
533 if (strpos($url, 'redir/') === 0) {
534 $sparkle = ' class="sparkle" ';
539 if ($contact['pending']) {
540 if (in_array($contact['rel'], [Model\Contact::FRIEND, Model\Contact::SHARING])) {
541 $alt_text = DI::l10n()->t('Pending outgoing contact request');
543 $alt_text = DI::l10n()->t('Pending incoming contact request');
547 if ($contact['self']) {
548 $alt_text = DI::l10n()->t('This is you');
549 $url = $contact['url'];
554 'id' => $contact['id'],
556 'img_hover' => DI::l10n()->t('Visit %s\'s profile [%s]', $contact['name'], $contact['url']),
557 'photo_menu' => Model\Contact::photoMenu($contact),
558 'thumb' => Model\Contact::getThumb($contact, true),
559 'alt_text' => $alt_text,
560 'name' => $contact['name'],
561 'nick' => $contact['nick'],
562 'details' => $contact['location'],
563 'tags' => $contact['keywords'],
564 'about' => $contact['about'],
565 'account_type' => Model\Contact::getAccountType($contact['contact-type']),
566 'sparkle' => $sparkle,
567 'itemurl' => ($contact['addr'] ?? '') ?: $contact['url'],
568 'network' => ContactSelector::networkToName($contact['network'], $contact['url'], $contact['protocol'], $contact['gsid']),