3 * @copyright Copyright (C) 2020, Friendica
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\Model;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Notify\Type;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\DFRN;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Protocol\OStatus;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
52 * functions for interacting with a contact
56 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
57 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
58 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
61 * @deprecated since version 2019.03
62 * @see User::PAGE_FLAGS_NORMAL
64 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
66 * @deprecated since version 2019.03
67 * @see User::PAGE_FLAGS_SOAPBOX
69 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
71 * @deprecated since version 2019.03
72 * @see User::PAGE_FLAGS_COMMUNITY
74 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
76 * @deprecated since version 2019.03
77 * @see User::PAGE_FLAGS_FREELOVE
79 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
81 * @deprecated since version 2019.03
82 * @see User::PAGE_FLAGS_BLOG
84 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
86 * @deprecated since version 2019.03
87 * @see User::PAGE_FLAGS_PRVGROUP
89 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
97 * TYPE_UNKNOWN - unknown type
99 * TYPE_PERSON - the account belongs to a person
100 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
102 * TYPE_ORGANISATION - the account belongs to an organisation
103 * Associated page type: PAGE_SOAPBOX
105 * TYPE_NEWS - the account is a news reflector
106 * Associated page type: PAGE_SOAPBOX
108 * TYPE_COMMUNITY - the account is community forum
109 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
111 * TYPE_RELAY - the account is a relay
112 * This will only be assigned to contacts, not to user accounts
115 const TYPE_UNKNOWN = -1;
116 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
117 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
118 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
119 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
120 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
140 * @param array $fields Array of selected fields, empty for all
141 * @param array $condition Array of fields for condition
142 * @param array $params Array of several parameters
146 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
148 return DBA::selectToArray('contact', $fields, $condition, $params);
152 * @param array $fields Array of selected fields, empty for all
153 * @param array $condition Array of fields for condition
154 * @param array $params Array of several parameters
158 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
160 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
166 * Insert a row into the contact table
167 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
169 * @param array $fields field array
170 * @param bool $on_duplicate_update Do an update on a duplicate entry
172 * @return boolean was the insert successful?
175 public static function insert(array $fields, bool $on_duplicate_update = false)
177 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
178 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
179 if (!DBA::isResult($contact)) {
184 // Search for duplicated contacts and get rid of them
185 self::removeDuplicates($contact['nurl'], $contact['uid']);
191 * @param integer $id Contact ID
192 * @param array $fields Array of selected fields, empty for all
193 * @return array|boolean Contact record if it exists, false otherwise
196 public static function getById($id, $fields = [])
198 return DBA::selectFirst('contact', $fields, ['id' => $id]);
202 * Fetches a contact by a given url
204 * @param string $url profile url
205 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
206 * @param array $fields Field list
207 * @param integer $uid User ID of the contact
208 * @return array contact array
210 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
212 if ($update || is_null($update)) {
213 $cid = self::getIdForURL($url, $uid, $update);
218 $contact = self::getById($cid, $fields);
219 if (empty($contact)) {
225 // Add internal fields
227 if (!empty($fields)) {
228 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
229 if (!in_array($internal, $fields)) {
230 $fields[] = $internal;
231 $removal[] = $internal;
236 // We first try the nurl (http://server.tld/nick), most common case
237 $options = ['order' => ['id']];
238 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
240 // Then the addr (nick@server.tld)
241 if (!DBA::isResult($contact)) {
242 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
245 // Then the alias (which could be anything)
246 if (!DBA::isResult($contact)) {
247 // The link could be provided as http although we stored it as https
248 $ssl_url = str_replace('http://', 'https://', $url);
249 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
250 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
253 if (!DBA::isResult($contact)) {
257 // Update the contact in the background if needed
258 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
259 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED)) {
260 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
263 // Remove the internal fields
264 foreach ($removal as $internal) {
265 unset($contact[$internal]);
272 * Fetches a contact for a given user by a given url.
273 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
275 * @param string $url profile url
276 * @param integer $uid User ID of the contact
277 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
278 * @param array $fields Field list
279 * @return array contact array
281 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
284 $contact = self::getByURL($url, $update, $fields, $uid);
285 if (!empty($contact)) {
286 if (!empty($contact['id'])) {
287 $contact['cid'] = $contact['id'];
294 $contact = self::getByURL($url, $update, $fields);
295 if (!empty($contact['id'])) {
297 $contact['zid'] = $contact['id'];
303 * Tests if the given contact is a follower
305 * @param int $cid Either public contact id or user's contact id
306 * @param int $uid User ID
308 * @return boolean is the contact id a follower?
309 * @throws HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 public static function isFollower($cid, $uid)
314 if (Contact\User::isBlocked($cid, $uid)) {
318 $cdata = self::getPublicAndUserContacID($cid, $uid);
319 if (empty($cdata['user'])) {
323 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
324 return DBA::exists('contact', $condition);
328 * Tests if the given contact url is a follower
330 * @param string $url Contact URL
331 * @param int $uid User ID
333 * @return boolean is the contact id a follower?
334 * @throws HTTPException\InternalServerErrorException
335 * @throws \ImagickException
337 public static function isFollowerByURL($url, $uid)
339 $cid = self::getIdForURL($url, $uid);
345 return self::isFollower($cid, $uid);
349 * Tests if the given user follow the given contact
351 * @param int $cid Either public contact id or user's contact id
352 * @param int $uid User ID
354 * @return boolean is the contact url being followed?
355 * @throws HTTPException\InternalServerErrorException
356 * @throws \ImagickException
358 public static function isSharing($cid, $uid)
360 if (Contact\User::isBlocked($cid, $uid)) {
364 $cdata = self::getPublicAndUserContacID($cid, $uid);
365 if (empty($cdata['user'])) {
369 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
370 return DBA::exists('contact', $condition);
374 * Tests if the given user follow the given contact url
376 * @param string $url Contact URL
377 * @param int $uid User ID
379 * @return boolean is the contact url being followed?
380 * @throws HTTPException\InternalServerErrorException
381 * @throws \ImagickException
383 public static function isSharingByURL($url, $uid)
385 $cid = self::getIdForURL($url, $uid);
391 return self::isSharing($cid, $uid);
395 * Get the basepath for a given contact link
397 * @param string $url The contact link
398 * @param boolean $dont_update Don't update the contact
400 * @return string basepath
401 * @throws HTTPException\InternalServerErrorException
402 * @throws \ImagickException
404 public static function getBasepath($url, $dont_update = false)
406 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
407 if (!DBA::isResult($contact)) {
411 if (!empty($contact['baseurl'])) {
412 return $contact['baseurl'];
413 } elseif ($dont_update) {
417 // Update the existing contact
418 self::updateFromProbe($contact['id']);
420 // And fetch the result
421 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
422 if (empty($contact['baseurl'])) {
423 Logger::info('No baseurl for contact', ['url' => $url]);
427 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
428 return $contact['baseurl'];
432 * Check if the given contact url is on the same server
434 * @param string $url The contact link
436 * @return boolean Is it the same server?
438 public static function isLocal($url)
440 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
444 * Check if the given contact ID is on the same server
446 * @param string $url The contact link
448 * @return boolean Is it the same server?
450 public static function isLocalById(int $cid)
452 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
453 if (!DBA::isResult($contact)) {
457 if (empty($contact['baseurl'])) {
458 $baseurl = self::getBasepath($contact['url'], true);
460 $baseurl = $contact['baseurl'];
463 return Strings::compareLink($baseurl, DI::baseUrl());
467 * Returns the public contact id of the given user id
469 * @param integer $uid User ID
471 * @return integer|boolean Public contact id for given user id
474 public static function getPublicIdByUserId($uid)
476 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
477 if (!DBA::isResult($self)) {
480 return self::getIdForURL($self['url']);
484 * Returns the contact id for the user and the public contact id for a given contact id
486 * @param int $cid Either public contact id or user's contact id
487 * @param int $uid User ID
489 * @return array with public and user's contact id
490 * @throws HTTPException\InternalServerErrorException
491 * @throws \ImagickException
493 public static function getPublicAndUserContacID($cid, $uid)
495 if (empty($uid) || empty($cid)) {
499 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
500 if (!DBA::isResult($contact)) {
504 // We quit when the user id don't match the user id of the provided contact
505 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
509 if ($contact['uid'] != 0) {
510 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
514 $ucid = $contact['id'];
516 $pcid = $contact['id'];
517 $ucid = Contact::getIdForURL($contact['url'], $uid);
520 return ['public' => $pcid, 'user' => $ucid];
524 * Returns contact details for a given contact id in combination with a user id
526 * @param int $cid A contact ID
527 * @param int $uid The User ID
528 * @param array $fields The selected fields for the contact
530 * @return array The contact details
534 public static function getContactForUser($cid, $uid, array $fields = [])
536 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
538 if (!DBA::isResult($contact)) {
546 * Creates the self-contact for the provided user id
549 * @return bool Operation success
550 * @throws HTTPException\InternalServerErrorException
552 public static function createSelfFromUserId($uid)
554 // Only create the entry if it doesn't exist yet
555 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
559 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'], ['uid' => $uid]);
560 if (!DBA::isResult($user)) {
564 $return = DBA::insert('contact', [
565 'uid' => $user['uid'],
566 'created' => DateTimeFormat::utcNow(),
568 'name' => $user['username'],
569 'nick' => $user['nickname'],
570 'pubkey' => $user['pubkey'],
571 'prvkey' => $user['prvkey'],
572 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
573 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
574 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
577 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
578 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
579 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
580 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
581 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
582 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
583 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
584 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
585 'name-date' => DateTimeFormat::utcNow(),
586 'uri-date' => DateTimeFormat::utcNow(),
587 'avatar-date' => DateTimeFormat::utcNow(),
595 * Updates the self-contact for the provided user id
598 * @param boolean $update_avatar Force the avatar update
599 * @throws HTTPException\InternalServerErrorException
601 public static function updateSelfFromUserID($uid, $update_avatar = false)
603 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
604 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
605 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
606 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
607 if (!DBA::isResult($self)) {
611 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
612 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
613 if (!DBA::isResult($user)) {
617 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
618 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
619 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
620 if (!DBA::isResult($profile)) {
624 $file_suffix = 'jpg';
626 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
627 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
628 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
629 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
630 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp']];
632 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
633 if (DBA::isResult($avatar)) {
634 if ($update_avatar) {
635 $fields['avatar-date'] = DateTimeFormat::utcNow();
638 // Creating the path to the avatar, beginning with the file suffix
639 $types = Images::supportedTypes();
640 if (isset($types[$avatar['type']])) {
641 $file_suffix = $types[$avatar['type']];
644 // We are adding a timestamp value so that other systems won't use cached content
645 $timestamp = strtotime($fields['avatar-date']);
647 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
648 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
650 $fields['photo'] = $prefix . '4' . $suffix;
651 $fields['thumb'] = $prefix . '5' . $suffix;
652 $fields['micro'] = $prefix . '6' . $suffix;
654 // We hadn't found a photo entry, so we use the default avatar
655 $fields['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
656 $fields['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
657 $fields['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
660 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
661 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
662 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
663 $fields['unsearchable'] = !$profile['net-publish'];
665 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
666 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
667 $fields['nurl'] = Strings::normaliseLink($fields['url']);
668 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
669 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
670 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
671 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
672 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
673 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
677 foreach ($fields as $field => $content) {
678 if ($self[$field] != $content) {
684 if ($fields['name'] != $self['name']) {
685 $fields['name-date'] = DateTimeFormat::utcNow();
687 $fields['updated'] = DateTimeFormat::utcNow();
688 DBA::update('contact', $fields, ['id' => $self['id']]);
690 // Update the public contact as well
691 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
693 // Update the profile
694 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
695 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
696 DBA::update('profile', $fields, ['uid' => $uid]);
701 * Marks a contact for removal
703 * @param int $id contact id
705 * @throws HTTPException\InternalServerErrorException
707 public static function remove($id)
709 // We want just to make sure that we don't delete our "self" contact
710 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
711 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
715 // Archive the contact
716 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
718 // Delete it in the background
719 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
723 * Sends an unfriend message. Does not remove the contact
725 * @param array $user User unfriending
726 * @param array $contact Contact unfriended
727 * @param boolean $dissolve Remove the contact on the remote side
729 * @throws HTTPException\InternalServerErrorException
730 * @throws \ImagickException
732 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
734 if (empty($contact['network'])) {
738 $protocol = $contact['network'];
739 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
740 $protocol = Protocol::ACTIVITYPUB;
743 if (($protocol == Protocol::DFRN) && $dissolve) {
744 DFRN::deliver($user, $contact, 'placeholder', true);
745 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
746 // create an unfollow slap
748 $item['verb'] = Activity::O_UNFOLLOW;
749 $item['gravity'] = GRAVITY_ACTIVITY;
750 $item['follow'] = $contact["url"];
755 $item['attach'] = '';
756 $slap = OStatus::salmon($item, $user);
758 if (!empty($contact['notify'])) {
759 Salmon::slapper($user, $contact['notify'], $slap);
761 } elseif ($protocol == Protocol::DIASPORA) {
762 Diaspora::sendUnshare($user, $contact);
763 } elseif ($protocol == Protocol::ACTIVITYPUB) {
764 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
767 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
773 * Marks a contact for archival after a communication issue delay
775 * Contact has refused to recognise us as a friend. We will start a countdown.
776 * If they still don't recognise us in 32 days, the relationship is over,
777 * and we won't waste any more time trying to communicate with them.
778 * This provides for the possibility that their database is temporarily messed
779 * up or some other transient event and that there's a possibility we could recover from it.
781 * @param array $contact contact to mark for archival
783 * @throws HTTPException\InternalServerErrorException
785 public static function markForArchival(array $contact)
787 if (!isset($contact['url']) && !empty($contact['id'])) {
788 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
789 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
790 if (!DBA::isResult($contact)) {
793 } elseif (!isset($contact['url'])) {
794 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
797 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
799 // Contact already archived or "self" contact? => nothing to do
800 if ($contact['archive'] || $contact['self']) {
804 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
805 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
806 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
809 * We really should send a notification to the owner after 2-3 weeks
810 * so they won't be surprised when the contact vanishes and can take
811 * remedial action if this was a serious mistake or glitch
814 /// @todo Check for contact vitality via probing
815 $archival_days = DI::config()->get('system', 'archival_days', 32);
817 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
818 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
819 /* Relationship is really truly dead. archive them rather than
820 * delete, though if the owner tries to unarchive them we'll start
821 * the whole process over again.
823 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
824 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
830 * Cancels the archival countdown
832 * @see Contact::markForArchival()
834 * @param array $contact contact to be unmarked for archival
838 public static function unmarkForArchival(array $contact)
840 // Always unarchive the relay contact entry
841 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
842 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
843 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
844 DBA::update('contact', $fields, $condition);
847 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
848 $exists = DBA::exists('contact', $condition);
850 // We don't need to update, we never marked this contact for archival
855 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
857 if (!isset($contact['url']) && !empty($contact['id'])) {
858 $fields = ['id', 'url', 'batch'];
859 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
860 if (!DBA::isResult($contact)) {
865 // It's a miracle. Our dead contact has inexplicably come back to life.
866 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
867 DBA::update('contact', $fields, ['id' => $contact['id']]);
868 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
872 * Returns the data array for the photo menu of a given contact
874 * @param array $contact contact
875 * @param int $uid optional, default 0
877 * @throws HTTPException\InternalServerErrorException
878 * @throws \ImagickException
880 public static function photoMenu(array $contact, $uid = 0)
885 $contact_drop_link = '';
892 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
894 $profile_link = self::magicLink($contact['url']);
895 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
900 // Look for our own contact if the uid doesn't match and isn't public
901 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
902 if (DBA::isResult($contact_own)) {
903 return self::photoMenu($contact_own, $uid);
908 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
910 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
912 $profile_link = $contact['url'];
915 if ($profile_link === 'mailbox') {
920 $status_link = $profile_link . '/status';
921 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
922 $profile_link = $profile_link . '/profile';
925 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
926 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
929 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
930 $poke_link = 'contact/' . $contact['id'] . '/poke';
933 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
935 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
937 if (!$contact['self']) {
938 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
943 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
944 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
945 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
946 } elseif(!$contact['pending']) {
947 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
951 if (!empty($follow_link) || !empty($unfollow_link)) {
952 $contact_drop_link = '';
957 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
959 if (empty($contact['uid'])) {
961 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
962 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
963 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
964 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
965 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
969 'status' => [DI::l10n()->t('View Status') , $status_link , true],
970 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
971 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
972 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
973 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
974 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
975 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
976 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
977 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
978 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
981 if (!empty($contact['pending'])) {
982 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
983 if (DBA::isResult($intro)) {
984 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
989 $args = ['contact' => $contact, 'menu' => &$menu];
991 Hook::callAll('contact_photo_menu', $args);
995 foreach ($menu as $menuname => $menuitem) {
996 if ($menuitem[1] != '') {
997 $menucondensed[$menuname] = $menuitem;
1001 return $menucondensed;
1005 * Fetch the contact id for a given URL and user
1007 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1008 * `addr` or `alias`.
1010 * If there's no record and we aren't looking for a public contact, we quit.
1011 * If there's one, we check that it isn't time to update the picture else we
1012 * directly return the found contact id.
1014 * Second, we probe the provided $url whether it's http://server.tld/profile or
1015 * nick@server.tld. We quit if we can't get any info back.
1017 * Third, we create the contact record if it doesn't exist
1019 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1020 * if there's any updates
1022 * @param string $url Contact URL
1023 * @param integer $uid The user id for the contact (0 = public contact)
1024 * @param boolean $update true = always update, false = never update, null = update when not found
1025 * @param array $default Default value for creating the contact when everything else fails
1027 * @return integer Contact ID
1028 * @throws HTTPException\InternalServerErrorException
1029 * @throws \ImagickException
1031 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1036 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1040 $contact = self::getByURL($url, false, ['id', 'network'], $uid);
1042 if (!empty($contact)) {
1043 $contact_id = $contact["id"];
1045 if (empty($update)) {
1046 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1049 } elseif ($uid != 0) {
1050 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1052 } elseif (empty($default) && !is_null($update) && !$update) {
1053 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1059 if (empty($default['network']) || $update) {
1060 $data = Probe::uri($url, "", $uid);
1062 // Take the default values when probing failed
1063 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1064 $data = array_merge($data, $default);
1066 } elseif (!empty($default['network'])) {
1070 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1071 // Fetch data for the public contact via the first found personal contact
1072 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1073 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'contact-type',
1074 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1075 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1077 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1078 if (!DBA::isResult($personal_contact)) {
1079 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1082 if (DBA::isResult($personal_contact)) {
1083 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1084 $data = $personal_contact;
1085 $data['photo'] = $personal_contact['avatar'];
1086 $data['account-type'] = $personal_contact['contact-type'];
1087 $data['hide'] = $personal_contact['unsearchable'];
1088 unset($data['avatar']);
1089 unset($data['contact-type']);
1090 unset($data['unsearchable']);
1094 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1095 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1100 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1101 if (!empty($data['alias'])) {
1102 $urls[] = Strings::normaliseLink($data['alias']);
1104 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1105 if (!empty($contact['id'])) {
1106 $contact_id = $contact['id'];
1107 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'probed_url' => $data['url'], 'alias' => $data['alias'], 'addr' => $data['addr']]);
1112 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1115 'url' => $data['url'],
1116 'nurl' => Strings::normaliseLink($data['url']),
1117 'network' => $data['network'],
1118 'created' => DateTimeFormat::utcNow(),
1119 'rel' => self::SHARING,
1125 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1127 // Before inserting we do check if the entry does exist now.
1128 DBA::lock('contact');
1129 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1130 if (DBA::isResult($contact)) {
1131 $contact_id = $contact['id'];
1132 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1134 DBA::insert('contact', $fields);
1135 $contact_id = DBA::lastInsertId();
1137 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1142 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1146 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1149 self::updateFromProbeArray($contact_id, $data);
1155 * Checks if the contact is archived
1157 * @param int $cid contact id
1159 * @return boolean Is the contact archived?
1160 * @throws HTTPException\InternalServerErrorException
1162 public static function isArchived(int $cid)
1168 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1169 if (!DBA::isResult($contact)) {
1173 if ($contact['archive']) {
1177 // Check status of ActivityPub endpoints
1178 $apcontact = APContact::getByURL($contact['url'], false);
1179 if (!empty($apcontact)) {
1180 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1184 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1189 // Check status of Diaspora endpoints
1190 if (!empty($contact['batch'])) {
1191 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1192 return DBA::exists('contact', $condition);
1199 * Checks if the contact is blocked
1201 * @param int $cid contact id
1203 * @return boolean Is the contact blocked?
1204 * @throws HTTPException\InternalServerErrorException
1206 public static function isBlocked($cid)
1212 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1213 if (!DBA::isResult($blocked)) {
1217 if (Network::isUrlBlocked($blocked['url'])) {
1221 return (bool) $blocked['blocked'];
1225 * Checks if the contact is hidden
1227 * @param int $cid contact id
1229 * @return boolean Is the contact hidden?
1230 * @throws \Exception
1232 public static function isHidden($cid)
1238 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1239 if (!DBA::isResult($hidden)) {
1242 return (bool) $hidden['hidden'];
1246 * Returns posts from a given contact url
1248 * @param string $contact_url Contact URL
1249 * @param bool $thread_mode
1250 * @param int $update Update mode
1251 * @param int $parent Item parent ID for the update mode
1252 * @return string posts in HTML
1253 * @throws \Exception
1255 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1257 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1261 * Returns posts from a given contact id
1263 * @param int $cid Contact ID
1264 * @param bool $thread_mode
1265 * @param int $update Update mode
1266 * @param int $parent Item parent ID for the update mode
1267 * @return string posts in HTML
1268 * @throws \Exception
1270 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1274 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1275 if (!DBA::isResult($contact)) {
1279 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1280 $sql = "`item`.`uid` IN (0, ?)";
1282 $sql = "`item`.`uid` = ?";
1285 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1288 $condition = ["(`$contact_field` = ? OR (`causer-id` = ? AND `post-type` = ?)) AND `gravity` = ? AND " . $sql,
1289 $cid, $cid, Item::PT_ANNOUNCEMENT, GRAVITY_PARENT, local_user()];
1291 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1292 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1295 if (!empty($parent)) {
1296 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1298 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1299 if (!empty($last_received)) {
1300 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1304 if (DI::mode()->isMobile()) {
1305 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1306 DI::config()->get('system', 'itemspage_network_mobile'));
1308 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1309 DI::config()->get('system', 'itemspage_network'));
1312 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1314 $params = ['order' => ['received' => true], 'group_by' => ['uri-id'],
1315 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1317 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1318 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1319 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1325 $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1327 while ($item = DBA::fetch($r)) {
1328 if ($item['gravity'] != GRAVITY_PARENT) {
1329 $item['uri'] = $item['parent-uri'];
1331 unset($item['parent-uri']);
1332 unset($item['gravity']);
1338 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1340 $r = Item::selectForUser(local_user(), [], $condition, $params);
1342 $items = Item::inArray($r);
1344 $o .= conversation($a, $items, 'contact-posts', $update);
1348 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1349 $o .= HTML::scrollLoader();
1351 $o .= $pager->renderMinimal(count($items));
1359 * Returns the account type name
1361 * The function can be called with either the user or the contact array
1363 * @param array $contact contact or user array
1366 public static function getAccountType(array $contact)
1368 // There are several fields that indicate that the contact or user is a forum
1369 // "page-flags" is a field in the user table,
1370 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1371 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1372 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1373 || (isset($contact['forum']) && intval($contact['forum']))
1374 || (isset($contact['prv']) && intval($contact['prv']))
1375 || (isset($contact['community']) && intval($contact['community']))
1377 $type = self::TYPE_COMMUNITY;
1379 $type = self::TYPE_PERSON;
1382 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1383 if (isset($contact["contact-type"])) {
1384 $type = $contact["contact-type"];
1387 if (isset($contact["account-type"])) {
1388 $type = $contact["account-type"];
1392 case self::TYPE_ORGANISATION:
1393 $account_type = DI::l10n()->t("Organisation");
1396 case self::TYPE_NEWS:
1397 $account_type = DI::l10n()->t('News');
1400 case self::TYPE_COMMUNITY:
1401 $account_type = DI::l10n()->t("Forum");
1409 return $account_type;
1417 * @throws \Exception
1419 public static function block($cid, $reason = null)
1421 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1427 * Unblocks a contact
1431 * @throws \Exception
1433 public static function unblock($cid)
1435 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1441 * Ensure that cached avatar exist
1443 * @param integer $cid
1445 public static function checkAvatarCache(int $cid)
1447 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1448 if (!DBA::isResult($contact)) {
1452 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1456 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1458 self::updateAvatar($cid, $contact['avatar'], true);
1462 * Return the photo path for a given contact array in the given size
1464 * @param array $contact contact array
1465 * @param string $field Fieldname of the photo in the contact array
1466 * @param string $default Default path when no picture had been found
1467 * @param string $size Size of the avatar picture
1468 * @param string $avatar Avatar path that is displayed when no photo had been found
1469 * @return string photo path
1471 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1473 if (!empty($contact)) {
1474 $contact = self::checkAvatarCacheByArray($contact);
1475 if (!empty($contact[$field])) {
1476 $avatar = $contact[$field];
1480 if (empty($avatar)) {
1484 if (Proxy::isLocalImage($avatar)) {
1487 return Proxy::proxifyUrl($avatar, false, $size);
1492 * Return the photo path for a given contact array
1494 * @param array $contact Contact array
1495 * @param string $avatar Avatar path that is displayed when no photo had been found
1496 * @return string photo path
1498 public static function getPhoto(array $contact, string $avatar = '')
1500 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO, Proxy::SIZE_SMALL, $avatar);
1504 * Return the photo path (thumb size) for a given contact array
1506 * @param array $contact Contact array
1507 * @param string $avatar Avatar path that is displayed when no photo had been found
1508 * @return string photo path
1510 public static function getThumb(array $contact, string $avatar = '')
1512 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . self::DEFAULT_AVATAR_THUMB, Proxy::SIZE_THUMB, $avatar);
1516 * Return the photo path (micro size) for a given contact array
1518 * @param array $contact Contact array
1519 * @param string $avatar Avatar path that is displayed when no photo had been found
1520 * @return string photo path
1522 public static function getMicro(array $contact, string $avatar = '')
1524 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . self::DEFAULT_AVATAR_MICRO, Proxy::SIZE_MICRO, $avatar);
1528 * Check the given contact array for avatar cache fields
1530 * @param array $contact
1531 * @return array contact array with avatar cache fields
1533 private static function checkAvatarCacheByArray(array $contact)
1536 $contact_fields = [];
1537 $fields = ['photo', 'thumb', 'micro'];
1538 foreach ($fields as $field) {
1539 if (isset($contact[$field])) {
1540 $contact_fields[] = $field;
1542 if (isset($contact[$field]) && empty($contact[$field])) {
1551 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1552 self::updateAvatar($contact['id'], $contact['avatar'], true);
1554 $new_contact = self::getById($contact['id'], $contact_fields);
1555 if (DBA::isResult($new_contact)) {
1556 // We only update the cache fields
1557 $contact = array_merge($contact, $new_contact);
1561 /// add the default avatars if the fields aren't filled
1562 if (isset($contact['photo']) && empty($contact['photo'])) {
1563 $contact['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
1565 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1566 $contact['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
1568 if (isset($contact['micro']) && empty($contact['micro'])) {
1569 $contact['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
1576 * Updates the avatar links in a contact only if needed
1578 * @param int $cid Contact id
1579 * @param string $avatar Link to avatar picture
1580 * @param bool $force force picture update
1581 * @param bool $create_cache Enforces the creation of cached avatar fields
1584 * @throws HTTPException\InternalServerErrorException
1585 * @throws HTTPException\NotFoundException
1586 * @throws \ImagickException
1588 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1590 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl', 'url', 'network'], ['id' => $cid, 'self' => false]);
1591 if (!DBA::isResult($contact)) {
1595 $uid = $contact['uid'];
1597 // Only update the cached photo links of public contacts when they already are cached
1598 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1599 if ($contact['avatar'] != $avatar) {
1600 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1601 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1606 // User contacts use are updated through the public contacts
1607 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1608 $pcid = self::getIdForURL($contact['url'], false);
1609 if (!empty($pcid)) {
1610 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1611 self::updateAvatar($pcid, $avatar, $force, true);
1616 // Replace cached avatar pictures from the default avatar with the default avatars in different sizes
1617 if (strpos($avatar, self::DEFAULT_AVATAR_PHOTO)) {
1618 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1619 'photo' => DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO,
1620 'thumb' => DI::baseUrl() . self::DEFAULT_AVATAR_THUMB,
1621 'micro' => DI::baseUrl() . self::DEFAULT_AVATAR_MICRO];
1622 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1625 // Use the data from the self account
1626 if (empty($fields)) {
1627 $local_uid = User::getIdForURL($contact['url']);
1628 if (!empty($local_uid)) {
1629 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1630 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1634 if (empty($fields)) {
1635 $update = ($contact['avatar'] != $avatar) || $force;
1639 $contact['photo'] ?? '',
1640 $contact['thumb'] ?? '',
1641 $contact['micro'] ?? '',
1644 foreach ($data as $image_uri) {
1645 $image_rid = Photo::ridFromURI($image_uri);
1646 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1647 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1654 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1656 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1657 $update = !empty($fields);
1658 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1664 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1673 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1674 // Collect all user contacts of the given public contact
1675 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1676 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1677 while ($personal_contact = DBA::fetch($personal_contacts)) {
1678 $cids[] = $personal_contact['id'];
1679 $uids[] = $personal_contact['uid'];
1681 DBA::close($personal_contacts);
1683 if (!empty($cids)) {
1684 // Delete possibly existing cached user contact avatars
1685 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1691 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1692 DBA::update('contact', $fields, ['id' => $cids]);
1696 * Helper function for "updateFromProbe". Updates personal and public contact
1698 * @param integer $id contact id
1699 * @param integer $uid user id
1700 * @param string $url The profile URL of the contact
1701 * @param array $fields The fields that are updated
1703 * @throws \Exception
1705 private static function updateContact($id, $uid, $url, array $fields)
1707 if (!DBA::update('contact', $fields, ['id' => $id])) {
1708 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1712 // Search for duplicated contacts and get rid of them
1713 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1717 // Archive or unarchive the contact. We only need to do this for the public contact.
1718 // The archive/unarchive function will update the personal contacts by themselves.
1719 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1720 if (!DBA::isResult($contact)) {
1721 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1725 if (!empty($fields['success_update'])) {
1726 self::unmarkForArchival($contact);
1727 } elseif (!empty($fields['failure_update'])) {
1728 self::markForArchival($contact);
1731 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1733 // These contacts are sharing with us, we don't poll them.
1734 // This means that we don't set the update fields in "OnePoll.php".
1735 $condition['rel'] = self::SHARING;
1736 DBA::update('contact', $fields, $condition);
1738 unset($fields['last-update']);
1739 unset($fields['success_update']);
1740 unset($fields['failure_update']);
1742 if (empty($fields)) {
1746 // We are polling these contacts, so we mustn't set the update fields here.
1747 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1748 DBA::update('contact', $fields, $condition);
1752 * Remove duplicated contacts
1754 * @param string $nurl Normalised contact url
1755 * @param integer $uid User id
1757 * @throws \Exception
1759 public static function removeDuplicates(string $nurl, int $uid)
1761 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1762 $count = DBA::count('contact', $condition);
1767 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1768 if (!DBA::isResult($first_contact)) {
1769 // Shouldn't happen - so we handle it
1773 $first = $first_contact['id'];
1774 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1775 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1776 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1777 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1781 // Find all duplicates
1782 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1783 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1784 while ($duplicate = DBA::fetch($duplicates)) {
1785 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1789 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1791 DBA::close($duplicates);
1792 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1797 * @param integer $id contact id
1798 * @param string $network Optional network we are probing for
1800 * @throws HTTPException\InternalServerErrorException
1801 * @throws \ImagickException
1803 public static function updateFromProbe(int $id, string $network = '')
1805 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1806 if (!DBA::isResult($contact)) {
1810 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1811 return self::updateFromProbeArray($id, $ret);
1815 * @param integer $id contact id
1816 * @param array $ret Probed data
1818 * @throws HTTPException\InternalServerErrorException
1819 * @throws \ImagickException
1821 private static function updateFromProbeArray(int $id, array $ret)
1824 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1825 This will reliably kill your communication with old Friendica contacts.
1828 // These fields aren't updated by this routine:
1829 // 'xmpp', 'sensitive'
1831 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe', 'manually-approve',
1832 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1833 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1834 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1835 if (!DBA::isResult($contact)) {
1839 $uid = $contact['uid'];
1840 unset($contact['uid']);
1842 $pubkey = $contact['pubkey'];
1843 unset($contact['pubkey']);
1845 $contact['photo'] = $contact['avatar'];
1846 unset($contact['avatar']);
1848 $updated = DateTimeFormat::utcNow();
1850 // We must not try to update relay contacts via probe. They are no real contacts.
1851 // We check after the probing to be able to correct falsely detected contact types.
1852 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1853 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1854 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1855 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1859 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1860 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1862 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1867 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1868 $ret['unsearchable'] = $ret['hide'];
1871 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1872 $ret['forum'] = false;
1873 $ret['prv'] = false;
1874 $ret['contact-type'] = $ret['account-type'];
1875 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1876 $ret['forum'] = (bool)!$ret['manually-approve'];
1877 $ret['prv'] = (bool)!$ret['forum'];
1881 $new_pubkey = $ret['pubkey'] ?? '';
1884 $ret['last-item'] = Probe::getLastUpdate($ret);
1885 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1890 // make sure to not overwrite existing values with blank entries except some technical fields
1891 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1892 foreach ($ret as $key => $val) {
1893 if (!array_key_exists($key, $contact)) {
1895 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1896 $ret[$key] = $contact[$key];
1897 } elseif ($ret[$key] != $contact[$key]) {
1902 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1905 unset($ret['last-item']);
1908 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1909 self::updateAvatar($id, $ret['photo'], $update);
1913 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1915 if (Contact\Relation::isDiscoverable($ret['url'])) {
1916 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1919 // Update the public contact
1921 $contact = self::getByURL($ret['url'], false, ['id']);
1922 if (!empty($contact['id'])) {
1923 self::updateFromProbeArray($contact['id'], $ret);
1930 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1931 $ret['updated'] = $updated;
1933 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1934 if (empty($pubkey) && !empty($new_pubkey)) {
1935 $ret['pubkey'] = $new_pubkey;
1938 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1939 $ret['uri-date'] = DateTimeFormat::utcNow();
1942 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1943 $ret['name-date'] = $updated;
1947 $ret['last-update'] = $updated;
1948 $ret['success_update'] = $updated;
1949 $ret['failed'] = false;
1952 unset($ret['photo']);
1954 self::updateContact($id, $uid, $ret['url'], $ret);
1956 if (Contact\Relation::isDiscoverable($ret['url'])) {
1957 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1964 * @param integer $url contact url
1965 * @return integer Contact id
1966 * @throws HTTPException\InternalServerErrorException
1967 * @throws \ImagickException
1969 public static function updateFromProbeByURL($url)
1971 $id = self::getIdForURL($url);
1977 self::updateFromProbe($id);
1983 * Detects if a given contact array belongs to a legacy DFRN connection
1985 * @param array $contact
1988 public static function isLegacyDFRNContact($contact)
1990 // Newer Friendica contacts are connected via AP, then these fields aren't set
1991 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1995 * Detects the communication protocol for a given contact url.
1996 * This is used to detect Friendica contacts that we can communicate via AP.
1998 * @param string $url contact url
1999 * @param string $network Network of that contact
2000 * @return string with protocol
2002 public static function getProtocol($url, $network)
2004 if ($network != Protocol::DFRN) {
2008 $apcontact = APContact::getByURL($url);
2009 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2010 return Protocol::ACTIVITYPUB;
2017 * Takes a $uid and a url/handle and adds a new contact
2019 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2020 * dfrn_request page.
2022 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2025 * $return['success'] boolean true if successful
2026 * $return['message'] error text if success is false.
2028 * Takes a $uid and a url/handle and adds a new contact
2030 * @param array $user The user the contact should be created for
2031 * @param string $url The profile URL of the contact
2032 * @param bool $interactive
2033 * @param string $network
2035 * @throws HTTPException\InternalServerErrorException
2036 * @throws HTTPException\NotFoundException
2037 * @throws \ImagickException
2039 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2041 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2043 // remove ajax junk, e.g. Twitter
2044 $url = str_replace('/#!/', '/', $url);
2046 if (!Network::isUrlAllowed($url)) {
2047 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2051 if (Network::isUrlBlocked($url)) {
2052 $result['message'] = DI::l10n()->t('Blocked domain');
2057 $result['message'] = DI::l10n()->t('Connect URL missing.');
2061 $arr = ['url' => $url, 'contact' => []];
2063 Hook::callAll('follow', $arr);
2066 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2070 if (!empty($arr['contact']['name'])) {
2071 $ret = $arr['contact'];
2073 $ret = Probe::uri($url, $network, $user['uid']);
2076 if (($network != '') && ($ret['network'] != $network)) {
2077 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2081 // check if we already have a contact
2082 // the poll url is more reliable than the profile url, as we may have
2083 // indirect links or webfinger links
2085 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2086 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2087 if (!DBA::isResult($contact)) {
2088 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2089 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2092 $protocol = self::getProtocol($ret['url'], $ret['network']);
2094 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2096 if (strlen(DI::baseUrl()->getUrlPath())) {
2097 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2099 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2102 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2106 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2107 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2108 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2112 // This extra param just confuses things, remove it
2113 if ($protocol === Protocol::DIASPORA) {
2114 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2117 // do we have enough information?
2118 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2119 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2120 if (empty($ret['poll'])) {
2121 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2123 if (empty($ret['name'])) {
2124 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2126 if (empty($ret['url'])) {
2127 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2129 if (strpos($ret['url'], '@') !== false) {
2130 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2131 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2136 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2137 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2138 $ret['notify'] = '';
2141 if (!$ret['notify']) {
2142 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2145 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2147 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2149 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2152 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2153 $pending = (bool)$ret['manually-approve'];
2156 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2160 if (DBA::isResult($contact)) {
2162 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2164 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2165 DBA::update('contact', $fields, ['id' => $contact['id']]);
2167 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2169 // create contact record
2171 'uid' => $user['uid'],
2172 'created' => DateTimeFormat::utcNow(),
2173 'url' => $ret['url'],
2174 'nurl' => Strings::normaliseLink($ret['url']),
2175 'addr' => $ret['addr'],
2176 'alias' => $ret['alias'],
2177 'batch' => $ret['batch'],
2178 'notify' => $ret['notify'],
2179 'poll' => $ret['poll'],
2180 'poco' => $ret['poco'],
2181 'name' => $ret['name'],
2182 'nick' => $ret['nick'],
2183 'network' => $ret['network'],
2184 'baseurl' => $ret['baseurl'],
2185 'gsid' => $ret['gsid'] ?? null,
2186 'protocol' => $protocol,
2187 'pubkey' => $ret['pubkey'],
2188 'rel' => $new_relation,
2189 'priority'=> $ret['priority'],
2190 'writable'=> $writeable,
2191 'hidden' => $hidden,
2194 'pending' => $pending,
2199 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2200 if (!DBA::isResult($contact)) {
2201 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2205 $contact_id = $contact['id'];
2206 $result['cid'] = $contact_id;
2208 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2210 // Update the avatar
2211 self::updateAvatar($contact_id, $ret['photo']);
2213 // pull feed and consume it, which should subscribe to the hub.
2215 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2217 $owner = User::getOwnerDataById($user['uid']);
2219 if (DBA::isResult($owner)) {
2220 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2221 // create a follow slap
2223 $item['verb'] = Activity::FOLLOW;
2224 $item['gravity'] = GRAVITY_ACTIVITY;
2225 $item['follow'] = $contact["url"];
2227 $item['title'] = '';
2229 $item['uri-id'] = 0;
2230 $item['attach'] = '';
2232 $slap = OStatus::salmon($item, $owner);
2234 if (!empty($contact['notify'])) {
2235 Salmon::slapper($owner, $contact['notify'], $slap);
2237 } elseif ($protocol == Protocol::DIASPORA) {
2238 $ret = Diaspora::sendShare($owner, $contact);
2239 Logger::log('share returns: ' . $ret);
2240 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2241 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2242 if (empty($activity_id)) {
2243 // This really should never happen
2247 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2248 Logger::log('Follow returns: ' . $ret);
2252 $result['success'] = true;
2257 * Updated contact's SSL policy
2259 * @param array $contact Contact array
2260 * @param string $new_policy New policy, valid: self,full
2262 * @return array Contact array with updated values
2263 * @throws \Exception
2265 public static function updateSslPolicy(array $contact, $new_policy)
2267 $ssl_changed = false;
2268 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2269 $ssl_changed = true;
2270 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2271 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2272 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2273 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2274 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2275 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2278 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2279 $ssl_changed = true;
2280 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2281 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2282 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2283 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2284 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2285 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2289 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2290 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2291 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2292 DBA::update('contact', $fields, ['id' => $contact['id']]);
2299 * @param array $importer Owner (local user) data
2300 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2301 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2302 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2303 * @param string $note Introduction additional message
2304 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2305 * @throws HTTPException\InternalServerErrorException
2306 * @throws \ImagickException
2308 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2310 // Should always be set
2311 if (empty($datarray['author-id'])) {
2315 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2316 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2317 if (!DBA::isResult($pub_contact)) {
2318 // Should never happen
2322 // Contact is blocked at node-level
2323 if (self::isBlocked($datarray['author-id'])) {
2327 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2328 $name = $pub_contact['name'];
2329 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2330 $nick = $pub_contact['nick'];
2331 $network = $pub_contact['network'];
2333 // Ensure that we don't create a new contact when there already is one
2334 $cid = self::getIdForURL($url, $importer['uid']);
2336 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2339 if (!empty($contact)) {
2340 if (!empty($contact['pending'])) {
2341 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2345 // Contact is blocked at user-level
2346 if (!empty($contact['id']) && !empty($importer['id']) &&
2347 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2351 // Make sure that the existing contact isn't archived
2352 self::unmarkForArchival($contact);
2354 if (($contact['rel'] == self::SHARING)
2355 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2356 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2357 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2360 // Ensure to always have the correct network type, independent from the connection request method
2361 self::updateFromProbe($contact['id']);
2365 // send email notification to owner?
2366 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2367 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2371 // create contact record
2372 DBA::insert('contact', [
2373 'uid' => $importer['uid'],
2374 'created' => DateTimeFormat::utcNow(),
2376 'nurl' => Strings::normaliseLink($url),
2379 'network' => $network,
2380 'rel' => self::FOLLOWER,
2387 $contact_id = DBA::lastInsertId();
2389 // Ensure to always have the correct network type, independent from the connection request method
2390 self::updateFromProbe($contact_id);
2392 self::updateAvatar($contact_id, $photo, true);
2394 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2396 /// @TODO Encapsulate this into a function/method
2397 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2398 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2399 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2400 // create notification
2401 $hash = Strings::getRandomHex();
2403 if (is_array($contact_record)) {
2404 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2405 'blocked' => false, 'knowyou' => false, 'note' => $note,
2406 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2409 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2411 if (($user['notify-flags'] & Type::INTRO) &&
2412 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2415 'type' => Type::INTRO,
2416 'notify_flags' => $user['notify-flags'],
2417 'language' => $user['language'],
2418 'to_name' => $user['username'],
2419 'to_email' => $user['email'],
2420 'uid' => $user['uid'],
2421 'link' => DI::baseUrl() . '/notifications/intros',
2422 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2423 'source_link' => $contact_record['url'],
2424 'source_photo' => $contact_record['photo'],
2425 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2429 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2430 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2431 self::createFromProbe($importer, $url, false, $network);
2434 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2435 $fields = ['pending' => false];
2436 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2437 $fields['rel'] = Contact::FRIEND;
2440 DBA::update('contact', $fields, $condition);
2449 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2451 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2452 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2454 Contact::remove($contact['id']);
2458 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2460 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2461 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2463 Contact::remove($contact['id']);
2468 * Create a birthday event.
2470 * Update the year and the birthday.
2472 public static function updateBirthdays()
2476 AND `bd` > "0001-01-01"
2477 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2478 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2479 AND NOT `contact`.`pending`
2480 AND NOT `contact`.`hidden`
2481 AND NOT `contact`.`blocked`
2482 AND NOT `contact`.`archive`
2483 AND NOT `contact`.`deleted`',
2488 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2490 while ($contact = DBA::fetch($contacts)) {
2491 Logger::log('update_contact_birthday: ' . $contact['bd']);
2493 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2495 if (Event::createBirthday($contact, $nextbd)) {
2499 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2500 ['id' => $contact['id']]
2504 DBA::close($contacts);
2508 * Remove the unavailable contact ids from the provided list
2510 * @param array $contact_ids Contact id list
2512 * @throws \Exception
2514 public static function pruneUnavailable(array $contact_ids)
2516 if (empty($contact_ids)) {
2520 $contacts = Contact::selectToArray(['id'], [
2521 'id' => $contact_ids,
2527 return array_column($contacts, 'id');
2531 * Returns a magic link to authenticate remote visitors
2533 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2535 * @param string $contact_url The address of the target contact profile
2536 * @param string $url An url that we will be redirected to after the authentication
2538 * @return string with "redir" link
2539 * @throws HTTPException\InternalServerErrorException
2540 * @throws \ImagickException
2542 public static function magicLink($contact_url, $url = '')
2544 if (!Session::isAuthenticated()) {
2545 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2548 $contact = self::getByURL($contact_url, false);
2549 if (empty($contact)) {
2550 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2553 // Prevents endless loop in case only a non-public contact exists for the contact URL
2554 unset($contact['uid']);
2556 return self::magicLinkByContact($contact, $url ?: $contact_url);
2560 * Returns a magic link to authenticate remote visitors
2562 * @param integer $cid The contact id of the target contact profile
2563 * @param string $url An url that we will be redirected to after the authentication
2565 * @return string with "redir" link
2566 * @throws HTTPException\InternalServerErrorException
2567 * @throws \ImagickException
2569 public static function magicLinkbyId($cid, $url = '')
2571 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2573 return self::magicLinkByContact($contact, $url);
2577 * Returns a magic link to authenticate remote visitors
2579 * @param array $contact The contact array with "uid", "network" and "url"
2580 * @param string $url An url that we will be redirected to after the authentication
2582 * @return string with "redir" link
2583 * @throws HTTPException\InternalServerErrorException
2584 * @throws \ImagickException
2586 public static function magicLinkByContact($contact, $url = '')
2588 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2590 if (!Session::isAuthenticated()) {
2591 return $destination;
2594 // Only redirections to the same host do make sense
2595 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2599 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2600 return 'contact/' . $contact['id'] . '/conversations';
2603 if ($contact['network'] != Protocol::DFRN) {
2604 return $destination;
2607 if (!empty($contact['uid'])) {
2608 return self::magicLink($contact['url'], $url);
2611 if (empty($contact['id'])) {
2612 return $destination;
2615 $redirect = 'redir/' . $contact['id'];
2617 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2618 $redirect .= '?url=' . $url;
2625 * Is the contact a forum?
2627 * @param integer $contactid ID of the contact
2629 * @return boolean "true" if it is a forum
2631 public static function isForum($contactid)
2633 $fields = ['forum', 'prv'];
2634 $condition = ['id' => $contactid];
2635 $contact = DBA::selectFirst('contact', $fields, $condition);
2636 if (!DBA::isResult($contact)) {
2641 return ($contact['forum'] || $contact['prv']);
2645 * Can the remote contact receive private messages?
2647 * @param array $contact
2650 public static function canReceivePrivateMessages(array $contact)
2652 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2653 $self = $contact['self'] ?? false;
2655 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2659 * Search contact table by nick or name
2661 * @param string $search Name or nick
2662 * @param string $mode Search mode (e.g. "community")
2664 * @return array with search results
2665 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2667 public static function searchByName($search, $mode = '')
2669 if (empty($search)) {
2673 // check supported networks
2674 if (DI::config()->get('system', 'diaspora_enabled')) {
2675 $diaspora = Protocol::DIASPORA;
2677 $diaspora = Protocol::DFRN;
2680 if (!DI::config()->get('system', 'ostatus_disabled')) {
2681 $ostatus = Protocol::OSTATUS;
2683 $ostatus = Protocol::DFRN;
2686 // check if we search only communities or every contact
2687 if ($mode === 'community') {
2688 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2695 $results = DBA::p("SELECT * FROM `contact`
2696 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2697 NOT `failed` AND `uid` = ? AND
2698 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2699 ORDER BY `nurl` DESC LIMIT 1000",
2700 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2703 $contacts = DBA::toArray($results);
2708 * Add public contacts from an array
2710 * @param array $urls
2711 * @return array result "count", "added" and "updated"
2713 public static function addByUrls(array $urls)
2720 foreach ($urls as $url) {
2721 $contact = Contact::getByURL($url, false, ['id', 'updated']);
2722 if (empty($contact['id'])) {
2723 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2725 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
2726 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2734 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
2738 * Returns a random, global contact of the current node
2740 * @return string The profile URL
2743 public static function getRandomUrl()
2745 $r = DBA::selectFirst('contact', ['url'], [
2746 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2747 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2748 ], ['order' => ['RAND()']]);
2750 if (DBA::isResult($r)) {