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\Contact\Avatar;
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\HTTPException;
39 use Friendica\Network\Probe;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\Images;
44 use Friendica\Util\Network;
45 use Friendica\Util\Proxy;
46 use Friendica\Util\Strings;
49 * functions for interacting with a contact
53 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
54 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
55 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
61 const LOCK_INSERT = 'contact-insert';
66 * TYPE_UNKNOWN - unknown type
68 * TYPE_PERSON - the account belongs to a person
69 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
71 * TYPE_ORGANISATION - the account belongs to an organisation
72 * Associated page type: PAGE_SOAPBOX
74 * TYPE_NEWS - the account is a news reflector
75 * Associated page type: PAGE_SOAPBOX
77 * TYPE_COMMUNITY - the account is community forum
78 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
80 * TYPE_RELAY - the account is a relay
81 * This will only be assigned to contacts, not to user accounts
84 const TYPE_UNKNOWN = -1;
85 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
86 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
87 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
88 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
89 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
109 const MIRROR_DEACTIVATED = 0;
110 const MIRROR_FORWARDED = 1;
111 const MIRROR_OWN_POST = 2;
112 const MIRROR_NATIVE_RESHARE = 3;
115 * @param array $fields Array of selected fields, empty for all
116 * @param array $condition Array of fields for condition
117 * @param array $params Array of several parameters
121 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
123 return DBA::selectToArray('contact', $fields, $condition, $params);
127 * @param array $fields Array of selected fields, empty for all
128 * @param array $condition Array of fields for condition
129 * @param array $params Array of several parameters
133 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
135 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
141 * @param array $fields Array of selected fields, empty for all
142 * @param array $condition Array of fields for condition
143 * @param array $params Array of several parameters
147 public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
149 return DBA::selectFirst('account-view', $fields, $condition, $params);
153 * Insert a row into the contact table
154 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
156 * @param array $fields field array
157 * @param int $duplicate_mode Do an update on a duplicate entry
159 * @return int id of the created contact
162 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
164 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
165 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
168 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
170 if (empty($fields['created'])) {
171 $fields['created'] = DateTimeFormat::utcNow();
174 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
175 DBA::insert('contact', $fields, $duplicate_mode);
176 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
177 if (!DBA::isResult($contact)) {
179 Logger::warning('Created contact could not be found', ['fields' => $fields]);
183 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
184 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
185 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
186 if (empty($account_user['id'])) {
187 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
188 } elseif ($account_user['id'] != $contact['id']) {
189 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
190 if (!empty($duplicate['id'])) {
191 $ret = Contact::deleteById($contact['id']);
192 Logger::notice('Deleted duplicated contact', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $duplicate['id'], 'uid' => $duplicate['uid'], 'uri-id' => $duplicate['uri-id'], 'url' => $duplicate['url']]);
193 $contact = $duplicate;
195 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
196 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
200 Contact\User::insertForContactArray($contact);
202 return $contact['id'];
206 * Delete contact by id
211 public static function deleteById(int $id): bool
213 Logger::debug('Delete contact', ['id' => $id]);
214 DBA::delete('account-user', ['id' => $id]);
215 return DBA::delete('contact', ['id' => $id]);
219 * Updates rows in the contact table
221 * @param array $fields contains the fields that are updated
222 * @param array $condition condition array with the key values
223 * @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)
225 * @return boolean was the update successfull?
227 * @todo Let's get rid of boolean type of $old_fields
229 public static function update(array $fields, array $condition, $old_fields = [])
231 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
232 $ret = DBA::update('contact', $fields, $condition, $old_fields);
234 // Apply changes to the "user-contact" table on dedicated fields
235 Contact\User::updateByContactUpdate($fields, $condition);
241 * @param integer $id Contact ID
242 * @param array $fields Array of selected fields, empty for all
243 * @return array|boolean Contact record if it exists, false otherwise
246 public static function getById(int $id, array $fields = [])
248 return DBA::selectFirst('contact', $fields, ['id' => $id]);
252 * Fetch the first contact with the provided uri-id.
254 * @param integer $uri_id uri-id of the contact
255 * @param array $fields Array of selected fields, empty for all
256 * @return array|boolean Contact record if it exists, false otherwise
259 public static function getByUriId(int $uri_id, array $fields = [])
261 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
265 * Fetches a contact by a given url
267 * @param string $url profile url
268 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
269 * @param array $fields Field list
270 * @param integer $uid User ID of the contact
271 * @return array contact array
273 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
275 if ($update || is_null($update)) {
276 $cid = self::getIdForURL($url, $uid, $update);
281 $contact = self::getById($cid, $fields);
282 if (empty($contact)) {
288 // Add internal fields
290 if (!empty($fields)) {
291 foreach (['id', 'next-update', 'network'] as $internal) {
292 if (!in_array($internal, $fields)) {
293 $fields[] = $internal;
294 $removal[] = $internal;
299 // We first try the nurl (http://server.tld/nick), most common case
300 $options = ['order' => ['id']];
301 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
303 // Then the addr (nick@server.tld)
304 if (!DBA::isResult($contact)) {
305 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
308 // Then the alias (which could be anything)
309 if (!DBA::isResult($contact)) {
310 // The link could be provided as http although we stored it as https
311 $ssl_url = str_replace('http://', 'https://', $url);
312 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
313 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
316 if (!DBA::isResult($contact)) {
320 // Update the contact in the background if needed
321 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
322 Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
325 // Remove the internal fields
326 foreach ($removal as $internal) {
327 unset($contact[$internal]);
334 * Fetches a contact for a given user by a given url.
335 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
337 * @param string $url profile url
338 * @param integer $uid User ID of the contact
339 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
340 * @param array $fields Field list
341 * @return array contact array
343 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
346 $contact = self::getByURL($url, $update, $fields, $uid);
347 if (!empty($contact)) {
348 if (!empty($contact['id'])) {
349 $contact['cid'] = $contact['id'];
356 $contact = self::getByURL($url, $update, $fields);
357 if (!empty($contact['id'])) {
359 $contact['zid'] = $contact['id'];
365 * Checks if a contact uses a specific platform
368 * @param string $platform
371 public static function isPlatform(string $url, string $platform): bool
373 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
377 * Tests if the given contact is a follower
379 * @param int $cid Either public contact id or user's contact id
380 * @param int $uid User ID
381 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
383 * @return boolean is the contact id a follower?
384 * @throws HTTPException\InternalServerErrorException
385 * @throws \ImagickException
387 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
389 if (Contact\User::isBlocked($cid, $uid)) {
393 $cdata = self::getPublicAndUserContactID($cid, $uid);
394 if (empty($cdata['user'])) {
398 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
400 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
402 return DBA::exists('contact', $condition);
406 * Tests if the given contact url is a follower
408 * @param string $url Contact URL
409 * @param int $uid User ID
410 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
412 * @return boolean is the contact id a follower?
413 * @throws HTTPException\InternalServerErrorException
414 * @throws \ImagickException
416 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
418 $cid = self::getIdForURL($url, $uid);
424 return self::isFollower($cid, $uid, $strict);
428 * Tests if the given user shares with the given contact
430 * @param int $cid Either public contact id or user's contact id
431 * @param int $uid User ID
432 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
434 * @return boolean is the contact sharing with given user?
435 * @throws HTTPException\InternalServerErrorException
436 * @throws \ImagickException
438 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
440 if (Contact\User::isBlocked($cid, $uid)) {
444 $cdata = self::getPublicAndUserContactID($cid, $uid);
445 if (empty($cdata['user'])) {
449 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
451 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
453 return DBA::exists('contact', $condition);
457 * Tests if the given user follow the given contact url
459 * @param string $url Contact URL
460 * @param int $uid User ID
461 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
463 * @return boolean is the contact url being followed?
464 * @throws HTTPException\InternalServerErrorException
465 * @throws \ImagickException
467 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
469 $cid = self::getIdForURL($url, $uid);
475 return self::isSharing($cid, $uid, $strict);
479 * Get the basepath for a given contact link
481 * @param string $url The contact link
482 * @param boolean $dont_update Don't update the contact
484 * @return string basepath
485 * @throws HTTPException\InternalServerErrorException
486 * @throws \ImagickException
488 public static function getBasepath(string $url, bool $dont_update = false): string
490 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
491 if (!DBA::isResult($contact)) {
495 if (!empty($contact['baseurl'])) {
496 return $contact['baseurl'];
497 } elseif ($dont_update) {
501 // Update the existing contact
502 self::updateFromProbe($contact['id']);
504 // And fetch the result
505 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
506 if (empty($contact['baseurl'])) {
507 Logger::info('No baseurl for contact', ['url' => $url]);
511 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
512 return $contact['baseurl'];
516 * Check if the given contact url is on the same server
518 * @param string $url The contact link
520 * @return boolean Is it the same server?
522 public static function isLocal(string $url): bool
524 if (!parse_url($url, PHP_URL_SCHEME)) {
525 $addr_parts = explode('@', $url);
526 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
529 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
533 * Check if the given contact ID is on the same server
535 * @param string $url The contact link
536 * @return boolean Is it the same server?
538 public static function isLocalById(int $cid): bool
540 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
541 if (!DBA::isResult($contact)) {
545 if (empty($contact['baseurl'])) {
546 $baseurl = self::getBasepath($contact['url'], true);
548 $baseurl = $contact['baseurl'];
551 return Strings::compareLink($baseurl, DI::baseUrl());
555 * Returns the public contact id of the given user id
557 * @param integer $uid User ID
559 * @return integer|boolean Public contact id for given user id
562 public static function getPublicIdByUserId(int $uid)
564 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
565 if (!DBA::isResult($self)) {
568 return self::getIdForURL($self['url']);
572 * Returns the contact id for the user and the public contact id for a given contact id
574 * @param int $cid Either public contact id or user's contact id
575 * @param int $uid User ID
577 * @return array with public and user's contact id
578 * @throws HTTPException\InternalServerErrorException
579 * @throws \ImagickException
581 public static function getPublicAndUserContactID(int $cid, int $uid): array
583 // We have to use the legacy function as long as the post update hasn't finished
584 if (DI::config()->get('system', 'post_update_version') < 1427) {
585 return self::legacyGetPublicAndUserContactID($cid, $uid);
588 if (empty($uid) || empty($cid)) {
592 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
593 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
597 $pcid = $contact['pid'];
598 if ($contact['uid'] == $uid) {
599 $ucid = $contact['id'];
601 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
602 if (DBA::isResult($contact)) {
603 $ucid = $contact['id'];
609 return ['public' => $pcid, 'user' => $ucid];
613 * Helper function for "getPublicAndUserContactID"
615 * @param int $cid Either public contact id or user's contact id
616 * @param int $uid User ID
617 * @return array with public and user's contact id
618 * @throws HTTPException\InternalServerErrorException
619 * @throws \ImagickException
621 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
623 if (empty($uid) || empty($cid)) {
627 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
628 if (!DBA::isResult($contact)) {
632 // We quit when the user id don't match the user id of the provided contact
633 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
637 if ($contact['uid'] != 0) {
638 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
642 $ucid = $contact['id'];
644 $pcid = $contact['id'];
645 $ucid = self::getIdForURL($contact['url'], $uid);
648 return ['public' => $pcid, 'user' => $ucid];
652 * Returns contact details for a given contact id in combination with a user id
654 * @param int $cid A contact ID
655 * @param int $uid The User ID
656 * @param array $fields The selected fields for the contact
657 * @return array The contact details
661 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
663 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
665 if (!DBA::isResult($contact)) {
673 * Creates the self-contact for the provided user id
676 * @return bool Operation success
677 * @throws HTTPException\InternalServerErrorException
679 public static function createSelfFromUserId(int $uid): bool
681 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
682 ['uid' => $uid, 'account_expired' => false]);
683 if (!DBA::isResult($user)) {
688 'uid' => $user['uid'],
689 'created' => DateTimeFormat::utcNow(),
691 'name' => $user['username'],
692 'nick' => $user['nickname'],
693 'pubkey' => $user['pubkey'],
694 'prvkey' => $user['prvkey'],
695 'photo' => User::getAvatarUrl($user),
696 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
697 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
700 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
701 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
702 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
703 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
704 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
705 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
706 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
707 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
708 'name-date' => DateTimeFormat::utcNow(),
709 'uri-date' => DateTimeFormat::utcNow(),
710 'avatar-date' => DateTimeFormat::utcNow(),
716 // Only create the entry if it doesn't exist yet
717 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
718 $return = (bool)self::insert($contact);
721 // Create the public contact
722 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
723 $contact['self'] = false;
725 $contact['prvkey'] = null;
727 self::insert($contact, Database::INSERT_IGNORE);
734 * Updates the self-contact for the provided user id
737 * @param bool $update_avatar Force the avatar update
738 * @return bool "true" if updated
739 * @throws HTTPException\InternalServerErrorException
741 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
743 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
744 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
745 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
746 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
747 if (!DBA::isResult($self)) {
751 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
752 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
753 if (!DBA::isResult($user)) {
757 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
758 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
759 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
760 if (!DBA::isResult($profile)) {
764 $file_suffix = 'jpg';
765 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
768 'name' => $profile['name'],
769 'nick' => $user['nickname'],
770 'avatar-date' => $self['avatar-date'],
771 'location' => Profile::formatLocation($profile),
772 'about' => $profile['about'],
773 'keywords' => $profile['pub_keywords'],
774 'contact-type' => $user['account-type'],
775 'prvkey' => $user['prvkey'],
776 'pubkey' => $user['pubkey'],
777 'xmpp' => $profile['xmpp'],
778 'matrix' => $profile['matrix'],
779 'network' => Protocol::DFRN,
781 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
782 'nurl' => Strings::normaliseLink($url),
783 'uri-id' => ItemURI::getIdByURI($url),
784 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
785 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
786 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
787 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
788 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
789 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
793 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
794 if (DBA::isResult($avatar)) {
795 if ($update_avatar) {
796 $fields['avatar-date'] = DateTimeFormat::utcNow();
799 // Creating the path to the avatar, beginning with the file suffix
800 $types = Images::supportedTypes();
801 if (isset($types[$avatar['type']])) {
802 $file_suffix = $types[$avatar['type']];
805 // We are adding a timestamp value so that other systems won't use cached content
806 $timestamp = strtotime($fields['avatar-date']);
808 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
809 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
811 $fields['photo'] = $prefix . '4' . $suffix;
812 $fields['thumb'] = $prefix . '5' . $suffix;
813 $fields['micro'] = $prefix . '6' . $suffix;
815 // We hadn't found a photo entry, so we use the default avatar
816 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
817 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
818 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
821 $fields['avatar'] = User::getAvatarUrl($user);
822 $fields['header'] = User::getBannerUrl($user);
823 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
824 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
825 $fields['unsearchable'] = !$profile['net-publish'];
826 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
830 foreach ($fields as $field => $content) {
831 if ($self[$field] != $content) {
837 if ($fields['name'] != $self['name']) {
838 $fields['name-date'] = DateTimeFormat::utcNow();
840 $fields['updated'] = DateTimeFormat::utcNow();
841 self::update($fields, ['id' => $self['id']]);
843 // Update the other contacts as well
844 unset($fields['prvkey']);
845 $fields['self'] = false;
846 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
848 // Update the profile
850 'photo' => User::getAvatarUrl($user),
851 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
854 DBA::update('profile', $fields, ['uid' => $uid]);
861 * Marks a contact for removal
863 * @param int $id contact id
865 * @throws HTTPException\InternalServerErrorException
867 public static function remove(int $id)
869 // We want just to make sure that we don't delete our "self" contact
870 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
871 if (!DBA::isResult($contact)) {
875 DBA::delete('account-user', ['id' => $id]);
877 self::clearFollowerFollowingEndpointCache($contact['uid']);
879 // Archive the contact
880 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
882 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
883 Avatar::deleteCache($contact);
886 // Delete it in the background
887 Worker::add(PRIORITY_MEDIUM, 'Contact\Remove', $id);
891 * Unfollow the remote contact
893 * @param array $contact Target user-specific contact (uid != 0) array
895 * @throws HTTPException\InternalServerErrorException
896 * @throws \ImagickException
898 public static function unfollow(array $contact): void
900 if (empty($contact['network'])) {
901 throw new \InvalidArgumentException('Empty network in contact array');
904 if (empty($contact['uid'])) {
905 throw new \InvalidArgumentException('Unexpected public contact record');
908 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
909 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
910 if (!empty($cdata['public'])) {
911 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
915 self::removeSharer($contact);
919 * Revoke follow privileges of the remote user contact
921 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
923 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
925 * @throws HTTPException\InternalServerErrorException
926 * @throws \ImagickException
928 public static function revokeFollow(array $contact): void
930 if (empty($contact['network'])) {
931 throw new \InvalidArgumentException('Empty network in contact array');
934 if (empty($contact['uid'])) {
935 throw new \InvalidArgumentException('Unexpected public contact record');
938 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
939 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
940 if (!empty($cdata['public'])) {
941 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
945 self::removeFollower($contact);
949 * Completely severs a relationship with a contact
951 * @param array $contact User-specific contact (uid != 0) array
953 * @throws HTTPException\InternalServerErrorException
954 * @throws \ImagickException
956 public static function terminateFriendship(array $contact)
958 if (empty($contact['network'])) {
959 throw new \InvalidArgumentException('Empty network in contact array');
962 if (empty($contact['uid'])) {
963 throw new \InvalidArgumentException('Unexpected public contact record');
966 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
968 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
969 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
972 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
973 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
976 self::remove($contact['id']);
979 private static function clearFollowerFollowingEndpointCache(int $uid)
985 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
986 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
990 * Marks a contact for archival after a communication issue delay
992 * Contact has refused to recognise us as a friend. We will start a countdown.
993 * If they still don't recognise us in 32 days, the relationship is over,
994 * and we won't waste any more time trying to communicate with them.
995 * This provides for the possibility that their database is temporarily messed
996 * up or some other transient event and that there's a possibility we could recover from it.
998 * @param array $contact contact to mark for archival
1000 * @throws HTTPException\InternalServerErrorException
1002 public static function markForArchival(array $contact)
1004 if (!isset($contact['url']) && !empty($contact['id'])) {
1005 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1006 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1007 if (!DBA::isResult($contact)) {
1010 } elseif (!isset($contact['url'])) {
1011 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1014 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1016 // Contact already archived or "self" contact? => nothing to do
1017 if ($contact['archive'] || $contact['self']) {
1021 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1022 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1023 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1026 * We really should send a notification to the owner after 2-3 weeks
1027 * so they won't be surprised when the contact vanishes and can take
1028 * remedial action if this was a serious mistake or glitch
1031 /// @todo Check for contact vitality via probing
1032 $archival_days = DI::config()->get('system', 'archival_days', 32);
1034 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1035 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1036 /* Relationship is really truly dead. archive them rather than
1037 * delete, though if the owner tries to unarchive them we'll start
1038 * the whole process over again.
1040 self::update(['archive' => true], ['id' => $contact['id']]);
1041 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1047 * Cancels the archival countdown
1049 * @see Contact::markForArchival()
1051 * @param array $contact contact to be unmarked for archival
1053 * @throws \Exception
1055 public static function unmarkForArchival(array $contact)
1057 // Always unarchive the relay contact entry
1058 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1059 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1060 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1061 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1062 self::update($fields, $condition);
1066 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1067 $exists = DBA::exists('contact', $condition);
1069 // We don't need to update, we never marked this contact for archival
1074 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1076 if (!isset($contact['url']) && !empty($contact['id'])) {
1077 $fields = ['id', 'url', 'batch'];
1078 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1079 if (!DBA::isResult($contact)) {
1084 // It's a miracle. Our dead contact has inexplicably come back to life.
1085 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1086 self::update($fields, ['id' => $contact['id']]);
1087 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1091 * Returns the data array for the photo menu of a given contact
1093 * @param array $contact contact
1094 * @param int $uid optional, default 0
1096 * @throws HTTPException\InternalServerErrorException
1097 * @throws \ImagickException
1099 public static function photoMenu(array $contact, int $uid = 0): array
1106 $uid = local_user();
1109 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1111 $profile_link = self::magicLinkByContact($contact);
1112 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1117 // Look for our own contact if the uid doesn't match and isn't public
1118 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1119 if (DBA::isResult($contact_own)) {
1120 return self::photoMenu($contact_own, $uid);
1125 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1127 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1129 $profile_link = $contact['url'];
1132 if ($profile_link === 'mailbox') {
1137 $status_link = $profile_link . '/status';
1138 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1139 $profile_link = $profile_link . '/profile';
1142 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1143 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1146 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1148 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1151 $unfollow_link = '';
1152 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1153 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1154 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1155 } elseif(!$contact['pending']) {
1156 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1162 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1164 if (empty($contact['uid'])) {
1166 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1167 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1168 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1169 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1170 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1174 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1175 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1176 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1177 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1178 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1179 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1180 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1181 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1184 if (!empty($contact['pending'])) {
1186 $intro = DI::intro()->selectForContact($contact['id']);
1187 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1188 } catch (IntroductionNotFoundException $exception) {
1189 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1194 $args = ['contact' => $contact, 'menu' => &$menu];
1196 Hook::callAll('contact_photo_menu', $args);
1198 $menucondensed = [];
1200 foreach ($menu as $menuname => $menuitem) {
1201 if ($menuitem[1] != '') {
1202 $menucondensed[$menuname] = $menuitem;
1206 return $menucondensed;
1210 * Fetch the contact id for a given URL and user
1212 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1213 * `addr` or `alias`.
1215 * If there's no record and we aren't looking for a public contact, we quit.
1216 * If there's one, we check that it isn't time to update the picture else we
1217 * directly return the found contact id.
1219 * Second, we probe the provided $url whether it's http://server.tld/profile or
1220 * nick@server.tld. We quit if we can't get any info back.
1222 * Third, we create the contact record if it doesn't exist
1224 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1225 * if there's any updates
1227 * @param string $url Contact URL
1228 * @param integer $uid The user id for the contact (0 = public contact)
1229 * @param boolean $update true = always update, false = never update, null = update when not found
1230 * @param array $default Default value for creating the contact when everything else fails
1232 * @return integer Contact ID
1233 * @throws HTTPException\InternalServerErrorException
1234 * @throws \ImagickException
1236 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1241 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1245 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
1247 if (!empty($contact)) {
1248 $contact_id = $contact['id'];
1250 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1251 Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
1254 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1255 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1258 } elseif ($uid != 0) {
1259 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1261 } elseif (empty($default) && !is_null($update) && !$update) {
1262 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1268 if (empty($default['network']) || $update) {
1269 $data = Probe::uri($url, '', $uid);
1271 // Take the default values when probing failed
1272 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1273 $data = array_merge($data, $default);
1275 } elseif (!empty($default['network'])) {
1279 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1280 // Fetch data for the public contact via the first found personal contact
1281 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1282 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1283 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1284 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1286 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1287 if (!DBA::isResult($personal_contact)) {
1288 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1291 if (DBA::isResult($personal_contact)) {
1292 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1293 $data = $personal_contact;
1294 $data['photo'] = $personal_contact['avatar'];
1295 $data['account-type'] = $personal_contact['contact-type'];
1296 $data['hide'] = $personal_contact['unsearchable'];
1297 unset($data['avatar']);
1298 unset($data['contact-type']);
1299 unset($data['unsearchable']);
1303 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1304 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1308 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1309 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1314 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1315 if (!empty($data['alias'])) {
1316 $urls[] = Strings::normaliseLink($data['alias']);
1318 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1319 if (!empty($contact['id'])) {
1320 $contact_id = $contact['id'];
1321 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1326 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1329 'url' => $data['url'],
1330 'nurl' => Strings::normaliseLink($data['url']),
1331 'network' => $data['network'],
1332 'created' => DateTimeFormat::utcNow(),
1333 'rel' => self::SHARING,
1339 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1341 // Before inserting we do check if the entry does exist now.
1342 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1343 if (DBA::isResult($contact)) {
1344 $contact_id = $contact['id'];
1345 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1347 $contact_id = self::insert($fields);
1349 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1354 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1358 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1361 if ($data['network'] == Protocol::DIASPORA) {
1362 FContact::updateFromProbeArray($data);
1365 self::updateFromProbeArray($contact_id, $data);
1367 // Don't return a number for a deleted account
1368 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1369 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1377 * Checks if the contact is archived
1379 * @param int $cid contact id
1381 * @return boolean Is the contact archived?
1382 * @throws HTTPException\InternalServerErrorException
1384 public static function isArchived(int $cid): bool
1390 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1391 if (!DBA::isResult($contact)) {
1395 if ($contact['archive']) {
1399 // Check status of ActivityPub endpoints
1400 $apcontact = APContact::getByURL($contact['url'], false);
1401 if (!empty($apcontact)) {
1402 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1406 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1411 // Check status of Diaspora endpoints
1412 if (!empty($contact['batch'])) {
1413 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1414 return DBA::exists('contact', $condition);
1421 * Checks if the contact is blocked
1423 * @param int $cid contact id
1424 * @return boolean Is the contact blocked?
1425 * @throws HTTPException\InternalServerErrorException
1427 public static function isBlocked(int $cid): bool
1433 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1434 if (!DBA::isResult($blocked)) {
1438 if (Network::isUrlBlocked($blocked['url'])) {
1442 return (bool) $blocked['blocked'];
1446 * Checks if the contact is hidden
1448 * @param int $cid contact id
1449 * @return boolean Is the contact hidden?
1450 * @throws \Exception
1452 public static function isHidden(int $cid): bool
1458 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1459 if (!DBA::isResult($hidden)) {
1462 return (bool) $hidden['hidden'];
1466 * Returns posts from a given contact url
1468 * @param string $contact_url Contact URL
1469 * @param bool $thread_mode
1470 * @param int $update Update mode
1471 * @param int $parent Item parent ID for the update mode
1472 * @param bool $only_media Only display media content
1473 * @return string posts in HTML
1474 * @throws \Exception
1476 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1478 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1482 * Returns posts from a given contact id
1484 * @param int $cid Contact ID
1485 * @param bool $thread_mode
1486 * @param int $update Update mode
1487 * @param int $parent Item parent ID for the update mode
1488 * @param bool $only_media Only display media content
1489 * @return string posts in HTML
1490 * @throws \Exception
1492 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1494 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1495 if (!DBA::isResult($contact)) {
1499 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1500 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1505 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1508 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1509 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1511 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1512 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1515 if (!empty($parent)) {
1516 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1518 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1519 if (!empty($last_received)) {
1520 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1525 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1526 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1529 if (DI::mode()->isMobile()) {
1530 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1531 DI::config()->get('system', 'itemspage_network_mobile'));
1533 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1534 DI::config()->get('system', 'itemspage_network'));
1537 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1539 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1541 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1542 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1543 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1549 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1550 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1552 if ($pager->getStart() == 0) {
1553 $cdata = self::getPublicAndUserContactID($cid, local_user());
1554 if (!empty($cdata['public'])) {
1555 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1556 $items = array_merge($items, $pinned);
1560 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', local_user());
1562 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1563 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1565 if ($pager->getStart() == 0) {
1566 $cdata = self::getPublicAndUserContactID($cid, local_user());
1567 if (!empty($cdata['public'])) {
1568 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1569 $cdata['public'], Post\Collection::FEATURED];
1570 $pinned = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1571 $items = array_merge($pinned, $items);
1575 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1579 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1580 $o .= HTML::scrollLoader();
1582 $o .= $pager->renderMinimal(count($items));
1590 * Returns the account type name
1592 * The function can be called with either the user or the contact array
1594 * @param int $type type of contact or account
1597 public static function getAccountType(int $type): string
1600 case self::TYPE_ORGANISATION:
1601 $account_type = DI::l10n()->t("Organisation");
1604 case self::TYPE_NEWS:
1605 $account_type = DI::l10n()->t('News');
1608 case self::TYPE_COMMUNITY:
1609 $account_type = DI::l10n()->t("Forum");
1617 return $account_type;
1623 * @param int $cid Contact id to block
1624 * @param string $reason Block reason
1625 * @return bool Whether it was successful
1627 public static function block(int $cid, string $reason = null): bool
1629 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1635 * Unblocks a contact
1637 * @param int $cid Contact id to unblock
1638 * @return bool Whether it was successfull
1640 public static function unblock(int $cid): bool
1642 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1648 * Ensure that cached avatar exist
1650 * @param integer $cid Contact id
1652 public static function checkAvatarCache(int $cid)
1654 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1655 if (!DBA::isResult($contact)) {
1659 if (Network::isLocalLink($contact['url'])) {
1663 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1664 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1665 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1666 self::updateAvatar($cid, $contact['avatar'], true);
1669 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1670 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1671 self::updateAvatar($cid, $contact['avatar'], true);
1673 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1674 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1675 self::updateAvatar($cid, $contact['avatar'], true);
1681 * Return the photo path for a given contact array in the given size
1683 * @param array $contact contact array
1684 * @param string $field Fieldname of the photo in the contact array
1685 * @param string $size Size of the avatar picture
1686 * @param string $avatar Avatar path that is displayed when no photo had been found
1687 * @param bool $no_update Don't perfom an update if no cached avatar was found
1688 * @return string photo path
1690 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1692 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1694 if (DI::config()->get('system', 'avatar_cache')) {
1696 case Proxy::SIZE_MICRO:
1697 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1698 return $contact['micro'];
1701 case Proxy::SIZE_THUMB:
1702 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1703 return $contact['thumb'];
1706 case Proxy::SIZE_SMALL:
1707 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1708 return $contact['photo'];
1714 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1718 * Return the photo path for a given contact array
1720 * @param array $contact Contact array
1721 * @param bool $no_update Don't perfom an update if no cached avatar was found
1722 * @return string photo path
1724 public static function getPhoto(array $contact, bool $no_update = false): string
1726 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1730 * Return the photo path (thumb size) for a given contact array
1732 * @param array $contact Contact array
1733 * @param bool $no_update Don't perfom an update if no cached avatar was found
1734 * @return string photo path
1736 public static function getThumb(array $contact, bool $no_update = false): string
1738 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1742 * Return the photo path (micro size) for a given contact array
1744 * @param array $contact Contact array
1745 * @param bool $no_update Don't perfom an update if no cached avatar was found
1746 * @return string photo path
1748 public static function getMicro(array $contact, bool $no_update = false): string
1750 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1754 * Check the given contact array for avatar cache fields
1756 * @param array $contact
1757 * @param bool $no_update Don't perfom an update if no cached avatar was found
1758 * @return array contact array with avatar cache fields
1760 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1763 $contact_fields = [];
1764 $fields = ['photo', 'thumb', 'micro'];
1765 foreach ($fields as $field) {
1766 if (isset($contact[$field])) {
1767 $contact_fields[] = $field;
1769 if (isset($contact[$field]) && empty($contact[$field])) {
1774 if (!$update || $no_update) {
1778 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1780 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1781 self::updateAvatar($contact['id'], $contact['avatar'], true);
1783 $new_contact = self::getById($contact['id'], $contact_fields);
1784 if (DBA::isResult($new_contact)) {
1785 // We only update the cache fields
1786 $contact = array_merge($contact, $new_contact);
1788 } elseif ($local && !empty($contact['avatar'])) {
1792 /// add the default avatars if the fields aren't filled
1793 if (isset($contact['photo']) && empty($contact['photo'])) {
1794 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1796 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1797 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1799 if (isset($contact['micro']) && empty($contact['micro'])) {
1800 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1807 * Fetch the default header for the given contact
1809 * @param array $contact contact array
1810 * @return string avatar URL
1812 public static function getDefaultHeader(array $contact): string
1814 if (!empty($contact['header'])) {
1815 return $contact['header'];
1818 if (!empty($contact['gsid'])) {
1819 // Use default banners for certain platforms
1820 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1821 $platform = strtolower($gserver['platform'] ?? '');
1826 switch ($platform) {
1831 * @author Lostinlight <https://mastodon.xyz/@lightone>
1832 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1833 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1835 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1840 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1841 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1842 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1844 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1848 * Use a random picture.
1849 * The service provides random pictures from Unsplash.
1850 * @license https://unsplash.com/license
1852 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1860 * Fetch the default avatar for the given contact and size
1862 * @param array $contact contact array
1863 * @param string $size Size of the avatar picture
1864 * @return string avatar URL
1866 public static function getDefaultAvatar(array $contact, string $size): string
1869 case Proxy::SIZE_MICRO:
1870 $avatar['size'] = 48;
1871 $default = self::DEFAULT_AVATAR_MICRO;
1874 case Proxy::SIZE_THUMB:
1875 $avatar['size'] = 80;
1876 $default = self::DEFAULT_AVATAR_THUMB;
1879 case Proxy::SIZE_SMALL:
1881 $avatar['size'] = 300;
1882 $default = self::DEFAULT_AVATAR_PHOTO;
1886 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1888 $type = Contact::TYPE_PERSON;
1890 if (!empty($contact['id'])) {
1891 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1892 $platform = $account['platform'] ?? '';
1893 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1896 if (empty($platform) && !empty($contact['uri-id'])) {
1897 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1898 $platform = $account['platform'] ?? '';
1899 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1902 switch ($platform) {
1906 * @license GNU Affero General Public License v3.0
1907 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1909 $default = '/images/default/corgidon.png';
1915 * @license GNU Affero General Public License v3.0
1916 * @link https://github.com/diaspora/diaspora/
1918 $default = '/images/default/diaspora.png';
1924 * @license GNU Affero General Public License v3.0
1925 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1927 $default = '/images/default/gotosocial.svg';
1933 * @license GNU Affero General Public License v3.0
1934 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1936 $default = '/images/default/hometown.png';
1942 * @license GNU Affero General Public License v3.0
1943 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1945 $default = '/images/default/koyuspace.png';
1953 * @license GNU Affero General Public License v3.0
1954 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1956 $default = '/images/default/mastodon.png';
1960 if ($type == Contact::TYPE_COMMUNITY) {
1963 * @license GNU Affero General Public License v3.0
1964 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
1966 $default = '/images/default/peertube-channel.png';
1970 * @license GNU Affero General Public License v3.0
1971 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
1973 $default = '/images/default/peertube-account.png';
1980 * @license GNU Affero General Public License v3.0
1981 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
1983 $default = '/images/default/pleroma.png';
1989 * @license GNU Affero General Public License v3.0
1990 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
1992 $default = '/images/default/plume.png';
1995 return DI::baseUrl() . $default;
1998 if (!empty($contact['xmpp'])) {
1999 $avatar['email'] = $contact['xmpp'];
2000 } elseif (!empty($contact['addr'])) {
2001 $avatar['email'] = $contact['addr'];
2002 } elseif (!empty($contact['url'])) {
2003 $avatar['email'] = $contact['url'];
2005 return DI::baseUrl() . $default;
2008 $avatar['url'] = '';
2009 $avatar['success'] = false;
2011 Hook::callAll('avatar_lookup', $avatar);
2013 if ($avatar['success'] && !empty($avatar['url'])) {
2014 return $avatar['url'];
2017 return DI::baseUrl() . $default;
2021 * Get avatar link for given contact id
2023 * @param integer $cid contact id
2024 * @param string $size One of the Proxy::SIZE_* constants
2025 * @param string $updated Contact update date
2026 * @return string avatar link
2028 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2030 // We have to fetch the "updated" variable when it wasn't provided
2031 // The parameter can be provided to improve performance
2032 if (empty($updated)) {
2033 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2034 $updated = $account['updated'] ?? '';
2035 $guid = $account['guid'] ?? '';
2038 $guid = urlencode($guid);
2040 $url = DI::baseUrl() . '/photo/contact/';
2042 case Proxy::SIZE_MICRO:
2043 $url .= Proxy::PIXEL_MICRO . '/';
2045 case Proxy::SIZE_THUMB:
2046 $url .= Proxy::PIXEL_THUMB . '/';
2048 case Proxy::SIZE_SMALL:
2049 $url .= Proxy::PIXEL_SMALL . '/';
2051 case Proxy::SIZE_MEDIUM:
2052 $url .= Proxy::PIXEL_MEDIUM . '/';
2054 case Proxy::SIZE_LARGE:
2055 $url .= Proxy::PIXEL_LARGE . '/';
2058 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2062 * Get avatar link for given contact URL
2064 * @param string $url contact url
2065 * @param integer $uid user id
2066 * @param string $size One of the Proxy::SIZE_* constants
2067 * @return string avatar link
2069 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2071 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2072 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2073 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2074 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2078 * Get header link for given contact id
2080 * @param integer $cid contact id
2081 * @param string $size One of the Proxy::SIZE_* constants
2082 * @param string $updated Contact update date
2083 * @return string header link
2085 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2087 // We have to fetch the "updated" variable when it wasn't provided
2088 // The parameter can be provided to improve performance
2089 if (empty($updated) || empty($guid)) {
2090 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2091 $updated = $account['updated'] ?? '';
2092 $guid = $account['guid'] ?? '';
2095 $guid = urlencode($guid);
2097 $url = DI::baseUrl() . '/photo/header/';
2099 case Proxy::SIZE_MICRO:
2100 $url .= Proxy::PIXEL_MICRO . '/';
2102 case Proxy::SIZE_THUMB:
2103 $url .= Proxy::PIXEL_THUMB . '/';
2105 case Proxy::SIZE_SMALL:
2106 $url .= Proxy::PIXEL_SMALL . '/';
2108 case Proxy::SIZE_MEDIUM:
2109 $url .= Proxy::PIXEL_MEDIUM . '/';
2111 case Proxy::SIZE_LARGE:
2112 $url .= Proxy::PIXEL_LARGE . '/';
2116 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2120 * Updates the avatar links in a contact only if needed
2122 * @param int $cid Contact id
2123 * @param string $avatar Link to avatar picture
2124 * @param bool $force force picture update
2125 * @param bool $create_cache Enforces the creation of cached avatar fields
2128 * @throws HTTPException\InternalServerErrorException
2129 * @throws HTTPException\NotFoundException
2130 * @throws \ImagickException
2132 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2134 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2135 ['id' => $cid, 'self' => false]);
2136 if (!DBA::isResult($contact)) {
2140 $uid = $contact['uid'];
2142 // Only update the cached photo links of public contacts when they already are cached
2143 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2144 if ($contact['avatar'] != $avatar) {
2145 self::update(['avatar' => $avatar], ['id' => $cid]);
2146 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2151 // User contacts use are updated through the public contacts
2152 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2153 $pcid = self::getIdForURL($contact['url'], 0, false);
2154 if (!empty($pcid)) {
2155 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2156 self::updateAvatar($pcid, $avatar, $force, true);
2161 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2163 if ($default_avatar) {
2164 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2167 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2169 // Local contact avatars don't need to be cached
2170 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2171 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2174 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2175 Avatar::deleteCache($contact);
2177 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2178 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2180 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2181 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2182 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2185 // Use the data from the self account
2186 if (empty($fields)) {
2187 $local_uid = User::getIdForURL($contact['url']);
2188 if (!empty($local_uid)) {
2189 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2190 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2194 if (empty($fields)) {
2195 $update = ($contact['avatar'] != $avatar) || $force;
2199 $contact['photo'] ?? '',
2200 $contact['thumb'] ?? '',
2201 $contact['micro'] ?? '',
2204 foreach ($data as $image_uri) {
2205 $image_rid = Photo::ridFromURI($image_uri);
2206 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2207 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2214 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2216 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2217 $update = !empty($fields);
2218 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2224 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2227 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2228 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2229 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2238 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2239 // Collect all user contacts of the given public contact
2240 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2241 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2242 while ($personal_contact = DBA::fetch($personal_contacts)) {
2243 $cids[] = $personal_contact['id'];
2244 $uids[] = $personal_contact['uid'];
2246 DBA::close($personal_contacts);
2248 if (!empty($cids)) {
2249 // Delete possibly existing cached user contact avatars
2250 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2256 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2257 self::update($fields, ['id' => $cids]);
2260 public static function deleteContactByUrl(string $url)
2262 // Update contact data for all users
2263 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2264 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2265 while ($contact = DBA::fetch($contacts)) {
2266 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2267 self::remove($contact['id']);
2272 * Helper function for "updateFromProbe". Updates personal and public contact
2274 * @param integer $id contact id
2275 * @param integer $uid user id
2276 * @param integer $uri_id Uri-Id
2277 * @param string $url The profile URL of the contact
2278 * @param array $fields The fields that are updated
2280 * @throws \Exception
2282 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2284 if (!self::update($fields, ['id' => $id])) {
2285 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2289 self::setAccountUser($id, $uid, $uri_id, $url);
2291 // Archive or unarchive the contact.
2292 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2293 if (!DBA::isResult($contact)) {
2294 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2298 if (isset($fields['failed'])) {
2299 if ($fields['failed']) {
2300 self::markForArchival($contact);
2302 self::unmarkForArchival($contact);
2306 if ($contact['uid'] != 0) {
2310 // Update contact data for all users
2311 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2313 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2314 self::update($fields, $condition);
2316 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2317 $condition['network'] = Protocol::OSTATUS;
2319 // If the contact failed, propagate the update fields to all contacts
2320 if (empty($fields['failed'])) {
2321 unset($fields['last-update']);
2322 unset($fields['success_update']);
2323 unset($fields['failure_update']);
2326 if (empty($fields)) {
2330 self::update($fields, $condition);
2334 * Create or update an "account-user" entry
2336 * @param integer $id
2337 * @param integer $uid
2338 * @param integer $uri_id
2339 * @param string $url
2342 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2344 if (empty($uri_id)) {
2348 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2349 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2350 if ($account_user['uid'] == $uid) {
2351 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2352 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2354 // This should never happen
2355 Logger::warning('account-user exists for a different uri-id and uid', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2359 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2360 if (!empty($account_user['id'])) {
2361 if ($account_user['id'] == $id) {
2362 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2364 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2365 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2366 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2369 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2370 Worker::add(PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2371 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2372 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2374 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2379 * Remove duplicated contacts
2381 * @param string $nurl Normalised contact url
2382 * @param integer $uid User id
2384 * @throws \Exception
2386 public static function removeDuplicates(string $nurl, int $uid)
2388 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2389 $count = DBA::count('contact', $condition);
2394 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2395 if (!DBA::isResult($first_contact)) {
2396 // Shouldn't happen - so we handle it
2400 $first = $first_contact['id'];
2401 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2403 // Find all duplicates
2404 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2405 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2406 while ($duplicate = DBA::fetch($duplicates)) {
2407 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2411 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2413 DBA::close($duplicates);
2414 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2419 * Updates contact record by provided id and optional network
2421 * @param integer $id contact id
2422 * @param string $network Optional network we are probing for
2424 * @throws HTTPException\InternalServerErrorException
2425 * @throws \ImagickException
2427 public static function updateFromProbe(int $id, string $network = '')
2429 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2430 if (!DBA::isResult($contact)) {
2434 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2436 if ($ret['network'] == Protocol::DIASPORA) {
2437 FContact::updateFromProbeArray($ret);
2440 return self::updateFromProbeArray($id, $ret);
2444 * Checks if the given contact has got local data
2447 * @param array $contact
2451 private static function hasLocalData(int $id, array $contact): bool
2453 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2454 // User contacts with the same uri-id exist
2456 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2457 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2460 if (DBA::exists('post-tag', ['cid' => $id])) {
2461 // Is tagged in a post
2464 if (DBA::exists('user-contact', ['cid' => $id])) {
2465 // Has got user-contact data
2468 if (Post::exists(['author-id' => $id])) {
2469 // Posts with this author exist
2472 if (Post::exists(['owner-id' => $id])) {
2473 // Posts with this owner exist
2476 if (Post::exists(['causer-id' => $id])) {
2477 // Posts with this causer exist
2480 // We don't have got this contact locally
2485 * Updates contact record by provided id and probed data
2487 * @param integer $id contact id
2488 * @param array $ret Probed data
2490 * @throws HTTPException\InternalServerErrorException
2491 * @throws \ImagickException
2493 private static function updateFromProbeArray(int $id, array $ret): bool
2496 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2497 This will reliably kill your communication with old Friendica contacts.
2500 // These fields aren't updated by this routine:
2503 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2504 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2505 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2506 'created', 'last-update'];
2507 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2508 if (!DBA::isResult($contact)) {
2512 if (self::isLocal($ret['url'])) {
2513 if ($contact['uid'] == 0) {
2514 Logger::info('Local contacts are not updated here.');
2516 self::updateFromPublicContact($id, $contact);
2521 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2522 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2525 // Delete all contacts with the same URL
2526 self::deleteContactByUrl($ret['url']);
2530 $uid = $contact['uid'];
2531 unset($contact['uid']);
2533 $uriid = $contact['uri-id'];
2534 unset($contact['uri-id']);
2536 $pubkey = $contact['pubkey'];
2537 unset($contact['pubkey']);
2539 $created = $contact['created'];
2540 unset($contact['created']);
2542 $last_update = $contact['last-update'];
2543 unset($contact['last-update']);
2545 $contact['photo'] = $contact['avatar'];
2546 unset($contact['avatar']);
2548 $updated = DateTimeFormat::utcNow();
2550 $has_local_data = self::hasLocalData($id, $contact);
2552 if (!Probe::isProbable($ret['network'])) {
2553 // Periodical checks are only done on federated contacts
2554 $failed_next_update = null;
2555 $success_next_update = null;
2556 } elseif ($has_local_data) {
2557 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2558 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2560 $failed_next_update = DateTimeFormat::utc('now +6 month');
2561 $success_next_update = DateTimeFormat::utc('now +1 month');
2564 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2565 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2566 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2570 // We must not try to update relay contacts via probe. They are no real contacts.
2571 // We check after the probing to be able to correct falsely detected contact types.
2572 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2573 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2574 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2575 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2579 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2580 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2581 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2585 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2586 $cid = self::getIdForURL($ret['url'], 0, false);
2587 if (!empty($cid) && ($cid != $id)) {
2588 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2589 return self::updateFromProbeArray($cid, $ret);
2593 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2594 $ret['unsearchable'] = $ret['hide'];
2597 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2598 $ret['forum'] = false;
2599 $ret['prv'] = false;
2600 $ret['contact-type'] = $ret['account-type'];
2601 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2602 $ret['forum'] = (bool)!$ret['manually-approve'];
2603 $ret['prv'] = (bool)!$ret['forum'];
2607 $new_pubkey = $ret['pubkey'] ?? '';
2609 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2610 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2611 $apcontact = APContact::getByURL($ret['url'], false);
2612 if (!empty($apcontact['featured'])) {
2613 Worker::add(PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2617 $ret['last-item'] = Probe::getLastUpdate($ret);
2618 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2622 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2624 // make sure to not overwrite existing values with blank entries except some technical fields
2625 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2626 foreach ($ret as $key => $val) {
2627 if (!array_key_exists($key, $contact)) {
2629 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2630 $ret[$key] = $contact[$key];
2631 } elseif ($ret[$key] != $contact[$key]) {
2636 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2639 unset($ret['last-item']);
2642 if (empty($uriid)) {
2646 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2647 self::updateAvatar($id, $ret['photo'], $update);
2651 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2653 if (Contact\Relation::isDiscoverable($ret['url'])) {
2654 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2657 // Update the public contact
2659 $contact = self::getByURL($ret['url'], false, ['id']);
2660 if (!empty($contact['id'])) {
2661 self::updateFromProbeArray($contact['id'], $ret);
2668 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2669 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2670 $ret['updated'] = $updated;
2671 $ret['failed'] = false;
2672 $ret['next-update'] = $success_next_update;
2673 $ret['local-data'] = $has_local_data;
2675 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2676 if (empty($pubkey) && !empty($new_pubkey)) {
2677 $ret['pubkey'] = $new_pubkey;
2680 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2681 $ret['uri-date'] = $updated;
2684 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2685 $ret['name-date'] = $updated;
2688 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2689 $ret['last-update'] = $updated;
2690 $ret['success_update'] = $updated;
2693 unset($ret['photo']);
2695 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2697 if (Contact\Relation::isDiscoverable($ret['url'])) {
2698 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2704 private static function updateFromPublicContact(int $id, array $contact)
2706 $public = self::getByURL($contact['url'], false);
2710 foreach ($contact as $field => $value) {
2711 if ($field == 'uid') {
2714 if ($public[$field] != $value) {
2715 $fields[$field] = $public[$field];
2718 if (!empty($fields)) {
2719 self::update($fields, ['id' => $id, 'self' => false]);
2720 Logger::info('Updating local contact', ['id' => $id]);
2725 * Updates contact record by provided URL
2727 * @param integer $url contact url
2728 * @return integer Contact id
2729 * @throws HTTPException\InternalServerErrorException
2730 * @throws \ImagickException
2732 public static function updateFromProbeByURL(string $url): int
2734 $id = self::getIdForURL($url);
2740 self::updateFromProbe($id);
2746 * Detects the communication protocol for a given contact url.
2747 * This is used to detect Friendica contacts that we can communicate via AP.
2749 * @param string $url contact url
2750 * @param string $network Network of that contact
2751 * @return string with protocol
2753 public static function getProtocol(string $url, string $network): string
2755 if ($network != Protocol::DFRN) {
2759 $apcontact = APContact::getByURL($url);
2760 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2761 return Protocol::ACTIVITYPUB;
2768 * Takes a $uid and a url/handle and adds a new contact
2770 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2771 * dfrn_request page.
2773 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2776 * $return['success'] boolean true if successful
2777 * $return['message'] error text if success is false.
2779 * Takes a $uid and a url/handle and adds a new contact
2781 * @param int $uid The user id the contact should be created for
2782 * @param string $url The profile URL of the contact
2783 * @param string $network
2785 * @throws HTTPException\InternalServerErrorException
2786 * @throws HTTPException\NotFoundException
2787 * @throws \ImagickException
2789 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2791 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2793 // remove ajax junk, e.g. Twitter
2794 $url = str_replace('/#!/', '/', $url);
2796 if (!Network::isUrlAllowed($url)) {
2797 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2801 if (Network::isUrlBlocked($url)) {
2802 $result['message'] = DI::l10n()->t('Blocked domain');
2807 $result['message'] = DI::l10n()->t('Connect URL missing.');
2811 $arr = ['url' => $url, 'contact' => []];
2813 Hook::callAll('follow', $arr);
2816 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2820 if (!empty($arr['contact']['name'])) {
2822 $ret = $arr['contact'];
2825 $ret = Probe::uri($url, $network, $uid);
2827 // Ensure that the public contact exists
2828 if ($ret['network'] != Protocol::PHANTOM) {
2829 self::getIdForURL($url);
2833 if (($network != '') && ($ret['network'] != $network)) {
2834 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2838 // check if we already have a contact
2839 // the poll url is more reliable than the profile url, as we may have
2840 // indirect links or webfinger links
2842 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2843 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2844 if (!DBA::isResult($contact)) {
2845 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2846 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2849 $protocol = self::getProtocol($ret['url'], $ret['network']);
2851 // This extra param just confuses things, remove it
2852 if ($protocol === Protocol::DIASPORA) {
2853 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2856 // do we have enough information?
2857 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2858 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2859 if (empty($ret['poll'])) {
2860 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2862 if (empty($ret['name'])) {
2863 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2865 if (empty($ret['url'])) {
2866 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2868 if (strpos($ret['url'], '@') !== false) {
2869 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2870 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2875 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2876 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2877 $ret['notify'] = '';
2880 if (!$ret['notify']) {
2881 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2884 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2886 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2888 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2891 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2892 $pending = (bool)$ret['manually-approve'];
2895 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2899 if (DBA::isResult($contact)) {
2901 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2903 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2904 self::update($fields, ['id' => $contact['id']]);
2906 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2908 // create contact record
2911 'created' => DateTimeFormat::utcNow(),
2912 'url' => $ret['url'],
2913 'nurl' => Strings::normaliseLink($ret['url']),
2914 'addr' => $ret['addr'],
2915 'alias' => $ret['alias'],
2916 'batch' => $ret['batch'],
2917 'notify' => $ret['notify'],
2918 'poll' => $ret['poll'],
2919 'poco' => $ret['poco'],
2920 'name' => $ret['name'],
2921 'nick' => $ret['nick'],
2922 'network' => $ret['network'],
2923 'baseurl' => $ret['baseurl'],
2924 'gsid' => $ret['gsid'] ?? null,
2925 'protocol' => $protocol,
2926 'pubkey' => $ret['pubkey'],
2927 'rel' => $new_relation,
2928 'priority'=> $ret['priority'],
2929 'writable'=> $writeable,
2930 'hidden' => $hidden,
2933 'pending' => $pending,
2938 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2939 if (!DBA::isResult($contact)) {
2940 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2944 $contact_id = $contact['id'];
2945 $result['cid'] = $contact_id;
2947 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2949 // Update the avatar
2950 self::updateAvatar($contact_id, $ret['photo']);
2952 // pull feed and consume it, which should subscribe to the hub.
2953 if ($contact['network'] == Protocol::OSTATUS) {
2954 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2958 self::updateFromProbeArray($contact_id, $ret);
2960 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2963 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2969 * @param array $importer Owner (local user) data
2970 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2971 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2972 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2973 * @param string $note Introduction additional message
2974 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2975 * @throws HTTPException\InternalServerErrorException
2976 * @throws \ImagickException
2978 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
2980 // Should always be set
2981 if (empty($datarray['author-id'])) {
2985 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2986 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2987 if (!DBA::isResult($pub_contact)) {
2988 // Should never happen
2992 // Contact is blocked at node-level
2993 if (self::isBlocked($datarray['author-id'])) {
2997 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2998 $name = $pub_contact['name'];
2999 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3000 $nick = $pub_contact['nick'];
3001 $network = $pub_contact['network'];
3003 // Ensure that we don't create a new contact when there already is one
3004 $cid = self::getIdForURL($url, $importer['uid']);
3006 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3009 self::clearFollowerFollowingEndpointCache($importer['uid']);
3011 if (!empty($contact)) {
3012 if (!empty($contact['pending'])) {
3013 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3017 // Contact is blocked at user-level
3018 if (!empty($contact['id']) && !empty($importer['id']) &&
3019 Contact\User::isBlocked($contact['id'], $importer['id'])) {
3023 // Make sure that the existing contact isn't archived
3024 self::unmarkForArchival($contact);
3026 if (($contact['rel'] == self::SHARING)
3027 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
3028 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3029 ['id' => $contact['id'], 'uid' => $importer['uid']]);
3032 // Ensure to always have the correct network type, independent from the connection request method
3033 self::updateFromProbe($contact['id']);
3035 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3039 // send email notification to owner?
3040 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3041 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3045 // create contact record
3046 $contact_id = self::insert([
3047 'uid' => $importer['uid'],
3048 'created' => DateTimeFormat::utcNow(),
3050 'nurl' => Strings::normaliseLink($url),
3053 'network' => $network,
3054 'rel' => self::FOLLOWER,
3061 // Ensure to always have the correct network type, independent from the connection request method
3062 self::updateFromProbe($contact_id);
3064 self::updateAvatar($contact_id, $photo, true);
3066 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3068 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
3070 /// @TODO Encapsulate this into a function/method
3071 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3072 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3073 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3074 // create notification
3075 if (is_array($contact_record)) {
3076 $intro = DI::introFactory()->createNew(
3078 $contact_record['id'],
3081 DI::intro()->save($intro);
3084 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
3086 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3087 DI::notify()->createFromArray([
3088 'type' => Notification\Type::INTRO,
3089 'otype' => Notification\ObjectType::INTRO,
3090 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3091 'uid' => $user['uid'],
3092 'cid' => $contact_record['id'],
3093 'link' => DI::baseUrl() . '/notifications/intros',
3096 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3097 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3098 self::createFromProbeForUser($importer['uid'], $url, $network);
3101 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3102 $fields = ['pending' => false];
3103 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3104 $fields['rel'] = self::FRIEND;
3107 self::update($fields, $condition);
3117 * Update the local relationship when a local user loses a follower
3119 * @param array $contact User-specific contact (uid != 0) array
3121 * @throws HTTPException\InternalServerErrorException
3122 * @throws \ImagickException
3124 public static function removeFollower(array $contact)
3126 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3127 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3128 } elseif (!empty($contact['id'])) {
3129 self::remove($contact['id']);
3131 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3135 self::clearFollowerFollowingEndpointCache($contact['uid']);
3137 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3139 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3143 * Update the local relationship when a local user unfollow a contact.
3144 * Removes the contact for sharing-only protocols (feed and mail).
3146 * @param array $contact User-specific contact (uid != 0) array
3147 * @throws HTTPException\InternalServerErrorException
3149 public static function removeSharer(array $contact)
3151 self::clearFollowerFollowingEndpointCache($contact['uid']);
3153 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3154 self::remove($contact['id']);
3156 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3161 * Create a birthday event.
3163 * Update the year and the birthday.
3165 public static function updateBirthdays()
3169 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3170 AND NOT `contact`.`pending`
3171 AND NOT `contact`.`hidden`
3172 AND NOT `contact`.`blocked`
3173 AND NOT `contact`.`archive`
3174 AND NOT `contact`.`deleted`',
3180 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3182 while ($contact = DBA::fetch($contacts)) {
3183 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3185 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3187 if (Event::createBirthday($contact, $nextbd)) {
3191 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3192 ['id' => $contact['id']]
3196 DBA::close($contacts);
3200 * Remove the unavailable contact ids from the provided list
3202 * @param array $contact_ids Contact id list
3204 * @throws \Exception
3206 public static function pruneUnavailable(array $contact_ids): array
3208 if (empty($contact_ids)) {
3212 $contacts = self::selectToArray(['id'], [
3213 'id' => $contact_ids,
3219 return array_column($contacts, 'id');
3223 * Returns a magic link to authenticate remote visitors
3225 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3227 * @param string $contact_url The address of the target contact profile
3228 * @param string $url An url that we will be redirected to after the authentication
3230 * @return string with "redir" link
3231 * @throws HTTPException\InternalServerErrorException
3232 * @throws \ImagickException
3234 public static function magicLink(string $contact_url, string $url = ''): string
3236 if (!Session::isAuthenticated()) {
3237 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3240 $contact = self::getByURL($contact_url, false);
3241 if (empty($contact)) {
3242 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3245 // Prevents endless loop in case only a non-public contact exists for the contact URL
3246 unset($contact['uid']);
3248 return self::magicLinkByContact($contact, $url ?: $contact_url);
3252 * Returns a magic link to authenticate remote visitors
3254 * @param integer $cid The contact id of the target contact profile
3255 * @param string $url An url that we will be redirected to after the authentication
3257 * @return string with "redir" link
3258 * @throws HTTPException\InternalServerErrorException
3259 * @throws \ImagickException
3261 public static function magicLinkById(int $cid, string $url = ''): string
3263 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3265 return self::magicLinkByContact($contact, $url);
3269 * Returns a magic link to authenticate remote visitors
3271 * @param array $contact The contact array with "uid", "network" and "url"
3272 * @param string $url An url that we will be redirected to after the authentication
3274 * @return string with "redir" link
3275 * @throws HTTPException\InternalServerErrorException
3276 * @throws \ImagickException
3278 public static function magicLinkByContact(array $contact, string $url = ''): string
3280 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3282 if (!Session::isAuthenticated()) {
3283 return $destination;
3286 // Only redirections to the same host do make sense
3287 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3291 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
3292 return 'contact/' . $contact['id'] . '/conversations';
3295 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3296 return $destination;
3299 if (empty($contact['id'])) {
3300 return $destination;
3303 $redirect = 'redir/' . $contact['id'];
3305 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3306 $redirect .= '?url=' . $url;
3313 * Is the contact a forum?
3315 * @param integer $contactid ID of the contact
3317 * @return boolean "true" if it is a forum
3319 public static function isForum(int $contactid): bool
3321 $fields = ['contact-type'];
3322 $condition = ['id' => $contactid];
3323 $contact = DBA::selectFirst('contact', $fields, $condition);
3324 if (!DBA::isResult($contact)) {
3329 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3333 * Can the remote contact receive private messages?
3335 * @param array $contact
3338 public static function canReceivePrivateMessages(array $contact): bool
3340 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3341 $self = $contact['self'] ?? false;
3343 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3347 * Search contact table by nick or name
3349 * @param string $search Name or nick
3350 * @param string $mode Search mode (e.g. "community")
3351 * @param int $uid User ID
3353 * @return array with search results
3354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3356 public static function searchByName(string $search, string $mode = '', int $uid = 0): array
3358 if (empty($search)) {
3362 // check supported networks
3363 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3364 if (DI::config()->get('system', 'diaspora_enabled')) {
3365 $networks[] = Protocol::DIASPORA;
3368 if (!DI::config()->get('system', 'ostatus_disabled')) {
3369 $networks[] = Protocol::OSTATUS;
3372 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3375 $condition['blocked'] = false;
3378 // check if we search only communities or every contact
3379 if ($mode === 'community') {
3380 $condition['contact-type'] = self::TYPE_COMMUNITY;
3385 $condition = DBA::mergeConditions($condition,
3386 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3387 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3389 $contacts = self::selectToArray([], $condition);
3394 * Add public contacts from an array
3396 * @param array $urls
3397 * @return array result "count", "added" and "updated"
3399 public static function addByUrls(array $urls): array
3406 foreach ($urls as $url) {
3407 if (empty($url) || !is_string($url)) {
3410 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3411 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3412 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3414 } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3415 Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
3423 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3427 * Returns a random, global contact array of the current node
3429 * @return array The profile array
3432 public static function getRandomContact(): array
3434 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3435 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3436 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3437 ], ['order' => ['RAND()']]);
3439 if (DBA::isResult($contact)) {