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\Model;
24 use Friendica\App\BaseURL;
25 use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
26 use Friendica\Content\Pager;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\Session;
33 use Friendica\Core\System;
34 use Friendica\Core\Worker;
35 use Friendica\Database\Database;
36 use Friendica\Database\DBA;
38 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
39 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
40 use Friendica\Network\HTTPException;
41 use Friendica\Network\Probe;
42 use Friendica\Object\Image;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy;
50 use Friendica\Util\Strings;
53 * functions for interacting with a contact
57 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
58 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
59 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
65 const LOCK_INSERT = 'contact-insert';
70 * TYPE_UNKNOWN - unknown type
72 * TYPE_PERSON - the account belongs to a person
73 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
75 * TYPE_ORGANISATION - the account belongs to an organisation
76 * Associated page type: PAGE_SOAPBOX
78 * TYPE_NEWS - the account is a news reflector
79 * Associated page type: PAGE_SOAPBOX
81 * TYPE_COMMUNITY - the account is community forum
82 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
84 * TYPE_RELAY - the account is a relay
85 * This will only be assigned to contacts, not to user accounts
88 const TYPE_UNKNOWN = -1;
89 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
90 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
91 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
92 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
93 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
113 const MIRROR_DEACTIVATED = 0;
114 const MIRROR_FORWARDED = 1;
115 const MIRROR_OWN_POST = 2;
116 const MIRROR_NATIVE_RESHARE = 3;
119 * @param array $fields Array of selected fields, empty for all
120 * @param array $condition Array of fields for condition
121 * @param array $params Array of several parameters
125 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
127 return DBA::selectToArray('contact', $fields, $condition, $params);
131 * @param array $fields Array of selected fields, empty for all
132 * @param array $condition Array of fields for condition
133 * @param array $params Array of several parameters
137 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
139 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
145 * Insert a row into the contact table
146 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
148 * @param array $fields field array
149 * @param int $duplicate_mode Do an update on a duplicate entry
151 * @return int id of the created contact
154 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT)
156 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
157 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
160 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
162 if (empty($fields['created'])) {
163 $fields['created'] = DateTimeFormat::utcNow();
166 DBA::insert('contact', $fields, $duplicate_mode);
167 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
168 if (!DBA::isResult($contact)) {
170 Logger::warning('Created contact could not be found', ['fields' => $fields]);
174 Contact\User::insertForContactArray($contact);
176 // Search for duplicated contacts and get rid of them
177 if (!$contact['self']) {
178 self::removeDuplicates($contact['nurl'], $contact['uid']);
181 return $contact['id'];
185 * Updates rows in the contact table
187 * @param array $fields contains the fields that are updated
188 * @param array $condition condition array with the key values
189 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
191 * @return boolean was the update successfull?
194 public static function update(array $fields, array $condition, $old_fields = [])
196 $ret = DBA::update('contact', $fields, $condition, $old_fields);
198 // Apply changes to the "user-contact" table on dedicated fields
199 Contact\User::updateByContactUpdate($fields, $condition);
205 * @param integer $id Contact ID
206 * @param array $fields Array of selected fields, empty for all
207 * @return array|boolean Contact record if it exists, false otherwise
210 public static function getById($id, $fields = [])
212 return DBA::selectFirst('contact', $fields, ['id' => $id]);
216 * Fetch the first contact with the provided uri-id.
218 * @param integer $uri_id uri-id of the contact
219 * @param array $fields Array of selected fields, empty for all
220 * @return array|boolean Contact record if it exists, false otherwise
223 public static function getByUriId($uri_id, $fields = [])
225 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
229 * Fetches a contact by a given url
231 * @param string $url profile url
232 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
233 * @param array $fields Field list
234 * @param integer $uid User ID of the contact
235 * @return array contact array
237 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
239 if ($update || is_null($update)) {
240 $cid = self::getIdForURL($url, $uid, $update);
245 $contact = self::getById($cid, $fields);
246 if (empty($contact)) {
252 // Add internal fields
254 if (!empty($fields)) {
255 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
256 if (!in_array($internal, $fields)) {
257 $fields[] = $internal;
258 $removal[] = $internal;
263 // We first try the nurl (http://server.tld/nick), most common case
264 $options = ['order' => ['id']];
265 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
267 // Then the addr (nick@server.tld)
268 if (!DBA::isResult($contact)) {
269 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
272 // Then the alias (which could be anything)
273 if (!DBA::isResult($contact)) {
274 // The link could be provided as http although we stored it as https
275 $ssl_url = str_replace('http://', 'https://', $url);
276 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
277 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
280 if (!DBA::isResult($contact)) {
284 // Update the contact in the background if needed
285 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
286 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
287 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
290 // Remove the internal fields
291 foreach ($removal as $internal) {
292 unset($contact[$internal]);
299 * Fetches a contact for a given user by a given url.
300 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
302 * @param string $url profile url
303 * @param integer $uid User ID of the contact
304 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
305 * @param array $fields Field list
306 * @return array contact array
308 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
311 $contact = self::getByURL($url, $update, $fields, $uid);
312 if (!empty($contact)) {
313 if (!empty($contact['id'])) {
314 $contact['cid'] = $contact['id'];
321 $contact = self::getByURL($url, $update, $fields);
322 if (!empty($contact['id'])) {
324 $contact['zid'] = $contact['id'];
330 * Tests if the given contact is a follower
332 * @param int $cid Either public contact id or user's contact id
333 * @param int $uid User ID
335 * @return boolean is the contact id a follower?
336 * @throws HTTPException\InternalServerErrorException
337 * @throws \ImagickException
339 public static function isFollower($cid, $uid)
341 if (Contact\User::isBlocked($cid, $uid)) {
345 $cdata = self::getPublicAndUserContactID($cid, $uid);
346 if (empty($cdata['user'])) {
350 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
351 return DBA::exists('contact', $condition);
355 * Tests if the given contact url is a follower
357 * @param string $url Contact URL
358 * @param int $uid User ID
360 * @return boolean is the contact id a follower?
361 * @throws HTTPException\InternalServerErrorException
362 * @throws \ImagickException
364 public static function isFollowerByURL($url, $uid)
366 $cid = self::getIdForURL($url, $uid);
372 return self::isFollower($cid, $uid);
376 * Tests if the given user follow the given contact
378 * @param int $cid Either public contact id or user's contact id
379 * @param int $uid User ID
381 * @return boolean is the contact url being followed?
382 * @throws HTTPException\InternalServerErrorException
383 * @throws \ImagickException
385 public static function isSharing($cid, $uid)
387 if (Contact\User::isBlocked($cid, $uid)) {
391 $cdata = self::getPublicAndUserContactID($cid, $uid);
392 if (empty($cdata['user'])) {
396 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
397 return DBA::exists('contact', $condition);
401 * Tests if the given user follow the given contact url
403 * @param string $url Contact URL
404 * @param int $uid User ID
406 * @return boolean is the contact url being followed?
407 * @throws HTTPException\InternalServerErrorException
408 * @throws \ImagickException
410 public static function isSharingByURL($url, $uid)
412 $cid = self::getIdForURL($url, $uid);
418 return self::isSharing($cid, $uid);
422 * Get the basepath for a given contact link
424 * @param string $url The contact link
425 * @param boolean $dont_update Don't update the contact
427 * @return string basepath
428 * @throws HTTPException\InternalServerErrorException
429 * @throws \ImagickException
431 public static function getBasepath($url, $dont_update = false)
433 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
434 if (!DBA::isResult($contact)) {
438 if (!empty($contact['baseurl'])) {
439 return $contact['baseurl'];
440 } elseif ($dont_update) {
444 // Update the existing contact
445 self::updateFromProbe($contact['id']);
447 // And fetch the result
448 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
449 if (empty($contact['baseurl'])) {
450 Logger::info('No baseurl for contact', ['url' => $url]);
454 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
455 return $contact['baseurl'];
459 * Check if the given contact url is on the same server
461 * @param string $url The contact link
463 * @return boolean Is it the same server?
465 public static function isLocal($url)
467 if (!parse_url($url, PHP_URL_SCHEME)) {
468 $addr_parts = explode('@', $url);
469 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
472 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
476 * Check if the given contact ID is on the same server
478 * @param string $url The contact link
480 * @return boolean Is it the same server?
482 public static function isLocalById(int $cid)
484 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
485 if (!DBA::isResult($contact)) {
489 if (empty($contact['baseurl'])) {
490 $baseurl = self::getBasepath($contact['url'], true);
492 $baseurl = $contact['baseurl'];
495 return Strings::compareLink($baseurl, DI::baseUrl());
499 * Returns the public contact id of the given user id
501 * @param integer $uid User ID
503 * @return integer|boolean Public contact id for given user id
506 public static function getPublicIdByUserId($uid)
508 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
509 if (!DBA::isResult($self)) {
512 return self::getIdForURL($self['url']);
516 * Returns the contact id for the user and the public contact id for a given contact id
518 * @param int $cid Either public contact id or user's contact id
519 * @param int $uid User ID
521 * @return array with public and user's contact id
522 * @throws HTTPException\InternalServerErrorException
523 * @throws \ImagickException
525 public static function getPublicAndUserContactID($cid, $uid)
527 // We have to use the legacy function as long as the post update hasn't finished
528 if (DI::config()->get('system', 'post_update_version') < 1427) {
529 return self::legacyGetPublicAndUserContactID($cid, $uid);
532 if (empty($uid) || empty($cid)) {
536 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
537 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
541 $pcid = $contact['pid'];
542 if ($contact['uid'] == $uid) {
543 $ucid = $contact['id'];
545 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
546 if (DBA::isResult($contact)) {
547 $ucid = $contact['id'];
553 return ['public' => $pcid, 'user' => $ucid];
557 * Helper function for "getPublicAndUserContactID"
559 * @param int $cid Either public contact id or user's contact id
560 * @param int $uid User ID
562 * @return array with public and user's contact id
563 * @throws HTTPException\InternalServerErrorException
564 * @throws \ImagickException
566 private static function legacyGetPublicAndUserContactID($cid, $uid)
568 if (empty($uid) || empty($cid)) {
572 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
573 if (!DBA::isResult($contact)) {
577 // We quit when the user id don't match the user id of the provided contact
578 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
582 if ($contact['uid'] != 0) {
583 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
587 $ucid = $contact['id'];
589 $pcid = $contact['id'];
590 $ucid = self::getIdForURL($contact['url'], $uid);
593 return ['public' => $pcid, 'user' => $ucid];
597 * Returns contact details for a given contact id in combination with a user id
599 * @param int $cid A contact ID
600 * @param int $uid The User ID
601 * @param array $fields The selected fields for the contact
603 * @return array The contact details
607 public static function getContactForUser($cid, $uid, array $fields = [])
609 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
611 if (!DBA::isResult($contact)) {
619 * Creates the self-contact for the provided user id
622 * @return bool Operation success
623 * @throws HTTPException\InternalServerErrorException
625 public static function createSelfFromUserId($uid)
627 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
628 ['uid' => $uid, 'account_expired' => false]);
629 if (!DBA::isResult($user)) {
634 'uid' => $user['uid'],
635 'created' => DateTimeFormat::utcNow(),
637 'name' => $user['username'],
638 'nick' => $user['nickname'],
639 'pubkey' => $user['pubkey'],
640 'prvkey' => $user['prvkey'],
641 'photo' => User::getAvatarUrl($user),
642 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
643 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
646 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
647 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
648 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
649 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
650 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
651 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
652 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
653 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
654 'name-date' => DateTimeFormat::utcNow(),
655 'uri-date' => DateTimeFormat::utcNow(),
656 'avatar-date' => DateTimeFormat::utcNow(),
662 // Only create the entry if it doesn't exist yet
663 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
664 $return = (bool)self::insert($contact);
667 // Create the public contact
668 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
669 $contact['self'] = false;
671 $contact['prvkey'] = null;
673 self::insert($contact, Database::INSERT_IGNORE);
680 * Updates the self-contact for the provided user id
683 * @param boolean $update_avatar Force the avatar update
684 * @return bool "true" if updated
685 * @throws HTTPException\InternalServerErrorException
687 public static function updateSelfFromUserID($uid, $update_avatar = false)
689 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
690 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
691 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
692 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
693 if (!DBA::isResult($self)) {
697 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
698 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
699 if (!DBA::isResult($user)) {
703 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
704 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
705 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
706 if (!DBA::isResult($profile)) {
710 $file_suffix = 'jpg';
712 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
713 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
714 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
715 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
716 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp'], 'matrix' => $profile['matrix'], 'network' => Protocol::DFRN];
718 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
719 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
720 $fields['nurl'] = Strings::normaliseLink($fields['url']);
721 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
722 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
723 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
724 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
725 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
726 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
728 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
729 if (DBA::isResult($avatar)) {
730 if ($update_avatar) {
731 $fields['avatar-date'] = DateTimeFormat::utcNow();
734 // Creating the path to the avatar, beginning with the file suffix
735 $types = Images::supportedTypes();
736 if (isset($types[$avatar['type']])) {
737 $file_suffix = $types[$avatar['type']];
740 // We are adding a timestamp value so that other systems won't use cached content
741 $timestamp = strtotime($fields['avatar-date']);
743 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
744 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
746 $fields['photo'] = $prefix . '4' . $suffix;
747 $fields['thumb'] = $prefix . '5' . $suffix;
748 $fields['micro'] = $prefix . '6' . $suffix;
750 // We hadn't found a photo entry, so we use the default avatar
751 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
752 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
753 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
756 $fields['avatar'] = User::getAvatarUrl($user);
757 $fields['header'] = User::getBannerUrl($user);
758 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
759 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
760 $fields['unsearchable'] = !$profile['net-publish'];
761 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
765 foreach ($fields as $field => $content) {
766 if ($self[$field] != $content) {
772 if ($fields['name'] != $self['name']) {
773 $fields['name-date'] = DateTimeFormat::utcNow();
775 $fields['updated'] = DateTimeFormat::utcNow();
776 self::update($fields, ['id' => $self['id']]);
778 // Update the public contact as well
779 $fields['prvkey'] = null;
780 $fields['self'] = false;
781 self::update($fields, ['uid' => 0, 'nurl' => $self['nurl']]);
783 // Update the profile
785 'photo' => User::getAvatarUrl($user),
786 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
789 DBA::update('profile', $fields, ['uid' => $uid]);
796 * Marks a contact for removal
798 * @param int $id contact id
799 * @throws HTTPException\InternalServerErrorException
801 public static function remove($id)
803 // We want just to make sure that we don't delete our "self" contact
804 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro'], ['id' => $id, 'self' => false]);
805 if (!DBA::isResult($contact)) {
809 // Archive the contact
810 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
812 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
813 self::deleteAvatarCache($contact['photo']);
814 self::deleteAvatarCache($contact['thumb']);
815 self::deleteAvatarCache($contact['micro']);
818 // Delete it in the background
819 Worker::add(PRIORITY_MEDIUM, 'Contact\Remove', $id);
823 * Unfollow the remote contact
825 * @param array $contact Target user-specific contact (uid != 0) array
826 * @throws HTTPException\InternalServerErrorException
827 * @throws \ImagickException
829 public static function unfollow(array $contact): void
831 if (empty($contact['network'])) {
832 throw new \InvalidArgumentException('Empty network in contact array');
835 if (empty($contact['uid'])) {
836 throw new \InvalidArgumentException('Unexpected public contact record');
839 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
840 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
841 if (!empty($cdata['public'])) {
842 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
846 self::removeSharer($contact);
850 * Revoke follow privileges of the remote user contact
852 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
854 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
855 * @throws HTTPException\InternalServerErrorException
856 * @throws \ImagickException
858 public static function revokeFollow(array $contact): void
860 if (empty($contact['network'])) {
861 throw new \InvalidArgumentException('Empty network in contact array');
864 if (empty($contact['uid'])) {
865 throw new \InvalidArgumentException('Unexpected public contact record');
868 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
869 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
870 if (!empty($cdata['public'])) {
871 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
875 self::removeFollower($contact);
879 * Completely severs a relationship with a contact
881 * @param array $contact User-specific contact (uid != 0) array
882 * @throws HTTPException\InternalServerErrorException
883 * @throws \ImagickException
885 public static function terminateFriendship(array $contact)
887 if (empty($contact['network'])) {
888 throw new \InvalidArgumentException('Empty network in contact array');
891 if (empty($contact['uid'])) {
892 throw new \InvalidArgumentException('Unexpected public contact record');
895 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
897 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
898 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
901 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
902 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
905 self::remove($contact['id']);
910 * Marks a contact for archival after a communication issue delay
912 * Contact has refused to recognise us as a friend. We will start a countdown.
913 * If they still don't recognise us in 32 days, the relationship is over,
914 * and we won't waste any more time trying to communicate with them.
915 * This provides for the possibility that their database is temporarily messed
916 * up or some other transient event and that there's a possibility we could recover from it.
918 * @param array $contact contact to mark for archival
920 * @throws HTTPException\InternalServerErrorException
922 public static function markForArchival(array $contact)
924 if (!isset($contact['url']) && !empty($contact['id'])) {
925 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
926 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
927 if (!DBA::isResult($contact)) {
930 } elseif (!isset($contact['url'])) {
931 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
934 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
936 // Contact already archived or "self" contact? => nothing to do
937 if ($contact['archive'] || $contact['self']) {
941 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
942 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
943 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
946 * We really should send a notification to the owner after 2-3 weeks
947 * so they won't be surprised when the contact vanishes and can take
948 * remedial action if this was a serious mistake or glitch
951 /// @todo Check for contact vitality via probing
952 $archival_days = DI::config()->get('system', 'archival_days', 32);
954 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
955 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
956 /* Relationship is really truly dead. archive them rather than
957 * delete, though if the owner tries to unarchive them we'll start
958 * the whole process over again.
960 self::update(['archive' => true], ['id' => $contact['id']]);
961 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
967 * Cancels the archival countdown
969 * @see Contact::markForArchival()
971 * @param array $contact contact to be unmarked for archival
975 public static function unmarkForArchival(array $contact)
977 // Always unarchive the relay contact entry
978 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
979 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
980 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
981 if (!DBA::exists('contact', array_merge($condition, $fields))) {
982 self::update($fields, $condition);
986 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
987 $exists = DBA::exists('contact', $condition);
989 // We don't need to update, we never marked this contact for archival
994 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
996 if (!isset($contact['url']) && !empty($contact['id'])) {
997 $fields = ['id', 'url', 'batch'];
998 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
999 if (!DBA::isResult($contact)) {
1004 // It's a miracle. Our dead contact has inexplicably come back to life.
1005 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1006 self::update($fields, ['id' => $contact['id']]);
1007 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1011 * Returns the data array for the photo menu of a given contact
1013 * @param array $contact contact
1014 * @param int $uid optional, default 0
1016 * @throws HTTPException\InternalServerErrorException
1017 * @throws \ImagickException
1019 public static function photoMenu(array $contact, $uid = 0)
1027 $uid = local_user();
1030 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1032 $profile_link = self::magicLinkByContact($contact);
1033 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1038 // Look for our own contact if the uid doesn't match and isn't public
1039 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1040 if (DBA::isResult($contact_own)) {
1041 return self::photoMenu($contact_own, $uid);
1046 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1048 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1050 $profile_link = $contact['url'];
1053 if ($profile_link === 'mailbox') {
1058 $status_link = $profile_link . '/status';
1059 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1060 $profile_link = $profile_link . '/profile';
1063 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1064 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1067 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1068 $poke_link = 'contact/' . $contact['id'] . '/poke';
1071 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1073 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1076 $unfollow_link = '';
1077 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1078 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1079 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1080 } elseif(!$contact['pending']) {
1081 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1087 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1089 if (empty($contact['uid'])) {
1091 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1092 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1093 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1094 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1095 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1099 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1100 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1101 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1102 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1103 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1104 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1105 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1106 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1107 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1110 if (!empty($contact['pending'])) {
1112 $intro = DI::intro()->selectForContact($contact['id']);
1113 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1114 } catch (IntroductionNotFoundException $exception) {
1115 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1120 $args = ['contact' => $contact, 'menu' => &$menu];
1122 Hook::callAll('contact_photo_menu', $args);
1124 $menucondensed = [];
1126 foreach ($menu as $menuname => $menuitem) {
1127 if ($menuitem[1] != '') {
1128 $menucondensed[$menuname] = $menuitem;
1132 return $menucondensed;
1136 * Fetch the contact id for a given URL and user
1138 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1139 * `addr` or `alias`.
1141 * If there's no record and we aren't looking for a public contact, we quit.
1142 * If there's one, we check that it isn't time to update the picture else we
1143 * directly return the found contact id.
1145 * Second, we probe the provided $url whether it's http://server.tld/profile or
1146 * nick@server.tld. We quit if we can't get any info back.
1148 * Third, we create the contact record if it doesn't exist
1150 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1151 * if there's any updates
1153 * @param string $url Contact URL
1154 * @param integer $uid The user id for the contact (0 = public contact)
1155 * @param boolean $update true = always update, false = never update, null = update when not found
1156 * @param array $default Default value for creating the contact when everything else fails
1158 * @return integer Contact ID
1159 * @throws HTTPException\InternalServerErrorException
1160 * @throws \ImagickException
1162 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1167 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1171 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1173 if (!empty($contact)) {
1174 $contact_id = $contact["id"];
1176 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1177 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1180 } elseif ($uid != 0) {
1181 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1183 } elseif (empty($default) && !is_null($update) && !$update) {
1184 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1190 if (empty($default['network']) || $update) {
1191 $data = Probe::uri($url, "", $uid);
1193 // Take the default values when probing failed
1194 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1195 $data = array_merge($data, $default);
1197 } elseif (!empty($default['network'])) {
1201 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1202 // Fetch data for the public contact via the first found personal contact
1203 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1204 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1205 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1206 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1208 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1209 if (!DBA::isResult($personal_contact)) {
1210 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1213 if (DBA::isResult($personal_contact)) {
1214 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1215 $data = $personal_contact;
1216 $data['photo'] = $personal_contact['avatar'];
1217 $data['account-type'] = $personal_contact['contact-type'];
1218 $data['hide'] = $personal_contact['unsearchable'];
1219 unset($data['avatar']);
1220 unset($data['contact-type']);
1221 unset($data['unsearchable']);
1225 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1226 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1231 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1232 if (!empty($data['alias'])) {
1233 $urls[] = Strings::normaliseLink($data['alias']);
1235 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1236 if (!empty($contact['id'])) {
1237 $contact_id = $contact['id'];
1238 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1243 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1246 'url' => $data['url'],
1247 'nurl' => Strings::normaliseLink($data['url']),
1248 'network' => $data['network'],
1249 'created' => DateTimeFormat::utcNow(),
1250 'rel' => self::SHARING,
1256 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1258 // Before inserting we do check if the entry does exist now.
1259 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1260 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1261 if (DBA::isResult($contact)) {
1262 $contact_id = $contact['id'];
1263 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1265 $contact_id = self::insert($fields);
1267 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1270 DI::lock()->release(self::LOCK_INSERT);
1272 Logger::warning('Contact lock had not been acquired');
1276 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1280 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1283 if ($data['network'] == Protocol::DIASPORA) {
1284 FContact::updateFromProbeArray($data);
1287 self::updateFromProbeArray($contact_id, $data);
1289 // Don't return a number for a deleted account
1290 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1291 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1299 * Checks if the contact is archived
1301 * @param int $cid contact id
1303 * @return boolean Is the contact archived?
1304 * @throws HTTPException\InternalServerErrorException
1306 public static function isArchived(int $cid)
1312 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1313 if (!DBA::isResult($contact)) {
1317 if ($contact['archive']) {
1321 // Check status of ActivityPub endpoints
1322 $apcontact = APContact::getByURL($contact['url'], false);
1323 if (!empty($apcontact)) {
1324 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1328 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1333 // Check status of Diaspora endpoints
1334 if (!empty($contact['batch'])) {
1335 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1336 return DBA::exists('contact', $condition);
1343 * Checks if the contact is blocked
1345 * @param int $cid contact id
1347 * @return boolean Is the contact blocked?
1348 * @throws HTTPException\InternalServerErrorException
1350 public static function isBlocked($cid)
1356 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1357 if (!DBA::isResult($blocked)) {
1361 if (Network::isUrlBlocked($blocked['url'])) {
1365 return (bool) $blocked['blocked'];
1369 * Checks if the contact is hidden
1371 * @param int $cid contact id
1373 * @return boolean Is the contact hidden?
1374 * @throws \Exception
1376 public static function isHidden($cid)
1382 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1383 if (!DBA::isResult($hidden)) {
1386 return (bool) $hidden['hidden'];
1390 * Returns posts from a given contact url
1392 * @param string $contact_url Contact URL
1393 * @param bool $thread_mode
1394 * @param int $update Update mode
1395 * @param int $parent Item parent ID for the update mode
1396 * @param bool $only_media Only display media content
1397 * @return string posts in HTML
1398 * @throws \Exception
1400 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0, bool $only_media = false)
1402 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1406 * Returns posts from a given contact id
1408 * @param int $cid Contact ID
1409 * @param bool $thread_mode
1410 * @param int $update Update mode
1411 * @param int $parent Item parent ID for the update mode
1412 * @param bool $only_media Only display media content
1413 * @return string posts in HTML
1414 * @throws \Exception
1416 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0, bool $only_media = false)
1418 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1419 if (!DBA::isResult($contact)) {
1423 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1424 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1429 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1432 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1433 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1435 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1436 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1439 if (!empty($parent)) {
1440 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1442 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1443 if (!empty($last_received)) {
1444 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1449 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1450 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1453 if (DI::mode()->isMobile()) {
1454 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1455 DI::config()->get('system', 'itemspage_network_mobile'));
1457 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1458 DI::config()->get('system', 'itemspage_network'));
1461 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1463 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1465 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1466 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1467 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1473 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1474 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1476 if ($pager->getStart() == 0) {
1477 $cdata = self::getPublicAndUserContactID($cid, local_user());
1478 if (!empty($cdata['public'])) {
1479 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1480 $items = array_merge($items, $pinned);
1484 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', local_user());
1486 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1487 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1489 if ($pager->getStart() == 0) {
1490 $cdata = self::getPublicAndUserContactID($cid, local_user());
1491 if (!empty($cdata['public'])) {
1492 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1493 $cdata['public'], Post\Collection::FEATURED];
1494 $pinned = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1495 $items = array_merge($pinned, $items);
1499 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1503 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1504 $o .= HTML::scrollLoader();
1506 $o .= $pager->renderMinimal(count($items));
1514 * Returns the account type name
1516 * The function can be called with either the user or the contact array
1518 * @param int $type type of contact or account
1521 public static function getAccountType(int $type)
1524 case self::TYPE_ORGANISATION:
1525 $account_type = DI::l10n()->t("Organisation");
1528 case self::TYPE_NEWS:
1529 $account_type = DI::l10n()->t('News');
1532 case self::TYPE_COMMUNITY:
1533 $account_type = DI::l10n()->t("Forum");
1541 return $account_type;
1549 * @throws \Exception
1551 public static function block($cid, $reason = null)
1553 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1559 * Unblocks a contact
1563 * @throws \Exception
1565 public static function unblock($cid)
1567 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1573 * Ensure that cached avatar exist
1575 * @param integer $cid
1577 public static function checkAvatarCache(int $cid)
1579 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1580 if (!DBA::isResult($contact)) {
1584 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1585 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1586 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1587 self::updateAvatar($cid, $contact['avatar'], true);
1590 } elseif (!self::getAvatarFile($contact['photo']) || !self::getAvatarFile($contact['thumb']) || !self::getAvatarFile($contact['micro'])) {
1591 Logger::info('Removing/replacing avatar cache', ['id' => $cid, 'contact' => $contact]);
1592 self::updateAvatar($cid, $contact['avatar'], true);
1598 * Return the photo path for a given contact array in the given size
1600 * @param array $contact contact array
1601 * @param string $field Fieldname of the photo in the contact array
1602 * @param string $size Size of the avatar picture
1603 * @param string $avatar Avatar path that is displayed when no photo had been found
1604 * @param bool $no_update Don't perfom an update if no cached avatar was found
1605 * @return string photo path
1607 private static function getAvatarPath(array $contact, string $size, $no_update = false)
1609 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1611 if (DI::config()->get('system', 'avatar_cache')) {
1613 case Proxy::SIZE_MICRO:
1614 if (self::getAvatarFile($contact['micro'])) {
1615 return $contact['micro'];
1618 case Proxy::SIZE_THUMB:
1619 if (self::getAvatarFile($contact['thumb'])) {
1620 return $contact['thumb'];
1623 case Proxy::SIZE_SMALL:
1624 if (self::getAvatarFile($contact['photo'])) {
1625 return $contact['photo'];
1631 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1635 * Return the photo path for a given contact array
1637 * @param array $contact Contact array
1638 * @param bool $no_update Don't perfom an update if no cached avatar was found
1639 * @return string photo path
1641 public static function getPhoto(array $contact, bool $no_update = false)
1643 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1647 * Return the photo path (thumb size) for a given contact array
1649 * @param array $contact Contact array
1650 * @param bool $no_update Don't perfom an update if no cached avatar was found
1651 * @return string photo path
1653 public static function getThumb(array $contact, bool $no_update = false)
1655 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1659 * Return the photo path (micro size) for a given contact array
1661 * @param array $contact Contact array
1662 * @param bool $no_update Don't perfom an update if no cached avatar was found
1663 * @return string photo path
1665 public static function getMicro(array $contact, bool $no_update = false)
1667 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1671 * Check the given contact array for avatar cache fields
1673 * @param array $contact
1674 * @param bool $no_update Don't perfom an update if no cached avatar was found
1675 * @return array contact array with avatar cache fields
1677 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false)
1680 $contact_fields = [];
1681 $fields = ['photo', 'thumb', 'micro'];
1682 foreach ($fields as $field) {
1683 if (isset($contact[$field])) {
1684 $contact_fields[] = $field;
1686 if (isset($contact[$field]) && empty($contact[$field])) {
1691 if (!$update || $no_update) {
1695 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1696 self::updateAvatar($contact['id'], $contact['avatar'], true);
1698 $new_contact = self::getById($contact['id'], $contact_fields);
1699 if (DBA::isResult($new_contact)) {
1700 // We only update the cache fields
1701 $contact = array_merge($contact, $new_contact);
1705 /// add the default avatars if the fields aren't filled
1706 if (isset($contact['photo']) && empty($contact['photo'])) {
1707 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1709 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1710 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1712 if (isset($contact['micro']) && empty($contact['micro'])) {
1713 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1720 * Fetch the default header for the given contact
1722 * @param array $contact contact array
1723 * @return string avatar URL
1725 public static function getDefaultHeader(array $contact): string
1727 if (!empty($contact['header'])) {
1728 return $contact['header'];
1731 if (!empty($contact['gsid'])) {
1732 // Use default banners for certain platforms
1733 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1734 $platform = strtolower($gserver['platform'] ?? '');
1739 switch ($platform) {
1744 * @author Lostinlight <https://mastodon.xyz/@lightone>
1745 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1746 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1748 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1753 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1754 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1755 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1757 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1761 * Use a random picture.
1762 * The service provides random pictures from Unsplash.
1763 * @license https://unsplash.com/license
1765 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1773 * Fetch the default avatar for the given contact and size
1775 * @param array $contact contact array
1776 * @param string $size Size of the avatar picture
1777 * @return string avatar URL
1779 public static function getDefaultAvatar(array $contact, string $size)
1782 case Proxy::SIZE_MICRO:
1783 $avatar['size'] = 48;
1784 $default = self::DEFAULT_AVATAR_MICRO;
1787 case Proxy::SIZE_THUMB:
1788 $avatar['size'] = 80;
1789 $default = self::DEFAULT_AVATAR_THUMB;
1792 case Proxy::SIZE_SMALL:
1794 $avatar['size'] = 300;
1795 $default = self::DEFAULT_AVATAR_PHOTO;
1799 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1800 return DI::baseUrl() . $default;
1803 if (!empty($contact['xmpp'])) {
1804 $avatar['email'] = $contact['xmpp'];
1805 } elseif (!empty($contact['addr'])) {
1806 $avatar['email'] = $contact['addr'];
1807 } elseif (!empty($contact['url'])) {
1808 $avatar['email'] = $contact['url'];
1810 return DI::baseUrl() . $default;
1813 $avatar['url'] = '';
1814 $avatar['success'] = false;
1816 Hook::callAll('avatar_lookup', $avatar);
1818 if ($avatar['success'] && !empty($avatar['url'])) {
1819 return $avatar['url'];
1822 return DI::baseUrl() . $default;
1826 * Get avatar link for given contact id
1828 * @param integer $cid contact id
1829 * @param string $size One of the Proxy::SIZE_* constants
1830 * @param string $updated Contact update date
1831 * @return string avatar link
1833 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''):string
1835 // We have to fetch the "updated" variable when it wasn't provided
1836 // The parameter can be provided to improve performance
1837 if (empty($updated)) {
1838 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1839 $updated = $account['updated'] ?? '';
1840 $guid = $account['guid'] ?? '';
1843 $guid = urlencode($guid);
1845 $url = DI::baseUrl() . '/photo/contact/';
1847 case Proxy::SIZE_MICRO:
1848 $url .= Proxy::PIXEL_MICRO . '/';
1850 case Proxy::SIZE_THUMB:
1851 $url .= Proxy::PIXEL_THUMB . '/';
1853 case Proxy::SIZE_SMALL:
1854 $url .= Proxy::PIXEL_SMALL . '/';
1856 case Proxy::SIZE_MEDIUM:
1857 $url .= Proxy::PIXEL_MEDIUM . '/';
1859 case Proxy::SIZE_LARGE:
1860 $url .= Proxy::PIXEL_LARGE . '/';
1863 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
1867 * Get avatar link for given contact URL
1869 * @param string $url contact url
1870 * @param integer $uid user id
1871 * @param string $size One of the Proxy::SIZE_* constants
1872 * @return string avatar link
1874 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''):string
1876 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
1877 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
1878 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
1879 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1883 * Get header link for given contact id
1885 * @param integer $cid contact id
1886 * @param string $size One of the Proxy::SIZE_* constants
1887 * @param string $updated Contact update date
1888 * @return string header link
1890 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''):string
1892 // We have to fetch the "updated" variable when it wasn't provided
1893 // The parameter can be provided to improve performance
1894 if (empty($updated) || empty($guid)) {
1895 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1896 $updated = $account['updated'] ?? '';
1897 $guid = $account['guid'] ?? '';
1900 $guid = urlencode($guid);
1902 $url = DI::baseUrl() . '/photo/header/';
1904 case Proxy::SIZE_MICRO:
1905 $url .= Proxy::PIXEL_MICRO . '/';
1907 case Proxy::SIZE_THUMB:
1908 $url .= Proxy::PIXEL_THUMB . '/';
1910 case Proxy::SIZE_SMALL:
1911 $url .= Proxy::PIXEL_SMALL . '/';
1913 case Proxy::SIZE_MEDIUM:
1914 $url .= Proxy::PIXEL_MEDIUM . '/';
1916 case Proxy::SIZE_LARGE:
1917 $url .= Proxy::PIXEL_LARGE . '/';
1921 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
1925 * Updates the avatar links in a contact only if needed
1927 * @param int $cid Contact id
1928 * @param string $avatar Link to avatar picture
1929 * @param bool $force force picture update
1930 * @param bool $create_cache Enforces the creation of cached avatar fields
1933 * @throws HTTPException\InternalServerErrorException
1934 * @throws HTTPException\NotFoundException
1935 * @throws \ImagickException
1937 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1939 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
1940 ['id' => $cid, 'self' => false]);
1941 if (!DBA::isResult($contact)) {
1945 $uid = $contact['uid'];
1947 // Only update the cached photo links of public contacts when they already are cached
1948 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1949 if ($contact['avatar'] != $avatar) {
1950 self::update(['avatar' => $avatar], ['id' => $cid]);
1951 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1956 // User contacts use are updated through the public contacts
1957 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1958 $pcid = self::getIdForURL($contact['url'], 0, false);
1959 if (!empty($pcid)) {
1960 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1961 self::updateAvatar($pcid, $avatar, $force, true);
1966 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
1968 if ($default_avatar) {
1969 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1972 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
1974 // Local contact avatars don't need to be cached
1975 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
1976 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
1979 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
1980 self::deleteAvatarCache($contact['photo']);
1981 self::deleteAvatarCache($contact['thumb']);
1982 self::deleteAvatarCache($contact['micro']);
1984 if ($default_avatar && Proxy::isLocalImage($avatar)) {
1985 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1987 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
1988 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
1989 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1992 // Use the data from the self account
1993 if (empty($fields)) {
1994 $local_uid = User::getIdForURL($contact['url']);
1995 if (!empty($local_uid)) {
1996 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1997 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2001 if (empty($fields)) {
2002 $update = ($contact['avatar'] != $avatar) || $force;
2006 $contact['photo'] ?? '',
2007 $contact['thumb'] ?? '',
2008 $contact['micro'] ?? '',
2011 foreach ($data as $image_uri) {
2012 $image_rid = Photo::ridFromURI($image_uri);
2013 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2014 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2021 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2023 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2024 $update = !empty($fields);
2025 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2031 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2034 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2035 $fields = self::fetchAvatarContact($contact, $avatar);
2036 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2045 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2046 // Collect all user contacts of the given public contact
2047 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2048 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2049 while ($personal_contact = DBA::fetch($personal_contacts)) {
2050 $cids[] = $personal_contact['id'];
2051 $uids[] = $personal_contact['uid'];
2053 DBA::close($personal_contacts);
2055 if (!empty($cids)) {
2056 // Delete possibly existing cached user contact avatars
2057 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2063 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2064 self::update($fields, ['id' => $cids]);
2068 * Returns a field array with locally cached avatar pictures
2070 * @param array $contact
2071 * @param string $avatar
2074 private static function fetchAvatarContact(array $contact, string $avatar): array
2076 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), 'photo' => '', 'thumb' => '', 'micro' => ''];
2078 if (!DI::config()->get('system', 'avatar_cache')) {
2079 self::deleteAvatarCache($contact['photo']);
2080 self::deleteAvatarCache($contact['thumb']);
2081 self::deleteAvatarCache($contact['micro']);
2085 if (Network::isLocalLink($avatar)) {
2089 if ($avatar != $contact['avatar']) {
2090 self::deleteAvatarCache($contact['photo']);
2091 self::deleteAvatarCache($contact['thumb']);
2092 self::deleteAvatarCache($contact['micro']);
2093 Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
2094 } elseif (self::getAvatarFile($contact['photo']) && self::getAvatarFile($contact['thumb']) && self::getAvatarFile($contact['micro'])) {
2095 $fields['photo'] = $contact['photo'];
2096 $fields['thumb'] = $contact['thumb'];
2097 $fields['micro'] = $contact['micro'];
2098 Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
2102 $guid = Item::guidFromUri($contact['url'], parse_url($contact['url'], PHP_URL_HOST));
2104 $filename = substr($guid, 0, 2) . '/' . substr($guid, 3, 2) . '/' . substr($guid, 5, 3) . '/' .
2105 substr($guid, 9, 2) .'/' . substr($guid, 11, 2) . '/' . substr($guid, 13, 4). '/' . substr($guid, 18) . '-';
2107 $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
2108 $img_str = $fetchResult->getBody();
2109 if (empty($img_str)) {
2110 Logger::debug('Avatar is invalid', ['avatar' => $avatar]);
2114 $image = new Image($img_str, Images::getMimeTypeByData($img_str));
2115 if (!$image->isValid()) {
2116 Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]);
2120 $fields['photo'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_SMALL);
2121 $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB);
2122 $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO);
2124 Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
2129 private static function storeAvatarCache(Image $image, string $filename, int $size): string
2131 $image->scaleDown($size);
2132 if (is_null($image) || !$image->isValid()) {
2136 $path = '/avatar/' . $filename . $size . '.' . $image->getExt();
2138 $filepath = DI::basePath() . $path;
2140 $dirpath = dirname($filepath);
2142 DI::profiler()->startRecording('file');
2144 if (!file_exists($dirpath)) {
2145 mkdir($dirpath, 0777, true);
2148 file_put_contents($filepath, $image->asString());
2149 DI::profiler()->stopRecording();
2151 return DI::baseUrl() . $path;
2155 * Fetch the name of locally cached avatar pictures
2157 * @param string $avatar
2160 private static function getAvatarFile(string $avatar): string
2162 if (empty($avatar) || !Network::isLocalLink($avatar)) {
2166 $path = Strings::normaliseLink(DI::baseUrl() . '/avatar');
2168 if (Network::getUrlMatch($path, $avatar) != $path) {
2172 $filename = str_replace($path, DI::basePath(). '/avatar/', Strings::normaliseLink($avatar));
2174 DI::profiler()->startRecording('file');
2175 $exists = file_exists($filename);
2176 DI::profiler()->stopRecording();
2185 * Delete a locally cached avatar picture
2187 * @param string $avatar
2190 public static function deleteAvatarCache(string $avatar)
2192 $localFile = self::getAvatarFile($avatar);
2193 if (!empty($localFile)) {
2195 Logger::debug('Unlink avatar', ['avatar' => $avatar]);
2199 public static function deleteContactByUrl(string $url)
2201 // Update contact data for all users
2202 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2203 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2204 while ($contact = DBA::fetch($contacts)) {
2205 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2206 self::remove($contact['id']);
2211 * Helper function for "updateFromProbe". Updates personal and public contact
2213 * @param integer $id contact id
2214 * @param integer $uid user id
2215 * @param string $old_url The previous profile URL of the contact
2216 * @param string $new_url The profile URL of the contact
2217 * @param array $fields The fields that are updated
2219 * @throws \Exception
2221 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
2223 if (!self::update($fields, ['id' => $id])) {
2224 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2228 // Search for duplicated contacts and get rid of them
2229 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
2233 // Archive or unarchive the contact.
2234 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2235 if (!DBA::isResult($contact)) {
2236 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2240 if (isset($fields['failed'])) {
2241 if ($fields['failed']) {
2242 self::markForArchival($contact);
2244 self::unmarkForArchival($contact);
2248 if ($contact['uid'] != 0) {
2252 // Update contact data for all users
2253 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
2255 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2256 self::update($fields, $condition);
2258 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2259 $condition['network'] = Protocol::OSTATUS;
2261 // If the contact failed, propagate the update fields to all contacts
2262 if (empty($fields['failed'])) {
2263 unset($fields['last-update']);
2264 unset($fields['success_update']);
2265 unset($fields['failure_update']);
2268 if (empty($fields)) {
2272 self::update($fields, $condition);
2276 * Remove duplicated contacts
2278 * @param string $nurl Normalised contact url
2279 * @param integer $uid User id
2281 * @throws \Exception
2283 public static function removeDuplicates(string $nurl, int $uid)
2285 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2286 $count = DBA::count('contact', $condition);
2291 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2292 if (!DBA::isResult($first_contact)) {
2293 // Shouldn't happen - so we handle it
2297 $first = $first_contact['id'];
2298 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2299 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2300 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2301 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2305 // Find all duplicates
2306 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2307 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2308 while ($duplicate = DBA::fetch($duplicates)) {
2309 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2313 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2315 DBA::close($duplicates);
2316 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2321 * @param integer $id contact id
2322 * @param string $network Optional network we are probing for
2324 * @throws HTTPException\InternalServerErrorException
2325 * @throws \ImagickException
2327 public static function updateFromProbe(int $id, string $network = '')
2329 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2330 if (!DBA::isResult($contact)) {
2334 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2336 if ($ret['network'] == Protocol::DIASPORA) {
2337 FContact::updateFromProbeArray($ret);
2340 return self::updateFromProbeArray($id, $ret);
2344 * @param integer $id contact id
2345 * @param array $ret Probed data
2347 * @throws HTTPException\InternalServerErrorException
2348 * @throws \ImagickException
2350 private static function updateFromProbeArray(int $id, array $ret)
2353 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2354 This will reliably kill your communication with old Friendica contacts.
2357 // These fields aren't updated by this routine:
2360 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2361 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2362 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix'];
2363 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2364 if (!DBA::isResult($contact)) {
2368 if (self::isLocal($ret['url'])) {
2369 if ($contact['uid'] == 0) {
2370 Logger::info('Local contacts are not updated here.');
2372 self::updateFromPublicContact($id, $contact);
2377 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2378 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2381 // Delete all contacts with the same URL
2382 self::deleteContactByUrl($ret['url']);
2386 $uid = $contact['uid'];
2387 unset($contact['uid']);
2389 $uriid = $contact['uri-id'];
2390 unset($contact['uri-id']);
2392 $pubkey = $contact['pubkey'];
2393 unset($contact['pubkey']);
2395 $contact['photo'] = $contact['avatar'];
2396 unset($contact['avatar']);
2398 $updated = DateTimeFormat::utcNow();
2400 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2401 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2402 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2406 // We must not try to update relay contacts via probe. They are no real contacts.
2407 // We check after the probing to be able to correct falsely detected contact types.
2408 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2409 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2410 self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2411 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2415 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2416 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2417 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2421 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2422 $cid = self::getIdForURL($ret['url'], 0, false);
2423 if (!empty($cid) && ($cid != $id)) {
2424 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2425 return self::updateFromProbeArray($cid, $ret);
2429 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2430 $ret['unsearchable'] = $ret['hide'];
2433 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2434 $ret['forum'] = false;
2435 $ret['prv'] = false;
2436 $ret['contact-type'] = $ret['account-type'];
2437 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2438 $ret['forum'] = (bool)!$ret['manually-approve'];
2439 $ret['prv'] = (bool)!$ret['forum'];
2443 $new_pubkey = $ret['pubkey'] ?? '';
2446 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2447 ActivityPub\Processor::fetchFeaturedPosts($ret['url']);
2450 $ret['last-item'] = Probe::getLastUpdate($ret);
2451 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2455 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2457 // make sure to not overwrite existing values with blank entries except some technical fields
2458 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2459 foreach ($ret as $key => $val) {
2460 if (!array_key_exists($key, $contact)) {
2462 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2463 $ret[$key] = $contact[$key];
2464 } elseif ($ret[$key] != $contact[$key]) {
2469 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2472 unset($ret['last-item']);
2475 if (empty($uriid)) {
2479 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2480 self::updateAvatar($id, $ret['photo'], $update);
2483 $uriid = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2486 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2488 if (Contact\Relation::isDiscoverable($ret['url'])) {
2489 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2492 // Update the public contact
2494 $contact = self::getByURL($ret['url'], false, ['id']);
2495 if (!empty($contact['id'])) {
2496 self::updateFromProbeArray($contact['id'], $ret);
2503 $ret['uri-id'] = $uriid;
2504 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2505 $ret['updated'] = $updated;
2506 $ret['failed'] = false;
2508 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2509 if (empty($pubkey) && !empty($new_pubkey)) {
2510 $ret['pubkey'] = $new_pubkey;
2513 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2514 $ret['uri-date'] = $updated;
2517 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2518 $ret['name-date'] = $updated;
2521 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2522 $ret['last-update'] = $updated;
2523 $ret['success_update'] = $updated;
2526 unset($ret['photo']);
2528 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2530 if (Contact\Relation::isDiscoverable($ret['url'])) {
2531 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2537 private static function updateFromPublicContact(int $id, array $contact)
2539 $public = self::getByURL($contact['url'], false);
2543 foreach ($contact as $field => $value) {
2544 if ($field == 'uid') {
2547 if ($public[$field] != $value) {
2548 $fields[$field] = $public[$field];
2551 if (!empty($fields)) {
2552 self::update($fields, ['id' => $id, 'self' => false]);
2553 Logger::info('Updating local contact', ['id' => $id]);
2558 * @param integer $url contact url
2559 * @return integer Contact id
2560 * @throws HTTPException\InternalServerErrorException
2561 * @throws \ImagickException
2563 public static function updateFromProbeByURL($url)
2565 $id = self::getIdForURL($url);
2571 self::updateFromProbe($id);
2577 * Detects the communication protocol for a given contact url.
2578 * This is used to detect Friendica contacts that we can communicate via AP.
2580 * @param string $url contact url
2581 * @param string $network Network of that contact
2582 * @return string with protocol
2584 public static function getProtocol($url, $network)
2586 if ($network != Protocol::DFRN) {
2590 $apcontact = APContact::getByURL($url);
2591 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2592 return Protocol::ACTIVITYPUB;
2599 * Takes a $uid and a url/handle and adds a new contact
2601 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2602 * dfrn_request page.
2604 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2607 * $return['success'] boolean true if successful
2608 * $return['message'] error text if success is false.
2610 * Takes a $uid and a url/handle and adds a new contact
2612 * @param int $uid The user id the contact should be created for
2613 * @param string $url The profile URL of the contact
2614 * @param string $network
2616 * @throws HTTPException\InternalServerErrorException
2617 * @throws HTTPException\NotFoundException
2618 * @throws \ImagickException
2620 public static function createFromProbeForUser(int $uid, $url, $network = '')
2622 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2624 // remove ajax junk, e.g. Twitter
2625 $url = str_replace('/#!/', '/', $url);
2627 if (!Network::isUrlAllowed($url)) {
2628 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2632 if (Network::isUrlBlocked($url)) {
2633 $result['message'] = DI::l10n()->t('Blocked domain');
2638 $result['message'] = DI::l10n()->t('Connect URL missing.');
2642 $arr = ['url' => $url, 'contact' => []];
2644 Hook::callAll('follow', $arr);
2647 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2651 if (!empty($arr['contact']['name'])) {
2653 $ret = $arr['contact'];
2656 $ret = Probe::uri($url, $network, $uid);
2659 if (($network != '') && ($ret['network'] != $network)) {
2660 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2664 // check if we already have a contact
2665 // the poll url is more reliable than the profile url, as we may have
2666 // indirect links or webfinger links
2668 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2669 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2670 if (!DBA::isResult($contact)) {
2671 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2672 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2675 $protocol = self::getProtocol($ret['url'], $ret['network']);
2677 // This extra param just confuses things, remove it
2678 if ($protocol === Protocol::DIASPORA) {
2679 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2682 // do we have enough information?
2683 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2684 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2685 if (empty($ret['poll'])) {
2686 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2688 if (empty($ret['name'])) {
2689 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2691 if (empty($ret['url'])) {
2692 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2694 if (strpos($ret['url'], '@') !== false) {
2695 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2696 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2701 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2702 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2703 $ret['notify'] = '';
2706 if (!$ret['notify']) {
2707 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2710 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2712 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2714 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2717 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2718 $pending = (bool)$ret['manually-approve'];
2721 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2725 if (DBA::isResult($contact)) {
2727 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2729 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2730 self::update($fields, ['id' => $contact['id']]);
2732 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2734 // create contact record
2737 'created' => DateTimeFormat::utcNow(),
2738 'url' => $ret['url'],
2739 'nurl' => Strings::normaliseLink($ret['url']),
2740 'addr' => $ret['addr'],
2741 'alias' => $ret['alias'],
2742 'batch' => $ret['batch'],
2743 'notify' => $ret['notify'],
2744 'poll' => $ret['poll'],
2745 'poco' => $ret['poco'],
2746 'name' => $ret['name'],
2747 'nick' => $ret['nick'],
2748 'network' => $ret['network'],
2749 'baseurl' => $ret['baseurl'],
2750 'gsid' => $ret['gsid'] ?? null,
2751 'protocol' => $protocol,
2752 'pubkey' => $ret['pubkey'],
2753 'rel' => $new_relation,
2754 'priority'=> $ret['priority'],
2755 'writable'=> $writeable,
2756 'hidden' => $hidden,
2759 'pending' => $pending,
2764 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2765 if (!DBA::isResult($contact)) {
2766 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2770 $contact_id = $contact['id'];
2771 $result['cid'] = $contact_id;
2773 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2775 // Update the avatar
2776 self::updateAvatar($contact_id, $ret['photo']);
2778 // pull feed and consume it, which should subscribe to the hub.
2779 if ($contact['network'] == Protocol::OSTATUS) {
2780 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2784 self::updateFromProbeArray($contact_id, $ret);
2786 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2789 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2795 * @param array $importer Owner (local user) data
2796 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2797 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2798 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2799 * @param string $note Introduction additional message
2800 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2801 * @throws HTTPException\InternalServerErrorException
2802 * @throws \ImagickException
2804 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2806 // Should always be set
2807 if (empty($datarray['author-id'])) {
2811 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2812 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2813 if (!DBA::isResult($pub_contact)) {
2814 // Should never happen
2818 // Contact is blocked at node-level
2819 if (self::isBlocked($datarray['author-id'])) {
2823 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2824 $name = $pub_contact['name'];
2825 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2826 $nick = $pub_contact['nick'];
2827 $network = $pub_contact['network'];
2829 // Ensure that we don't create a new contact when there already is one
2830 $cid = self::getIdForURL($url, $importer['uid']);
2832 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2835 if (!empty($contact)) {
2836 if (!empty($contact['pending'])) {
2837 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2841 // Contact is blocked at user-level
2842 if (!empty($contact['id']) && !empty($importer['id']) &&
2843 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2847 // Make sure that the existing contact isn't archived
2848 self::unmarkForArchival($contact);
2850 if (($contact['rel'] == self::SHARING)
2851 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2852 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2853 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2856 // Ensure to always have the correct network type, independent from the connection request method
2857 self::updateFromProbe($contact['id']);
2859 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2863 // send email notification to owner?
2864 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2865 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
2869 // create contact record
2870 $contact_id = self::insert([
2871 'uid' => $importer['uid'],
2872 'created' => DateTimeFormat::utcNow(),
2874 'nurl' => Strings::normaliseLink($url),
2877 'network' => $network,
2878 'rel' => self::FOLLOWER,
2885 // Ensure to always have the correct network type, independent from the connection request method
2886 self::updateFromProbe($contact_id);
2888 self::updateAvatar($contact_id, $photo, true);
2890 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2892 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2894 /// @TODO Encapsulate this into a function/method
2895 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2896 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2897 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2898 // create notification
2899 if (is_array($contact_record)) {
2900 $intro = DI::introFactory()->createNew(
2902 $contact_record['id'],
2905 DI::intro()->save($intro);
2908 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
2910 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
2911 DI::notify()->createFromArray([
2912 'type' => Notification\Type::INTRO,
2913 'otype' => Notification\ObjectType::INTRO,
2914 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2915 'uid' => $user['uid'],
2916 'cid' => $contact_record['id'],
2917 'link' => DI::baseUrl() . '/notifications/intros',
2920 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2921 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2922 self::createFromProbeForUser($importer['uid'], $url, $network);
2925 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2926 $fields = ['pending' => false];
2927 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2928 $fields['rel'] = self::FRIEND;
2931 self::update($fields, $condition);
2941 * Update the local relationship when a local user loses a follower
2943 * @param array $contact User-specific contact (uid != 0) array
2944 * @throws HTTPException\InternalServerErrorException
2945 * @throws \ImagickException
2947 public static function removeFollower(array $contact)
2949 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
2950 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
2951 } elseif (!empty($contact['id'])) {
2952 self::remove($contact['id']);
2954 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
2958 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
2960 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
2964 * Update the local relationship when a local user unfollow a contact.
2965 * Removes the contact for sharing-only protocols (feed and mail).
2967 * @param array $contact User-specific contact (uid != 0) array
2968 * @throws HTTPException\InternalServerErrorException
2970 public static function removeSharer(array $contact)
2972 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2973 self::remove($contact['id']);
2975 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2980 * Create a birthday event.
2982 * Update the year and the birthday.
2984 public static function updateBirthdays()
2988 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2989 AND NOT `contact`.`pending`
2990 AND NOT `contact`.`hidden`
2991 AND NOT `contact`.`blocked`
2992 AND NOT `contact`.`archive`
2993 AND NOT `contact`.`deleted`',
2999 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3001 while ($contact = DBA::fetch($contacts)) {
3002 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3004 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3006 if (Event::createBirthday($contact, $nextbd)) {
3010 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3011 ['id' => $contact['id']]
3015 DBA::close($contacts);
3019 * Remove the unavailable contact ids from the provided list
3021 * @param array $contact_ids Contact id list
3023 * @throws \Exception
3025 public static function pruneUnavailable(array $contact_ids)
3027 if (empty($contact_ids)) {
3031 $contacts = self::selectToArray(['id'], [
3032 'id' => $contact_ids,
3038 return array_column($contacts, 'id');
3042 * Returns a magic link to authenticate remote visitors
3044 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3046 * @param string $contact_url The address of the target contact profile
3047 * @param string $url An url that we will be redirected to after the authentication
3049 * @return string with "redir" link
3050 * @throws HTTPException\InternalServerErrorException
3051 * @throws \ImagickException
3053 public static function magicLink($contact_url, $url = '')
3055 if (!Session::isAuthenticated()) {
3056 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3059 $contact = self::getByURL($contact_url, false);
3060 if (empty($contact)) {
3061 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3064 // Prevents endless loop in case only a non-public contact exists for the contact URL
3065 unset($contact['uid']);
3067 return self::magicLinkByContact($contact, $url ?: $contact_url);
3071 * Returns a magic link to authenticate remote visitors
3073 * @param integer $cid The contact id of the target contact profile
3074 * @param string $url An url that we will be redirected to after the authentication
3076 * @return string with "redir" link
3077 * @throws HTTPException\InternalServerErrorException
3078 * @throws \ImagickException
3080 public static function magicLinkById($cid, $url = '')
3082 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3084 return self::magicLinkByContact($contact, $url);
3088 * Returns a magic link to authenticate remote visitors
3090 * @param array $contact The contact array with "uid", "network" and "url"
3091 * @param string $url An url that we will be redirected to after the authentication
3093 * @return string with "redir" link
3094 * @throws HTTPException\InternalServerErrorException
3095 * @throws \ImagickException
3097 public static function magicLinkByContact($contact, $url = '')
3099 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3101 if (!Session::isAuthenticated()) {
3102 return $destination;
3105 // Only redirections to the same host do make sense
3106 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3110 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
3111 return 'contact/' . $contact['id'] . '/conversations';
3114 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3115 return $destination;
3118 if (empty($contact['id'])) {
3119 return $destination;
3122 $redirect = 'redir/' . $contact['id'];
3124 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3125 $redirect .= '?url=' . $url;
3132 * Is the contact a forum?
3134 * @param integer $contactid ID of the contact
3136 * @return boolean "true" if it is a forum
3138 public static function isForum($contactid)
3140 $fields = ['contact-type'];
3141 $condition = ['id' => $contactid];
3142 $contact = DBA::selectFirst('contact', $fields, $condition);
3143 if (!DBA::isResult($contact)) {
3148 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3152 * Can the remote contact receive private messages?
3154 * @param array $contact
3157 public static function canReceivePrivateMessages(array $contact)
3159 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3160 $self = $contact['self'] ?? false;
3162 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3166 * Search contact table by nick or name
3168 * @param string $search Name or nick
3169 * @param string $mode Search mode (e.g. "community")
3170 * @param int $uid User ID
3172 * @return array with search results
3173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3175 public static function searchByName(string $search, string $mode = '', int $uid = 0)
3177 if (empty($search)) {
3181 // check supported networks
3182 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3183 if (DI::config()->get('system', 'diaspora_enabled')) {
3184 $networks[] = Protocol::DIASPORA;
3187 if (!DI::config()->get('system', 'ostatus_disabled')) {
3188 $networks[] = Protocol::OSTATUS;
3191 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3194 $condition['blocked'] = false;
3197 // check if we search only communities or every contact
3198 if ($mode === 'community') {
3199 $condition['contact-type'] = self::TYPE_COMMUNITY;
3204 $condition = DBA::mergeConditions($condition,
3205 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3206 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3208 $contacts = self::selectToArray([], $condition);
3213 * Add public contacts from an array
3215 * @param array $urls
3216 * @return array result "count", "added" and "updated"
3218 public static function addByUrls(array $urls)
3225 foreach ($urls as $url) {
3226 if (empty($url) || !is_string($url)) {
3229 $contact = self::getByURL($url, false, ['id', 'updated']);
3230 if (empty($contact['id'])) {
3231 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3233 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3234 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3242 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3246 * Returns a random, global contact array of the current node
3248 * @return array The profile array
3251 public static function getRandomContact()
3253 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3254 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3255 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3256 ], ['order' => ['RAND()']]);
3258 if (DBA::isResult($contact)) {