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;
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 selectFirstAccount(array $fields = [], array $condition = [], array $params = [])
148 return DBA::selectFirst('account-view', $fields, $condition, $params);
152 * Insert a row into the contact table
153 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
155 * @param array $fields field array
156 * @param int $duplicate_mode Do an update on a duplicate entry
158 * @return int id of the created contact
161 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
163 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
164 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
167 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
169 if (empty($fields['created'])) {
170 $fields['created'] = DateTimeFormat::utcNow();
173 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
174 DBA::insert('contact', $fields, $duplicate_mode);
175 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
176 if (!DBA::isResult($contact)) {
178 Logger::warning('Created contact could not be found', ['fields' => $fields]);
182 $fields = DI::dbaDefinition()->truncateFieldsForTable('account-user', $contact);
183 DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
184 $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
185 if (empty($account_user['id'])) {
186 Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
187 } elseif ($account_user['id'] != $contact['id']) {
188 $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
189 if (!empty($duplicate['id'])) {
190 $ret = Contact::deleteById($contact['id']);
191 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']]);
192 $contact = $duplicate;
194 $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
195 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']]);
199 Contact\User::insertForContactArray($contact);
201 return $contact['id'];
205 * Delete contact by id
210 public static function deleteById(int $id): bool
212 Logger::debug('Delete contact', ['id' => $id]);
213 DBA::delete('account-user', ['id' => $id]);
214 return DBA::delete('contact', ['id' => $id]);
218 * Updates rows in the contact table
220 * @param array $fields contains the fields that are updated
221 * @param array $condition condition array with the key values
222 * @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)
224 * @return boolean was the update successfull?
226 * @todo Let's get rid of boolean type of $old_fields
228 public static function update(array $fields, array $condition, $old_fields = [])
230 $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
231 $ret = DBA::update('contact', $fields, $condition, $old_fields);
233 // Apply changes to the "user-contact" table on dedicated fields
234 Contact\User::updateByContactUpdate($fields, $condition);
240 * @param integer $id Contact ID
241 * @param array $fields Array of selected fields, empty for all
242 * @return array|boolean Contact record if it exists, false otherwise
245 public static function getById(int $id, array $fields = [])
247 return DBA::selectFirst('contact', $fields, ['id' => $id]);
251 * Fetch the first contact with the provided uri-id.
253 * @param integer $uri_id uri-id of the contact
254 * @param array $fields Array of selected fields, empty for all
255 * @return array|boolean Contact record if it exists, false otherwise
258 public static function getByUriId(int $uri_id, array $fields = [])
260 return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
264 * Fetch all remote contacts for a given contact url
266 * @param string $url The URL of the contact
267 * @param array $fields The wanted fields
269 * @return array all remote contacts
273 public static function getVisitorByUrl(string $url, array $fields = ['id', 'uid']): array
277 $remote_contacts = DBA::select('contact', ['id', 'uid'], ['nurl' => Strings::normaliseLink($url), 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'self' => false]);
278 while ($contact = DBA::fetch($remote_contacts)) {
279 if (($contact['uid'] == 0) || Contact\User::isBlocked($contact['id'], $contact['uid'])) {
282 $remote[$contact['uid']] = $contact['id'];
284 DBA::close($remote_contacts);
290 * Fetches a contact by a given url
292 * @param string $url profile url
293 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
294 * @param array $fields Field list
295 * @param integer $uid User ID of the contact
296 * @return array contact array
298 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
300 if ($update || is_null($update)) {
301 $cid = self::getIdForURL($url, $uid, $update);
306 $contact = self::getById($cid, $fields);
307 if (empty($contact)) {
313 // Add internal fields
315 if (!empty($fields)) {
316 foreach (['id', 'next-update', 'network'] as $internal) {
317 if (!in_array($internal, $fields)) {
318 $fields[] = $internal;
319 $removal[] = $internal;
324 // We first try the nurl (http://server.tld/nick), most common case
325 $options = ['order' => ['id']];
326 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
328 // Then the addr (nick@server.tld)
329 if (!DBA::isResult($contact)) {
330 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
333 // Then the alias (which could be anything)
334 if (!DBA::isResult($contact)) {
335 // The link could be provided as http although we stored it as https
336 $ssl_url = str_replace('http://', 'https://', $url);
337 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
338 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
341 if (!DBA::isResult($contact)) {
345 // Update the contact in the background if needed
346 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
347 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
350 // Remove the internal fields
351 foreach ($removal as $internal) {
352 unset($contact[$internal]);
359 * Fetches a contact for a given user by a given url.
360 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
362 * @param string $url profile url
363 * @param integer $uid User ID of the contact
364 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
365 * @param array $fields Field list
366 * @return array contact array
368 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
371 $contact = self::getByURL($url, $update, $fields, $uid);
372 if (!empty($contact)) {
373 if (!empty($contact['id'])) {
374 $contact['cid'] = $contact['id'];
381 $contact = self::getByURL($url, $update, $fields);
382 if (!empty($contact['id'])) {
384 $contact['zid'] = $contact['id'];
390 * Checks if a contact uses a specific platform
393 * @param string $platform
396 public static function isPlatform(string $url, string $platform): bool
398 return DBA::exists('account-view', ['nurl' => Strings::normaliseLink($url), 'platform' => $platform]);
402 * Tests if the given contact is a follower
404 * @param int $cid Either public contact id or user's contact id
405 * @param int $uid User ID
406 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
408 * @return boolean is the contact id a follower?
409 * @throws HTTPException\InternalServerErrorException
410 * @throws \ImagickException
412 public static function isFollower(int $cid, int $uid, bool $strict = false): bool
414 if (Contact\User::isBlocked($cid, $uid)) {
418 $cdata = self::getPublicAndUserContactID($cid, $uid);
419 if (empty($cdata['user'])) {
423 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
425 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
427 return DBA::exists('contact', $condition);
431 * Tests if the given contact url is a follower
433 * @param string $url Contact URL
434 * @param int $uid User ID
435 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
437 * @return boolean is the contact id a follower?
438 * @throws HTTPException\InternalServerErrorException
439 * @throws \ImagickException
441 public static function isFollowerByURL(string $url, int $uid, bool $strict = false): bool
443 $cid = self::getIdForURL($url, $uid);
449 return self::isFollower($cid, $uid, $strict);
453 * Tests if the given user shares with the given contact
455 * @param int $cid Either public contact id or user's contact id
456 * @param int $uid User ID
457 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
459 * @return boolean is the contact sharing with given user?
460 * @throws HTTPException\InternalServerErrorException
461 * @throws \ImagickException
463 public static function isSharing(int $cid, int $uid, bool $strict = false): bool
465 if (Contact\User::isBlocked($cid, $uid)) {
469 $cdata = self::getPublicAndUserContactID($cid, $uid);
470 if (empty($cdata['user'])) {
474 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
476 $condition = array_merge($condition, ['pending' => false, 'readonly' => false, 'blocked' => false]);
478 return DBA::exists('contact', $condition);
482 * Tests if the given user follow the given contact url
484 * @param string $url Contact URL
485 * @param int $uid User ID
486 * @param bool $strict If "true" then contact mustn't be set to pending or readonly
488 * @return boolean is the contact url being followed?
489 * @throws HTTPException\InternalServerErrorException
490 * @throws \ImagickException
492 public static function isSharingByURL(string $url, int $uid, bool $strict = false): bool
494 $cid = self::getIdForURL($url, $uid);
500 return self::isSharing($cid, $uid, $strict);
504 * Get the basepath for a given contact link
506 * @param string $url The contact link
507 * @param boolean $dont_update Don't update the contact
509 * @return string basepath
510 * @throws HTTPException\InternalServerErrorException
511 * @throws \ImagickException
513 public static function getBasepath(string $url, bool $dont_update = false): string
515 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
516 if (!DBA::isResult($contact)) {
520 if (!empty($contact['baseurl'])) {
521 return $contact['baseurl'];
522 } elseif ($dont_update) {
526 // Update the existing contact
527 self::updateFromProbe($contact['id']);
529 // And fetch the result
530 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
531 if (empty($contact['baseurl'])) {
532 Logger::info('No baseurl for contact', ['url' => $url]);
536 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
537 return $contact['baseurl'];
541 * Check if the given contact url is on the same server
543 * @param string $url The contact link
545 * @return boolean Is it the same server?
547 public static function isLocal(string $url): bool
549 if (!parse_url($url, PHP_URL_SCHEME)) {
550 $addr_parts = explode('@', $url);
551 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
554 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
558 * Check if the given contact ID is on the same server
560 * @param string $url The contact link
561 * @return boolean Is it the same server?
563 public static function isLocalById(int $cid): bool
565 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
566 if (!DBA::isResult($contact)) {
570 if (empty($contact['baseurl'])) {
571 $baseurl = self::getBasepath($contact['url'], true);
573 $baseurl = $contact['baseurl'];
576 return Strings::compareLink($baseurl, DI::baseUrl());
580 * Returns the public contact id of the given user id
582 * @param integer $uid User ID
584 * @return integer|boolean Public contact id for given user id
587 public static function getPublicIdByUserId(int $uid)
589 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
590 if (!DBA::isResult($self)) {
593 return self::getIdForURL($self['url']);
597 * Returns the contact id for the user and the public contact id for a given contact id
599 * @param int $cid Either public contact id or user's contact id
600 * @param int $uid User ID
602 * @return array with public and user's contact id
603 * @throws HTTPException\InternalServerErrorException
604 * @throws \ImagickException
606 public static function getPublicAndUserContactID(int $cid, int $uid): array
608 // We have to use the legacy function as long as the post update hasn't finished
609 if (DI::config()->get('system', 'post_update_version') < 1427) {
610 return self::legacyGetPublicAndUserContactID($cid, $uid);
613 if (empty($uid) || empty($cid)) {
617 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
618 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
622 $pcid = $contact['pid'];
623 if ($contact['uid'] == $uid) {
624 $ucid = $contact['id'];
626 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
627 if (DBA::isResult($contact)) {
628 $ucid = $contact['id'];
634 return ['public' => $pcid, 'user' => $ucid];
638 * Helper function for "getPublicAndUserContactID"
640 * @param int $cid Either public contact id or user's contact id
641 * @param int $uid User ID
642 * @return array with public and user's contact id
643 * @throws HTTPException\InternalServerErrorException
644 * @throws \ImagickException
646 private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
648 if (empty($uid) || empty($cid)) {
652 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
653 if (!DBA::isResult($contact)) {
657 // We quit when the user id don't match the user id of the provided contact
658 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
662 if ($contact['uid'] != 0) {
663 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
667 $ucid = $contact['id'];
669 $pcid = $contact['id'];
670 $ucid = self::getIdForURL($contact['url'], $uid);
673 return ['public' => $pcid, 'user' => $ucid];
677 * Returns contact details for a given contact id in combination with a user id
679 * @param int $cid A contact ID
680 * @param int $uid The User ID
681 * @param array $fields The selected fields for the contact
682 * @return array The contact details
686 public static function getContactForUser(int $cid, int $uid, array $fields = []): array
688 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
690 if (!DBA::isResult($contact)) {
698 * Creates the self-contact for the provided user id
701 * @return bool Operation success
702 * @throws HTTPException\InternalServerErrorException
704 public static function createSelfFromUserId(int $uid): bool
706 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
707 ['uid' => $uid, 'account_expired' => false]);
708 if (!DBA::isResult($user)) {
713 'uid' => $user['uid'],
714 'created' => DateTimeFormat::utcNow(),
716 'name' => $user['username'],
717 'nick' => $user['nickname'],
718 'pubkey' => $user['pubkey'],
719 'prvkey' => $user['prvkey'],
720 'photo' => User::getAvatarUrl($user),
721 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
722 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
725 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
726 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
727 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
728 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
729 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
730 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
731 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
732 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
733 'name-date' => DateTimeFormat::utcNow(),
734 'uri-date' => DateTimeFormat::utcNow(),
735 'avatar-date' => DateTimeFormat::utcNow(),
741 // Only create the entry if it doesn't exist yet
742 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
743 $return = (bool)self::insert($contact);
746 // Create the public contact
747 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
748 $contact['self'] = false;
750 $contact['prvkey'] = null;
752 self::insert($contact, Database::INSERT_IGNORE);
759 * Updates the self-contact for the provided user id
762 * @param bool $update_avatar Force the avatar update
763 * @return bool "true" if updated
764 * @throws HTTPException\InternalServerErrorException
766 public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
768 $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
769 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
770 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
771 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
772 if (!DBA::isResult($self)) {
776 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
777 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
778 if (!DBA::isResult($user)) {
782 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
783 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
784 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
785 if (!DBA::isResult($profile)) {
789 $file_suffix = 'jpg';
790 $url = DI::baseUrl() . '/profile/' . $user['nickname'];
793 'name' => $profile['name'],
794 'nick' => $user['nickname'],
795 'avatar-date' => $self['avatar-date'],
796 'location' => Profile::formatLocation($profile),
797 'about' => $profile['about'],
798 'keywords' => $profile['pub_keywords'],
799 'contact-type' => $user['account-type'],
800 'prvkey' => $user['prvkey'],
801 'pubkey' => $user['pubkey'],
802 'xmpp' => $profile['xmpp'],
803 'matrix' => $profile['matrix'],
804 'network' => Protocol::DFRN,
806 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
807 'nurl' => Strings::normaliseLink($url),
808 'uri-id' => ItemURI::getIdByURI($url),
809 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
810 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
811 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
812 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
813 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
814 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
818 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
819 if (DBA::isResult($avatar)) {
820 if ($update_avatar) {
821 $fields['avatar-date'] = DateTimeFormat::utcNow();
824 // Creating the path to the avatar, beginning with the file suffix
825 $types = Images::supportedTypes();
826 if (isset($types[$avatar['type']])) {
827 $file_suffix = $types[$avatar['type']];
830 // We are adding a timestamp value so that other systems won't use cached content
831 $timestamp = strtotime($fields['avatar-date']);
833 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
834 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
836 $fields['photo'] = $prefix . '4' . $suffix;
837 $fields['thumb'] = $prefix . '5' . $suffix;
838 $fields['micro'] = $prefix . '6' . $suffix;
840 // We hadn't found a photo entry, so we use the default avatar
841 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
842 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
843 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
846 $fields['avatar'] = User::getAvatarUrl($user);
847 $fields['header'] = User::getBannerUrl($user);
848 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
849 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
850 $fields['unsearchable'] = !$profile['net-publish'];
851 $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
855 foreach ($fields as $field => $content) {
856 if ($self[$field] != $content) {
862 if ($fields['name'] != $self['name']) {
863 $fields['name-date'] = DateTimeFormat::utcNow();
865 $fields['updated'] = DateTimeFormat::utcNow();
866 self::update($fields, ['id' => $self['id']]);
868 // Update the other contacts as well
869 unset($fields['prvkey']);
870 $fields['self'] = false;
871 self::update($fields, ['uri-id' => $self['uri-id'], 'self' => false]);
873 // Update the profile
875 'photo' => User::getAvatarUrl($user),
876 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
879 DBA::update('profile', $fields, ['uid' => $uid]);
886 * Marks a contact for removal
888 * @param int $id contact id
890 * @throws HTTPException\InternalServerErrorException
892 public static function remove(int $id)
894 // We want just to make sure that we don't delete our "self" contact
895 $contact = DBA::selectFirst('contact', ['uri-id', 'photo', 'thumb', 'micro', 'uid'], ['id' => $id, 'self' => false]);
896 if (!DBA::isResult($contact)) {
900 DBA::delete('account-user', ['id' => $id]);
902 self::clearFollowerFollowingEndpointCache($contact['uid']);
904 // Archive the contact
905 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
907 if (!DBA::exists('contact', ['uri-id' => $contact['uri-id'], 'deleted' => false])) {
908 Avatar::deleteCache($contact);
911 // Delete it in the background
912 Worker::add(Worker::PRIORITY_MEDIUM, 'Contact\Remove', $id);
916 * Unfollow the remote contact
918 * @param array $contact Target user-specific contact (uid != 0) array
920 * @throws HTTPException\InternalServerErrorException
921 * @throws \ImagickException
923 public static function unfollow(array $contact): void
925 if (empty($contact['network'])) {
926 throw new \InvalidArgumentException('Empty network in contact array');
929 if (empty($contact['uid'])) {
930 throw new \InvalidArgumentException('Unexpected public contact record');
933 if (in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
934 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
935 if (!empty($cdata['public'])) {
936 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
940 self::removeSharer($contact);
944 * Revoke follow privileges of the remote user contact
946 * The local relationship is updated immediately, the eventual remote server is messaged in the background.
948 * @param array $contact User-specific contact array (uid != 0) to revoke the follow from
950 * @throws HTTPException\InternalServerErrorException
951 * @throws \ImagickException
953 public static function revokeFollow(array $contact): void
955 if (empty($contact['network'])) {
956 throw new \InvalidArgumentException('Empty network in contact array');
959 if (empty($contact['uid'])) {
960 throw new \InvalidArgumentException('Unexpected public contact record');
963 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND])) {
964 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
965 if (!empty($cdata['public'])) {
966 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
970 self::removeFollower($contact);
974 * Completely severs a relationship with a contact
976 * @param array $contact User-specific contact (uid != 0) array
978 * @throws HTTPException\InternalServerErrorException
979 * @throws \ImagickException
981 public static function terminateFriendship(array $contact)
983 if (empty($contact['network'])) {
984 throw new \InvalidArgumentException('Empty network in contact array');
987 if (empty($contact['uid'])) {
988 throw new \InvalidArgumentException('Unexpected public contact record');
991 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
993 if (in_array($contact['rel'], [self::SHARING, self::FRIEND]) && !empty($cdata['public'])) {
994 Worker::add(Worker::PRIORITY_HIGH, 'Contact\Unfollow', $cdata['public'], $contact['uid']);
997 if (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) && !empty($cdata['public'])) {
998 Worker::add(Worker::PRIORITY_HIGH, 'Contact\RevokeFollow', $cdata['public'], $contact['uid']);
1001 self::remove($contact['id']);
1004 private static function clearFollowerFollowingEndpointCache(int $uid)
1010 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'followers:' . $uid);
1011 DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_CONTACTS . 'following:' . $uid);
1015 * Marks a contact for archival after a communication issue delay
1017 * Contact has refused to recognise us as a friend. We will start a countdown.
1018 * If they still don't recognise us in 32 days, the relationship is over,
1019 * and we won't waste any more time trying to communicate with them.
1020 * This provides for the possibility that their database is temporarily messed
1021 * up or some other transient event and that there's a possibility we could recover from it.
1023 * @param array $contact contact to mark for archival
1025 * @throws HTTPException\InternalServerErrorException
1027 public static function markForArchival(array $contact)
1029 if (!isset($contact['url']) && !empty($contact['id'])) {
1030 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
1031 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1032 if (!DBA::isResult($contact)) {
1035 } elseif (!isset($contact['url'])) {
1036 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
1039 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1041 // Contact already archived or "self" contact? => nothing to do
1042 if ($contact['archive'] || $contact['self']) {
1046 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
1047 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
1048 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
1051 * We really should send a notification to the owner after 2-3 weeks
1052 * so they won't be surprised when the contact vanishes and can take
1053 * remedial action if this was a serious mistake or glitch
1056 /// @todo Check for contact vitality via probing
1057 $archival_days = DI::config()->get('system', 'archival_days', 32);
1059 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
1060 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
1061 /* Relationship is really truly dead. archive them rather than
1062 * delete, though if the owner tries to unarchive them we'll start
1063 * the whole process over again.
1065 self::update(['archive' => true], ['id' => $contact['id']]);
1066 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1072 * Cancels the archival countdown
1074 * @see Contact::markForArchival()
1076 * @param array $contact contact to be unmarked for archival
1078 * @throws \Exception
1080 public static function unmarkForArchival(array $contact)
1082 // Always unarchive the relay contact entry
1083 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
1084 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1085 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1086 if (!DBA::exists('contact', array_merge($condition, $fields))) {
1087 self::update($fields, $condition);
1091 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
1092 $exists = DBA::exists('contact', $condition);
1094 // We don't need to update, we never marked this contact for archival
1099 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
1101 if (!isset($contact['url']) && !empty($contact['id'])) {
1102 $fields = ['id', 'url', 'batch'];
1103 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
1104 if (!DBA::isResult($contact)) {
1109 // It's a miracle. Our dead contact has inexplicably come back to life.
1110 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
1111 self::update($fields, ['id' => $contact['id']]);
1112 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
1116 * Returns the data array for the photo menu of a given contact
1118 * @param array $contact contact
1119 * @param int $uid optional, default 0
1121 * @throws HTTPException\InternalServerErrorException
1122 * @throws \ImagickException
1124 public static function photoMenu(array $contact, int $uid = 0): array
1131 $uid = DI::userSession()->getLocalUserId();
1134 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1136 $profile_link = self::magicLinkByContact($contact);
1137 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1142 // Look for our own contact if the uid doesn't match and isn't public
1143 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1144 if (DBA::isResult($contact_own)) {
1145 return self::photoMenu($contact_own, $uid);
1150 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1152 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1154 $profile_link = $contact['url'];
1157 if ($profile_link === 'mailbox') {
1162 $status_link = $profile_link . '/status';
1163 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1164 $profile_link = $profile_link . '/profile';
1167 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1168 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1171 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1173 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1176 $unfollow_link = '';
1177 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1178 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1179 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1180 } elseif(!$contact['pending']) {
1181 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1187 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1189 if (empty($contact['uid'])) {
1191 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1192 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1193 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1194 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1195 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1199 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1200 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1201 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1202 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1203 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1204 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1205 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1206 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1209 if (!empty($contact['pending'])) {
1211 $intro = DI::intro()->selectForContact($contact['id']);
1212 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1213 } catch (IntroductionNotFoundException $exception) {
1214 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1219 $args = ['contact' => $contact, 'menu' => &$menu];
1221 Hook::callAll('contact_photo_menu', $args);
1223 $menucondensed = [];
1225 foreach ($menu as $menuname => $menuitem) {
1226 if ($menuitem[1] != '') {
1227 $menucondensed[$menuname] = $menuitem;
1231 return $menucondensed;
1235 * Fetch the contact id for a given URL and user
1237 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1238 * `addr` or `alias`.
1240 * If there's no record and we aren't looking for a public contact, we quit.
1241 * If there's one, we check that it isn't time to update the picture else we
1242 * directly return the found contact id.
1244 * Second, we probe the provided $url whether it's http://server.tld/profile or
1245 * nick@server.tld. We quit if we can't get any info back.
1247 * Third, we create the contact record if it doesn't exist
1249 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1250 * if there's any updates
1252 * @param string $url Contact URL
1253 * @param integer $uid The user id for the contact (0 = public contact)
1254 * @param boolean $update true = always update, false = never update, null = update when not found
1255 * @param array $default Default value for creating the contact when everything else fails
1257 * @return integer Contact ID
1258 * @throws HTTPException\InternalServerErrorException
1259 * @throws \ImagickException
1261 public static function getIdForURL(string $url = null, int $uid = 0, $update = null, array $default = []): int
1266 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1270 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
1272 if (!empty($contact)) {
1273 $contact_id = $contact['id'];
1275 if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
1276 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
1279 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1280 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1283 } elseif ($uid != 0) {
1284 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1286 } elseif (empty($default) && !is_null($update) && !$update) {
1287 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1293 if (empty($default['network']) || $update) {
1294 $data = Probe::uri($url, '', $uid);
1296 // Take the default values when probing failed
1297 if (!empty($default) && !in_array($data['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1298 $data = array_merge($data, $default);
1300 } elseif (!empty($default['network'])) {
1304 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1305 // Fetch data for the public contact via the first found personal contact
1306 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1307 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1308 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1309 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1311 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1312 if (!DBA::isResult($personal_contact)) {
1313 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1316 if (DBA::isResult($personal_contact)) {
1317 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1318 $data = $personal_contact;
1319 $data['photo'] = $personal_contact['avatar'];
1320 $data['account-type'] = $personal_contact['contact-type'];
1321 $data['hide'] = $personal_contact['unsearchable'];
1322 unset($data['avatar']);
1323 unset($data['contact-type']);
1324 unset($data['unsearchable']);
1328 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1329 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1333 if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1334 Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
1339 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1340 if (!empty($data['alias'])) {
1341 $urls[] = Strings::normaliseLink($data['alias']);
1343 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1344 if (!empty($contact['id'])) {
1345 $contact_id = $contact['id'];
1346 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1351 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1354 'url' => $data['url'],
1355 'nurl' => Strings::normaliseLink($data['url']),
1356 'network' => $data['network'],
1357 'created' => DateTimeFormat::utcNow(),
1358 'rel' => self::SHARING,
1365 $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false];
1367 // Before inserting we do check if the entry does exist now.
1368 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1369 if (DBA::isResult($contact)) {
1370 $contact_id = $contact['id'];
1371 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1373 $contact_id = self::insert($fields);
1375 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1380 Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1384 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1387 if ($data['network'] == Protocol::DIASPORA) {
1388 FContact::updateFromProbeArray($data);
1391 self::updateFromProbeArray($contact_id, $data);
1393 // Don't return a number for a deleted account
1394 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1395 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1403 * Checks if the contact is archived
1405 * @param int $cid contact id
1407 * @return boolean Is the contact archived?
1408 * @throws HTTPException\InternalServerErrorException
1410 public static function isArchived(int $cid): bool
1416 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1417 if (!DBA::isResult($contact)) {
1421 if ($contact['archive']) {
1425 // Check status of ActivityPub endpoints
1426 $apcontact = APContact::getByURL($contact['url'], false);
1427 if (!empty($apcontact)) {
1428 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1432 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1437 // Check status of Diaspora endpoints
1438 if (!empty($contact['batch'])) {
1439 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1440 return DBA::exists('contact', $condition);
1447 * Checks if the contact is blocked
1449 * @param int $cid contact id
1450 * @return boolean Is the contact blocked?
1451 * @throws HTTPException\InternalServerErrorException
1453 public static function isBlocked(int $cid): bool
1459 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1460 if (!DBA::isResult($blocked)) {
1464 if (Network::isUrlBlocked($blocked['url'])) {
1468 return (bool) $blocked['blocked'];
1472 * Checks if the contact is hidden
1474 * @param int $cid contact id
1475 * @return boolean Is the contact hidden?
1476 * @throws \Exception
1478 public static function isHidden(int $cid): bool
1484 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1485 if (!DBA::isResult($hidden)) {
1488 return (bool) $hidden['hidden'];
1492 * Returns posts from a given contact url
1494 * @param string $contact_url Contact URL
1495 * @param bool $thread_mode
1496 * @param int $update Update mode
1497 * @param int $parent Item parent ID for the update mode
1498 * @param bool $only_media Only display media content
1499 * @return string posts in HTML
1500 * @throws \Exception
1502 public static function getPostsFromUrl(string $contact_url, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1504 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1508 * Returns posts from a given contact id
1510 * @param int $cid Contact ID
1511 * @param bool $thread_mode
1512 * @param int $update Update mode
1513 * @param int $parent Item parent ID for the update mode
1514 * @param bool $only_media Only display media content
1515 * @return string posts in HTML
1516 * @throws \Exception
1518 public static function getPostsFromId(int $cid, bool $thread_mode = false, int $update = 0, int $parent = 0, bool $only_media = false): string
1520 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1521 if (!DBA::isResult($contact)) {
1525 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1526 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1531 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1534 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
1535 $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), DI::userSession()->getLocalUserId()];
1537 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1538 $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
1541 if (!empty($parent)) {
1542 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1544 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1545 if (!empty($last_received)) {
1546 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1551 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1552 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1555 if (DI::mode()->isMobile()) {
1556 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
1557 DI::config()->get('system', 'itemspage_network_mobile'));
1559 $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
1560 DI::config()->get('system', 'itemspage_network'));
1563 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1565 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1567 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1568 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1569 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1575 $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'commented'];
1576 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1578 if ($pager->getStart() == 0) {
1579 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1580 if (!empty($cdata['public'])) {
1581 $pinned = Post\Collection::selectToArrayForContact($cdata['public'], Post\Collection::FEATURED, $fields);
1582 $items = array_merge($items, $pinned);
1586 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
1588 $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
1589 $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1591 if ($pager->getStart() == 0) {
1592 $cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
1593 if (!empty($cdata['public'])) {
1594 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
1595 $cdata['public'], Post\Collection::FEATURED];
1596 $pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
1597 $items = array_merge($pinned, $items);
1601 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1605 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'infinite_scroll')) {
1606 $o .= HTML::scrollLoader();
1608 $o .= $pager->renderMinimal(count($items));
1616 * Returns the account type name
1618 * The function can be called with either the user or the contact array
1620 * @param int $type type of contact or account
1623 public static function getAccountType(int $type): string
1626 case self::TYPE_ORGANISATION:
1627 $account_type = DI::l10n()->t("Organisation");
1630 case self::TYPE_NEWS:
1631 $account_type = DI::l10n()->t('News');
1634 case self::TYPE_COMMUNITY:
1635 $account_type = DI::l10n()->t("Forum");
1643 return $account_type;
1649 * @param int $cid Contact id to block
1650 * @param string $reason Block reason
1651 * @return bool Whether it was successful
1653 public static function block(int $cid, string $reason = null): bool
1655 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1661 * Unblocks a contact
1663 * @param int $cid Contact id to unblock
1664 * @return bool Whether it was successfull
1666 public static function unblock(int $cid): bool
1668 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1674 * Ensure that cached avatar exist
1676 * @param integer $cid Contact id
1678 public static function checkAvatarCache(int $cid)
1680 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1681 if (!DBA::isResult($contact)) {
1685 if (Network::isLocalLink($contact['url'])) {
1689 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1690 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1691 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1692 self::updateAvatar($cid, $contact['avatar'], true);
1695 } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
1696 Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
1697 self::updateAvatar($cid, $contact['avatar'], true);
1699 } elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1700 Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
1701 self::updateAvatar($cid, $contact['avatar'], true);
1707 * Return the photo path for a given contact array in the given size
1709 * @param array $contact contact array
1710 * @param string $size Size of the avatar picture
1711 * @param bool $no_update Don't perfom an update if no cached avatar was found
1712 * @return string photo path
1714 private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
1716 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1718 if (DI::config()->get('system', 'avatar_cache')) {
1720 case Proxy::SIZE_MICRO:
1721 if (!empty($contact['micro']) && !Photo::isPhotoURI($contact['micro'])) {
1722 return $contact['micro'];
1725 case Proxy::SIZE_THUMB:
1726 if (!empty($contact['thumb']) && !Photo::isPhotoURI($contact['thumb'])) {
1727 return $contact['thumb'];
1730 case Proxy::SIZE_SMALL:
1731 if (!empty($contact['photo']) && !Photo::isPhotoURI($contact['photo'])) {
1732 return $contact['photo'];
1738 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1742 * Return the photo path for a given contact array
1744 * @param array $contact Contact array
1745 * @param bool $no_update Don't perfom an update if no cached avatar was found
1746 * @return string photo path
1748 public static function getPhoto(array $contact, bool $no_update = false): string
1750 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1754 * Return the photo path (thumb size) for a given contact array
1756 * @param array $contact Contact array
1757 * @param bool $no_update Don't perfom an update if no cached avatar was found
1758 * @return string photo path
1760 public static function getThumb(array $contact, bool $no_update = false): string
1762 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1766 * Return the photo path (micro size) for a given contact array
1768 * @param array $contact Contact array
1769 * @param bool $no_update Don't perfom an update if no cached avatar was found
1770 * @return string photo path
1772 public static function getMicro(array $contact, bool $no_update = false): string
1774 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1778 * Check the given contact array for avatar cache fields
1780 * @param array $contact
1781 * @param bool $no_update Don't perfom an update if no cached avatar was found
1782 * @return array contact array with avatar cache fields
1784 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
1787 $contact_fields = [];
1788 $fields = ['photo', 'thumb', 'micro'];
1789 foreach ($fields as $field) {
1790 if (isset($contact[$field])) {
1791 $contact_fields[] = $field;
1793 if (isset($contact[$field]) && empty($contact[$field])) {
1798 if (!$update || $no_update) {
1802 $local = !empty($contact['url']) && Network::isLocalLink($contact['url']);
1804 if (!$local && !empty($contact['id']) && !empty($contact['avatar'])) {
1805 self::updateAvatar($contact['id'], $contact['avatar'], true);
1807 $new_contact = self::getById($contact['id'], $contact_fields);
1808 if (DBA::isResult($new_contact)) {
1809 // We only update the cache fields
1810 $contact = array_merge($contact, $new_contact);
1812 } elseif ($local && !empty($contact['avatar'])) {
1816 /// add the default avatars if the fields aren't filled
1817 if (isset($contact['photo']) && empty($contact['photo'])) {
1818 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1820 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1821 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1823 if (isset($contact['micro']) && empty($contact['micro'])) {
1824 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1831 * Fetch the default header for the given contact
1833 * @param array $contact contact array
1834 * @return string avatar URL
1836 public static function getDefaultHeader(array $contact): string
1838 if (!empty($contact['header'])) {
1839 return $contact['header'];
1842 if (!empty($contact['gsid'])) {
1843 // Use default banners for certain platforms
1844 $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]);
1845 $platform = strtolower($gserver['platform'] ?? '');
1850 switch ($platform) {
1855 * @author Lostinlight <https://mastodon.xyz/@lightone>
1856 * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
1857 * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
1859 $header = DI::baseUrl() . '/images/friendica-banner.jpg';
1864 * @author John Liu <https://www.flickr.com/photos/8047705@N02/>
1865 * @license CC BY 2.0 https://creativecommons.org/licenses/by/2.0/
1866 * @link https://www.flickr.com/photos/8047705@N02/5572197407
1868 $header = DI::baseUrl() . '/images/diaspora-banner.jpg';
1872 * Use a random picture.
1873 * The service provides random pictures from Unsplash.
1874 * @license https://unsplash.com/license
1876 $header = 'https://picsum.photos/seed/' . hash('ripemd128', $contact['url']) . '/960/300';
1884 * Fetch the default avatar for the given contact and size
1886 * @param array $contact contact array
1887 * @param string $size Size of the avatar picture
1888 * @return string avatar URL
1890 public static function getDefaultAvatar(array $contact, string $size): string
1893 case Proxy::SIZE_MICRO:
1894 $avatar['size'] = 48;
1895 $default = self::DEFAULT_AVATAR_MICRO;
1898 case Proxy::SIZE_THUMB:
1899 $avatar['size'] = 80;
1900 $default = self::DEFAULT_AVATAR_THUMB;
1903 case Proxy::SIZE_SMALL:
1905 $avatar['size'] = 300;
1906 $default = self::DEFAULT_AVATAR_PHOTO;
1910 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1912 $type = Contact::TYPE_PERSON;
1914 if (!empty($contact['id'])) {
1915 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]);
1916 $platform = $account['platform'] ?? '';
1917 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1920 if (empty($platform) && !empty($contact['uri-id'])) {
1921 $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]);
1922 $platform = $account['platform'] ?? '';
1923 $type = $account['contact-type'] ?? Contact::TYPE_PERSON;
1926 switch ($platform) {
1930 * @license GNU Affero General Public License v3.0
1931 * @link https://github.com/msdos621/corgidon/blob/main/public/avatars/original/missing.png
1933 $default = '/images/default/corgidon.png';
1939 * @license GNU Affero General Public License v3.0
1940 * @link https://github.com/diaspora/diaspora/
1942 $default = '/images/default/diaspora.png';
1948 * @license GNU Affero General Public License v3.0
1949 * @link https://github.com/superseriousbusiness/gotosocial/blob/main/web/assets/default_avatars/GoToSocial_icon1.svg
1951 $default = '/images/default/gotosocial.svg';
1957 * @license GNU Affero General Public License v3.0
1958 * @link https://github.com/hometown-fork/hometown/blob/hometown-dev/public/avatars/original/missing.png
1960 $default = '/images/default/hometown.png';
1966 * @license GNU Affero General Public License v3.0
1967 * @link https://github.com/koyuspace/mastodon/blob/main/public/avatars/original/missing.png
1969 $default = '/images/default/koyuspace.png';
1977 * @license GNU Affero General Public License v3.0
1978 * @link https://github.com/mastodon/mastodon/tree/main/public/avatars/original/missing.png
1980 $default = '/images/default/mastodon.png';
1984 if ($type == Contact::TYPE_COMMUNITY) {
1987 * @license GNU Affero General Public License v3.0
1988 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-video-channel.png
1990 $default = '/images/default/peertube-channel.png';
1994 * @license GNU Affero General Public License v3.0
1995 * @link https://github.com/Chocobozzz/PeerTube/blob/develop/client/src/assets/images/default-avatar-account.png
1997 $default = '/images/default/peertube-account.png';
2004 * @license GNU Affero General Public License v3.0
2005 * @link https://git.pleroma.social/pleroma/pleroma/-/blob/develop/priv/static/images/avi.png
2007 $default = '/images/default/pleroma.png';
2013 * @license GNU Affero General Public License v3.0
2014 * @link https://github.com/Plume-org/Plume/blob/main/assets/images/default-avatar.png
2016 $default = '/images/default/plume.png';
2019 return DI::baseUrl() . $default;
2022 if (!empty($contact['xmpp'])) {
2023 $avatar['email'] = $contact['xmpp'];
2024 } elseif (!empty($contact['addr'])) {
2025 $avatar['email'] = $contact['addr'];
2026 } elseif (!empty($contact['url'])) {
2027 $avatar['email'] = $contact['url'];
2029 return DI::baseUrl() . $default;
2032 $avatar['url'] = '';
2033 $avatar['success'] = false;
2035 Hook::callAll('avatar_lookup', $avatar);
2037 if ($avatar['success'] && !empty($avatar['url'])) {
2038 return $avatar['url'];
2041 return DI::baseUrl() . $default;
2045 * Get avatar link for given contact id
2047 * @param integer $cid contact id
2048 * @param string $size One of the Proxy::SIZE_* constants
2049 * @param string $updated Contact update date
2050 * @return string avatar link
2052 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2054 // We have to fetch the "updated" variable when it wasn't provided
2055 // The parameter can be provided to improve performance
2056 if (empty($updated)) {
2057 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2058 $updated = $account['updated'] ?? '';
2059 $guid = $account['guid'] ?? '';
2062 $guid = urlencode($guid);
2064 $url = DI::baseUrl() . '/photo/contact/';
2066 case Proxy::SIZE_MICRO:
2067 $url .= Proxy::PIXEL_MICRO . '/';
2069 case Proxy::SIZE_THUMB:
2070 $url .= Proxy::PIXEL_THUMB . '/';
2072 case Proxy::SIZE_SMALL:
2073 $url .= Proxy::PIXEL_SMALL . '/';
2075 case Proxy::SIZE_MEDIUM:
2076 $url .= Proxy::PIXEL_MEDIUM . '/';
2078 case Proxy::SIZE_LARGE:
2079 $url .= Proxy::PIXEL_LARGE . '/';
2082 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2086 * Get avatar link for given contact URL
2088 * @param string $url contact url
2089 * @param integer $uid user id
2090 * @param string $size One of the Proxy::SIZE_* constants
2091 * @return string avatar link
2093 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
2095 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
2096 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
2097 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
2098 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
2102 * Get header link for given contact id
2104 * @param integer $cid contact id
2105 * @param string $size One of the Proxy::SIZE_* constants
2106 * @param string $updated Contact update date
2107 * @return string header link
2109 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
2111 // We have to fetch the "updated" variable when it wasn't provided
2112 // The parameter can be provided to improve performance
2113 if (empty($updated) || empty($guid)) {
2114 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
2115 $updated = $account['updated'] ?? '';
2116 $guid = $account['guid'] ?? '';
2119 $guid = urlencode($guid);
2121 $url = DI::baseUrl() . '/photo/header/';
2123 case Proxy::SIZE_MICRO:
2124 $url .= Proxy::PIXEL_MICRO . '/';
2126 case Proxy::SIZE_THUMB:
2127 $url .= Proxy::PIXEL_THUMB . '/';
2129 case Proxy::SIZE_SMALL:
2130 $url .= Proxy::PIXEL_SMALL . '/';
2132 case Proxy::SIZE_MEDIUM:
2133 $url .= Proxy::PIXEL_MEDIUM . '/';
2135 case Proxy::SIZE_LARGE:
2136 $url .= Proxy::PIXEL_LARGE . '/';
2140 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
2144 * Updates the avatar links in a contact only if needed
2146 * @param int $cid Contact id
2147 * @param string $avatar Link to avatar picture
2148 * @param bool $force force picture update
2149 * @param bool $create_cache Enforces the creation of cached avatar fields
2152 * @throws HTTPException\InternalServerErrorException
2153 * @throws HTTPException\NotFoundException
2154 * @throws \ImagickException
2156 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
2158 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
2159 ['id' => $cid, 'self' => false]);
2160 if (!DBA::isResult($contact)) {
2164 $uid = $contact['uid'];
2166 // Only update the cached photo links of public contacts when they already are cached
2167 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
2168 if ($contact['avatar'] != $avatar) {
2169 self::update(['avatar' => $avatar], ['id' => $cid]);
2170 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
2175 // User contacts use are updated through the public contacts
2176 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2177 $pcid = self::getIdForURL($contact['url'], 0, false);
2178 if (!empty($pcid)) {
2179 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
2180 self::updateAvatar($pcid, $avatar, $force, true);
2185 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
2187 if ($default_avatar) {
2188 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
2191 $cache_avatar = DI::config()->get('system', 'cache_contact_avatar');
2193 // Local contact avatars don't need to be cached
2194 if ($cache_avatar && Network::isLocalLink($contact['url'])) {
2195 $cache_avatar = !DBA::exists('contact', ['nurl' => $contact['nurl'], 'self' => true]);
2198 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
2199 Avatar::deleteCache($contact);
2201 if ($default_avatar && Proxy::isLocalImage($avatar)) {
2202 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
2204 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
2205 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
2206 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
2209 // Use the data from the self account
2210 if (empty($fields)) {
2211 $local_uid = User::getIdForURL($contact['url']);
2212 if (!empty($local_uid)) {
2213 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
2214 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2218 if (empty($fields)) {
2219 $update = ($contact['avatar'] != $avatar) || $force;
2223 $contact['photo'] ?? '',
2224 $contact['thumb'] ?? '',
2225 $contact['micro'] ?? '',
2228 foreach ($data as $image_uri) {
2229 $image_rid = Photo::ridFromURI($image_uri);
2230 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
2231 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
2238 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
2240 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
2241 $update = !empty($fields);
2242 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
2248 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2251 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
2252 $fields = Avatar::fetchAvatarContact($contact, $avatar, $force);
2253 $update = ($avatar . $fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
2262 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
2263 // Collect all user contacts of the given public contact
2264 $personal_contacts = DBA::select('contact', ['id', 'uid'],
2265 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
2266 while ($personal_contact = DBA::fetch($personal_contacts)) {
2267 $cids[] = $personal_contact['id'];
2268 $uids[] = $personal_contact['uid'];
2270 DBA::close($personal_contacts);
2272 if (!empty($cids)) {
2273 // Delete possibly existing cached user contact avatars
2274 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
2280 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
2281 self::update($fields, ['id' => $cids]);
2284 public static function deleteContactByUrl(string $url)
2286 // Update contact data for all users
2287 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2288 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
2289 while ($contact = DBA::fetch($contacts)) {
2290 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
2291 self::remove($contact['id']);
2296 * Helper function for "updateFromProbe". Updates personal and public contact
2298 * @param integer $id contact id
2299 * @param integer $uid user id
2300 * @param integer $uri_id Uri-Id
2301 * @param string $url The profile URL of the contact
2302 * @param array $fields The fields that are updated
2304 * @throws \Exception
2306 private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
2308 if (!self::update($fields, ['id' => $id])) {
2309 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
2313 self::setAccountUser($id, $uid, $uri_id, $url);
2315 // Archive or unarchive the contact.
2316 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
2317 if (!DBA::isResult($contact)) {
2318 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
2322 if (isset($fields['failed'])) {
2323 if ($fields['failed']) {
2324 self::markForArchival($contact);
2326 self::unmarkForArchival($contact);
2330 if ($contact['uid'] != 0) {
2334 // Update contact data for all users
2335 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
2337 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
2338 self::update($fields, $condition);
2340 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
2341 $condition['network'] = Protocol::OSTATUS;
2343 // If the contact failed, propagate the update fields to all contacts
2344 if (empty($fields['failed'])) {
2345 unset($fields['last-update']);
2346 unset($fields['success_update']);
2347 unset($fields['failure_update']);
2350 if (empty($fields)) {
2354 self::update($fields, $condition);
2358 * Create or update an "account-user" entry
2360 * @param integer $id
2361 * @param integer $uid
2362 * @param integer $uri_id
2363 * @param string $url
2366 public static function setAccountUser(int $id, int $uid, int $uri_id, string $url)
2368 if (empty($uri_id)) {
2372 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['id' => $id]);
2373 if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
2374 if ($account_user['uid'] == $uid) {
2375 $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
2376 Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2378 // This should never happen
2379 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]);
2383 $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
2384 if (!empty($account_user['id'])) {
2385 if ($account_user['id'] == $id) {
2386 Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2388 } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
2389 $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
2390 Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2393 Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2394 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
2395 } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
2396 Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2398 Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
2403 * Remove duplicated contacts
2405 * @param string $nurl Normalised contact url
2406 * @param integer $uid User id
2408 * @throws \Exception
2410 public static function removeDuplicates(string $nurl, int $uid)
2412 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2413 $count = DBA::count('contact', $condition);
2418 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2419 if (!DBA::isResult($first_contact)) {
2420 // Shouldn't happen - so we handle it
2424 $first = $first_contact['id'];
2425 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2427 // Find all duplicates
2428 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2429 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2430 while ($duplicate = DBA::fetch($duplicates)) {
2431 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2435 Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2437 DBA::close($duplicates);
2438 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2443 * Updates contact record by provided id and optional network
2445 * @param integer $id contact id
2446 * @param string $network Optional network we are probing for
2448 * @throws HTTPException\InternalServerErrorException
2449 * @throws \ImagickException
2451 public static function updateFromProbe(int $id, string $network = '')
2453 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2454 if (!DBA::isResult($contact)) {
2458 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2460 if ($ret['network'] == Protocol::DIASPORA) {
2461 FContact::updateFromProbeArray($ret);
2464 return self::updateFromProbeArray($id, $ret);
2468 * Checks if the given contact has got local data
2471 * @param array $contact
2475 private static function hasLocalData(int $id, array $contact): bool
2477 if (!empty($contact['uri-id']) && DBA::exists('contact', ["`uri-id` = ? AND `uid` != ?", $contact['uri-id'], 0])) {
2478 // User contacts with the same uri-id exist
2480 } elseif (DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($contact['url']), 0])) {
2481 // User contacts with the same nurl exists (compatibility mode for systems with missing uri-id values)
2484 if (DBA::exists('post-tag', ['cid' => $id])) {
2485 // Is tagged in a post
2488 if (DBA::exists('user-contact', ['cid' => $id])) {
2489 // Has got user-contact data
2492 if (Post::exists(['author-id' => $id])) {
2493 // Posts with this author exist
2496 if (Post::exists(['owner-id' => $id])) {
2497 // Posts with this owner exist
2500 if (Post::exists(['causer-id' => $id])) {
2501 // Posts with this causer exist
2504 // We don't have got this contact locally
2509 * Updates contact record by provided id and probed data
2511 * @param integer $id contact id
2512 * @param array $ret Probed data
2514 * @throws HTTPException\InternalServerErrorException
2515 * @throws \ImagickException
2517 private static function updateFromProbeArray(int $id, array $ret): bool
2520 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2521 This will reliably kill your communication with old Friendica contacts.
2524 // These fields aren't updated by this routine:
2527 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2528 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2529 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
2530 'created', 'last-update'];
2531 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2532 if (!DBA::isResult($contact)) {
2536 if (self::isLocal($ret['url'])) {
2537 if ($contact['uid'] == 0) {
2538 Logger::info('Local contacts are not updated here.');
2540 self::updateFromPublicContact($id, $contact);
2545 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2546 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2549 // Delete all contacts with the same URL
2550 self::deleteContactByUrl($ret['url']);
2554 $uid = $contact['uid'];
2555 unset($contact['uid']);
2557 $uriid = $contact['uri-id'];
2558 unset($contact['uri-id']);
2560 $pubkey = $contact['pubkey'];
2561 unset($contact['pubkey']);
2563 $created = $contact['created'];
2564 unset($contact['created']);
2566 $last_update = $contact['last-update'];
2567 unset($contact['last-update']);
2569 $contact['photo'] = $contact['avatar'];
2570 unset($contact['avatar']);
2572 $updated = DateTimeFormat::utcNow();
2574 $has_local_data = self::hasLocalData($id, $contact);
2576 if (!Probe::isProbable($ret['network'])) {
2577 // Periodical checks are only done on federated contacts
2578 $failed_next_update = null;
2579 $success_next_update = null;
2580 } elseif ($has_local_data) {
2581 $failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2582 $success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
2584 $failed_next_update = DateTimeFormat::utc('now +6 month');
2585 $success_next_update = DateTimeFormat::utc('now +1 month');
2588 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2589 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2590 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]);
2594 // We must not try to update relay contacts via probe. They are no real contacts.
2595 // We check after the probing to be able to correct falsely detected contact types.
2596 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2597 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2598 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]);
2599 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2603 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2604 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2605 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]);
2609 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2610 $cid = self::getIdForURL($ret['url'], 0, false);
2611 if (!empty($cid) && ($cid != $id)) {
2612 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2613 return self::updateFromProbeArray($cid, $ret);
2617 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2618 $ret['unsearchable'] = $ret['hide'];
2621 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2622 $ret['forum'] = false;
2623 $ret['prv'] = false;
2624 $ret['contact-type'] = $ret['account-type'];
2625 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2626 $ret['forum'] = (bool)!$ret['manually-approve'];
2627 $ret['prv'] = (bool)!$ret['forum'];
2631 $new_pubkey = $ret['pubkey'] ?? '';
2633 if ($uid == 0 && DI::config()->get('system', 'fetch_featured_posts')) {
2634 if ($ret['network'] == Protocol::ACTIVITYPUB) {
2635 $apcontact = APContact::getByURL($ret['url'], false);
2636 if (!empty($apcontact['featured'])) {
2637 Worker::add(Worker::PRIORITY_LOW, 'FetchFeaturedPosts', $ret['url']);
2641 $ret['last-item'] = Probe::getLastUpdate($ret);
2642 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2646 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2648 // make sure to not overwrite existing values with blank entries except some technical fields
2649 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2650 foreach ($ret as $key => $val) {
2651 if (!array_key_exists($key, $contact)) {
2653 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2654 $ret[$key] = $contact[$key];
2655 } elseif ($ret[$key] != $contact[$key]) {
2660 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2663 unset($ret['last-item']);
2666 if (empty($uriid)) {
2670 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2671 self::updateAvatar($id, $ret['photo'], $update);
2675 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]);
2677 if (Contact\Relation::isDiscoverable($ret['url'])) {
2678 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2681 // Update the public contact
2683 $contact = self::getByURL($ret['url'], false, ['id']);
2684 if (!empty($contact['id'])) {
2685 self::updateFromProbeArray($contact['id'], $ret);
2692 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2693 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2694 $ret['updated'] = $updated;
2695 $ret['failed'] = false;
2696 $ret['next-update'] = $success_next_update;
2697 $ret['local-data'] = $has_local_data;
2699 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2700 if (empty($pubkey) && !empty($new_pubkey)) {
2701 $ret['pubkey'] = $new_pubkey;
2704 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2705 $ret['uri-date'] = $updated;
2708 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2709 $ret['name-date'] = $updated;
2712 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2713 $ret['last-update'] = $updated;
2714 $ret['success_update'] = $updated;
2717 unset($ret['photo']);
2719 self::updateContact($id, $uid, $ret['uri-id'], $ret['url'], $ret);
2721 if (Contact\Relation::isDiscoverable($ret['url'])) {
2722 Worker::add(Worker::PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2728 private static function updateFromPublicContact(int $id, array $contact)
2730 $public = self::getByURL($contact['url'], false);
2734 foreach ($contact as $field => $value) {
2735 if ($field == 'uid') {
2738 if ($public[$field] != $value) {
2739 $fields[$field] = $public[$field];
2742 if (!empty($fields)) {
2743 self::update($fields, ['id' => $id, 'self' => false]);
2744 Logger::info('Updating local contact', ['id' => $id]);
2749 * Updates contact record by provided URL
2751 * @param integer $url contact url
2752 * @return integer Contact id
2753 * @throws HTTPException\InternalServerErrorException
2754 * @throws \ImagickException
2756 public static function updateFromProbeByURL(string $url): int
2758 $id = self::getIdForURL($url);
2764 self::updateFromProbe($id);
2770 * Detects the communication protocol for a given contact url.
2771 * This is used to detect Friendica contacts that we can communicate via AP.
2773 * @param string $url contact url
2774 * @param string $network Network of that contact
2775 * @return string with protocol
2777 public static function getProtocol(string $url, string $network): string
2779 if ($network != Protocol::DFRN) {
2783 $apcontact = APContact::getByURL($url);
2784 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2785 return Protocol::ACTIVITYPUB;
2792 * Takes a $uid and a url/handle and adds a new contact
2794 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2795 * dfrn_request page.
2797 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2800 * $return['success'] boolean true if successful
2801 * $return['message'] error text if success is false.
2803 * Takes a $uid and a url/handle and adds a new contact
2805 * @param int $uid The user id the contact should be created for
2806 * @param string $url The profile URL of the contact
2807 * @param string $network
2809 * @throws HTTPException\InternalServerErrorException
2810 * @throws HTTPException\NotFoundException
2811 * @throws \ImagickException
2813 public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
2815 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2817 // remove ajax junk, e.g. Twitter
2818 $url = str_replace('/#!/', '/', $url);
2820 if (!Network::isUrlAllowed($url)) {
2821 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2825 if (Network::isUrlBlocked($url)) {
2826 $result['message'] = DI::l10n()->t('Blocked domain');
2831 $result['message'] = DI::l10n()->t('Connect URL missing.');
2835 $arr = ['url' => $url, 'contact' => []];
2837 Hook::callAll('follow', $arr);
2840 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2844 if (!empty($arr['contact']['name'])) {
2846 $ret = $arr['contact'];
2849 $ret = Probe::uri($url, $network, $uid);
2851 // Ensure that the public contact exists
2852 if ($ret['network'] != Protocol::PHANTOM) {
2853 self::getIdForURL($url);
2857 if (($network != '') && ($ret['network'] != $network)) {
2858 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2862 // check if we already have a contact
2863 // the poll url is more reliable than the profile url, as we may have
2864 // indirect links or webfinger links
2866 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2867 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2868 if (!DBA::isResult($contact)) {
2869 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2870 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2873 $protocol = self::getProtocol($ret['url'], $ret['network']);
2875 // This extra param just confuses things, remove it
2876 if ($protocol === Protocol::DIASPORA) {
2877 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2880 // do we have enough information?
2881 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2882 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . '<br />';
2883 if (empty($ret['poll'])) {
2884 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . '<br />';
2886 if (empty($ret['name'])) {
2887 $result['message'] .= DI::l10n()->t('An author or name was not found.') . '<br />';
2889 if (empty($ret['url'])) {
2890 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . '<br />';
2892 if (strpos($ret['url'], '@') !== false) {
2893 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . '<br />';
2894 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . '<br />';
2899 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2900 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . '<br />';
2901 $ret['notify'] = '';
2904 if (!$ret['notify']) {
2905 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . '<br />';
2908 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2910 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2912 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2915 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2916 $pending = (bool)$ret['manually-approve'];
2919 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2923 if (DBA::isResult($contact)) {
2925 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2927 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2928 self::update($fields, ['id' => $contact['id']]);
2930 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2932 // create contact record
2935 'created' => DateTimeFormat::utcNow(),
2936 'url' => $ret['url'],
2937 'nurl' => Strings::normaliseLink($ret['url']),
2938 'addr' => $ret['addr'],
2939 'alias' => $ret['alias'],
2940 'batch' => $ret['batch'],
2941 'notify' => $ret['notify'],
2942 'poll' => $ret['poll'],
2943 'poco' => $ret['poco'],
2944 'name' => $ret['name'],
2945 'nick' => $ret['nick'],
2946 'network' => $ret['network'],
2947 'baseurl' => $ret['baseurl'],
2948 'gsid' => $ret['gsid'] ?? null,
2949 'protocol' => $protocol,
2950 'pubkey' => $ret['pubkey'],
2951 'rel' => $new_relation,
2952 'priority'=> $ret['priority'],
2953 'writable'=> $writeable,
2954 'hidden' => $hidden,
2957 'pending' => $pending,
2962 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2963 if (!DBA::isResult($contact)) {
2964 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . '<br />';
2968 $contact_id = $contact['id'];
2969 $result['cid'] = $contact_id;
2971 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2973 // Update the avatar
2974 self::updateAvatar($contact_id, $ret['photo']);
2976 // pull feed and consume it, which should subscribe to the hub.
2977 if ($contact['network'] == Protocol::OSTATUS) {
2978 Worker::add(Worker::PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2982 self::updateFromProbeArray($contact_id, $ret);
2984 Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
2987 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2993 * @param array $importer Owner (local user) data
2994 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2995 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2996 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2997 * @param string $note Introduction additional message
2998 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2999 * @throws HTTPException\InternalServerErrorException
3000 * @throws \ImagickException
3002 public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
3004 // Should always be set
3005 if (empty($datarray['author-id'])) {
3009 $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
3010 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
3011 if (!DBA::isResult($pub_contact)) {
3012 // Should never happen
3016 // Contact is blocked at node-level
3017 if (self::isBlocked($datarray['author-id'])) {
3021 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
3022 $name = $pub_contact['name'];
3023 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
3024 $nick = $pub_contact['nick'];
3025 $network = $pub_contact['network'];
3027 // Ensure that we don't create a new contact when there already is one
3028 $cid = self::getIdForURL($url, $importer['uid']);
3030 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
3033 self::clearFollowerFollowingEndpointCache($importer['uid']);
3035 if (!empty($contact)) {
3036 if (!empty($contact['pending'])) {
3037 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
3041 // Contact is blocked at user-level
3042 if (!empty($contact['id']) && !empty($importer['id']) &&
3043 Contact\User::isBlocked($contact['id'], $importer['id'])) {
3047 // Make sure that the existing contact isn't archived
3048 self::unmarkForArchival($contact);
3050 if (($contact['rel'] == self::SHARING)
3051 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
3052 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
3053 ['id' => $contact['id'], 'uid' => $importer['uid']]);
3056 // Ensure to always have the correct network type, independent from the connection request method
3057 self::updateFromProbe($contact['id']);
3059 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3063 // send email notification to owner?
3064 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
3065 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
3069 // create contact record
3070 $contact_id = self::insert([
3071 'uid' => $importer['uid'],
3072 'created' => DateTimeFormat::utcNow(),
3074 'nurl' => Strings::normaliseLink($url),
3077 'network' => $network,
3078 'rel' => self::FOLLOWER,
3085 // Ensure to always have the correct network type, independent from the connection request method
3086 self::updateFromProbe($contact_id);
3088 self::updateAvatar($contact_id, $photo, true);
3090 Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
3092 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
3094 /// @TODO Encapsulate this into a function/method
3095 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
3096 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
3097 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3098 // create notification
3099 if (is_array($contact_record)) {
3100 $intro = DI::introFactory()->createNew(
3102 $contact_record['id'],
3105 DI::intro()->save($intro);
3108 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
3110 if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
3111 DI::notify()->createFromArray([
3112 'type' => Notification\Type::INTRO,
3113 'otype' => Notification\ObjectType::INTRO,
3114 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
3115 'uid' => $user['uid'],
3116 'cid' => $contact_record['id'],
3117 'link' => DI::baseUrl() . '/notifications/intros',
3120 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
3121 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
3122 self::createFromProbeForUser($importer['uid'], $url, $network);
3125 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
3126 $fields = ['pending' => false];
3127 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
3128 $fields['rel'] = self::FRIEND;
3131 self::update($fields, $condition);
3141 * Update the local relationship when a local user loses a follower
3143 * @param array $contact User-specific contact (uid != 0) array
3145 * @throws HTTPException\InternalServerErrorException
3146 * @throws \ImagickException
3148 public static function removeFollower(array $contact)
3150 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
3151 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
3152 } elseif (!empty($contact['id'])) {
3153 self::remove($contact['id']);
3155 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
3159 self::clearFollowerFollowingEndpointCache($contact['uid']);
3161 $cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
3163 DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
3167 * Update the local relationship when a local user unfollow a contact.
3168 * Removes the contact for sharing-only protocols (feed and mail).
3170 * @param array $contact User-specific contact (uid != 0) array
3171 * @throws HTTPException\InternalServerErrorException
3173 public static function removeSharer(array $contact)
3175 self::clearFollowerFollowingEndpointCache($contact['uid']);
3177 if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
3178 self::remove($contact['id']);
3180 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
3185 * Create a birthday event.
3187 * Update the year and the birthday.
3189 public static function updateBirthdays()
3193 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
3194 AND NOT `contact`.`pending`
3195 AND NOT `contact`.`hidden`
3196 AND NOT `contact`.`blocked`
3197 AND NOT `contact`.`archive`
3198 AND NOT `contact`.`deleted`',
3204 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
3206 while ($contact = DBA::fetch($contacts)) {
3207 Logger::notice('update_contact_birthday: ' . $contact['bd']);
3209 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
3211 if (Event::createBirthday($contact, $nextbd)) {
3215 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
3216 ['id' => $contact['id']]
3220 DBA::close($contacts);
3224 * Remove the unavailable contact ids from the provided list
3226 * @param array $contact_ids Contact id list
3228 * @throws \Exception
3230 public static function pruneUnavailable(array $contact_ids): array
3232 if (empty($contact_ids)) {
3236 $contacts = self::selectToArray(['id'], [
3237 'id' => $contact_ids,
3243 return array_column($contacts, 'id');
3247 * Returns a magic link to authenticate remote visitors
3249 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
3251 * @param string $contact_url The address of the target contact profile
3252 * @param string $url An url that we will be redirected to after the authentication
3254 * @return string with "redir" link
3255 * @throws HTTPException\InternalServerErrorException
3256 * @throws \ImagickException
3258 public static function magicLink(string $contact_url, string $url = ''): string
3260 if (!DI::userSession()->isAuthenticated()) {
3261 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3264 $contact = self::getByURL($contact_url, false);
3265 if (empty($contact)) {
3266 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
3269 // Prevents endless loop in case only a non-public contact exists for the contact URL
3270 unset($contact['uid']);
3272 return self::magicLinkByContact($contact, $url ?: $contact_url);
3276 * Returns a magic link to authenticate remote visitors
3278 * @param integer $cid The contact id of the target contact profile
3279 * @param string $url An url that we will be redirected to after the authentication
3281 * @return string with "redir" link
3282 * @throws HTTPException\InternalServerErrorException
3283 * @throws \ImagickException
3285 public static function magicLinkById(int $cid, string $url = ''): string
3287 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
3289 return self::magicLinkByContact($contact, $url);
3293 * Returns a magic link to authenticate remote visitors
3295 * @param array $contact The contact array with "uid", "network" and "url"
3296 * @param string $url An url that we will be redirected to after the authentication
3298 * @return string with "redir" link
3299 * @throws HTTPException\InternalServerErrorException
3300 * @throws \ImagickException
3302 public static function magicLinkByContact(array $contact, string $url = ''): string
3304 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
3306 if (!DI::userSession()->isAuthenticated()) {
3307 return $destination;
3310 // Only redirections to the same host do make sense
3311 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
3315 if (DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'stay_local') && ($url == '')) {
3316 return 'contact/' . $contact['id'] . '/conversations';
3319 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
3320 return $destination;
3323 if (empty($contact['id'])) {
3324 return $destination;
3327 $redirect = 'redir/' . $contact['id'];
3329 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
3330 $redirect .= '?url=' . $url;
3337 * Is the contact a forum?
3339 * @param integer $contactid ID of the contact
3341 * @return boolean "true" if it is a forum
3343 public static function isForum(int $contactid): bool
3345 $fields = ['contact-type'];
3346 $condition = ['id' => $contactid];
3347 $contact = DBA::selectFirst('contact', $fields, $condition);
3348 if (!DBA::isResult($contact)) {
3353 return ($contact['contact-type'] == self::TYPE_COMMUNITY);
3357 * Can the remote contact receive private messages?
3359 * @param array $contact
3362 public static function canReceivePrivateMessages(array $contact): bool
3364 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
3365 $self = $contact['self'] ?? false;
3367 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
3371 * Search contact table by nick or name
3373 * @param string $search Name or nick
3374 * @param string $mode Search mode (e.g. "community")
3375 * @param int $uid User ID
3377 * @return array with search results
3378 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
3380 public static function searchByName(string $search, string $mode = '', int $uid = 0): array
3382 if (empty($search)) {
3386 // check supported networks
3387 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
3388 if (DI::config()->get('system', 'diaspora_enabled')) {
3389 $networks[] = Protocol::DIASPORA;
3392 if (!DI::config()->get('system', 'ostatus_disabled')) {
3393 $networks[] = Protocol::OSTATUS;
3396 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
3399 $condition['blocked'] = false;
3402 // check if we search only communities or every contact
3403 if ($mode === 'community') {
3404 $condition['contact-type'] = self::TYPE_COMMUNITY;
3409 $condition = DBA::mergeConditions($condition,
3410 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
3411 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
3413 $contacts = self::selectToArray([], $condition);
3418 * Add public contacts from an array
3420 * @param array $urls
3421 * @return array result "count", "added" and "updated"
3423 public static function addByUrls(array $urls): array
3430 foreach ($urls as $url) {
3431 if (empty($url) || !is_string($url)) {
3434 $contact = self::getByURL($url, false, ['id', 'network', 'next-update']);
3435 if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
3436 Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
3438 } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
3439 Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
3447 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3451 * Returns a random, global contact array of the current node
3453 * @return array The profile array
3456 public static function getRandomContact(): array
3458 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3459 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3460 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3461 ], ['order' => ['RAND()']]);
3463 if (DBA::isResult($contact)) {