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\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\Database;
35 use Friendica\Database\DBA;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\Images;
43 use Friendica\Util\Network;
44 use Friendica\Util\Proxy;
45 use Friendica\Util\Strings;
48 * functions for interacting with a contact
52 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
53 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
54 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
60 const LOCK_INSERT = 'contact-insert';
65 * TYPE_UNKNOWN - unknown type
67 * TYPE_PERSON - the account belongs to a person
68 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
70 * TYPE_ORGANISATION - the account belongs to an organisation
71 * Associated page type: PAGE_SOAPBOX
73 * TYPE_NEWS - the account is a news reflector
74 * Associated page type: PAGE_SOAPBOX
76 * TYPE_COMMUNITY - the account is community forum
77 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
79 * TYPE_RELAY - the account is a relay
80 * This will only be assigned to contacts, not to user accounts
83 const TYPE_UNKNOWN = -1;
84 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
85 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
86 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
87 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
88 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
99 const NOTHING = 0; // There is no relationship between the contact and the user
100 const FOLLOWER = 1; // The contact is following this user (the contact is the subscriber)
101 const SHARING = 2; // The contact shares their content with this user (the user is the subscriber)
102 const FRIEND = 3; // There is a mutual relationship between the contact and the user
103 const SELF = 4; // This is the user theirself
108 const MIRROR_DEACTIVATED = 0;
109 const MIRROR_FORWARDED = 1; // Deprecated, now does the same like MIRROR_OWN_POST
110 const MIRROR_OWN_POST = 2;
111 const MIRROR_NATIVE_RESHARE = 3;
114 * @param array $fields Array of selected fields, empty for all
115 * @param array $condition Array of fields for condition
116 * @param array $params Array of several parameters
120 public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
122 return DBA::selectToArray('contact', $fields, $condition, $params);
126 * @param array $fields Array of selected fields, empty for all
127 * @param array $condition Array of fields for condition
128 * @param array $params Array of several parameters
132 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
134 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
140 * @param array $fields Array of selected fields, empty for all
141 * @param array $condition Array of fields for condition
142 * @param array $params Array of several parameters
146 public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
148 return DBA::selectToArray('account-user-view', $fields, $condition, $params);
152 * @param array $fields Array of selected fields, empty for all
153 * @param array $condition Array of fields for condition
154 * @param array $params Array of several parameters
158 public static function selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
160 return DBA::selectFirst('account-view', $fields, $condition, $params);
164 * Insert a row into the contact table
165 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
167 * @param array $fields field array
168 * @param int $duplicate_mode Do an update on a duplicate entry
170 * @return int id of the created contact
173 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
175 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
176 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
179 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
181 if (empty($fields['created'])) {
182 $fields['created'] = DateTimeFormat::utcNow();
185 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
186 DBA::insert('contact', $fields, $duplicate_mode);
187 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
188 if (!DBA::isResult($contact)) {
190 Logger::warning('Created contact could not be found', ['fields' => $fields]);
194 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
195 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
196 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
197 if (empty($account_user['id'])) {
198 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
199 } elseif ($account_user['id'] != $contact['id']) {
200 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
201 if (!empty($duplicate['id'])) {
202 $ret = Contact::deleteById($contact['id']);
203 Logger::notice('Deleted duplicated contact', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $duplicate['id'], 'uid' => $duplicate['uid'], 'uri-id' => $duplicate['uri-id'], 'url' => $duplicate['url']]);
204 $contact = $duplicate;
206 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
207 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
211 Contact\User::insertForContactArray($contact);
213 return $contact['id'];
217 * Delete contact by id
222 public static function deleteById(int $id): bool
224 Logger::debug('Delete contact', ['id' => $id]);
225 DBA::delete('account-user', ['id' => $id]);
226 return DBA::delete('contact', ['id' => $id]);
230 * Updates rows in the contact table
232 * @param array $fields contains the fields that are updated
233 * @param array $condition condition array with the key values
234 * @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)
236 * @return boolean was the update successfull?
238 * @todo Let's get rid of boolean type of $old_fields
240 public static function update(array $fields, array $condition, $old_fields = [])
242 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
243 $ret = DBA::update('contact', $fields, $condition, $old_fields);
245 // Apply changes to the "user-contact" table on dedicated fields
246 Contact\User::updateByContactUpdate($fields, $condition);
252 * @param integer $id Contact ID
253 * @param array $fields Array of selected fields, empty for all
254 * @return array|boolean Contact record if it exists, false otherwise
257 public static function getById(int $id, array $fields = [])
259 return DBA::selectFirst('contact', $fields, ['id' => $id]);
263 * Fetch the first contact with the provided uri-id.
265 * @param integer $uri_id uri-id of the contact
266 * @param array $fields Array of selected fields, empty for all
267 * @return array|boolean Contact record if it exists, false otherwise
270 public static function getByUriId(int $uri_id, array $fields = [])
272 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
276 * Fetch all remote contacts for a given contact url
278 * @param string $url The URL of the contact
279 * @param array $fields The wanted fields
281 * @return array all remote contacts
285 public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
289 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
290 while ($contact = DBA::fetch($remote_contacts)) {
291 if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
294 $remote[$contact['uid']] = $contact['id'];
296 DBA::close($remote_contacts);
302 * Fetches a contact by a given url
304 * @param string $url profile url
305 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
306 * @param array $fields Field list
307 * @param integer $uid User ID of the contact
308 * @return array contact array
310 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
312 if ($update || is_null($update)) {
313 $cid = self::getIdForURL($url, $uid, $update);
318 $contact = self::getById($cid, $fields);
319 if (empty($contact)) {
325 // Add internal fields
327 if (!empty($fields)) {
328 foreach (['id', 'next-update', 'network'] as $internal) {
329 if (!in_array($internal, $fields)) {
330 $fields[] = $internal;
331 $removal[] = $internal;
336 // We first try the nurl (http://server.tld/nick), most common case
337 $options = ['order' => ['id']];
338 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
340 // Then the addr (nick@server.tld)
341 if (!DBA::isResult($contact)) {
342 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
345 // Then the alias (which could be anything)
346 if (!DBA::isResult($contact)) {
347 // The link could be provided as http although we stored it as https
348 $ssl_url = str_replace('http://', 'https://', $url);
349 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
350 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
353 if (!DBA::isResult($contact)) {
357 // Update the contact in the background if needed
358 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
359 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
362 // Remove the internal fields
363 foreach ($removal as $internal) {
364 unset($contact[$internal]);
371 * Fetches a contact for a given user by a given url.
372 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
374 * @param string $url profile url
375 * @param integer $uid User ID of the contact
376 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
377 * @param array $fields Field list
378 * @return array contact array
380 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
383 $contact = self::getByURL($url, $update, $fields, $uid);
384 if (!empty($contact)) {
385 if (!empty($contact['id'])) {
386 $contact['cid'] = $contact['id'];
393 $contact = self::getByURL($url, $update, $fields);
394 if (!empty($contact['id'])) {
396 $contact['zid'] = $contact['id'];
402 * Checks if a contact uses a specific platform
405 * @param string $platform
408 public static function isPlatform(string $url, string $platform): bool
410 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
414 * Tests if the given contact is a follower
416 * @param int $cid Either public contact id or user's contact id
417 * @param int $uid User ID
418 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
420 * @return boolean is the contact id a follower?
421 * @throws HTTPException\InternalServerErrorException
422 * @throws \ImagickException
424 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
426 if (Contact\User::isBlocked($cid, $uid)) {
430 $cdata = self::getPublicAndUserContactID($cid, $uid);
431 if (empty($cdata['user'])) {
435 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
437 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
439 return DBA::exists('contact', $condition);
443 * Tests if the given contact url is a follower
445 * @param string $url Contact URL
446 * @param int $uid User ID
447 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
449 * @return boolean is the contact id a follower?
450 * @throws HTTPException\InternalServerErrorException
451 * @throws \ImagickException
453 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
455 $cid = self::getIdForURL($url, $uid);
461 return self::isFollower($cid, $uid, $strict);
465 * Tests if the given user shares with the given contact
467 * @param int $cid Either public contact id or user's contact id
468 * @param int $uid User ID
469 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
471 * @return boolean is the contact sharing with given user?
472 * @throws HTTPException\InternalServerErrorException
473 * @throws \ImagickException
475 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
477 if (Contact\User::isBlocked($cid, $uid)) {
481 $cdata = self::getPublicAndUserContactID($cid, $uid);
482 if (empty($cdata['user'])) {
486 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
488 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
490 return DBA::exists('contact', $condition);
494 * Tests if the given user follow the given contact url
496 * @param string $url Contact URL
497 * @param int $uid User ID
498 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
500 * @return boolean is the contact url being followed?
501 * @throws HTTPException\InternalServerErrorException
502 * @throws \ImagickException
504 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
506 $cid = self::getIdForURL($url, $uid);
512 return self::isSharing($cid, $uid, $strict);
516 * Get the basepath for a given contact link
518 * @param string $url The contact link
519 * @param boolean $dont_update Don't update the contact
521 * @return string basepath
522 * @throws HTTPException\InternalServerErrorException
523 * @throws \ImagickException
525 public static function getBasepath(string $url, bool $dont_update = false): string
527 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
528 if (!DBA::isResult($contact)) {
532 if (!empty($contact['baseurl'])) {
533 return $contact['baseurl'];
534 } elseif ($dont_update) {
538 // Update the existing contact
539 self::updateFromProbe($contact['id']);
541 // And fetch the result
542 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
543 if (empty($contact['baseurl'])) {
544 Logger::info('No baseurl for contact', ['url' => $url]);
548 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
549 return $contact['baseurl'];
553 * Check if the given contact url is on the same server
555 * @param string $url The contact link
557 * @return boolean Is it the same server?
559 public static function isLocal(string $url): bool
561 if (!parse_url($url, PHP_URL_SCHEME)) {
562 $addr_parts = explode('@', $url);
563 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
566 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
570 * Check if the given contact ID is on the same server
572 * @param string $url The contact link
573 * @return boolean Is it the same server?
575 public static function isLocalById(int $cid): bool
577 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
578 if (!DBA::isResult($contact)) {
582 if (empty($contact['baseurl'])) {
583 $baseurl = self::getBasepath($contact['url'], true);
585 $baseurl = $contact['baseurl'];
588 return Strings::compareLink($baseurl, DI::baseUrl());
592 * Returns the public contact id of the given user id
594 * @param integer $uid User ID
596 * @return integer|boolean Public contact id for given user id
599 public static function getPublicIdByUserId(int $uid)
601 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
602 if (!DBA::isResult($self)) {
605 return self::getIdForURL($self['url']);
609 * Returns the contact id for the user and the public contact id for a given contact id
611 * @param int $cid Either public contact id or user's contact id
612 * @param int $uid User ID
614 * @return array with public and user's contact id
615 * @throws HTTPException\InternalServerErrorException
616 * @throws \ImagickException
618 public static function getPublicAndUserContactID(int $cid, int $uid): array
620 // We have to use the legacy function as long as the post update hasn't finished
621 if (DI::config()->get('system', 'post_update_version') < 1427) {
622 return self::legacyGetPublicAndUserContactID($cid, $uid);
625 if (empty($uid) || empty($cid)) {
629 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
630 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
634 $pcid = $contact['pid'];
635 if ($contact['uid'] == $uid) {
636 $ucid = $contact['id'];
638 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
639 if (DBA::isResult($contact)) {
640 $ucid = $contact['id'];
646 return ['public' => $pcid, 'user' => $ucid];
650 * Helper function for "getPublicAndUserContactID"
652 * @param int $cid Either public contact id or user's contact id
653 * @param int $uid User ID
654 * @return array with public and user's contact id
655 * @throws HTTPException\InternalServerErrorException
656 * @throws \ImagickException
658 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
660 if (empty($uid) || empty($cid)) {
664 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
665 if (!DBA::isResult($contact)) {
669 // We quit when the user id don't match the user id of the provided contact
670 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
674 if ($contact['uid'] != 0) {
675 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
679 $ucid = $contact['id'];
681 $pcid = $contact['id'];
682 $ucid = self::getIdForURL($contact['url'], $uid);
685 return ['public' => $pcid, 'user' => $ucid];
689 * Returns contact details for a given contact id in combination with a user id
691 * @param int $cid A contact ID
692 * @param int $uid The User ID
693 * @param array $fields The selected fields for the contact
694 * @return array The contact details
698 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
700 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
702 if (!DBA::isResult($contact)) {
710 * Creates the self-contact for the provided user id
713 * @return bool Operation success
714 * @throws HTTPException\InternalServerErrorException
716 public static function createSelfFromUserId(int $uid): bool
718 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
719 ['uid' => $uid, 'account_expired' => false]);
720 if (!DBA::isResult($user)) {
725 'uid' => $user['uid'],
726 'created' => DateTimeFormat::utcNow(),
728 'name' => $user['username'],
729 'nick' => $user['nickname'],
730 'pubkey' => $user['pubkey'],
731 'prvkey' => $user['prvkey'],
732 'photo' => User::getAvatarUrl($user),
733 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
734 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
737 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
738 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
739 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
740 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
741 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
742 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
743 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
744 'name-date' => DateTimeFormat::utcNow(),
745 'uri-date' => DateTimeFormat::utcNow(),
746 'avatar-date' => DateTimeFormat::utcNow(),
752 // Only create the entry if it doesn't exist yet
753 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
754 $return = (bool)self::insert($contact);
757 // Create the public contact
758 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
759 $contact['self'] = false;
761 $contact['prvkey'] = null;
763 self::insert($contact, Database::INSERT_IGNORE);
770 * Updates the self-contact for the provided user id
773 * @param bool $update_avatar Force the avatar update
774 * @return bool "true" if updated
775 * @throws HTTPException\InternalServerErrorException
777 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
779 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
780 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
781 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
782 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
783 if (!DBA::isResult($self)) {
787 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
788 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
789 if (!DBA::isResult($user)) {
793 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
794 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
795 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
796 if (!DBA::isResult($profile)) {
800 $file_suffix = 'jpg';
801 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
804 'name' => $profile['name'],
805 'nick' => $user['nickname'],
806 'avatar-date' => $self['avatar-date'],
807 'location' => Profile::formatLocation($profile),
808 'about' => $profile['about'],
809 'keywords' => $profile['pub_keywords'],
810 'contact-type' => $user['account-type'],
811 'prvkey' => $user['prvkey'],
812 'pubkey' => $user['pubkey'],
813 'xmpp' => $profile['xmpp'],
814 'matrix' => $profile['matrix'],
815 'network' => Protocol::DFRN,
817 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
818 'nurl' => Strings::normaliseLink($url),
819 'uri-id' => ItemURI::getIdByURI($url),
820 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
821 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
822 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
823 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
824 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
828 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
829 if (DBA::isResult($avatar)) {
830 if ($update_avatar) {
831 $fields['avatar-date'] = DateTimeFormat::utcNow();
834 // Creating the path to the avatar, beginning with the file suffix
835 $types = Images::supportedTypes();
836 if (isset($types[$avatar['type']])) {
837 $file_suffix = $types[$avatar['type']];
840 // We are adding a timestamp value so that other systems won't use cached content
841 $timestamp = strtotime($fields['avatar-date']);
843 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
844 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
846 $fields['photo'] = $prefix . '4' . $suffix;
847 $fields['thumb'] = $prefix . '5' . $suffix;
848 $fields['micro'] = $prefix . '6' . $suffix;
850 // We hadn't found a photo entry, so we use the default avatar
851 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
852 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
853 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
856 $fields['avatar'] = User::getAvatarUrl($user);
857 $fields['header'] = User::getBannerUrl($user);
858 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
859 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
860 $fields['unsearchable'] = !$profile['net-publish'];
861 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
865 foreach ($fields as $field => $content) {
866 if ($self[$field] != $content) {
872 if ($fields['name'] != $self['name']) {
873 $fields['name-date'] = DateTimeFormat::utcNow();
875 $fields['updated'] = DateTimeFormat::utcNow();
876 self::update($fields, ['id' => $self['id']]);
878 // Update the other contacts as well
879 unset($fields['prvkey']);
880 $fields['self'] = false;
881 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
883 // Update the profile
885 'photo' => User::getAvatarUrl($user),
886 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
889 DBA::update('profile', $fields, ['uid' => $uid]);
896 * Marks a contact for removal
898 * @param int $id contact id
900 * @throws HTTPException\InternalServerErrorException
902 public static function remove(int $id)
904 // We want just to make sure that we don't delete our "self" contact
905 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
906 if (!DBA::isResult($contact)) {
910 DBA::delete('account-user', ['id' => $id]);
912 self::clearFollowerFollowingEndpointCache($contact['uid']);
914 // Archive the contact
915 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'rel' => self::NOTHING, 'deleted' => true], ['id' => $id]);
917 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
918 Avatar::deleteCache($contact);
921 // Delete it in the background
922 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
926 * Unfollow the remote contact
928 * @param array $contact Target user-specific contact (uid != 0) array
930 * @throws HTTPException\InternalServerErrorException
931 * @throws \ImagickException
933 public static function unfollow(array $contact): void
935 if (empty($contact['network'])) {
936 throw new \InvalidArgumentException('Empty network in contact array');
939 if (empty($contact['uid'])) {
940 throw new \InvalidArgumentException('Unexpected public contact record');
943 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
944 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
945 if (!empty($cdata['public'])) {
946 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
950 self::removeSharer($contact);
954 * Revoke follow privileges of the remote user contact
956 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
958 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
960 * @throws HTTPException\InternalServerErrorException
961 * @throws \ImagickException
963 public static function revokeFollow(array $contact): void
965 if (empty($contact['network'])) {
966 throw new \InvalidArgumentException('Empty network in contact array');
969 if (empty($contact['uid'])) {
970 throw new \InvalidArgumentException('Unexpected public contact record');
973 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
974 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
975 if (!empty($cdata['public'])) {
976 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
980 self::removeFollower($contact);
984 * Completely severs a relationship with a contact
986 * @param array $contact User-specific contact (uid != 0) array
988 * @throws HTTPException\InternalServerErrorException
989 * @throws \ImagickException
991 public static function terminateFriendship(array $contact)
993 if (empty($contact['network'])) {
994 throw new \InvalidArgumentException('Empty network in contact array');
997 if (empty($contact['uid'])) {
998 throw new \InvalidArgumentException('Unexpected public contact record');
1001 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
1003 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
1004 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
1007 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
1008 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1011 self::remove($contact['id']);
1014 private static function clearFollowerFollowingEndpointCache(int $uid)
1020 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1021 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1025 * Marks a contact for archival after a communication issue delay
1027 * Contact has refused to recognise us as a friend. We will start a countdown.
1028 * If they still don't recognise us in 32 days, the relationship is over,
1029 * and we won't waste any more time trying to communicate with them.
1030 * This provides for the possibility that their database is temporarily messed
1031 * up or some other transient event and that there's a possibility we could recover from it.
1033 * @param array $contact contact to mark for archival
1035 * @throws HTTPException\InternalServerErrorException
1037 public static function markForArchival(array $contact)
1039 if (!isset($contact['url']) && !empty($contact['id'])) {
1040 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1041 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1042 if (!DBA::isResult($contact)) {
1045 } elseif (!isset($contact['url'])) {
1046 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1049 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1051 // Contact already archived or "self" contact? => nothing to do
1052 if ($contact['archive'] || $contact['self']) {
1056 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1057 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1058 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1061 * We really should send a notification to the owner after 2-3 weeks
1062 * so they won't be surprised when the contact vanishes and can take
1063 * remedial action if this was a serious mistake or glitch
1066 /// @todo Check for contact vitality via probing
1067 $archival_days = DI::config()->get('system', 'archival_days', 32);
1069 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1070 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1071 /* Relationship is really truly dead. archive them rather than
1072 * delete, though if the owner tries to unarchive them we'll start
1073 * the whole process over again.
1075 self::update(['archive' => true], ['id' => $contact['id']]);
1076 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1082 * Cancels the archival countdown
1084 * @see Contact::markForArchival()
1086 * @param array $contact contact to be unmarked for archival
1088 * @throws \Exception
1090 public static function unmarkForArchival(array $contact)
1092 // Always unarchive the relay contact entry
1093 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1094 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1095 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1096 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1097 self::update($fields, $condition);
1101 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1102 $exists = DBA::exists('contact', $condition);
1104 // We don't need to update, we never marked this contact for archival
1109 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1111 if (!isset($contact['url']) && !empty($contact['id'])) {
1112 $fields = ['id', 'url', 'batch'];
1113 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1114 if (!DBA::isResult($contact)) {
1119 // It's a miracle. Our dead contact has inexplicably come back to life.
1120 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1121 self::update($fields, ['id' => $contact['id']]);
1122 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1126 * Returns the data array for the photo menu of a given contact
1128 * @param array $contact contact
1129 * @param int $uid optional, default 0
1131 * @throws HTTPException\InternalServerErrorException
1132 * @throws \ImagickException
1134 public static function photoMenu(array $contact, int $uid = 0): array
1141 $uid = DI::userSession()->getLocalUserId();
1144 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1146 $profile_link = self::magicLinkByContact($contact);
1147 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1152 // Look for our own contact if the uid doesn't match and isn't public
1153 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1154 if (DBA::isResult($contact_own)) {
1155 return self::photoMenu($contact_own, $uid);
1160 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1162 $profile_link = 'contact/redir/' . $contact['id'];
1164 $profile_link = $contact['url'];
1167 if ($profile_link === 'mailbox') {
1172 $status_link = $profile_link . '/status';
1173 $photos_link = $profile_link . '/photos';
1174 $profile_link = $profile_link . '/profile';
1177 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1178 $pm_url = 'message/new/' . $contact['id'];
1181 $contact_url = 'contact/' . $contact['id'];
1183 $posts_link = 'contact/' . $contact['id'] . '/conversations';
1186 $unfollow_link = '';
1187 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1188 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1189 $unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1190 } elseif(!$contact['pending']) {
1191 $follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
1197 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1199 if (empty($contact['uid'])) {
1201 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1202 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1203 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1204 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1205 'unfollow'=> [DI::l10n()->t('Unfollow') , $unfollow_link, true],
1209 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1210 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1211 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1212 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1213 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1214 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1215 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1216 'unfollow'=> [DI::l10n()->t('Unfollow') , $unfollow_link , true],
1219 if (!empty($contact['pending'])) {
1221 $intro = DI::intro()->selectForContact($contact['id']);
1222 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1223 } catch (IntroductionNotFoundException $exception) {
1224 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1229 $args = ['contact' => $contact, 'menu' => &$menu];
1231 Hook::callAll('contact_photo_menu', $args);
1233 $menucondensed = [];
1235 foreach ($menu as $menuname => $menuitem) {
1236 if ($menuitem[1] != '') {
1237 $menucondensed[$menuname] = $menuitem;
1241 return $menucondensed;
1245 * Fetch the contact id for a given URL and user
1247 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1248 * `addr` or `alias`.
1250 * If there's no record and we aren't looking for a public contact, we quit.
1251 * If there's one, we check that it isn't time to update the picture else we
1252 * directly return the found contact id.
1254 * Second, we probe the provided $url whether it's http://server.tld/profile or
1255 * nick@server.tld. We quit if we can't get any info back.
1257 * Third, we create the contact record if it doesn't exist
1259 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1260 * if there's any updates
1262 * @param string $url Contact URL
1263 * @param integer $uid The user id for the contact (0 = public contact)
1264 * @param boolean $update true = always update, false = never update, null = update when not found
1265 * @param array $default Default value for creating the contact when everything else fails
1267 * @return integer Contact ID
1268 * @throws HTTPException\InternalServerErrorException
1269 * @throws \ImagickException
1271 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1276 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1280 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
1282 if (!empty($contact)) {
1283 $contact_id = $contact['id'];
1285 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1286 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
1289 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1290 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1293 } elseif ($uid != 0) {
1294 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1296 } elseif (empty($default) && !is_null($update) && !$update) {
1297 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1303 if (empty($default['network']) || $update) {
1304 $data = Probe::uri($url, '', $uid);
1306 // Take the default values when probing failed
1307 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1308 $data = array_merge($data, $default);
1310 } elseif (!empty($default['network'])) {
1314 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1315 // Fetch data for the public contact via the first found personal contact
1316 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1317 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1318 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1319 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1321 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1322 if (!DBA::isResult($personal_contact)) {
1323 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1326 if (DBA::isResult($personal_contact)) {
1327 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1328 $data = $personal_contact;
1329 $data['photo'] = $personal_contact['avatar'];
1330 $data['account-type'] = $personal_contact['contact-type'];
1331 $data['hide'] = $personal_contact['unsearchable'];
1332 unset($data['avatar']);
1333 unset($data['contact-type']);
1334 unset($data['unsearchable']);
1338 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1339 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1343 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1344 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1349 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1350 if (!empty($data['alias'])) {
1351 $urls[] = Strings::normaliseLink($data['alias']);
1353 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1354 if (!empty($contact['id'])) {
1355 $contact_id = $contact['id'];
1356 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1361 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1364 'url' => $data['url'],
1365 'nurl' => Strings::normaliseLink($data['url']),
1366 'network' => $data['network'],
1367 'created' => DateTimeFormat::utcNow(),
1368 'rel' => self::SHARING,
1375 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1377 // Before inserting we do check if the entry does exist now.
1378 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1379 if (DBA::isResult($contact)) {
1380 $contact_id = $contact['id'];
1381 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1383 $contact_id = self::insert($fields);
1385 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1390 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1394 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1397 if ($data['network'] == Protocol::DIASPORA) {
1398 FContact::updateFromProbeArray($data);
1401 self::updateFromProbeArray($contact_id, $data);
1403 // Don't return a number for a deleted account
1404 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1405 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1413 * Checks if the contact is archived
1415 * @param int $cid contact id
1417 * @return boolean Is the contact archived?
1418 * @throws HTTPException\InternalServerErrorException
1420 public static function isArchived(int $cid): bool
1426 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1427 if (!DBA::isResult($contact)) {
1431 if ($contact['archive']) {
1435 // Check status of ActivityPub endpoints
1436 $apcontact = APContact::getByURL($contact['url'], false);
1437 if (!empty($apcontact)) {
1438 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1442 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1447 // Check status of Diaspora endpoints
1448 if (!empty($contact['batch'])) {
1449 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1450 return DBA::exists('contact', $condition);
1457 * Checks if the contact is blocked
1459 * @param int $cid contact id
1460 * @return boolean Is the contact blocked?
1461 * @throws HTTPException\InternalServerErrorException
1463 public static function isBlocked(int $cid): bool
1469 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1470 if (!DBA::isResult($blocked)) {
1474 if (Network::isUrlBlocked($blocked['url'])) {
1478 return (bool) $blocked['blocked'];
1482 * Checks if the contact is hidden
1484 * @param int $cid contact id
1485 * @return boolean Is the contact hidden?
1486 * @throws \Exception
1488 public static function isHidden(int $cid): bool
1494 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1495 if (!DBA::isResult($hidden)) {
1498 return (bool) $hidden['hidden'];
1502 * Returns posts from a given contact url
1504 * @param string $contact_url Contact URL
1505 * @param bool $thread_mode
1506 * @param int $update Update mode
1507 * @param int $parent Item parent ID for the update mode
1508 * @param bool $only_media Only display media content
1509 * @return string posts in HTML
1510 * @throws \Exception
1512 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1514 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1518 * Returns posts from a given contact id
1520 * @param int $cid Contact ID
1521 * @param bool $thread_mode
1522 * @param int $update Update mode
1523 * @param int $parent Item parent ID for the update mode
1524 * @param bool $only_media Only display media content
1525 * @return string posts in HTML
1526 * @throws \Exception
1528 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1530 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1531 if (!DBA::isResult($contact)) {
1535 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1536 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1541 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1544 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1545 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), DI::userSession()->getLocalUserId()];
1547 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1548 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
1551 if (!empty($parent)) {
1552 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1554 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1555 if (!empty($last_received)) {
1556 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1561 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1562 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1565 if (DI::mode()->isMobile()) {
1566 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
1567 DI::config()->get('system', 'itemspage_network_mobile'));
1569 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
1570 DI::config()->get('system', 'itemspage_network'));
1573 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1575 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1577 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1578 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1579 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1585 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1586 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1588 if ($pager->getStart() == 0) {
1589 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1590 if (!empty($cdata['public'])) {
1591 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1592 $items = array_merge($items, $pinned);
1596 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1598 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1599 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1601 if ($pager->getStart() == 0) {
1602 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1603 if (!empty($cdata['public'])) {
1604 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1605 $cdata['public'], Post\Collection::FEATURED];
1606 $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1607 $items = array_merge($pinned, $items);
1611 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1615 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1616 $o .= HTML::scrollLoader();
1618 $o .= $pager->renderMinimal(count($items));
1626 * Returns the account type name
1628 * The function can be called with either the user or the contact array
1630 * @param int $type type of contact or account
1633 public static function getAccountType(int $type): string
1636 case self::TYPE_ORGANISATION:
1637 $account_type = DI::l10n()->t("Organisation");
1640 case self::TYPE_NEWS:
1641 $account_type = DI::l10n()->t('News');
1644 case self::TYPE_COMMUNITY:
1645 $account_type = DI::l10n()->t("Forum");
1653 return $account_type;
1659 * @param int $cid Contact id to block
1660 * @param string $reason Block reason
1661 * @return bool Whether it was successful
1663 public static function block(int $cid, string $reason = null): bool
1665 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1671 * Unblocks a contact
1673 * @param int $cid Contact id to unblock
1674 * @return bool Whether it was successfull
1676 public static function unblock(int $cid): bool
1678 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1684 * Ensure that cached avatar exist
1686 * @param integer $cid Contact id
1688 public static function checkAvatarCache(int $cid)
1690 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1691 if (!DBA::isResult($contact)) {
1695 if (Network::isLocalLink($contact['url'])) {
1699 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1700 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1701 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1702 self::updateAvatar($cid, $contact['avatar'], true);
1705 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1706 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1707 self::updateAvatar($cid, $contact['avatar'], true);
1709 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1710 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1711 self::updateAvatar($cid, $contact['avatar'], true);
1717 * Return the photo path for a given contact array in the given size
1719 * @param array $contact contact array
1720 * @param string $size Size of the avatar picture
1721 * @param bool $no_update Don't perfom an update if no cached avatar was found
1722 * @return string photo path
1724 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1726 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1728 if (DI::config()->get('system', 'avatar_cache')) {
1730 case Proxy::SIZE_MICRO:
1731 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1732 return $contact['micro'];
1735 case Proxy::SIZE_THUMB:
1736 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1737 return $contact['thumb'];
1740 case Proxy::SIZE_SMALL:
1741 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1742 return $contact['photo'];
1748 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1752 * Return the photo path for a given contact array
1754 * @param array $contact Contact array
1755 * @param bool $no_update Don't perfom an update if no cached avatar was found
1756 * @return string photo path
1758 public static function getPhoto(array $contact, bool $no_update = false): string
1760 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1764 * Return the photo path (thumb size) for a given contact array
1766 * @param array $contact Contact array
1767 * @param bool $no_update Don't perfom an update if no cached avatar was found
1768 * @return string photo path
1770 public static function getThumb(array $contact, bool $no_update = false): string
1772 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1776 * Return the photo path (micro size) for a given contact array
1778 * @param array $contact Contact array
1779 * @param bool $no_update Don't perfom an update if no cached avatar was found
1780 * @return string photo path
1782 public static function getMicro(array $contact, bool $no_update = false): string
1784 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1788 * Check the given contact array for avatar cache fields
1790 * @param array $contact
1791 * @param bool $no_update Don't perfom an update if no cached avatar was found
1792 * @return array contact array with avatar cache fields
1794 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1797 $contact_fields = [];
1798 $fields = ['photo', 'thumb', 'micro'];
1799 foreach ($fields as $field) {
1800 if (isset($contact[$field])) {
1801 $contact_fields[] = $field;
1803 if (isset($contact[$field]) && empty($contact[$field])) {
1808 if (!$update || $no_update) {
1812 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1814 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1815 self::updateAvatar($contact['id'], $contact['avatar'], true);
1817 $new_contact = self::getById($contact['id'], $contact_fields);
1818 if (DBA::isResult($new_contact)) {
1819 // We only update the cache fields
1820 $contact = array_merge($contact, $new_contact);
1822 } elseif ($local && !empty($contact['avatar'])) {
1826 /// add the default avatars if the fields aren't filled
1827 if (isset($contact['photo']) && empty($contact['photo'])) {
1828 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1830 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1831 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1833 if (isset($contact['micro']) && empty($contact['micro'])) {
1834 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1841 * Fetch the default header for the given contact
1843 * @param array $contact contact array
1844 * @return string avatar URL
1846 public static function getDefaultHeader(array $contact): string
1848 if (!empty($contact['header'])) {
1849 return $contact['header'];
1852 if (!empty($contact['gsid'])) {
1853 // Use default banners for certain platforms
1854 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1855 $platform = strtolower($gserver['platform'] ?? '');
1860 switch ($platform) {
1865 * @author Lostinlight <https://mastodon.xyz/@lightone>
1866 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1867 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1869 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1874 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1875 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1876 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1878 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1882 * Use a random picture.
1883 * The service provides random pictures from Unsplash.
1884 * @license https://unsplash.com/license
1886 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1894 * Fetch the default avatar for the given contact and size
1896 * @param array $contact contact array
1897 * @param string $size Size of the avatar picture
1898 * @return string avatar URL
1900 public static function getDefaultAvatar(array $contact, string $size): string
1903 case Proxy::SIZE_MICRO:
1904 $avatar['size'] = 48;
1905 $default = self::DEFAULT_AVATAR_MICRO;
1908 case Proxy::SIZE_THUMB:
1909 $avatar['size'] = 80;
1910 $default = self::DEFAULT_AVATAR_THUMB;
1913 case Proxy::SIZE_SMALL:
1915 $avatar['size'] = 300;
1916 $default = self::DEFAULT_AVATAR_PHOTO;
1920 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1922 $type = Contact::TYPE_PERSON;
1924 if (!empty($contact['id'])) {
1925 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1926 $platform = $account['platform'] ?? '';
1927 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1930 if (empty($platform) && !empty($contact['uri-id'])) {
1931 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1932 $platform = $account['platform'] ?? '';
1933 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1936 switch ($platform) {
1940 * @license GNU Affero General Public License v3.0
1941 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1943 $default = '/images/default/corgidon.png';
1949 * @license GNU Affero General Public License v3.0
1950 * @link https://github.com/diaspora/diaspora/
1952 $default = '/images/default/diaspora.png';
1958 * @license GNU Affero General Public License v3.0
1959 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1961 $default = '/images/default/gotosocial.svg';
1967 * @license GNU Affero General Public License v3.0
1968 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1970 $default = '/images/default/hometown.png';
1976 * @license GNU Affero General Public License v3.0
1977 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1979 $default = '/images/default/koyuspace.png';
1987 * @license GNU Affero General Public License v3.0
1988 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1990 $default = '/images/default/mastodon.png';
1994 if ($type == Contact::TYPE_COMMUNITY) {
1997 * @license GNU Affero General Public License v3.0
1998 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
2000 $default = '/images/default/peertube-channel.png';
2004 * @license GNU Affero General Public License v3.0
2005 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
2007 $default = '/images/default/peertube-account.png';
2014 * @license GNU Affero General Public License v3.0
2015 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2017 $default = '/images/default/pleroma.png';
2023 * @license GNU Affero General Public License v3.0
2024 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2026 $default = '/images/default/plume.png';
2029 return DI::baseUrl() . $default;
2032 if (!empty($contact['xmpp'])) {
2033 $avatar['email'] = $contact['xmpp'];
2034 } elseif (!empty($contact['addr'])) {
2035 $avatar['email'] = $contact['addr'];
2036 } elseif (!empty($contact['url'])) {
2037 $avatar['email'] = $contact['url'];
2039 return DI::baseUrl() . $default;
2042 $avatar['url'] = '';
2043 $avatar['success'] = false;
2045 Hook::callAll('avatar_lookup', $avatar);
2047 if ($avatar['success'] && !empty($avatar['url'])) {
2048 return $avatar['url'];
2051 return DI::baseUrl() . $default;
2055 * Get avatar link for given contact id
2057 * @param integer $cid contact id
2058 * @param string $size One of the Proxy::SIZE_* constants
2059 * @param string $updated Contact update date
2060 * @param bool $static If "true" a parameter is added to convert the header to a static one
2061 * @return string avatar link
2063 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2065 // We have to fetch the "updated" variable when it wasn't provided
2066 // The parameter can be provided to improve performance
2067 if (empty($updated)) {
2068 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2069 $updated = $account['updated'] ?? '';
2070 $guid = $account['guid'] ?? '';
2073 $guid = urlencode($guid);
2075 $url = DI::baseUrl() . '/photo/contact/';
2077 case Proxy::SIZE_MICRO:
2078 $url .= Proxy::PIXEL_MICRO . '/';
2080 case Proxy::SIZE_THUMB:
2081 $url .= Proxy::PIXEL_THUMB . '/';
2083 case Proxy::SIZE_SMALL:
2084 $url .= Proxy::PIXEL_SMALL . '/';
2086 case Proxy::SIZE_MEDIUM:
2087 $url .= Proxy::PIXEL_MEDIUM . '/';
2089 case Proxy::SIZE_LARGE:
2090 $url .= Proxy::PIXEL_LARGE . '/';
2095 $query_params['ts'] = strtotime($updated);
2098 $query_params['static'] = true;
2101 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2105 * Get avatar link for given contact URL
2107 * @param string $url contact url
2108 * @param integer $uid user id
2109 * @param string $size One of the Proxy::SIZE_* constants
2110 * @return string avatar link
2112 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2114 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2115 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2116 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2117 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2121 * Get header link for given contact id
2123 * @param integer $cid contact id
2124 * @param string $size One of the Proxy::SIZE_* constants
2125 * @param string $updated Contact update date
2126 * @param bool $static If "true" a parameter is added to convert the header to a static one
2127 * @return string header link
2129 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
2131 // We have to fetch the "updated" variable when it wasn't provided
2132 // The parameter can be provided to improve performance
2133 if (empty($updated) || empty($guid)) {
2134 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2135 $updated = $account['updated'] ?? '';
2136 $guid = $account['guid'] ?? '';
2139 $guid = urlencode($guid);
2141 $url = DI::baseUrl() . '/photo/header/';
2143 case Proxy::SIZE_MICRO:
2144 $url .= Proxy::PIXEL_MICRO . '/';
2146 case Proxy::SIZE_THUMB:
2147 $url .= Proxy::PIXEL_THUMB . '/';
2149 case Proxy::SIZE_SMALL:
2150 $url .= Proxy::PIXEL_SMALL . '/';
2152 case Proxy::SIZE_MEDIUM:
2153 $url .= Proxy::PIXEL_MEDIUM . '/';
2155 case Proxy::SIZE_LARGE:
2156 $url .= Proxy::PIXEL_LARGE . '/';
2162 $query_params['ts'] = strtotime($updated);
2165 $query_params['static'] = true;
2168 return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
2172 * Updates the avatar links in a contact only if needed
2174 * @param int $cid Contact id
2175 * @param string $avatar Link to avatar picture
2176 * @param bool $force force picture update
2177 * @param bool $create_cache Enforces the creation of cached avatar fields
2180 * @throws HTTPException\InternalServerErrorException
2181 * @throws HTTPException\NotFoundException
2182 * @throws \ImagickException
2184 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2186 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2187 ['id' => $cid, 'self' => false]);
2188 if (!DBA::isResult($contact)) {
2192 $uid = $contact['uid'];
2194 // Only update the cached photo links of public contacts when they already are cached
2195 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2196 if ($contact['avatar'] != $avatar) {
2197 self::update(['avatar' => $avatar], ['id' => $cid]);
2198 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2203 // User contacts use are updated through the public contacts
2204 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2205 $pcid = self::getIdForURL($contact['url'], 0, false);
2206 if (!empty($pcid)) {
2207 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2208 self::updateAvatar($pcid, $avatar, $force, true);
2213 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2215 if ($default_avatar) {
2216 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2219 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2221 // Local contact avatars don't need to be cached
2222 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2223 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2226 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2227 Avatar::deleteCache($contact);
2229 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2230 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2232 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2233 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2234 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2237 // Use the data from the self account
2238 if (empty($fields)) {
2239 $local_uid = User::getIdForURL($contact['url']);
2240 if (!empty($local_uid)) {
2241 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2242 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2246 if (empty($fields)) {
2247 $update = ($contact['avatar'] != $avatar) || $force;
2251 $contact['photo'] ?? '',
2252 $contact['thumb'] ?? '',
2253 $contact['micro'] ?? '',
2256 foreach ($data as $image_uri) {
2257 $image_rid = Photo::ridFromURI($image_uri);
2258 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2259 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2266 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2268 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2269 $update = !empty($fields);
2270 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2276 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2279 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2280 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2281 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2290 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2291 // Collect all user contacts of the given public contact
2292 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2293 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2294 while ($personal_contact = DBA::fetch($personal_contacts)) {
2295 $cids[] = $personal_contact['id'];
2296 $uids[] = $personal_contact['uid'];
2298 DBA::close($personal_contacts);
2300 if (!empty($cids)) {
2301 // Delete possibly existing cached user contact avatars
2302 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2308 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2309 self::update($fields, ['id' => $cids]);
2312 public static function deleteContactByUrl(string $url)
2314 // Update contact data for all users
2315 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2316 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2317 while ($contact = DBA::fetch($contacts)) {
2318 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2319 self::remove($contact['id']);
2324 * Helper function for "updateFromProbe". Updates personal and public contact
2326 * @param integer $id contact id
2327 * @param integer $uid user id
2328 * @param integer $uri_id Uri-Id
2329 * @param string $url The profile URL of the contact
2330 * @param array $fields The fields that are updated
2332 * @throws \Exception
2334 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2336 if (!self::update($fields, ['id' => $id])) {
2337 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2341 self::setAccountUser($id, $uid, $uri_id, $url);
2343 // Archive or unarchive the contact.
2344 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2345 if (!DBA::isResult($contact)) {
2346 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2350 if (isset($fields['failed'])) {
2351 if ($fields['failed']) {
2352 self::markForArchival($contact);
2354 self::unmarkForArchival($contact);
2358 if ($contact['uid'] != 0) {
2362 // Update contact data for all users
2363 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2365 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2366 self::update($fields, $condition);
2368 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2369 $condition['network'] = Protocol::OSTATUS;
2371 // If the contact failed, propagate the update fields to all contacts
2372 if (empty($fields['failed'])) {
2373 unset($fields['last-update']);
2374 unset($fields['success_update']);
2375 unset($fields['failure_update']);
2378 if (empty($fields)) {
2382 self::update($fields, $condition);
2386 * Create or update an "account-user" entry
2388 * @param integer $id
2389 * @param integer $uid
2390 * @param integer $uri_id
2391 * @param string $url
2394 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2396 if (empty($uri_id)) {
2400 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2401 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2402 if ($account_user['uid'] == $uid) {
2403 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2404 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2406 // This should never happen
2407 Logger::warning('account-user exists for a different uri-id and uid', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2411 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2412 if (!empty($account_user['id'])) {
2413 if ($account_user['id'] == $id) {
2414 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2416 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2417 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2418 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2421 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2422 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2423 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2424 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2426 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2431 * Remove duplicated contacts
2433 * @param string $nurl Normalised contact url
2434 * @param integer $uid User id
2436 * @throws \Exception
2438 public static function removeDuplicates(string $nurl, int $uid)
2440 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2441 $count = DBA::count('contact', $condition);
2446 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2447 if (!DBA::isResult($first_contact)) {
2448 // Shouldn't happen - so we handle it
2452 $first = $first_contact['id'];
2453 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2455 // Find all duplicates
2456 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2457 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2458 while ($duplicate = DBA::fetch($duplicates)) {
2459 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2463 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2465 DBA::close($duplicates);
2466 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2471 * Updates contact record by provided id and optional network
2473 * @param integer $id contact id
2474 * @param string $network Optional network we are probing for
2476 * @throws HTTPException\InternalServerErrorException
2477 * @throws \ImagickException
2479 public static function updateFromProbe(int $id, string $network = '')
2481 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2482 if (!DBA::isResult($contact)) {
2486 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2488 if ($ret['network'] == Protocol::DIASPORA) {
2489 FContact::updateFromProbeArray($ret);
2492 return self::updateFromProbeArray($id, $ret);
2496 * Checks if the given contact has got local data
2499 * @param array $contact
2503 private static function hasLocalData(int $id, array $contact): bool
2505 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2506 // User contacts with the same uri-id exist
2508 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2509 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2512 if (DBA::exists('post-tag', ['cid' => $id])) {
2513 // Is tagged in a post
2516 if (DBA::exists('user-contact', ['cid' => $id])) {
2517 // Has got user-contact data
2520 if (Post::exists(['author-id' => $id])) {
2521 // Posts with this author exist
2524 if (Post::exists(['owner-id' => $id])) {
2525 // Posts with this owner exist
2528 if (Post::exists(['causer-id' => $id])) {
2529 // Posts with this causer exist
2532 // We don't have got this contact locally
2537 * Updates contact record by provided id and probed data
2539 * @param integer $id contact id
2540 * @param array $ret Probed data
2542 * @throws HTTPException\InternalServerErrorException
2543 * @throws \ImagickException
2545 private static function updateFromProbeArray(int $id, array $ret): bool
2548 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2549 This will reliably kill your communication with old Friendica contacts.
2552 // These fields aren't updated by this routine:
2555 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2556 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2557 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2558 'created', 'last-update'];
2559 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2560 if (!DBA::isResult($contact)) {
2564 if (self::isLocal($ret['url'])) {
2565 if ($contact['uid'] == 0) {
2566 Logger::info('Local contacts are not updated here.');
2568 self::updateFromPublicContact($id, $contact);
2573 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2574 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2577 // Delete all contacts with the same URL
2578 self::deleteContactByUrl($ret['url']);
2582 $uid = $contact['uid'];
2583 unset($contact['uid']);
2585 $uriid = $contact['uri-id'];
2586 unset($contact['uri-id']);
2588 $pubkey = $contact['pubkey'];
2589 unset($contact['pubkey']);
2591 $created = $contact['created'];
2592 unset($contact['created']);
2594 $last_update = $contact['last-update'];
2595 unset($contact['last-update']);
2597 $contact['photo'] = $contact['avatar'];
2598 unset($contact['avatar']);
2600 $updated = DateTimeFormat::utcNow();
2602 $has_local_data = self::hasLocalData($id, $contact);
2604 if (!Probe::isProbable($ret['network'])) {
2605 // Periodical checks are only done on federated contacts
2606 $failed_next_update = null;
2607 $success_next_update = null;
2608 } elseif ($has_local_data) {
2609 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2610 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2612 $failed_next_update = DateTimeFormat::utc('now +6 month');
2613 $success_next_update = DateTimeFormat::utc('now +1 month');
2616 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2617 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2618 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2622 // We must not try to update relay contacts via probe. They are no real contacts.
2623 // We check after the probing to be able to correct falsely detected contact types.
2624 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2625 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2626 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2627 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2631 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2632 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2633 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
2637 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2638 $cid = self::getIdForURL($ret['url'], 0, false);
2639 if (!empty($cid) && ($cid != $id)) {
2640 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2641 return self::updateFromProbeArray($cid, $ret);
2645 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2646 $ret['unsearchable'] = $ret['hide'];
2649 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2650 $ret['forum'] = false;
2651 $ret['prv'] = false;
2652 $ret['contact-type'] = $ret['account-type'];
2653 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2654 $ret['forum'] = (bool)!$ret['manually-approve'];
2655 $ret['prv'] = (bool)!$ret['forum'];
2659 $new_pubkey = $ret['pubkey'] ?? '';
2661 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2662 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2663 $apcontact = APContact::getByURL($ret['url'], false);
2664 if (!empty($apcontact['featured'])) {
2665 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2669 $ret['last-item'] = Probe::getLastUpdate($ret);
2670 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2674 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2676 // make sure to not overwrite existing values with blank entries except some technical fields
2677 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2678 foreach ($ret as $key => $val) {
2679 if (!array_key_exists($key, $contact)) {
2681 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2682 $ret[$key] = $contact[$key];
2683 } elseif ($ret[$key] != $contact[$key]) {
2688 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2691 unset($ret['last-item']);
2694 if (empty($uriid)) {
2698 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2699 self::updateAvatar($id, $ret['photo'], $update);
2703 self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
2705 if (Contact\Relation::isDiscoverable($ret['url'])) {
2706 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2709 // Update the public contact
2711 $contact = self::getByURL($ret['url'], false, ['id']);
2712 if (!empty($contact['id'])) {
2713 self::updateFromProbeArray($contact['id'], $ret);
2720 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2721 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2722 $ret['updated'] = $updated;
2723 $ret['failed'] = false;
2724 $ret['next-update'] = $success_next_update;
2725 $ret['local-data'] = $has_local_data;
2727 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2728 if (empty($pubkey) && !empty($new_pubkey)) {
2729 $ret['pubkey'] = $new_pubkey;
2732 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2733 $ret['uri-date'] = $updated;
2736 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2737 $ret['name-date'] = $updated;
2740 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2741 $ret['last-update'] = $updated;
2742 $ret['success_update'] = $updated;
2745 unset($ret['photo']);
2747 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2749 if (Contact\Relation::isDiscoverable($ret['url'])) {
2750 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2756 private static function updateFromPublicContact(int $id, array $contact)
2758 $public = self::getByURL($contact['url'], false);
2762 foreach ($contact as $field => $value) {
2763 if ($field == 'uid') {
2766 if ($public[$field] != $value) {
2767 $fields[$field] = $public[$field];
2770 if (!empty($fields)) {
2771 self::update($fields, ['id' => $id, 'self' => false]);
2772 Logger::info('Updating local contact', ['id' => $id]);
2777 * Updates contact record by provided URL
2779 * @param integer $url contact url
2780 * @return integer Contact id
2781 * @throws HTTPException\InternalServerErrorException
2782 * @throws \ImagickException
2784 public static function updateFromProbeByURL(string $url): int
2786 $id = self::getIdForURL($url);
2792 self::updateFromProbe($id);
2798 * Detects the communication protocol for a given contact url.
2799 * This is used to detect Friendica contacts that we can communicate via AP.
2801 * @param string $url contact url
2802 * @param string $network Network of that contact
2803 * @return string with protocol
2805 public static function getProtocol(string $url, string $network): string
2807 if ($network != Protocol::DFRN) {
2811 $apcontact = APContact::getByURL($url);
2812 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2813 return Protocol::ACTIVITYPUB;
2820 * Takes a $uid and a url/handle and adds a new contact
2822 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2823 * dfrn_request page.
2825 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2828 * $return['success'] boolean true if successful
2829 * $return['message'] error text if success is false.
2831 * Takes a $uid and a url/handle and adds a new contact
2833 * @param int $uid The user id the contact should be created for
2834 * @param string $url The profile URL of the contact
2835 * @param string $network
2837 * @throws HTTPException\InternalServerErrorException
2838 * @throws HTTPException\NotFoundException
2839 * @throws \ImagickException
2841 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2843 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2845 // remove ajax junk, e.g. Twitter
2846 $url = str_replace('/#!/', '/', $url);
2848 if (!Network::isUrlAllowed($url)) {
2849 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2853 if (Network::isUrlBlocked($url)) {
2854 $result['message'] = DI::l10n()->t('Blocked domain');
2859 $result['message'] = DI::l10n()->t('Connect URL missing.');
2863 $arr = ['url' => $url, 'contact' => []];
2865 Hook::callAll('follow', $arr);
2868 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2872 if (!empty($arr['contact']['name'])) {
2874 $ret = $arr['contact'];
2877 $ret = Probe::uri($url, $network, $uid);
2879 // Ensure that the public contact exists
2880 if ($ret['network'] != Protocol::PHANTOM) {
2881 self::getIdForURL($url);
2885 if (($network != '') && ($ret['network'] != $network)) {
2886 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2890 // check if we already have a contact
2891 // the poll url is more reliable than the profile url, as we may have
2892 // indirect links or webfinger links
2894 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2895 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2896 if (!DBA::isResult($contact)) {
2897 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2898 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2901 $protocol = self::getProtocol($ret['url'], $ret['network']);
2903 // This extra param just confuses things, remove it
2904 if ($protocol === Protocol::DIASPORA) {
2905 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2908 // do we have enough information?
2909 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2910 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
2911 if (empty($ret['poll'])) {
2912 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
2914 if (empty($ret['name'])) {
2915 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
2917 if (empty($ret['url'])) {
2918 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
2920 if (strpos($ret['url'], '@') !== false) {
2921 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
2922 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
2927 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2928 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
2929 $ret['notify'] = '';
2932 if (!$ret['notify']) {
2933 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
2936 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2938 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2940 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2943 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2944 $pending = (bool)$ret['manually-approve'];
2947 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2951 if (DBA::isResult($contact)) {
2953 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2955 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2956 self::update($fields, ['id' => $contact['id']]);
2958 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2960 // create contact record
2963 'created' => DateTimeFormat::utcNow(),
2964 'url' => $ret['url'],
2965 'nurl' => Strings::normaliseLink($ret['url']),
2966 'addr' => $ret['addr'],
2967 'alias' => $ret['alias'],
2968 'batch' => $ret['batch'],
2969 'notify' => $ret['notify'],
2970 'poll' => $ret['poll'],
2971 'poco' => $ret['poco'],
2972 'name' => $ret['name'],
2973 'nick' => $ret['nick'],
2974 'network' => $ret['network'],
2975 'baseurl' => $ret['baseurl'],
2976 'gsid' => $ret['gsid'] ?? null,
2977 'protocol' => $protocol,
2978 'pubkey' => $ret['pubkey'],
2979 'rel' => $new_relation,
2980 'priority'=> $ret['priority'],
2981 'writable'=> $writeable,
2982 'hidden' => $hidden,
2985 'pending' => $pending,
2990 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2991 if (!DBA::isResult($contact)) {
2992 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
2996 $contact_id = $contact['id'];
2997 $result['cid'] = $contact_id;
2999 Group::addMember(User::getDefaultGroup($uid), $contact_id);
3001 // Update the avatar
3002 self::updateAvatar($contact_id, $ret['photo']);
3004 // pull feed and consume it, which should subscribe to the hub.
3005 if ($contact['network'] == Protocol::OSTATUS) {
3006 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
3010 self::updateFromProbeArray($contact_id, $ret);
3012 Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
3015 $result['success'] = Protocol::follow($uid, $contact, $protocol);
3021 * @param array $importer Owner (local user) data
3022 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
3023 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
3024 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
3025 * @param string $note Introduction additional message
3026 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
3027 * @throws HTTPException\InternalServerErrorException
3028 * @throws \ImagickException
3030 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3032 // Should always be set
3033 if (empty($datarray['author-id'])) {
3037 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3038 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3039 if (!DBA::isResult($pub_contact)) {
3040 // Should never happen
3044 // Contact is blocked at node-level
3045 if (self::isBlocked($datarray['author-id'])) {
3049 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3050 $name = $pub_contact['name'];
3051 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3052 $nick = $pub_contact['nick'];
3053 $network = $pub_contact['network'];
3055 // Ensure that we don't create a new contact when there already is one
3056 $cid = self::getIdForURL($url, $importer['uid']);
3058 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3061 self::clearFollowerFollowingEndpointCache($importer['uid']);
3063 if (!empty($contact)) {
3064 if (!empty($contact['pending'])) {
3065 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3069 // Contact is blocked at user-level
3070 if (!empty($contact['id']) && !empty($importer['id']) &&
3071 Contact\User::isBlocked($contact['id'], $importer['id'])) {
3075 // Make sure that the existing contact isn't archived
3076 self::unmarkForArchival($contact);
3078 if (($contact['rel'] == self::SHARING)
3079 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
3080 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3081 ['id' => $contact['id'], 'uid' => $importer['uid']]);
3084 // Ensure to always have the correct network type, independent from the connection request method
3085 self::updateFromProbe($contact['id']);
3087 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3091 // send email notification to owner?
3092 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3093 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3097 // create contact record
3098 $contact_id = self::insert([
3099 'uid' => $importer['uid'],
3100 'created' => DateTimeFormat::utcNow(),
3102 'nurl' => Strings::normaliseLink($url),
3105 'network' => $network,
3106 'rel' => self::FOLLOWER,
3113 // Ensure to always have the correct network type, independent from the connection request method
3114 self::updateFromProbe($contact_id);
3116 self::updateAvatar($contact_id, $photo, true);
3118 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3120 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
3122 /// @TODO Encapsulate this into a function/method
3123 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3124 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3125 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3126 // create notification
3127 if (is_array($contact_record)) {
3128 $intro = DI::introFactory()->createNew(
3130 $contact_record['id'],
3133 DI::intro()->save($intro);
3136 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
3138 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3139 DI::notify()->createFromArray([
3140 'type' => Notification\Type::INTRO,
3141 'otype' => Notification\ObjectType::INTRO,
3142 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3143 'uid' => $user['uid'],
3144 'cid' => $contact_record['id'],
3145 'link' => DI::baseUrl() . '/notifications/intros',
3148 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3149 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3150 self::createFromProbeForUser($importer['uid'], $url, $network);
3153 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3154 $fields = ['pending' => false];
3155 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3156 $fields['rel'] = self::FRIEND;
3159 self::update($fields, $condition);
3169 * Update the local relationship when a local user loses a follower
3171 * @param array $contact User-specific contact (uid != 0) array
3173 * @throws HTTPException\InternalServerErrorException
3174 * @throws \ImagickException
3176 public static function removeFollower(array $contact)
3178 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3179 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3180 } elseif (!empty($contact['id'])) {
3181 self::remove($contact['id']);
3183 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3187 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3189 self::clearFollowerFollowingEndpointCache($contact['uid']);
3191 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3193 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3197 * Update the local relationship when a local user unfollow a contact.
3198 * Removes the contact for sharing-only protocols (feed and mail).
3200 * @param array $contact User-specific contact (uid != 0) array
3201 * @throws HTTPException\InternalServerErrorException
3203 public static function removeSharer(array $contact)
3205 self::clearFollowerFollowingEndpointCache($contact['uid']);
3207 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3208 self::remove($contact['id']);
3210 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3213 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
3217 * Create a birthday event.
3219 * Update the year and the birthday.
3221 public static function updateBirthdays()
3225 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3226 AND NOT `contact`.`pending`
3227 AND NOT `contact`.`hidden`
3228 AND NOT `contact`.`blocked`
3229 AND NOT `contact`.`archive`
3230 AND NOT `contact`.`deleted`',
3236 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3238 while ($contact = DBA::fetch($contacts)) {
3239 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3241 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3243 if (Event::createBirthday($contact, $nextbd)) {
3247 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3248 ['id' => $contact['id']]
3252 DBA::close($contacts);
3256 * Remove the unavailable contact ids from the provided list
3258 * @param array $contact_ids Contact id list
3260 * @throws \Exception
3262 public static function pruneUnavailable(array $contact_ids): array
3264 if (empty($contact_ids)) {
3268 $contacts = self::selectToArray(['id'], [
3269 'id' => $contact_ids,
3275 return array_column($contacts, 'id');
3279 * Returns a magic link to authenticate remote visitors
3281 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3283 * @param string $contact_url The address of the target contact profile
3284 * @param string $url An url that we will be redirected to after the authentication
3286 * @return string with "redir" link
3287 * @throws HTTPException\InternalServerErrorException
3288 * @throws \ImagickException
3290 public static function magicLink(string $contact_url, string $url = ''): string
3292 if (!DI::userSession()->isAuthenticated()) {
3293 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3296 $contact = self::getByURL($contact_url, false);
3297 if (empty($contact)) {
3298 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3301 // Prevents endless loop in case only a non-public contact exists for the contact URL
3302 unset($contact['uid']);
3304 return self::magicLinkByContact($contact, $url ?: $contact_url);
3308 * Returns a magic link to authenticate remote visitors
3310 * @param integer $cid The contact id of the target contact profile
3311 * @param string $url An url that we will be redirected to after the authentication
3313 * @return string with "redir" link
3314 * @throws HTTPException\InternalServerErrorException
3315 * @throws \ImagickException
3317 public static function magicLinkById(int $cid, string $url = ''): string
3319 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3321 return self::magicLinkByContact($contact, $url);
3325 * Returns a magic link to authenticate remote visitors
3327 * @param array $contact The contact array with "uid", "network" and "url"
3328 * @param string $url An url that we will be redirected to after the authentication
3330 * @return string with "redir" link
3331 * @throws HTTPException\InternalServerErrorException
3332 * @throws \ImagickException
3334 public static function magicLinkByContact(array $contact, string $url = ''): string
3336 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3338 if (!DI::userSession()->isAuthenticated()) {
3339 return $destination;
3342 // Only redirections to the same host do make sense
3343 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3347 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3348 return 'contact/' . $contact['id'] . '/conversations';
3351 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3352 return $destination;
3355 if (empty($contact['id'])) {
3356 return $destination;
3359 $redirect = 'contact/redir/' . $contact['id'];
3361 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3362 $redirect .= '?url=' . $url;
3369 * Is the contact a forum?
3371 * @param integer $contactid ID of the contact
3373 * @return boolean "true" if it is a forum
3375 public static function isForum(int $contactid): bool
3377 $fields = ['contact-type'];
3378 $condition = ['id' => $contactid];
3379 $contact = DBA::selectFirst('contact', $fields, $condition);
3380 if (!DBA::isResult($contact)) {
3385 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3389 * Can the remote contact receive private messages?
3391 * @param array $contact
3394 public static function canReceivePrivateMessages(array $contact): bool
3396 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3397 $self = $contact['self'] ?? false;
3399 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3403 * Search contact table by nick or name
3405 * @param string $search Name or nick
3406 * @param string $mode Search mode (e.g. "community")
3407 * @param int $uid User ID
3408 * @param int $limit Maximum amount of returned values
3409 * @param int $offset Limit offset
3411 * @return array with search results
3412 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3414 public static function searchByName(string $search, string $mode = '', int $uid = 0, int $limit = 0, int $offset = 0): array
3416 if (empty($search)) {
3420 // check supported networks
3421 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3422 if (DI::config()->get('system', 'diaspora_enabled')) {
3423 $networks[] = Protocol::DIASPORA;
3426 if (!DI::config()->get('system', 'ostatus_disabled')) {
3427 $networks[] = Protocol::OSTATUS;
3430 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3433 $condition['blocked'] = false;
3435 $condition['rel'] = [Contact::SHARING, Contact::FRIEND];
3438 // check if we search only communities or every contact
3439 if ($mode === 'community') {
3440 $condition['contact-type'] = self::TYPE_COMMUNITY;
3447 if (!empty($limit) && !empty($offset)) {
3448 $params['limit'] = [$offset, $limit];
3449 } elseif (!empty($limit)) {
3450 $params['limit'] = $limit;
3453 $condition = DBA::mergeConditions($condition,
3454 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3455 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3457 return self::selectToArray([], $condition, $params);
3461 * Add public contacts from an array
3463 * @param array $urls
3464 * @return array result "count", "added" and "updated"
3466 public static function addByUrls(array $urls): array
3473 foreach ($urls as $url) {
3474 if (empty($url) || !is_string($url)) {
3477 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3478 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3479 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3481 } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3482 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
3490 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3494 * Returns a random, global contact array of the current node
3496 * @return array The profile array
3499 public static function getRandomContact(): array
3501 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3502 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3503 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3504 ], ['order' => ['RAND()']]);
3506 if (DBA::isResult($contact)) {
3514 * Checks, if contacts with the given condition exists
3516 * @param array $condition
3519 * @throws \Exception
3521 public static function exists(array $condition): bool
3523 return DBA::exists('contact', $condition);