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\Module\NoScrape;
39 use Friendica\Network\HTTPException;
40 use Friendica\Network\Probe;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
50 * functions for interacting with a contact
54 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
55 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
56 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
62 const LOCK_INSERT = 'contact-insert';
67 * TYPE_UNKNOWN - unknown type
69 * TYPE_PERSON - the account belongs to a person
70 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
72 * TYPE_ORGANISATION - the account belongs to an organisation
73 * Associated page type: PAGE_SOAPBOX
75 * TYPE_NEWS - the account is a news reflector
76 * Associated page type: PAGE_SOAPBOX
78 * TYPE_COMMUNITY - the account is community forum
79 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
81 * TYPE_RELAY - the account is a relay
82 * This will only be assigned to contacts, not to user accounts
85 const TYPE_UNKNOWN = -1;
86 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
87 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
88 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
89 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
90 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
110 const MIRROR_DEACTIVATED = 0;
111 const MIRROR_FORWARDED = 1;
112 const MIRROR_OWN_POST = 2;
113 const MIRROR_NATIVE_RESHARE = 3;
116 * @param array $fields Array of selected fields, empty for all
117 * @param array $condition Array of fields for condition
118 * @param array $params Array of several parameters
122 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
124 return DBA::selectToArray('contact', $fields, $condition, $params);
128 * @param array $fields Array of selected fields, empty for all
129 * @param array $condition Array of fields for condition
130 * @param array $params Array of several parameters
134 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
136 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
142 * Insert a row into the contact table
143 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
145 * @param array $fields field array
146 * @param int $duplicate_mode Do an update on a duplicate entry
148 * @return int id of the created contact
151 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
153 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
154 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
157 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
159 if (empty($fields['created'])) {
160 $fields['created'] = DateTimeFormat::utcNow();
163 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
164 DBA::insert('contact', $fields, $duplicate_mode);
165 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
166 if (!DBA::isResult($contact)) {
168 Logger::warning('Created contact could not be found', ['fields' => $fields]);
172 Contact\User::insertForContactArray($contact);
174 // Search for duplicated contacts and get rid of them
175 if (!$contact['self']) {
176 self::removeDuplicates($contact['nurl'], $contact['uid']);
179 return $contact['id'];
183 * Updates rows in the contact table
185 * @param array $fields contains the fields that are updated
186 * @param array $condition condition array with the key values
187 * @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)
189 * @return boolean was the update successfull?
191 * @todo Let's get rid of boolean type of $old_fields
193 public static function update(array $fields, array $condition, $old_fields = [])
195 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
196 $ret = DBA::update('contact', $fields, $condition, $old_fields);
198 // Apply changes to the "user-contact" table on dedicated fields
199 Contact\User::updateByContactUpdate($fields, $condition);
205 * @param integer $id Contact ID
206 * @param array $fields Array of selected fields, empty for all
207 * @return array|boolean Contact record if it exists, false otherwise
210 public static function getById(int $id, array $fields = [])
212 return DBA::selectFirst('contact', $fields, ['id' => $id]);
216 * Fetch the first contact with the provided uri-id.
218 * @param integer $uri_id uri-id of the contact
219 * @param array $fields Array of selected fields, empty for all
220 * @return array|boolean Contact record if it exists, false otherwise
223 public static function getByUriId(int $uri_id, array $fields = [])
225 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
229 * Fetches a contact by a given url
231 * @param string $url profile url
232 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
233 * @param array $fields Field list
234 * @param integer $uid User ID of the contact
235 * @return array contact array
237 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
239 if ($update || is_null($update)) {
240 $cid = self::getIdForURL($url, $uid, $update);
245 $contact = self::getById($cid, $fields);
246 if (empty($contact)) {
252 // Add internal fields
254 if (!empty($fields)) {
255 foreach (['id', 'next-update', 'network'] as $internal) {
256 if (!in_array($internal, $fields)) {
257 $fields[] = $internal;
258 $removal[] = $internal;
263 // We first try the nurl (http://server.tld/nick), most common case
264 $options = ['order' => ['id']];
265 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
267 // Then the addr (nick@server.tld)
268 if (!DBA::isResult($contact)) {
269 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
272 // Then the alias (which could be anything)
273 if (!DBA::isResult($contact)) {
274 // The link could be provided as http although we stored it as https
275 $ssl_url = str_replace('http://', 'https://', $url);
276 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
277 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
280 if (!DBA::isResult($contact)) {
284 // Update the contact in the background if needed
285 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
286 Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
289 // Remove the internal fields
290 foreach ($removal as $internal) {
291 unset($contact[$internal]);
298 * Fetches a contact for a given user by a given url.
299 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
301 * @param string $url profile url
302 * @param integer $uid User ID of the contact
303 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
304 * @param array $fields Field list
305 * @return array contact array
307 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
310 $contact = self::getByURL($url, $update, $fields, $uid);
311 if (!empty($contact)) {
312 if (!empty($contact['id'])) {
313 $contact['cid'] = $contact['id'];
320 $contact = self::getByURL($url, $update, $fields);
321 if (!empty($contact['id'])) {
323 $contact['zid'] = $contact['id'];
329 * Tests if the given contact is a follower
331 * @param int $cid Either public contact id or user's contact id
332 * @param int $uid User ID
333 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
335 * @return boolean is the contact id a follower?
336 * @throws HTTPException\InternalServerErrorException
337 * @throws \ImagickException
339 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
341 if (Contact\User::isBlocked($cid, $uid)) {
345 $cdata = self::getPublicAndUserContactID($cid, $uid);
346 if (empty($cdata['user'])) {
350 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
352 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
354 return DBA::exists('contact', $condition);
358 * Tests if the given contact url is a follower
360 * @param string $url Contact URL
361 * @param int $uid User ID
362 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
364 * @return boolean is the contact id a follower?
365 * @throws HTTPException\InternalServerErrorException
366 * @throws \ImagickException
368 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
370 $cid = self::getIdForURL($url, $uid);
376 return self::isFollower($cid, $uid, $strict);
380 * Tests if the given user shares with the given contact
382 * @param int $cid Either public contact id or user's contact id
383 * @param int $uid User ID
384 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
386 * @return boolean is the contact sharing with given user?
387 * @throws HTTPException\InternalServerErrorException
388 * @throws \ImagickException
390 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
392 if (Contact\User::isBlocked($cid, $uid)) {
396 $cdata = self::getPublicAndUserContactID($cid, $uid);
397 if (empty($cdata['user'])) {
401 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
403 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
405 return DBA::exists('contact', $condition);
409 * Tests if the given user follow the given contact url
411 * @param string $url Contact URL
412 * @param int $uid User ID
413 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
415 * @return boolean is the contact url being followed?
416 * @throws HTTPException\InternalServerErrorException
417 * @throws \ImagickException
419 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
421 $cid = self::getIdForURL($url, $uid);
427 return self::isSharing($cid, $uid, $strict);
431 * Get the basepath for a given contact link
433 * @param string $url The contact link
434 * @param boolean $dont_update Don't update the contact
436 * @return string basepath
437 * @throws HTTPException\InternalServerErrorException
438 * @throws \ImagickException
440 public static function getBasepath(string $url, bool $dont_update = false): string
442 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
443 if (!DBA::isResult($contact)) {
447 if (!empty($contact['baseurl'])) {
448 return $contact['baseurl'];
449 } elseif ($dont_update) {
453 // Update the existing contact
454 self::updateFromProbe($contact['id']);
456 // And fetch the result
457 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
458 if (empty($contact['baseurl'])) {
459 Logger::info('No baseurl for contact', ['url' => $url]);
463 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
464 return $contact['baseurl'];
468 * Check if the given contact url is on the same server
470 * @param string $url The contact link
472 * @return boolean Is it the same server?
474 public static function isLocal(string $url): bool
476 if (!parse_url($url, PHP_URL_SCHEME)) {
477 $addr_parts = explode('@', $url);
478 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
481 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
485 * Check if the given contact ID is on the same server
487 * @param string $url The contact link
488 * @return boolean Is it the same server?
490 public static function isLocalById(int $cid): bool
492 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
493 if (!DBA::isResult($contact)) {
497 if (empty($contact['baseurl'])) {
498 $baseurl = self::getBasepath($contact['url'], true);
500 $baseurl = $contact['baseurl'];
503 return Strings::compareLink($baseurl, DI::baseUrl());
507 * Returns the public contact id of the given user id
509 * @param integer $uid User ID
511 * @return integer|boolean Public contact id for given user id
514 public static function getPublicIdByUserId(int $uid)
516 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
517 if (!DBA::isResult($self)) {
520 return self::getIdForURL($self['url']);
524 * Returns the contact id for the user and the public contact id for a given contact id
526 * @param int $cid Either public contact id or user's contact id
527 * @param int $uid User ID
529 * @return array with public and user's contact id
530 * @throws HTTPException\InternalServerErrorException
531 * @throws \ImagickException
533 public static function getPublicAndUserContactID(int $cid, int $uid): array
535 // We have to use the legacy function as long as the post update hasn't finished
536 if (DI::config()->get('system', 'post_update_version') < 1427) {
537 return self::legacyGetPublicAndUserContactID($cid, $uid);
540 if (empty($uid) || empty($cid)) {
544 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
545 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
549 $pcid = $contact['pid'];
550 if ($contact['uid'] == $uid) {
551 $ucid = $contact['id'];
553 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
554 if (DBA::isResult($contact)) {
555 $ucid = $contact['id'];
561 return ['public' => $pcid, 'user' => $ucid];
565 * Helper function for "getPublicAndUserContactID"
567 * @param int $cid Either public contact id or user's contact id
568 * @param int $uid User ID
569 * @return array with public and user's contact id
570 * @throws HTTPException\InternalServerErrorException
571 * @throws \ImagickException
573 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
575 if (empty($uid) || empty($cid)) {
579 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
580 if (!DBA::isResult($contact)) {
584 // We quit when the user id don't match the user id of the provided contact
585 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
589 if ($contact['uid'] != 0) {
590 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
594 $ucid = $contact['id'];
596 $pcid = $contact['id'];
597 $ucid = self::getIdForURL($contact['url'], $uid);
600 return ['public' => $pcid, 'user' => $ucid];
604 * Returns contact details for a given contact id in combination with a user id
606 * @param int $cid A contact ID
607 * @param int $uid The User ID
608 * @param array $fields The selected fields for the contact
609 * @return array The contact details
613 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
615 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
617 if (!DBA::isResult($contact)) {
625 * Creates the self-contact for the provided user id
628 * @return bool Operation success
629 * @throws HTTPException\InternalServerErrorException
631 public static function createSelfFromUserId(int $uid): bool
633 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
634 ['uid' => $uid, 'account_expired' => false]);
635 if (!DBA::isResult($user)) {
640 'uid' => $user['uid'],
641 'created' => DateTimeFormat::utcNow(),
643 'name' => $user['username'],
644 'nick' => $user['nickname'],
645 'pubkey' => $user['pubkey'],
646 'prvkey' => $user['prvkey'],
647 'photo' => User::getAvatarUrl($user),
648 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
649 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
652 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
653 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
654 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
655 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
656 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
657 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
658 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
659 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
660 'name-date' => DateTimeFormat::utcNow(),
661 'uri-date' => DateTimeFormat::utcNow(),
662 'avatar-date' => DateTimeFormat::utcNow(),
668 // Only create the entry if it doesn't exist yet
669 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
670 $return = (bool)self::insert($contact);
673 // Create the public contact
674 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
675 $contact['self'] = false;
677 $contact['prvkey'] = null;
679 self::insert($contact, Database::INSERT_IGNORE);
686 * Updates the self-contact for the provided user id
689 * @param bool $update_avatar Force the avatar update
690 * @return bool "true" if updated
691 * @throws HTTPException\InternalServerErrorException
693 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
695 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
696 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
697 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
698 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
699 if (!DBA::isResult($self)) {
703 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
704 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
705 if (!DBA::isResult($user)) {
709 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
710 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
711 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
712 if (!DBA::isResult($profile)) {
716 $file_suffix = 'jpg';
717 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
720 'name' => $profile['name'],
721 'nick' => $user['nickname'],
722 'avatar-date' => $self['avatar-date'],
723 'location' => Profile::formatLocation($profile),
724 'about' => $profile['about'],
725 'keywords' => $profile['pub_keywords'],
726 'contact-type' => $user['account-type'],
727 'prvkey' => $user['prvkey'],
728 'pubkey' => $user['pubkey'],
729 'xmpp' => $profile['xmpp'],
730 'matrix' => $profile['matrix'],
731 'network' => Protocol::DFRN,
733 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
734 'nurl' => Strings::normaliseLink($url),
735 'uri-id' => ItemURI::getIdByURI($url),
736 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
737 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
738 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
739 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
740 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
741 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
745 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
746 if (DBA::isResult($avatar)) {
747 if ($update_avatar) {
748 $fields['avatar-date'] = DateTimeFormat::utcNow();
751 // Creating the path to the avatar, beginning with the file suffix
752 $types = Images::supportedTypes();
753 if (isset($types[$avatar['type']])) {
754 $file_suffix = $types[$avatar['type']];
757 // We are adding a timestamp value so that other systems won't use cached content
758 $timestamp = strtotime($fields['avatar-date']);
760 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
761 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
763 $fields['photo'] = $prefix . '4' . $suffix;
764 $fields['thumb'] = $prefix . '5' . $suffix;
765 $fields['micro'] = $prefix . '6' . $suffix;
767 // We hadn't found a photo entry, so we use the default avatar
768 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
769 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
770 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
773 $fields['avatar'] = User::getAvatarUrl($user);
774 $fields['header'] = User::getBannerUrl($user);
775 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
776 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
777 $fields['unsearchable'] = !$profile['net-publish'];
778 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
782 foreach ($fields as $field => $content) {
783 if ($self[$field] != $content) {
789 if ($fields['name'] != $self['name']) {
790 $fields['name-date'] = DateTimeFormat::utcNow();
792 $fields['updated'] = DateTimeFormat::utcNow();
793 self::update($fields, ['id' => $self['id']]);
795 // Update the other contacts as well
796 unset($fields['prvkey']);
797 $fields['self'] = false;
798 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
800 // Update the profile
802 'photo' => User::getAvatarUrl($user),
803 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
806 DBA::update('profile', $fields, ['uid' => $uid]);
813 * Marks a contact for removal
815 * @param int $id contact id
817 * @throws HTTPException\InternalServerErrorException
819 public static function remove(int $id)
821 // We want just to make sure that we don't delete our "self" contact
822 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
823 if (!DBA::isResult($contact)) {
827 self::clearFollowerFollowingEndpointCache($contact['uid']);
829 // Archive the contact
830 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
832 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
833 Avatar::deleteCache($contact);
836 // Delete it in the background
837 Worker::add(PRIORITY_MEDIUM, 'Contact\Remove', $id);
841 * Unfollow the remote contact
843 * @param array $contact Target user-specific contact (uid != 0) array
845 * @throws HTTPException\InternalServerErrorException
846 * @throws \ImagickException
848 public static function unfollow(array $contact): void
850 if (empty($contact['network'])) {
851 throw new \InvalidArgumentException('Empty network in contact array');
854 if (empty($contact['uid'])) {
855 throw new \InvalidArgumentException('Unexpected public contact record');
858 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
859 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
860 if (!empty($cdata['public'])) {
861 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
865 self::removeSharer($contact);
869 * Revoke follow privileges of the remote user contact
871 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
873 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
875 * @throws HTTPException\InternalServerErrorException
876 * @throws \ImagickException
878 public static function revokeFollow(array $contact): void
880 if (empty($contact['network'])) {
881 throw new \InvalidArgumentException('Empty network in contact array');
884 if (empty($contact['uid'])) {
885 throw new \InvalidArgumentException('Unexpected public contact record');
888 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
889 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
890 if (!empty($cdata['public'])) {
891 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
895 self::removeFollower($contact);
899 * Completely severs a relationship with a contact
901 * @param array $contact User-specific contact (uid != 0) array
903 * @throws HTTPException\InternalServerErrorException
904 * @throws \ImagickException
906 public static function terminateFriendship(array $contact)
908 if (empty($contact['network'])) {
909 throw new \InvalidArgumentException('Empty network in contact array');
912 if (empty($contact['uid'])) {
913 throw new \InvalidArgumentException('Unexpected public contact record');
916 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
918 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
919 Worker::add(PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
922 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
923 Worker::add(PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
926 self::remove($contact['id']);
929 private static function clearFollowerFollowingEndpointCache(int $uid)
935 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
936 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
940 * Marks a contact for archival after a communication issue delay
942 * Contact has refused to recognise us as a friend. We will start a countdown.
943 * If they still don't recognise us in 32 days, the relationship is over,
944 * and we won't waste any more time trying to communicate with them.
945 * This provides for the possibility that their database is temporarily messed
946 * up or some other transient event and that there's a possibility we could recover from it.
948 * @param array $contact contact to mark for archival
950 * @throws HTTPException\InternalServerErrorException
952 public static function markForArchival(array $contact)
954 if (!isset($contact['url']) && !empty($contact['id'])) {
955 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
956 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
957 if (!DBA::isResult($contact)) {
960 } elseif (!isset($contact['url'])) {
961 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
964 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
966 // Contact already archived or "self" contact? => nothing to do
967 if ($contact['archive'] || $contact['self']) {
971 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
972 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
973 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
976 * We really should send a notification to the owner after 2-3 weeks
977 * so they won't be surprised when the contact vanishes and can take
978 * remedial action if this was a serious mistake or glitch
981 /// @todo Check for contact vitality via probing
982 $archival_days = DI::config()->get('system', 'archival_days', 32);
984 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
985 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
986 /* Relationship is really truly dead. archive them rather than
987 * delete, though if the owner tries to unarchive them we'll start
988 * the whole process over again.
990 self::update(['archive' => true], ['id' => $contact['id']]);
991 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
997 * Cancels the archival countdown
999 * @see Contact::markForArchival()
1001 * @param array $contact contact to be unmarked for archival
1003 * @throws \Exception
1005 public static function unmarkForArchival(array $contact)
1007 // Always unarchive the relay contact entry
1008 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1009 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1010 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1011 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1012 self::update($fields, $condition);
1016 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1017 $exists = DBA::exists('contact', $condition);
1019 // We don't need to update, we never marked this contact for archival
1024 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1026 if (!isset($contact['url']) && !empty($contact['id'])) {
1027 $fields = ['id', 'url', 'batch'];
1028 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1029 if (!DBA::isResult($contact)) {
1034 // It's a miracle. Our dead contact has inexplicably come back to life.
1035 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1036 self::update($fields, ['id' => $contact['id']]);
1037 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1041 * Returns the data array for the photo menu of a given contact
1043 * @param array $contact contact
1044 * @param int $uid optional, default 0
1046 * @throws HTTPException\InternalServerErrorException
1047 * @throws \ImagickException
1049 public static function photoMenu(array $contact, int $uid = 0): array
1056 $uid = local_user();
1059 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1061 $profile_link = self::magicLinkByContact($contact);
1062 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1067 // Look for our own contact if the uid doesn't match and isn't public
1068 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1069 if (DBA::isResult($contact_own)) {
1070 return self::photoMenu($contact_own, $uid);
1075 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1077 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1079 $profile_link = $contact['url'];
1082 if ($profile_link === 'mailbox') {
1087 $status_link = $profile_link . '/status';
1088 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1089 $profile_link = $profile_link . '/profile';
1092 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1093 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1096 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1098 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1101 $unfollow_link = '';
1102 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1103 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1104 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1105 } elseif(!$contact['pending']) {
1106 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1112 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1114 if (empty($contact['uid'])) {
1116 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1117 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1118 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1119 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1120 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1124 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1125 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1126 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1127 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1128 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1129 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1130 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1131 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1134 if (!empty($contact['pending'])) {
1136 $intro = DI::intro()->selectForContact($contact['id']);
1137 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1138 } catch (IntroductionNotFoundException $exception) {
1139 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1144 $args = ['contact' => $contact, 'menu' => &$menu];
1146 Hook::callAll('contact_photo_menu', $args);
1148 $menucondensed = [];
1150 foreach ($menu as $menuname => $menuitem) {
1151 if ($menuitem[1] != '') {
1152 $menucondensed[$menuname] = $menuitem;
1156 return $menucondensed;
1160 * Fetch the contact id for a given URL and user
1162 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1163 * `addr` or `alias`.
1165 * If there's no record and we aren't looking for a public contact, we quit.
1166 * If there's one, we check that it isn't time to update the picture else we
1167 * directly return the found contact id.
1169 * Second, we probe the provided $url whether it's http://server.tld/profile or
1170 * nick@server.tld. We quit if we can't get any info back.
1172 * Third, we create the contact record if it doesn't exist
1174 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1175 * if there's any updates
1177 * @param string $url Contact URL
1178 * @param integer $uid The user id for the contact (0 = public contact)
1179 * @param boolean $update true = always update, false = never update, null = update when not found
1180 * @param array $default Default value for creating the contact when everything else fails
1182 * @return integer Contact ID
1183 * @throws HTTPException\InternalServerErrorException
1184 * @throws \ImagickException
1186 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1191 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1195 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
1197 if (!empty($contact)) {
1198 $contact_id = $contact['id'];
1200 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1201 Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
1204 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1205 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1208 } elseif ($uid != 0) {
1209 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1211 } elseif (empty($default) && !is_null($update) && !$update) {
1212 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1218 if (empty($default['network']) || $update) {
1219 $data = Probe::uri($url, '', $uid);
1221 // Take the default values when probing failed
1222 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1223 $data = array_merge($data, $default);
1225 } elseif (!empty($default['network'])) {
1229 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1230 // Fetch data for the public contact via the first found personal contact
1231 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1232 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1233 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1234 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1236 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1237 if (!DBA::isResult($personal_contact)) {
1238 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1241 if (DBA::isResult($personal_contact)) {
1242 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1243 $data = $personal_contact;
1244 $data['photo'] = $personal_contact['avatar'];
1245 $data['account-type'] = $personal_contact['contact-type'];
1246 $data['hide'] = $personal_contact['unsearchable'];
1247 unset($data['avatar']);
1248 unset($data['contact-type']);
1249 unset($data['unsearchable']);
1253 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1254 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1259 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1260 if (!empty($data['alias'])) {
1261 $urls[] = Strings::normaliseLink($data['alias']);
1263 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1264 if (!empty($contact['id'])) {
1265 $contact_id = $contact['id'];
1266 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1271 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1274 'url' => $data['url'],
1275 'nurl' => Strings::normaliseLink($data['url']),
1276 'network' => $data['network'],
1277 'created' => DateTimeFormat::utcNow(),
1278 'rel' => self::SHARING,
1284 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1286 // Before inserting we do check if the entry does exist now.
1287 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1288 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1289 if (DBA::isResult($contact)) {
1290 $contact_id = $contact['id'];
1291 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1293 $contact_id = self::insert($fields);
1295 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1298 DI::lock()->release(self::LOCK_INSERT);
1300 Logger::warning('Contact lock had not been acquired');
1304 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1308 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1311 if ($data['network'] == Protocol::DIASPORA) {
1312 FContact::updateFromProbeArray($data);
1315 self::updateFromProbeArray($contact_id, $data);
1317 // Don't return a number for a deleted account
1318 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1319 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1327 * Checks if the contact is archived
1329 * @param int $cid contact id
1331 * @return boolean Is the contact archived?
1332 * @throws HTTPException\InternalServerErrorException
1334 public static function isArchived(int $cid): bool
1340 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1341 if (!DBA::isResult($contact)) {
1345 if ($contact['archive']) {
1349 // Check status of ActivityPub endpoints
1350 $apcontact = APContact::getByURL($contact['url'], false);
1351 if (!empty($apcontact)) {
1352 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1356 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1361 // Check status of Diaspora endpoints
1362 if (!empty($contact['batch'])) {
1363 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1364 return DBA::exists('contact', $condition);
1371 * Checks if the contact is blocked
1373 * @param int $cid contact id
1374 * @return boolean Is the contact blocked?
1375 * @throws HTTPException\InternalServerErrorException
1377 public static function isBlocked(int $cid): bool
1383 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1384 if (!DBA::isResult($blocked)) {
1388 if (Network::isUrlBlocked($blocked['url'])) {
1392 return (bool) $blocked['blocked'];
1396 * Checks if the contact is hidden
1398 * @param int $cid contact id
1399 * @return boolean Is the contact hidden?
1400 * @throws \Exception
1402 public static function isHidden(int $cid): bool
1408 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1409 if (!DBA::isResult($hidden)) {
1412 return (bool) $hidden['hidden'];
1416 * Returns posts from a given contact url
1418 * @param string $contact_url Contact URL
1419 * @param bool $thread_mode
1420 * @param int $update Update mode
1421 * @param int $parent Item parent ID for the update mode
1422 * @param bool $only_media Only display media content
1423 * @return string posts in HTML
1424 * @throws \Exception
1426 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1428 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1432 * Returns posts from a given contact id
1434 * @param int $cid Contact ID
1435 * @param bool $thread_mode
1436 * @param int $update Update mode
1437 * @param int $parent Item parent ID for the update mode
1438 * @param bool $only_media Only display media content
1439 * @return string posts in HTML
1440 * @throws \Exception
1442 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1444 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1445 if (!DBA::isResult($contact)) {
1449 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1450 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1455 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1458 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1459 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1461 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1462 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1465 if (!empty($parent)) {
1466 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1468 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1469 if (!empty($last_received)) {
1470 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1475 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1476 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1479 if (DI::mode()->isMobile()) {
1480 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1481 DI::config()->get('system', 'itemspage_network_mobile'));
1483 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1484 DI::config()->get('system', 'itemspage_network'));
1487 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1489 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1491 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1492 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1493 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1499 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1500 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1502 if ($pager->getStart() == 0) {
1503 $cdata = self::getPublicAndUserContactID($cid, local_user());
1504 if (!empty($cdata['public'])) {
1505 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1506 $items = array_merge($items, $pinned);
1510 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', local_user());
1512 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1513 $items = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1515 if ($pager->getStart() == 0) {
1516 $cdata = self::getPublicAndUserContactID($cid, local_user());
1517 if (!empty($cdata['public'])) {
1518 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1519 $cdata['public'], Post\Collection::FEATURED];
1520 $pinned = Post::toArray(Post::selectForUser(local_user(), $fields, $condition, $params));
1521 $items = array_merge($pinned, $items);
1525 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1529 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1530 $o .= HTML::scrollLoader();
1532 $o .= $pager->renderMinimal(count($items));
1540 * Returns the account type name
1542 * The function can be called with either the user or the contact array
1544 * @param int $type type of contact or account
1547 public static function getAccountType(int $type): string
1550 case self::TYPE_ORGANISATION:
1551 $account_type = DI::l10n()->t("Organisation");
1554 case self::TYPE_NEWS:
1555 $account_type = DI::l10n()->t('News');
1558 case self::TYPE_COMMUNITY:
1559 $account_type = DI::l10n()->t("Forum");
1567 return $account_type;
1573 * @param int $cid Contact id to block
1574 * @param string $reason Block reason
1575 * @return bool Whether it was successful
1577 public static function block(int $cid, string $reason = null): bool
1579 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1585 * Unblocks a contact
1587 * @param int $cid Contact id to unblock
1588 * @return bool Whether it was successfull
1590 public static function unblock(int $cid): bool
1592 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1598 * Ensure that cached avatar exist
1600 * @param integer $cid Contact id
1602 public static function checkAvatarCache(int $cid)
1604 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1605 if (!DBA::isResult($contact)) {
1609 if (Network::isLocalLink($contact['url'])) {
1613 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1614 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1615 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1616 self::updateAvatar($cid, $contact['avatar'], true);
1619 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1620 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1621 self::updateAvatar($cid, $contact['avatar'], true);
1623 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1624 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1625 self::updateAvatar($cid, $contact['avatar'], true);
1631 * Return the photo path for a given contact array in the given size
1633 * @param array $contact contact array
1634 * @param string $field Fieldname of the photo in the contact array
1635 * @param string $size Size of the avatar picture
1636 * @param string $avatar Avatar path that is displayed when no photo had been found
1637 * @param bool $no_update Don't perfom an update if no cached avatar was found
1638 * @return string photo path
1640 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1642 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1644 if (DI::config()->get('system', 'avatar_cache')) {
1646 case Proxy::SIZE_MICRO:
1647 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1648 return $contact['micro'];
1651 case Proxy::SIZE_THUMB:
1652 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1653 return $contact['thumb'];
1656 case Proxy::SIZE_SMALL:
1657 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1658 return $contact['photo'];
1664 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1668 * Return the photo path for a given contact array
1670 * @param array $contact Contact array
1671 * @param bool $no_update Don't perfom an update if no cached avatar was found
1672 * @return string photo path
1674 public static function getPhoto(array $contact, bool $no_update = false): string
1676 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1680 * Return the photo path (thumb size) for a given contact array
1682 * @param array $contact Contact array
1683 * @param bool $no_update Don't perfom an update if no cached avatar was found
1684 * @return string photo path
1686 public static function getThumb(array $contact, bool $no_update = false): string
1688 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1692 * Return the photo path (micro size) for a given contact array
1694 * @param array $contact Contact array
1695 * @param bool $no_update Don't perfom an update if no cached avatar was found
1696 * @return string photo path
1698 public static function getMicro(array $contact, bool $no_update = false): string
1700 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1704 * Check the given contact array for avatar cache fields
1706 * @param array $contact
1707 * @param bool $no_update Don't perfom an update if no cached avatar was found
1708 * @return array contact array with avatar cache fields
1710 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1713 $contact_fields = [];
1714 $fields = ['photo', 'thumb', 'micro'];
1715 foreach ($fields as $field) {
1716 if (isset($contact[$field])) {
1717 $contact_fields[] = $field;
1719 if (isset($contact[$field]) && empty($contact[$field])) {
1724 if (!$update || $no_update) {
1728 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1730 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1731 self::updateAvatar($contact['id'], $contact['avatar'], true);
1733 $new_contact = self::getById($contact['id'], $contact_fields);
1734 if (DBA::isResult($new_contact)) {
1735 // We only update the cache fields
1736 $contact = array_merge($contact, $new_contact);
1738 } elseif ($local && !empty($contact['avatar'])) {
1742 /// add the default avatars if the fields aren't filled
1743 if (isset($contact['photo']) && empty($contact['photo'])) {
1744 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1746 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1747 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1749 if (isset($contact['micro']) && empty($contact['micro'])) {
1750 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1757 * Fetch the default header for the given contact
1759 * @param array $contact contact array
1760 * @return string avatar URL
1762 public static function getDefaultHeader(array $contact): string
1764 if (!empty($contact['header'])) {
1765 return $contact['header'];
1768 if (!empty($contact['gsid'])) {
1769 // Use default banners for certain platforms
1770 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1771 $platform = strtolower($gserver['platform'] ?? '');
1776 switch ($platform) {
1781 * @author Lostinlight <https://mastodon.xyz/@lightone>
1782 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1783 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1785 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1790 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1791 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1792 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1794 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1798 * Use a random picture.
1799 * The service provides random pictures from Unsplash.
1800 * @license https://unsplash.com/license
1802 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1810 * Fetch the default avatar for the given contact and size
1812 * @param array $contact contact array
1813 * @param string $size Size of the avatar picture
1814 * @return string avatar URL
1816 public static function getDefaultAvatar(array $contact, string $size): string
1819 case Proxy::SIZE_MICRO:
1820 $avatar['size'] = 48;
1821 $default = self::DEFAULT_AVATAR_MICRO;
1824 case Proxy::SIZE_THUMB:
1825 $avatar['size'] = 80;
1826 $default = self::DEFAULT_AVATAR_THUMB;
1829 case Proxy::SIZE_SMALL:
1831 $avatar['size'] = 300;
1832 $default = self::DEFAULT_AVATAR_PHOTO;
1836 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1838 $type = Contact::TYPE_PERSON;
1840 if (!empty($contact['id'])) {
1841 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1842 $platform = $account['platform'] ?? '';
1843 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1846 if (empty($platform) && !empty($contact['uri-id'])) {
1847 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1848 $platform = $account['platform'] ?? '';
1849 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1852 switch ($platform) {
1856 * @license GNU Affero General Public License v3.0
1857 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1859 $default = '/images/default/corgidon.png';
1865 * @license GNU Affero General Public License v3.0
1866 * @link https://github.com/diaspora/diaspora/
1868 $default = '/images/default/diaspora.png';
1874 * @license GNU Affero General Public License v3.0
1875 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1877 $default = '/images/default/gotosocial.svg';
1883 * @license GNU Affero General Public License v3.0
1884 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1886 $default = '/images/default/hometown.png';
1892 * @license GNU Affero General Public License v3.0
1893 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1895 $default = '/images/default/koyuspace.png';
1903 * @license GNU Affero General Public License v3.0
1904 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1906 $default = '/images/default/mastodon.png';
1910 if ($type == Contact::TYPE_COMMUNITY) {
1913 * @license GNU Affero General Public License v3.0
1914 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
1916 $default = '/images/default/peertube-channel.png';
1920 * @license GNU Affero General Public License v3.0
1921 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
1923 $default = '/images/default/peertube-account.png';
1930 * @license GNU Affero General Public License v3.0
1931 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
1933 $default = '/images/default/pleroma.png';
1939 * @license GNU Affero General Public License v3.0
1940 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
1942 $default = '/images/default/plume.png';
1945 return DI::baseUrl() . $default;
1948 if (!empty($contact['xmpp'])) {
1949 $avatar['email'] = $contact['xmpp'];
1950 } elseif (!empty($contact['addr'])) {
1951 $avatar['email'] = $contact['addr'];
1952 } elseif (!empty($contact['url'])) {
1953 $avatar['email'] = $contact['url'];
1955 return DI::baseUrl() . $default;
1958 $avatar['url'] = '';
1959 $avatar['success'] = false;
1961 Hook::callAll('avatar_lookup', $avatar);
1963 if ($avatar['success'] && !empty($avatar['url'])) {
1964 return $avatar['url'];
1967 return DI::baseUrl() . $default;
1971 * Get avatar link for given contact id
1973 * @param integer $cid contact id
1974 * @param string $size One of the Proxy::SIZE_* constants
1975 * @param string $updated Contact update date
1976 * @return string avatar link
1978 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
1980 // We have to fetch the "updated" variable when it wasn't provided
1981 // The parameter can be provided to improve performance
1982 if (empty($updated)) {
1983 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1984 $updated = $account['updated'] ?? '';
1985 $guid = $account['guid'] ?? '';
1988 $guid = urlencode($guid);
1990 $url = DI::baseUrl() . '/photo/contact/';
1992 case Proxy::SIZE_MICRO:
1993 $url .= Proxy::PIXEL_MICRO . '/';
1995 case Proxy::SIZE_THUMB:
1996 $url .= Proxy::PIXEL_THUMB . '/';
1998 case Proxy::SIZE_SMALL:
1999 $url .= Proxy::PIXEL_SMALL . '/';
2001 case Proxy::SIZE_MEDIUM:
2002 $url .= Proxy::PIXEL_MEDIUM . '/';
2004 case Proxy::SIZE_LARGE:
2005 $url .= Proxy::PIXEL_LARGE . '/';
2008 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2012 * Get avatar link for given contact URL
2014 * @param string $url contact url
2015 * @param integer $uid user id
2016 * @param string $size One of the Proxy::SIZE_* constants
2017 * @return string avatar link
2019 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2021 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2022 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2023 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2024 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2028 * Get header link for given contact id
2030 * @param integer $cid contact id
2031 * @param string $size One of the Proxy::SIZE_* constants
2032 * @param string $updated Contact update date
2033 * @return string header link
2035 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2037 // We have to fetch the "updated" variable when it wasn't provided
2038 // The parameter can be provided to improve performance
2039 if (empty($updated) || empty($guid)) {
2040 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2041 $updated = $account['updated'] ?? '';
2042 $guid = $account['guid'] ?? '';
2045 $guid = urlencode($guid);
2047 $url = DI::baseUrl() . '/photo/header/';
2049 case Proxy::SIZE_MICRO:
2050 $url .= Proxy::PIXEL_MICRO . '/';
2052 case Proxy::SIZE_THUMB:
2053 $url .= Proxy::PIXEL_THUMB . '/';
2055 case Proxy::SIZE_SMALL:
2056 $url .= Proxy::PIXEL_SMALL . '/';
2058 case Proxy::SIZE_MEDIUM:
2059 $url .= Proxy::PIXEL_MEDIUM . '/';
2061 case Proxy::SIZE_LARGE:
2062 $url .= Proxy::PIXEL_LARGE . '/';
2066 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2070 * Updates the avatar links in a contact only if needed
2072 * @param int $cid Contact id
2073 * @param string $avatar Link to avatar picture
2074 * @param bool $force force picture update
2075 * @param bool $create_cache Enforces the creation of cached avatar fields
2078 * @throws HTTPException\InternalServerErrorException
2079 * @throws HTTPException\NotFoundException
2080 * @throws \ImagickException
2082 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2084 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2085 ['id' => $cid, 'self' => false]);
2086 if (!DBA::isResult($contact)) {
2090 $uid = $contact['uid'];
2092 // Only update the cached photo links of public contacts when they already are cached
2093 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2094 if ($contact['avatar'] != $avatar) {
2095 self::update(['avatar' => $avatar], ['id' => $cid]);
2096 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2101 // User contacts use are updated through the public contacts
2102 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2103 $pcid = self::getIdForURL($contact['url'], 0, false);
2104 if (!empty($pcid)) {
2105 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2106 self::updateAvatar($pcid, $avatar, $force, true);
2111 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2113 if ($default_avatar) {
2114 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2117 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2119 // Local contact avatars don't need to be cached
2120 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2121 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2124 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2125 Avatar::deleteCache($contact);
2127 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2128 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2130 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2131 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2132 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2135 // Use the data from the self account
2136 if (empty($fields)) {
2137 $local_uid = User::getIdForURL($contact['url']);
2138 if (!empty($local_uid)) {
2139 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2140 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2144 if (empty($fields)) {
2145 $update = ($contact['avatar'] != $avatar) || $force;
2149 $contact['photo'] ?? '',
2150 $contact['thumb'] ?? '',
2151 $contact['micro'] ?? '',
2154 foreach ($data as $image_uri) {
2155 $image_rid = Photo::ridFromURI($image_uri);
2156 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2157 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2164 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2166 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2167 $update = !empty($fields);
2168 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2174 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2177 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2178 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2179 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2188 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2189 // Collect all user contacts of the given public contact
2190 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2191 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2192 while ($personal_contact = DBA::fetch($personal_contacts)) {
2193 $cids[] = $personal_contact['id'];
2194 $uids[] = $personal_contact['uid'];
2196 DBA::close($personal_contacts);
2198 if (!empty($cids)) {
2199 // Delete possibly existing cached user contact avatars
2200 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2206 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2207 self::update($fields, ['id' => $cids]);
2210 public static function deleteContactByUrl(string $url)
2212 // Update contact data for all users
2213 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2214 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2215 while ($contact = DBA::fetch($contacts)) {
2216 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2217 self::remove($contact['id']);
2222 * Helper function for "updateFromProbe". Updates personal and public contact
2224 * @param integer $id contact id
2225 * @param integer $uid user id
2226 * @param string $old_url The previous profile URL of the contact
2227 * @param string $new_url The profile URL of the contact
2228 * @param array $fields The fields that are updated
2230 * @throws \Exception
2232 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
2234 if (!self::update($fields, ['id' => $id])) {
2235 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2239 // Search for duplicated contacts and get rid of them
2240 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
2244 // Archive or unarchive the contact.
2245 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2246 if (!DBA::isResult($contact)) {
2247 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2251 if (isset($fields['failed'])) {
2252 if ($fields['failed']) {
2253 self::markForArchival($contact);
2255 self::unmarkForArchival($contact);
2259 if ($contact['uid'] != 0) {
2263 // Update contact data for all users
2264 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
2266 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2267 self::update($fields, $condition);
2269 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2270 $condition['network'] = Protocol::OSTATUS;
2272 // If the contact failed, propagate the update fields to all contacts
2273 if (empty($fields['failed'])) {
2274 unset($fields['last-update']);
2275 unset($fields['success_update']);
2276 unset($fields['failure_update']);
2279 if (empty($fields)) {
2283 self::update($fields, $condition);
2287 * Remove duplicated contacts
2289 * @param string $nurl Normalised contact url
2290 * @param integer $uid User id
2292 * @throws \Exception
2294 public static function removeDuplicates(string $nurl, int $uid)
2296 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2297 $count = DBA::count('contact', $condition);
2302 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2303 if (!DBA::isResult($first_contact)) {
2304 // Shouldn't happen - so we handle it
2308 $first = $first_contact['id'];
2309 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2310 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2311 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2312 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2316 // Find all duplicates
2317 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2318 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2319 while ($duplicate = DBA::fetch($duplicates)) {
2320 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2324 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2326 DBA::close($duplicates);
2327 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2332 * Updates contact record by provided id and optional network
2334 * @param integer $id contact id
2335 * @param string $network Optional network we are probing for
2337 * @throws HTTPException\InternalServerErrorException
2338 * @throws \ImagickException
2340 public static function updateFromProbe(int $id, string $network = '')
2342 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2343 if (!DBA::isResult($contact)) {
2347 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2349 if ($ret['network'] == Protocol::DIASPORA) {
2350 FContact::updateFromProbeArray($ret);
2353 return self::updateFromProbeArray($id, $ret);
2357 * Checks if the given contact has got local data
2360 * @param array $contact
2364 private static function hasLocalData(int $id, array $contact): bool
2366 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2367 // User contacts with the same uri-id exist
2369 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2370 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2373 if (DBA::exists('post-tag', ['cid' => $id])) {
2374 // Is tagged in a post
2377 if (DBA::exists('user-contact', ['cid' => $id])) {
2378 // Has got user-contact data
2381 if (Post::exists(['author-id' => $id])) {
2382 // Posts with this author exist
2385 if (Post::exists(['owner-id' => $id])) {
2386 // Posts with this owner exist
2389 if (Post::exists(['causer-id' => $id])) {
2390 // Posts with this causer exist
2393 // We don't have got this contact locally
2398 * Updates contact record by provided id and probed data
2400 * @param integer $id contact id
2401 * @param array $ret Probed data
2403 * @throws HTTPException\InternalServerErrorException
2404 * @throws \ImagickException
2406 private static function updateFromProbeArray(int $id, array $ret): bool
2409 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2410 This will reliably kill your communication with old Friendica contacts.
2413 // These fields aren't updated by this routine:
2416 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2417 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2418 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2419 'created', 'last-update'];
2420 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2421 if (!DBA::isResult($contact)) {
2425 if (self::isLocal($ret['url'])) {
2426 if ($contact['uid'] == 0) {
2427 Logger::info('Local contacts are not updated here.');
2429 self::updateFromPublicContact($id, $contact);
2434 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2435 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2438 // Delete all contacts with the same URL
2439 self::deleteContactByUrl($ret['url']);
2443 $uid = $contact['uid'];
2444 unset($contact['uid']);
2446 $uriid = $contact['uri-id'];
2447 unset($contact['uri-id']);
2449 $pubkey = $contact['pubkey'];
2450 unset($contact['pubkey']);
2452 $created = $contact['created'];
2453 unset($contact['created']);
2455 $last_update = $contact['last-update'];
2456 unset($contact['last-update']);
2458 $contact['photo'] = $contact['avatar'];
2459 unset($contact['avatar']);
2461 $updated = DateTimeFormat::utcNow();
2463 $has_local_data = self::hasLocalData($id, $contact);
2465 if (!Probe::isProbable($ret['network'])) {
2466 // Periodical checks are only done on federated contacts
2467 $failed_next_update = null;
2468 $success_next_update = null;
2469 } elseif ($has_local_data) {
2470 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2471 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2473 $failed_next_update = DateTimeFormat::utc('now +6 month');
2474 $success_next_update = DateTimeFormat::utc('now +1 month');
2477 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2478 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2479 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2483 // We must not try to update relay contacts via probe. They are no real contacts.
2484 // We check after the probing to be able to correct falsely detected contact types.
2485 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2486 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2487 self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2488 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2492 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2493 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2494 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2498 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2499 $cid = self::getIdForURL($ret['url'], 0, false);
2500 if (!empty($cid) && ($cid != $id)) {
2501 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2502 return self::updateFromProbeArray($cid, $ret);
2506 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2507 $ret['unsearchable'] = $ret['hide'];
2510 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2511 $ret['forum'] = false;
2512 $ret['prv'] = false;
2513 $ret['contact-type'] = $ret['account-type'];
2514 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2515 $ret['forum'] = (bool)!$ret['manually-approve'];
2516 $ret['prv'] = (bool)!$ret['forum'];
2520 $new_pubkey = $ret['pubkey'] ?? '';
2522 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2523 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2524 $apcontact = APContact::getByURL($ret['url'], false);
2525 if (!empty($apcontact['featured'])) {
2526 Worker::add(PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2530 $ret['last-item'] = Probe::getLastUpdate($ret);
2531 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2535 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2537 // make sure to not overwrite existing values with blank entries except some technical fields
2538 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2539 foreach ($ret as $key => $val) {
2540 if (!array_key_exists($key, $contact)) {
2542 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2543 $ret[$key] = $contact[$key];
2544 } elseif ($ret[$key] != $contact[$key]) {
2549 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2552 unset($ret['last-item']);
2555 if (empty($uriid)) {
2559 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2560 self::updateAvatar($id, $ret['photo'], $update);
2563 $uriid = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2566 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2568 if (Contact\Relation::isDiscoverable($ret['url'])) {
2569 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2572 // Update the public contact
2574 $contact = self::getByURL($ret['url'], false, ['id']);
2575 if (!empty($contact['id'])) {
2576 self::updateFromProbeArray($contact['id'], $ret);
2583 $ret['uri-id'] = $uriid;
2584 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2585 $ret['updated'] = $updated;
2586 $ret['failed'] = false;
2587 $ret['next-update'] = $success_next_update;
2588 $ret['local-data'] = $has_local_data;
2590 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2591 if (empty($pubkey) && !empty($new_pubkey)) {
2592 $ret['pubkey'] = $new_pubkey;
2595 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2596 $ret['uri-date'] = $updated;
2599 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2600 $ret['name-date'] = $updated;
2603 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2604 $ret['last-update'] = $updated;
2605 $ret['success_update'] = $updated;
2608 unset($ret['photo']);
2610 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2612 if (Contact\Relation::isDiscoverable($ret['url'])) {
2613 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2619 private static function updateFromPublicContact(int $id, array $contact)
2621 $public = self::getByURL($contact['url'], false);
2625 foreach ($contact as $field => $value) {
2626 if ($field == 'uid') {
2629 if ($public[$field] != $value) {
2630 $fields[$field] = $public[$field];
2633 if (!empty($fields)) {
2634 self::update($fields, ['id' => $id, 'self' => false]);
2635 Logger::info('Updating local contact', ['id' => $id]);
2640 * Updates contact record by provided URL
2642 * @param integer $url contact url
2643 * @return integer Contact id
2644 * @throws HTTPException\InternalServerErrorException
2645 * @throws \ImagickException
2647 public static function updateFromProbeByURL(string $url): int
2649 $id = self::getIdForURL($url);
2655 self::updateFromProbe($id);
2661 * Detects the communication protocol for a given contact url.
2662 * This is used to detect Friendica contacts that we can communicate via AP.
2664 * @param string $url contact url
2665 * @param string $network Network of that contact
2666 * @return string with protocol
2668 public static function getProtocol(string $url, string $network): string
2670 if ($network != Protocol::DFRN) {
2674 $apcontact = APContact::getByURL($url);
2675 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2676 return Protocol::ACTIVITYPUB;
2683 * Takes a $uid and a url/handle and adds a new contact
2685 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2686 * dfrn_request page.
2688 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2691 * $return['success'] boolean true if successful
2692 * $return['message'] error text if success is false.
2694 * Takes a $uid and a url/handle and adds a new contact
2696 * @param int $uid The user id the contact should be created for
2697 * @param string $url The profile URL of the contact
2698 * @param string $network
2700 * @throws HTTPException\InternalServerErrorException
2701 * @throws HTTPException\NotFoundException
2702 * @throws \ImagickException
2704 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2706 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2708 // remove ajax junk, e.g. Twitter
2709 $url = str_replace('/#!/', '/', $url);
2711 if (!Network::isUrlAllowed($url)) {
2712 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2716 if (Network::isUrlBlocked($url)) {
2717 $result['message'] = DI::l10n()->t('Blocked domain');
2722 $result['message'] = DI::l10n()->t('Connect URL missing.');
2726 $arr = ['url' => $url, 'contact' => []];
2728 Hook::callAll('follow', $arr);
2731 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2735 if (!empty($arr['contact']['name'])) {
2737 $ret = $arr['contact'];
2740 $ret = Probe::uri($url, $network, $uid);
2742 // Ensure that the public contact exists
2743 if ($ret['network'] != Protocol::PHANTOM) {
2744 self::getIdForURL($url);
2748 if (($network != '') && ($ret['network'] != $network)) {
2749 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2753 // check if we already have a contact
2754 // the poll url is more reliable than the profile url, as we may have
2755 // indirect links or webfinger links
2757 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2758 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2759 if (!DBA::isResult($contact)) {
2760 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2761 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2764 $protocol = self::getProtocol($ret['url'], $ret['network']);
2766 // This extra param just confuses things, remove it
2767 if ($protocol === Protocol::DIASPORA) {
2768 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2771 // do we have enough information?
2772 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2773 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2774 if (empty($ret['poll'])) {
2775 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2777 if (empty($ret['name'])) {
2778 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2780 if (empty($ret['url'])) {
2781 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2783 if (strpos($ret['url'], '@') !== false) {
2784 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2785 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2790 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2791 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2792 $ret['notify'] = '';
2795 if (!$ret['notify']) {
2796 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2799 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2801 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2803 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2806 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2807 $pending = (bool)$ret['manually-approve'];
2810 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2814 if (DBA::isResult($contact)) {
2816 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2818 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2819 self::update($fields, ['id' => $contact['id']]);
2821 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2823 // create contact record
2826 'created' => DateTimeFormat::utcNow(),
2827 'url' => $ret['url'],
2828 'nurl' => Strings::normaliseLink($ret['url']),
2829 'addr' => $ret['addr'],
2830 'alias' => $ret['alias'],
2831 'batch' => $ret['batch'],
2832 'notify' => $ret['notify'],
2833 'poll' => $ret['poll'],
2834 'poco' => $ret['poco'],
2835 'name' => $ret['name'],
2836 'nick' => $ret['nick'],
2837 'network' => $ret['network'],
2838 'baseurl' => $ret['baseurl'],
2839 'gsid' => $ret['gsid'] ?? null,
2840 'protocol' => $protocol,
2841 'pubkey' => $ret['pubkey'],
2842 'rel' => $new_relation,
2843 'priority'=> $ret['priority'],
2844 'writable'=> $writeable,
2845 'hidden' => $hidden,
2848 'pending' => $pending,
2853 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2854 if (!DBA::isResult($contact)) {
2855 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2859 $contact_id = $contact['id'];
2860 $result['cid'] = $contact_id;
2862 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2864 // Update the avatar
2865 self::updateAvatar($contact_id, $ret['photo']);
2867 // pull feed and consume it, which should subscribe to the hub.
2868 if ($contact['network'] == Protocol::OSTATUS) {
2869 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2873 self::updateFromProbeArray($contact_id, $ret);
2875 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2878 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2884 * @param array $importer Owner (local user) data
2885 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2886 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2887 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2888 * @param string $note Introduction additional message
2889 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2890 * @throws HTTPException\InternalServerErrorException
2891 * @throws \ImagickException
2893 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
2895 // Should always be set
2896 if (empty($datarray['author-id'])) {
2900 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2901 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2902 if (!DBA::isResult($pub_contact)) {
2903 // Should never happen
2907 // Contact is blocked at node-level
2908 if (self::isBlocked($datarray['author-id'])) {
2912 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2913 $name = $pub_contact['name'];
2914 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2915 $nick = $pub_contact['nick'];
2916 $network = $pub_contact['network'];
2918 // Ensure that we don't create a new contact when there already is one
2919 $cid = self::getIdForURL($url, $importer['uid']);
2921 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2924 self::clearFollowerFollowingEndpointCache($importer['uid']);
2926 if (!empty($contact)) {
2927 if (!empty($contact['pending'])) {
2928 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2932 // Contact is blocked at user-level
2933 if (!empty($contact['id']) && !empty($importer['id']) &&
2934 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2938 // Make sure that the existing contact isn't archived
2939 self::unmarkForArchival($contact);
2941 if (($contact['rel'] == self::SHARING)
2942 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2943 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2944 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2947 // Ensure to always have the correct network type, independent from the connection request method
2948 self::updateFromProbe($contact['id']);
2950 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2954 // send email notification to owner?
2955 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2956 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
2960 // create contact record
2961 $contact_id = self::insert([
2962 'uid' => $importer['uid'],
2963 'created' => DateTimeFormat::utcNow(),
2965 'nurl' => Strings::normaliseLink($url),
2968 'network' => $network,
2969 'rel' => self::FOLLOWER,
2976 // Ensure to always have the correct network type, independent from the connection request method
2977 self::updateFromProbe($contact_id);
2979 self::updateAvatar($contact_id, $photo, true);
2981 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
2983 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2985 /// @TODO Encapsulate this into a function/method
2986 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2987 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2988 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2989 // create notification
2990 if (is_array($contact_record)) {
2991 $intro = DI::introFactory()->createNew(
2993 $contact_record['id'],
2996 DI::intro()->save($intro);
2999 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
3001 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3002 DI::notify()->createFromArray([
3003 'type' => Notification\Type::INTRO,
3004 'otype' => Notification\ObjectType::INTRO,
3005 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3006 'uid' => $user['uid'],
3007 'cid' => $contact_record['id'],
3008 'link' => DI::baseUrl() . '/notifications/intros',
3011 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3012 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3013 self::createFromProbeForUser($importer['uid'], $url, $network);
3016 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3017 $fields = ['pending' => false];
3018 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3019 $fields['rel'] = self::FRIEND;
3022 self::update($fields, $condition);
3032 * Update the local relationship when a local user loses a follower
3034 * @param array $contact User-specific contact (uid != 0) array
3036 * @throws HTTPException\InternalServerErrorException
3037 * @throws \ImagickException
3039 public static function removeFollower(array $contact)
3041 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3042 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3043 } elseif (!empty($contact['id'])) {
3044 self::remove($contact['id']);
3046 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3050 self::clearFollowerFollowingEndpointCache($contact['uid']);
3052 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3054 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3058 * Update the local relationship when a local user unfollow a contact.
3059 * Removes the contact for sharing-only protocols (feed and mail).
3061 * @param array $contact User-specific contact (uid != 0) array
3062 * @throws HTTPException\InternalServerErrorException
3064 public static function removeSharer(array $contact)
3066 self::clearFollowerFollowingEndpointCache($contact['uid']);
3068 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3069 self::remove($contact['id']);
3071 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3076 * Create a birthday event.
3078 * Update the year and the birthday.
3080 public static function updateBirthdays()
3084 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3085 AND NOT `contact`.`pending`
3086 AND NOT `contact`.`hidden`
3087 AND NOT `contact`.`blocked`
3088 AND NOT `contact`.`archive`
3089 AND NOT `contact`.`deleted`',
3095 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3097 while ($contact = DBA::fetch($contacts)) {
3098 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3100 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3102 if (Event::createBirthday($contact, $nextbd)) {
3106 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3107 ['id' => $contact['id']]
3111 DBA::close($contacts);
3115 * Remove the unavailable contact ids from the provided list
3117 * @param array $contact_ids Contact id list
3119 * @throws \Exception
3121 public static function pruneUnavailable(array $contact_ids): array
3123 if (empty($contact_ids)) {
3127 $contacts = self::selectToArray(['id'], [
3128 'id' => $contact_ids,
3134 return array_column($contacts, 'id');
3138 * Returns a magic link to authenticate remote visitors
3140 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3142 * @param string $contact_url The address of the target contact profile
3143 * @param string $url An url that we will be redirected to after the authentication
3145 * @return string with "redir" link
3146 * @throws HTTPException\InternalServerErrorException
3147 * @throws \ImagickException
3149 public static function magicLink(string $contact_url, string $url = ''): string
3151 if (!Session::isAuthenticated()) {
3152 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3155 $contact = self::getByURL($contact_url, false);
3156 if (empty($contact)) {
3157 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3160 // Prevents endless loop in case only a non-public contact exists for the contact URL
3161 unset($contact['uid']);
3163 return self::magicLinkByContact($contact, $url ?: $contact_url);
3167 * Returns a magic link to authenticate remote visitors
3169 * @param integer $cid The contact id of the target contact profile
3170 * @param string $url An url that we will be redirected to after the authentication
3172 * @return string with "redir" link
3173 * @throws HTTPException\InternalServerErrorException
3174 * @throws \ImagickException
3176 public static function magicLinkById(int $cid, string $url = ''): string
3178 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3180 return self::magicLinkByContact($contact, $url);
3184 * Returns a magic link to authenticate remote visitors
3186 * @param array $contact The contact array with "uid", "network" and "url"
3187 * @param string $url An url that we will be redirected to after the authentication
3189 * @return string with "redir" link
3190 * @throws HTTPException\InternalServerErrorException
3191 * @throws \ImagickException
3193 public static function magicLinkByContact(array $contact, string $url = ''): string
3195 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3197 if (!Session::isAuthenticated()) {
3198 return $destination;
3201 // Only redirections to the same host do make sense
3202 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3206 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
3207 return 'contact/' . $contact['id'] . '/conversations';
3210 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3211 return $destination;
3214 if (empty($contact['id'])) {
3215 return $destination;
3218 $redirect = 'redir/' . $contact['id'];
3220 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3221 $redirect .= '?url=' . $url;
3228 * Is the contact a forum?
3230 * @param integer $contactid ID of the contact
3232 * @return boolean "true" if it is a forum
3234 public static function isForum(int $contactid): bool
3236 $fields = ['contact-type'];
3237 $condition = ['id' => $contactid];
3238 $contact = DBA::selectFirst('contact', $fields, $condition);
3239 if (!DBA::isResult($contact)) {
3244 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3248 * Can the remote contact receive private messages?
3250 * @param array $contact
3253 public static function canReceivePrivateMessages(array $contact): bool
3255 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3256 $self = $contact['self'] ?? false;
3258 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3262 * Search contact table by nick or name
3264 * @param string $search Name or nick
3265 * @param string $mode Search mode (e.g. "community")
3266 * @param int $uid User ID
3268 * @return array with search results
3269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3271 public static function searchByName(string $search, string $mode = '', int $uid = 0): array
3273 if (empty($search)) {
3277 // check supported networks
3278 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3279 if (DI::config()->get('system', 'diaspora_enabled')) {
3280 $networks[] = Protocol::DIASPORA;
3283 if (!DI::config()->get('system', 'ostatus_disabled')) {
3284 $networks[] = Protocol::OSTATUS;
3287 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3290 $condition['blocked'] = false;
3293 // check if we search only communities or every contact
3294 if ($mode === 'community') {
3295 $condition['contact-type'] = self::TYPE_COMMUNITY;
3300 $condition = DBA::mergeConditions($condition,
3301 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3302 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3304 $contacts = self::selectToArray([], $condition);
3309 * Add public contacts from an array
3311 * @param array $urls
3312 * @return array result "count", "added" and "updated"
3314 public static function addByUrls(array $urls): array
3321 foreach ($urls as $url) {
3322 if (empty($url) || !is_string($url)) {
3325 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3326 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3327 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3329 } elseif (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3330 Worker::add(['priority' => PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
3338 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3342 * Returns a random, global contact array of the current node
3344 * @return array The profile array
3347 public static function getRandomContact(): array
3349 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3350 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3351 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3352 ], ['order' => ['RAND()']]);
3354 if (DBA::isResult($contact)) {