3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\App\BaseURL;
25 use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
26 use Friendica\Content\Pager;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Renderer;
32 use Friendica\Core\Session;
33 use Friendica\Core\System;
34 use Friendica\Core\Worker;
35 use Friendica\Database\Database;
36 use Friendica\Database\DBA;
38 use Friendica\Network\HTTPException;
39 use Friendica\Network\Probe;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Protocol\OStatus;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
52 * functions for interacting with a contact
56 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
57 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
58 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
64 const LOCK_INSERT = 'contact-insert';
69 * TYPE_UNKNOWN - unknown type
71 * TYPE_PERSON - the account belongs to a person
72 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
74 * TYPE_ORGANISATION - the account belongs to an organisation
75 * Associated page type: PAGE_SOAPBOX
77 * TYPE_NEWS - the account is a news reflector
78 * Associated page type: PAGE_SOAPBOX
80 * TYPE_COMMUNITY - the account is community forum
81 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
83 * TYPE_RELAY - the account is a relay
84 * This will only be assigned to contacts, not to user accounts
87 const TYPE_UNKNOWN = -1;
88 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
89 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
90 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
91 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
92 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
112 const MIRROR_DEACTIVATED = 0;
113 const MIRROR_FORWARDED = 1;
114 const MIRROR_OWN_POST = 2;
115 const MIRROR_NATIVE_RESHARE = 3;
118 * @param array $fields Array of selected fields, empty for all
119 * @param array $condition Array of fields for condition
120 * @param array $params Array of several parameters
124 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
126 return DBA::selectToArray('contact', $fields, $condition, $params);
130 * @param array $fields Array of selected fields, empty for all
131 * @param array $condition Array of fields for condition
132 * @param array $params Array of several parameters
136 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
138 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
144 * Insert a row into the contact table
145 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
147 * @param array $fields field array
148 * @param int $duplicate_mode Do an update on a duplicate entry
150 * @return int id of the created contact
153 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT)
155 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
156 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
159 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
161 if (empty($fields['created'])) {
162 $fields['created'] = DateTimeFormat::utcNow();
165 DBA::insert('contact', $fields, $duplicate_mode);
166 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
167 if (!DBA::isResult($contact)) {
169 Logger::warning('Created contact could not be found', ['fields' => $fields]);
173 Contact\User::insertForContactArray($contact);
175 // Search for duplicated contacts and get rid of them
176 if (!$contact['self']) {
177 self::removeDuplicates($contact['nurl'], $contact['uid']);
180 return $contact['id'];
184 * Updates rows in the contact table
186 * @param array $fields contains the fields that are updated
187 * @param array $condition condition array with the key values
188 * @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)
190 * @return boolean was the update successfull?
193 public static function update(array $fields, array $condition, $old_fields = [])
195 $ret = DBA::update('contact', $fields, $condition, $old_fields);
197 // Apply changes to the "user-contact" table on dedicated fields
198 Contact\User::updateByContactUpdate($fields, $condition);
204 * @param integer $id Contact ID
205 * @param array $fields Array of selected fields, empty for all
206 * @return array|boolean Contact record if it exists, false otherwise
209 public static function getById($id, $fields = [])
211 return DBA::selectFirst('contact', $fields, ['id' => $id]);
215 * Fetches a contact by a given url
217 * @param string $url profile url
218 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
219 * @param array $fields Field list
220 * @param integer $uid User ID of the contact
221 * @return array contact array
223 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
225 if ($update || is_null($update)) {
226 $cid = self::getIdForURL($url, $uid, $update);
231 $contact = self::getById($cid, $fields);
232 if (empty($contact)) {
238 // Add internal fields
240 if (!empty($fields)) {
241 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
242 if (!in_array($internal, $fields)) {
243 $fields[] = $internal;
244 $removal[] = $internal;
249 // We first try the nurl (http://server.tld/nick), most common case
250 $options = ['order' => ['id']];
251 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
253 // Then the addr (nick@server.tld)
254 if (!DBA::isResult($contact)) {
255 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
258 // Then the alias (which could be anything)
259 if (!DBA::isResult($contact)) {
260 // The link could be provided as http although we stored it as https
261 $ssl_url = str_replace('http://', 'https://', $url);
262 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
263 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
266 if (!DBA::isResult($contact)) {
270 // Update the contact in the background if needed
271 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
272 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
273 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
276 // Remove the internal fields
277 foreach ($removal as $internal) {
278 unset($contact[$internal]);
285 * Fetches a contact for a given user by a given url.
286 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
288 * @param string $url profile url
289 * @param integer $uid User ID of the contact
290 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
291 * @param array $fields Field list
292 * @return array contact array
294 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
297 $contact = self::getByURL($url, $update, $fields, $uid);
298 if (!empty($contact)) {
299 if (!empty($contact['id'])) {
300 $contact['cid'] = $contact['id'];
307 $contact = self::getByURL($url, $update, $fields);
308 if (!empty($contact['id'])) {
310 $contact['zid'] = $contact['id'];
316 * Tests if the given contact is a follower
318 * @param int $cid Either public contact id or user's contact id
319 * @param int $uid User ID
321 * @return boolean is the contact id a follower?
322 * @throws HTTPException\InternalServerErrorException
323 * @throws \ImagickException
325 public static function isFollower($cid, $uid)
327 if (Contact\User::isBlocked($cid, $uid)) {
331 $cdata = self::getPublicAndUserContactID($cid, $uid);
332 if (empty($cdata['user'])) {
336 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
337 return DBA::exists('contact', $condition);
341 * Tests if the given contact url is a follower
343 * @param string $url Contact URL
344 * @param int $uid User ID
346 * @return boolean is the contact id a follower?
347 * @throws HTTPException\InternalServerErrorException
348 * @throws \ImagickException
350 public static function isFollowerByURL($url, $uid)
352 $cid = self::getIdForURL($url, $uid);
358 return self::isFollower($cid, $uid);
362 * Tests if the given user follow the given contact
364 * @param int $cid Either public contact id or user's contact id
365 * @param int $uid User ID
367 * @return boolean is the contact url being followed?
368 * @throws HTTPException\InternalServerErrorException
369 * @throws \ImagickException
371 public static function isSharing($cid, $uid)
373 if (Contact\User::isBlocked($cid, $uid)) {
377 $cdata = self::getPublicAndUserContactID($cid, $uid);
378 if (empty($cdata['user'])) {
382 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
383 return DBA::exists('contact', $condition);
387 * Tests if the given user follow the given contact url
389 * @param string $url Contact URL
390 * @param int $uid User ID
392 * @return boolean is the contact url being followed?
393 * @throws HTTPException\InternalServerErrorException
394 * @throws \ImagickException
396 public static function isSharingByURL($url, $uid)
398 $cid = self::getIdForURL($url, $uid);
404 return self::isSharing($cid, $uid);
408 * Get the basepath for a given contact link
410 * @param string $url The contact link
411 * @param boolean $dont_update Don't update the contact
413 * @return string basepath
414 * @throws HTTPException\InternalServerErrorException
415 * @throws \ImagickException
417 public static function getBasepath($url, $dont_update = false)
419 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
420 if (!DBA::isResult($contact)) {
424 if (!empty($contact['baseurl'])) {
425 return $contact['baseurl'];
426 } elseif ($dont_update) {
430 // Update the existing contact
431 self::updateFromProbe($contact['id']);
433 // And fetch the result
434 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
435 if (empty($contact['baseurl'])) {
436 Logger::info('No baseurl for contact', ['url' => $url]);
440 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
441 return $contact['baseurl'];
445 * Check if the given contact url is on the same server
447 * @param string $url The contact link
449 * @return boolean Is it the same server?
451 public static function isLocal($url)
453 if (!parse_url($url, PHP_URL_SCHEME)) {
454 $addr_parts = explode('@', $url);
455 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
458 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
462 * Check if the given contact ID is on the same server
464 * @param string $url The contact link
466 * @return boolean Is it the same server?
468 public static function isLocalById(int $cid)
470 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
471 if (!DBA::isResult($contact)) {
475 if (empty($contact['baseurl'])) {
476 $baseurl = self::getBasepath($contact['url'], true);
478 $baseurl = $contact['baseurl'];
481 return Strings::compareLink($baseurl, DI::baseUrl());
485 * Returns the public contact id of the given user id
487 * @param integer $uid User ID
489 * @return integer|boolean Public contact id for given user id
492 public static function getPublicIdByUserId($uid)
494 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
495 if (!DBA::isResult($self)) {
498 return self::getIdForURL($self['url']);
502 * Returns the contact id for the user and the public contact id for a given contact id
504 * @param int $cid Either public contact id or user's contact id
505 * @param int $uid User ID
507 * @return array with public and user's contact id
508 * @throws HTTPException\InternalServerErrorException
509 * @throws \ImagickException
511 public static function getPublicAndUserContactID($cid, $uid)
513 // We have to use the legacy function as long as the post update hasn't finished
514 if (DI::config()->get('system', 'post_update_version') < 1427) {
515 return self::legacyGetPublicAndUserContactID($cid, $uid);
518 if (empty($uid) || empty($cid)) {
522 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
523 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
527 $pcid = $contact['pid'];
528 if ($contact['uid'] == $uid) {
529 $ucid = $contact['id'];
531 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
532 if (DBA::isResult($contact)) {
533 $ucid = $contact['id'];
539 return ['public' => $pcid, 'user' => $ucid];
543 * Helper function for "getPublicAndUserContactID"
545 * @param int $cid Either public contact id or user's contact id
546 * @param int $uid User ID
548 * @return array with public and user's contact id
549 * @throws HTTPException\InternalServerErrorException
550 * @throws \ImagickException
552 private static function legacyGetPublicAndUserContactID($cid, $uid)
554 if (empty($uid) || empty($cid)) {
558 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
559 if (!DBA::isResult($contact)) {
563 // We quit when the user id don't match the user id of the provided contact
564 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
568 if ($contact['uid'] != 0) {
569 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
573 $ucid = $contact['id'];
575 $pcid = $contact['id'];
576 $ucid = self::getIdForURL($contact['url'], $uid);
579 return ['public' => $pcid, 'user' => $ucid];
583 * Returns contact details for a given contact id in combination with a user id
585 * @param int $cid A contact ID
586 * @param int $uid The User ID
587 * @param array $fields The selected fields for the contact
589 * @return array The contact details
593 public static function getContactForUser($cid, $uid, array $fields = [])
595 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
597 if (!DBA::isResult($contact)) {
605 * Creates the self-contact for the provided user id
608 * @return bool Operation success
609 * @throws HTTPException\InternalServerErrorException
611 public static function createSelfFromUserId($uid)
613 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
614 ['uid' => $uid, 'account_expired' => false]);
615 if (!DBA::isResult($user)) {
620 'uid' => $user['uid'],
621 'created' => DateTimeFormat::utcNow(),
623 'name' => $user['username'],
624 'nick' => $user['nickname'],
625 'pubkey' => $user['pubkey'],
626 'prvkey' => $user['prvkey'],
627 'photo' => User::getAvatarUrl($user),
628 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB),
629 'micro' => User::getAvatarUrl($user, Proxy::SIZE_MICRO),
632 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
633 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
634 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
635 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
636 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
637 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
638 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
639 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
640 'name-date' => DateTimeFormat::utcNow(),
641 'uri-date' => DateTimeFormat::utcNow(),
642 'avatar-date' => DateTimeFormat::utcNow(),
648 // Only create the entry if it doesn't exist yet
649 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
650 $return = (bool)self::insert($contact);
653 // Create the public contact
654 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
655 $contact['self'] = false;
657 $contact['prvkey'] = null;
659 self::insert($contact, Database::INSERT_IGNORE);
666 * Updates the self-contact for the provided user id
669 * @param boolean $update_avatar Force the avatar update
670 * @return bool "true" if updated
671 * @throws HTTPException\InternalServerErrorException
673 public static function updateSelfFromUserID($uid, $update_avatar = false)
675 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
676 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
677 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
678 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
679 if (!DBA::isResult($self)) {
683 $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
684 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
685 if (!DBA::isResult($user)) {
689 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
690 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
691 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
692 if (!DBA::isResult($profile)) {
696 $file_suffix = 'jpg';
698 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
699 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
700 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
701 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
702 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp'], 'matrix' => $profile['matrix'], 'network' => Protocol::DFRN];
704 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
705 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
706 $fields['nurl'] = Strings::normaliseLink($fields['url']);
707 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
708 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
709 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
710 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
711 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
712 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
714 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
715 if (DBA::isResult($avatar)) {
716 if ($update_avatar) {
717 $fields['avatar-date'] = DateTimeFormat::utcNow();
720 // Creating the path to the avatar, beginning with the file suffix
721 $types = Images::supportedTypes();
722 if (isset($types[$avatar['type']])) {
723 $file_suffix = $types[$avatar['type']];
726 // We are adding a timestamp value so that other systems won't use cached content
727 $timestamp = strtotime($fields['avatar-date']);
729 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
730 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
732 $fields['photo'] = $prefix . '4' . $suffix;
733 $fields['thumb'] = $prefix . '5' . $suffix;
734 $fields['micro'] = $prefix . '6' . $suffix;
736 // We hadn't found a photo entry, so we use the default avatar
737 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
738 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
739 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
742 $fields['avatar'] = User::getAvatarUrl($user);
743 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
744 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
745 $fields['unsearchable'] = !$profile['net-publish'];
749 foreach ($fields as $field => $content) {
750 if ($self[$field] != $content) {
756 if ($fields['name'] != $self['name']) {
757 $fields['name-date'] = DateTimeFormat::utcNow();
759 $fields['updated'] = DateTimeFormat::utcNow();
760 self::update($fields, ['id' => $self['id']]);
762 // Update the public contact as well
763 $fields['prvkey'] = null;
764 $fields['self'] = false;
765 self::update($fields, ['uid' => 0, 'nurl' => $self['nurl']]);
767 // Update the profile
769 'photo' => User::getAvatarUrl($user),
770 'thumb' => User::getAvatarUrl($user, Proxy::SIZE_THUMB)
773 DBA::update('profile', $fields, ['uid' => $uid]);
780 * Marks a contact for removal
782 * @param int $id contact id
783 * @throws HTTPException\InternalServerErrorException
785 public static function remove($id)
787 // We want just to make sure that we don't delete our "self" contact
788 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
789 if (!DBA::isResult($contact)) {
793 // Archive the contact
794 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
796 // Delete it in the background
797 Worker::add(PRIORITY_MEDIUM, 'Contact\Remove', $id);
801 * Sends an unfriend message. Removes the contact for two-way unfriending or sharing only protocols (feed an mail)
803 * @param array $user User unfriending
804 * @param array $contact Contact (uid != 0) unfriended
805 * @param boolean $two_way Revoke eventual inbound follow as well
806 * @return bool|null true if successful, false if not, null if no remote action was performed
807 * @throws HTTPException\InternalServerErrorException
808 * @throws \ImagickException
810 public static function terminateFriendship(array $user, array $contact): ?bool
812 $result = Protocol::terminateFriendship($user, $contact);
814 if ($contact['rel'] == Contact::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
815 self::remove($contact['id']);
817 self::update(['rel' => Contact::FOLLOWER], ['id' => $contact['id']]);
824 * Revoke follow privileges of the remote user contact
826 * @param array $contact Contact unfriended
827 * @return bool|null Whether the remote operation is successful or null if no remote operation was performed
828 * @throws HTTPException\InternalServerErrorException
829 * @throws \ImagickException
831 public static function revokeFollow(array $contact): ?bool
833 if (empty($contact['network'])) {
834 throw new \InvalidArgumentException('Empty network in contact array');
837 if (empty($contact['uid'])) {
838 throw new \InvalidArgumentException('Unexpected public contact record');
841 $result = Protocol::revokeFollow($contact);
843 // A null value here means the remote network doesn't support explicit follow revocation, we can still
844 // break the locally recorded relationship
845 if ($result !== false) {
846 if ($contact['rel'] == self::FRIEND) {
847 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
849 self::remove($contact['id']);
858 * Marks a contact for archival after a communication issue delay
860 * Contact has refused to recognise us as a friend. We will start a countdown.
861 * If they still don't recognise us in 32 days, the relationship is over,
862 * and we won't waste any more time trying to communicate with them.
863 * This provides for the possibility that their database is temporarily messed
864 * up or some other transient event and that there's a possibility we could recover from it.
866 * @param array $contact contact to mark for archival
868 * @throws HTTPException\InternalServerErrorException
870 public static function markForArchival(array $contact)
872 if (!isset($contact['url']) && !empty($contact['id'])) {
873 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
874 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
875 if (!DBA::isResult($contact)) {
878 } elseif (!isset($contact['url'])) {
879 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
882 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
884 // Contact already archived or "self" contact? => nothing to do
885 if ($contact['archive'] || $contact['self']) {
889 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
890 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
891 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
894 * We really should send a notification to the owner after 2-3 weeks
895 * so they won't be surprised when the contact vanishes and can take
896 * remedial action if this was a serious mistake or glitch
899 /// @todo Check for contact vitality via probing
900 $archival_days = DI::config()->get('system', 'archival_days', 32);
902 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
903 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
904 /* Relationship is really truly dead. archive them rather than
905 * delete, though if the owner tries to unarchive them we'll start
906 * the whole process over again.
908 self::update(['archive' => true], ['id' => $contact['id']]);
909 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
915 * Cancels the archival countdown
917 * @see Contact::markForArchival()
919 * @param array $contact contact to be unmarked for archival
923 public static function unmarkForArchival(array $contact)
925 // Always unarchive the relay contact entry
926 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
927 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
928 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
929 if (!DBA::exists('contact', array_merge($condition, $fields))) {
930 self::update($fields, $condition);
934 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
935 $exists = DBA::exists('contact', $condition);
937 // We don't need to update, we never marked this contact for archival
942 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
944 if (!isset($contact['url']) && !empty($contact['id'])) {
945 $fields = ['id', 'url', 'batch'];
946 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
947 if (!DBA::isResult($contact)) {
952 // It's a miracle. Our dead contact has inexplicably come back to life.
953 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
954 self::update($fields, ['id' => $contact['id']]);
955 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
959 * Returns the data array for the photo menu of a given contact
961 * @param array $contact contact
962 * @param int $uid optional, default 0
964 * @throws HTTPException\InternalServerErrorException
965 * @throws \ImagickException
967 public static function photoMenu(array $contact, $uid = 0)
978 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
980 $profile_link = self::magicLinkByContact($contact);
981 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
986 // Look for our own contact if the uid doesn't match and isn't public
987 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
988 if (DBA::isResult($contact_own)) {
989 return self::photoMenu($contact_own, $uid);
994 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
996 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
998 $profile_link = $contact['url'];
1001 if ($profile_link === 'mailbox') {
1006 $status_link = $profile_link . '/status';
1007 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1008 $profile_link = $profile_link . '/profile';
1011 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1012 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1015 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1016 $poke_link = 'contact/' . $contact['id'] . '/poke';
1019 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1021 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1024 $unfollow_link = '';
1025 if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
1026 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1027 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1028 } elseif(!$contact['pending']) {
1029 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1035 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1037 if (empty($contact['uid'])) {
1039 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1040 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1041 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1042 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1043 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1047 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1048 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1049 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1050 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1051 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1052 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1053 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1054 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1055 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1058 if (!empty($contact['pending'])) {
1060 $intro = DI::intro()->selectForContact($contact['id']);
1061 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
1062 } catch (IntroductionNotFoundException $exception) {
1063 DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
1068 $args = ['contact' => $contact, 'menu' => &$menu];
1070 Hook::callAll('contact_photo_menu', $args);
1072 $menucondensed = [];
1074 foreach ($menu as $menuname => $menuitem) {
1075 if ($menuitem[1] != '') {
1076 $menucondensed[$menuname] = $menuitem;
1080 return $menucondensed;
1084 * Fetch the contact id for a given URL and user
1086 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1087 * `addr` or `alias`.
1089 * If there's no record and we aren't looking for a public contact, we quit.
1090 * If there's one, we check that it isn't time to update the picture else we
1091 * directly return the found contact id.
1093 * Second, we probe the provided $url whether it's http://server.tld/profile or
1094 * nick@server.tld. We quit if we can't get any info back.
1096 * Third, we create the contact record if it doesn't exist
1098 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1099 * if there's any updates
1101 * @param string $url Contact URL
1102 * @param integer $uid The user id for the contact (0 = public contact)
1103 * @param boolean $update true = always update, false = never update, null = update when not found
1104 * @param array $default Default value for creating the contact when everything else fails
1106 * @return integer Contact ID
1107 * @throws HTTPException\InternalServerErrorException
1108 * @throws \ImagickException
1110 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1115 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1119 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1121 if (!empty($contact)) {
1122 $contact_id = $contact["id"];
1124 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1125 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1128 } elseif ($uid != 0) {
1129 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1131 } elseif (empty($default) && !is_null($update) && !$update) {
1132 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1138 if (empty($default['network']) || $update) {
1139 $data = Probe::uri($url, "", $uid);
1141 // Take the default values when probing failed
1142 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1143 $data = array_merge($data, $default);
1145 } elseif (!empty($default['network'])) {
1149 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1150 // Fetch data for the public contact via the first found personal contact
1151 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1152 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1153 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1154 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1156 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1157 if (!DBA::isResult($personal_contact)) {
1158 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1161 if (DBA::isResult($personal_contact)) {
1162 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1163 $data = $personal_contact;
1164 $data['photo'] = $personal_contact['avatar'];
1165 $data['account-type'] = $personal_contact['contact-type'];
1166 $data['hide'] = $personal_contact['unsearchable'];
1167 unset($data['avatar']);
1168 unset($data['contact-type']);
1169 unset($data['unsearchable']);
1173 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1174 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1179 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1180 if (!empty($data['alias'])) {
1181 $urls[] = Strings::normaliseLink($data['alias']);
1183 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1184 if (!empty($contact['id'])) {
1185 $contact_id = $contact['id'];
1186 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1191 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1194 'url' => $data['url'],
1195 'nurl' => Strings::normaliseLink($data['url']),
1196 'network' => $data['network'],
1197 'created' => DateTimeFormat::utcNow(),
1198 'rel' => self::SHARING,
1204 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1206 // Before inserting we do check if the entry does exist now.
1207 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1208 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1209 if (DBA::isResult($contact)) {
1210 $contact_id = $contact['id'];
1211 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1213 $contact_id = self::insert($fields);
1215 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1218 DI::lock()->release(self::LOCK_INSERT);
1220 Logger::warning('Contact lock had not been acquired');
1224 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1228 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1231 self::updateFromProbeArray($contact_id, $data);
1233 // Don't return a number for a deleted account
1234 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1235 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1243 * Checks if the contact is archived
1245 * @param int $cid contact id
1247 * @return boolean Is the contact archived?
1248 * @throws HTTPException\InternalServerErrorException
1250 public static function isArchived(int $cid)
1256 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1257 if (!DBA::isResult($contact)) {
1261 if ($contact['archive']) {
1265 // Check status of ActivityPub endpoints
1266 $apcontact = APContact::getByURL($contact['url'], false);
1267 if (!empty($apcontact)) {
1268 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1272 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1277 // Check status of Diaspora endpoints
1278 if (!empty($contact['batch'])) {
1279 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1280 return DBA::exists('contact', $condition);
1287 * Checks if the contact is blocked
1289 * @param int $cid contact id
1291 * @return boolean Is the contact blocked?
1292 * @throws HTTPException\InternalServerErrorException
1294 public static function isBlocked($cid)
1300 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1301 if (!DBA::isResult($blocked)) {
1305 if (Network::isUrlBlocked($blocked['url'])) {
1309 return (bool) $blocked['blocked'];
1313 * Checks if the contact is hidden
1315 * @param int $cid contact id
1317 * @return boolean Is the contact hidden?
1318 * @throws \Exception
1320 public static function isHidden($cid)
1326 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1327 if (!DBA::isResult($hidden)) {
1330 return (bool) $hidden['hidden'];
1334 * Returns posts from a given contact url
1336 * @param string $contact_url Contact URL
1337 * @param bool $thread_mode
1338 * @param int $update Update mode
1339 * @param int $parent Item parent ID for the update mode
1340 * @param bool $only_media Only display media content
1341 * @return string posts in HTML
1342 * @throws \Exception
1344 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0, bool $only_media = false)
1346 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent, $only_media);
1350 * Returns posts from a given contact id
1352 * @param int $cid Contact ID
1353 * @param bool $thread_mode
1354 * @param int $update Update mode
1355 * @param int $parent Item parent ID for the update mode
1356 * @param bool $only_media Only display media content
1357 * @return string posts in HTML
1358 * @throws \Exception
1360 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0, bool $only_media = false)
1362 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1363 if (!DBA::isResult($contact)) {
1367 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1368 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1373 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1376 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1377 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1379 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1380 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1383 if (!empty($parent)) {
1384 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1386 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1387 if (!empty($last_received)) {
1388 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1393 $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
1394 Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
1397 if (DI::mode()->isMobile()) {
1398 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1399 DI::config()->get('system', 'itemspage_network_mobile'));
1401 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1402 DI::config()->get('system', 'itemspage_network'));
1405 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1407 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1409 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1410 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1411 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1417 $items = Post::toArray(Post::selectForUser(local_user(), ['uri-id', 'gravity', 'parent-uri-id', 'thr-parent-id', 'author-id'], $condition, $params));
1419 $o .= DI::conversation()->create($items, 'contacts', $update, false, 'commented', local_user());
1421 $items = Post::toArray(Post::selectForUser(local_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1423 $o .= DI::conversation()->create($items, 'contact-posts', $update);
1427 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1428 $o .= HTML::scrollLoader();
1430 $o .= $pager->renderMinimal(count($items));
1438 * Returns the account type name
1440 * The function can be called with either the user or the contact array
1442 * @param array $contact contact or user array
1445 public static function getAccountType(array $contact)
1447 // There are several fields that indicate that the contact or user is a forum
1448 // "page-flags" is a field in the user table,
1449 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1450 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1451 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1452 || (isset($contact['forum']) && intval($contact['forum']))
1453 || (isset($contact['prv']) && intval($contact['prv']))
1454 || (isset($contact['community']) && intval($contact['community']))
1456 $type = self::TYPE_COMMUNITY;
1458 $type = self::TYPE_PERSON;
1461 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1462 if (isset($contact["contact-type"])) {
1463 $type = $contact["contact-type"];
1466 if (isset($contact["account-type"])) {
1467 $type = $contact["account-type"];
1471 case self::TYPE_ORGANISATION:
1472 $account_type = DI::l10n()->t("Organisation");
1475 case self::TYPE_NEWS:
1476 $account_type = DI::l10n()->t('News');
1479 case self::TYPE_COMMUNITY:
1480 $account_type = DI::l10n()->t("Forum");
1488 return $account_type;
1496 * @throws \Exception
1498 public static function block($cid, $reason = null)
1500 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1506 * Unblocks a contact
1510 * @throws \Exception
1512 public static function unblock($cid)
1514 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1520 * Ensure that cached avatar exist
1522 * @param integer $cid
1524 public static function checkAvatarCache(int $cid)
1526 $contact = DBA::selectFirst('contact', ['url', 'network', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1527 if (!DBA::isResult($contact)) {
1531 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1532 if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
1533 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1534 self::updateAvatar($cid, $contact['avatar'], true);
1537 } elseif (!empty($contact['photo']) || !empty($contact['thumb']) || !empty($contact['micro'])) {
1538 Logger::info('Removing avatar cache', ['id' => $cid, 'contact' => $contact]);
1539 self::updateAvatar($cid, $contact['avatar'], true);
1545 * Return the photo path for a given contact array in the given size
1547 * @param array $contact contact array
1548 * @param string $field Fieldname of the photo in the contact array
1549 * @param string $size Size of the avatar picture
1550 * @param string $avatar Avatar path that is displayed when no photo had been found
1551 * @param bool $no_update Don't perfom an update if no cached avatar was found
1552 * @return string photo path
1554 private static function getAvatarPath(array $contact, string $size, $no_update = false)
1556 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1557 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1561 * Return the photo path for a given contact array
1563 * @param array $contact Contact array
1564 * @param bool $no_update Don't perfom an update if no cached avatar was found
1565 * @return string photo path
1567 public static function getPhoto(array $contact, bool $no_update = false)
1569 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1573 * Return the photo path (thumb size) for a given contact array
1575 * @param array $contact Contact array
1576 * @param bool $no_update Don't perfom an update if no cached avatar was found
1577 * @return string photo path
1579 public static function getThumb(array $contact, bool $no_update = false)
1581 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1585 * Return the photo path (micro size) for a given contact array
1587 * @param array $contact Contact array
1588 * @param bool $no_update Don't perfom an update if no cached avatar was found
1589 * @return string photo path
1591 public static function getMicro(array $contact, bool $no_update = false)
1593 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1597 * Check the given contact array for avatar cache fields
1599 * @param array $contact
1600 * @param bool $no_update Don't perfom an update if no cached avatar was found
1601 * @return array contact array with avatar cache fields
1603 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false)
1606 $contact_fields = [];
1607 $fields = ['photo', 'thumb', 'micro'];
1608 foreach ($fields as $field) {
1609 if (isset($contact[$field])) {
1610 $contact_fields[] = $field;
1612 if (isset($contact[$field]) && empty($contact[$field])) {
1617 if (!$update || $no_update) {
1621 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1622 self::updateAvatar($contact['id'], $contact['avatar'], true);
1624 $new_contact = self::getById($contact['id'], $contact_fields);
1625 if (DBA::isResult($new_contact)) {
1626 // We only update the cache fields
1627 $contact = array_merge($contact, $new_contact);
1631 /// add the default avatars if the fields aren't filled
1632 if (isset($contact['photo']) && empty($contact['photo'])) {
1633 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1635 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1636 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1638 if (isset($contact['micro']) && empty($contact['micro'])) {
1639 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1646 * Fetch the default avatar for the given contact and size
1648 * @param array $contact contact array
1649 * @param string $size Size of the avatar picture
1650 * @return string avatar URL
1652 public static function getDefaultAvatar(array $contact, string $size)
1655 case Proxy::SIZE_MICRO:
1656 $avatar['size'] = 48;
1657 $default = self::DEFAULT_AVATAR_MICRO;
1660 case Proxy::SIZE_THUMB:
1661 $avatar['size'] = 80;
1662 $default = self::DEFAULT_AVATAR_THUMB;
1665 case Proxy::SIZE_SMALL:
1667 $avatar['size'] = 300;
1668 $default = self::DEFAULT_AVATAR_PHOTO;
1672 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1673 return DI::baseUrl() . $default;
1676 if (!empty($contact['xmpp'])) {
1677 $avatar['email'] = $contact['xmpp'];
1678 } elseif (!empty($contact['addr'])) {
1679 $avatar['email'] = $contact['addr'];
1680 } elseif (!empty($contact['url'])) {
1681 $avatar['email'] = $contact['url'];
1683 return DI::baseUrl() . $default;
1686 $avatar['url'] = '';
1687 $avatar['success'] = false;
1689 Hook::callAll('avatar_lookup', $avatar);
1691 if ($avatar['success'] && !empty($avatar['url'])) {
1692 return $avatar['url'];
1695 return DI::baseUrl() . $default;
1699 * Get avatar link for given contact id
1701 * @param integer $cid contact id
1702 * @param string $size One of the Proxy::SIZE_* constants
1703 * @param string $updated Contact update date
1704 * @return string avatar link
1706 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''):string
1708 // We have to fetch the "updated" variable when it wasn't provided
1709 // The parameter can be provided to improve performance
1710 if (empty($updated) || empty($guid)) {
1711 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1712 $updated = $account['updated'] ?? '';
1713 $guid = $account['guid'] ?? '';
1716 $guid = urlencode($guid);
1718 $url = DI::baseUrl() . '/photo/contact/';
1720 case Proxy::SIZE_MICRO:
1721 $url .= Proxy::PIXEL_MICRO . '/';
1723 case Proxy::SIZE_THUMB:
1724 $url .= Proxy::PIXEL_THUMB . '/';
1726 case Proxy::SIZE_SMALL:
1727 $url .= Proxy::PIXEL_SMALL . '/';
1729 case Proxy::SIZE_MEDIUM:
1730 $url .= Proxy::PIXEL_MEDIUM . '/';
1732 case Proxy::SIZE_LARGE:
1733 $url .= Proxy::PIXEL_LARGE . '/';
1736 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
1740 * Get avatar link for given contact URL
1742 * @param string $url contact url
1743 * @param integer $uid user id
1744 * @param string $size One of the Proxy::SIZE_* constants
1745 * @return string avatar link
1747 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''):string
1749 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
1750 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
1751 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
1752 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1756 * Get header link for given contact id
1758 * @param integer $cid contact id
1759 * @param string $size One of the Proxy::SIZE_* constants
1760 * @param string $updated Contact update date
1761 * @return string header link
1763 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''):string
1765 // We have to fetch the "updated" variable when it wasn't provided
1766 // The parameter can be provided to improve performance
1767 if (empty($updated) || empty($guid)) {
1768 $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]);
1769 $updated = $account['updated'] ?? '';
1770 $guid = $account['guid'] ?? '';
1773 $guid = urlencode($guid);
1775 $url = DI::baseUrl() . '/photo/header/';
1777 case Proxy::SIZE_MICRO:
1778 $url .= Proxy::PIXEL_MICRO . '/';
1780 case Proxy::SIZE_THUMB:
1781 $url .= Proxy::PIXEL_THUMB . '/';
1783 case Proxy::SIZE_SMALL:
1784 $url .= Proxy::PIXEL_SMALL . '/';
1786 case Proxy::SIZE_MEDIUM:
1787 $url .= Proxy::PIXEL_MEDIUM . '/';
1789 case Proxy::SIZE_LARGE:
1790 $url .= Proxy::PIXEL_LARGE . '/';
1794 return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
1798 * Updates the avatar links in a contact only if needed
1800 * @param int $cid Contact id
1801 * @param string $avatar Link to avatar picture
1802 * @param bool $force force picture update
1803 * @param bool $create_cache Enforces the creation of cached avatar fields
1806 * @throws HTTPException\InternalServerErrorException
1807 * @throws HTTPException\NotFoundException
1808 * @throws \ImagickException
1810 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1812 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network'],
1813 ['id' => $cid, 'self' => false]);
1814 if (!DBA::isResult($contact)) {
1818 $uid = $contact['uid'];
1820 // Only update the cached photo links of public contacts when they already are cached
1821 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1822 if ($contact['avatar'] != $avatar) {
1823 self::update(['avatar' => $avatar], ['id' => $cid]);
1824 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1829 // User contacts use are updated through the public contacts
1830 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1831 $pcid = self::getIdForURL($contact['url'], 0, false);
1832 if (!empty($pcid)) {
1833 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1834 self::updateAvatar($pcid, $avatar, $force, true);
1839 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
1841 if ($default_avatar) {
1842 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1845 if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
1846 if ($default_avatar && Proxy::isLocalImage($avatar)) {
1847 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1849 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
1850 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
1851 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1854 // Use the data from the self account
1855 if (empty($fields)) {
1856 $local_uid = User::getIdForURL($contact['url']);
1857 if (!empty($local_uid)) {
1858 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1859 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1863 if (empty($fields)) {
1864 $update = ($contact['avatar'] != $avatar) || $force;
1868 $contact['photo'] ?? '',
1869 $contact['thumb'] ?? '',
1870 $contact['micro'] ?? '',
1873 foreach ($data as $image_uri) {
1874 $image_rid = Photo::ridFromURI($image_uri);
1875 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1876 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1883 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1885 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1886 $update = !empty($fields);
1887 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1893 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1896 Photo::delete(['uid' => $uid, 'contact-id' => $cid, 'photo-type' => Photo::CONTACT_AVATAR]);
1897 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1898 'photo' => '', 'thumb' => '', 'micro' => ''];
1899 $update = ($avatar != $contact['avatar'] . $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1908 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1909 // Collect all user contacts of the given public contact
1910 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1911 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1912 while ($personal_contact = DBA::fetch($personal_contacts)) {
1913 $cids[] = $personal_contact['id'];
1914 $uids[] = $personal_contact['uid'];
1916 DBA::close($personal_contacts);
1918 if (!empty($cids)) {
1919 // Delete possibly existing cached user contact avatars
1920 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'photo-type' => Photo::CONTACT_AVATAR]);
1926 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1927 self::update($fields, ['id' => $cids]);
1930 public static function deleteContactByUrl(string $url)
1932 // Update contact data for all users
1933 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
1934 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
1935 while ($contact = DBA::fetch($contacts)) {
1936 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
1937 self::remove($contact['id']);
1942 * Helper function for "updateFromProbe". Updates personal and public contact
1944 * @param integer $id contact id
1945 * @param integer $uid user id
1946 * @param string $old_url The previous profile URL of the contact
1947 * @param string $new_url The profile URL of the contact
1948 * @param array $fields The fields that are updated
1950 * @throws \Exception
1952 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
1954 if (!self::update($fields, ['id' => $id])) {
1955 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1959 // Search for duplicated contacts and get rid of them
1960 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
1964 // Archive or unarchive the contact.
1965 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1966 if (!DBA::isResult($contact)) {
1967 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1971 if (isset($fields['failed'])) {
1972 if ($fields['failed']) {
1973 self::markForArchival($contact);
1975 self::unmarkForArchival($contact);
1979 if ($contact['uid'] != 0) {
1983 // Update contact data for all users
1984 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
1986 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
1987 self::update($fields, $condition);
1989 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
1990 $condition['network'] = Protocol::OSTATUS;
1992 // If the contact failed, propagate the update fields to all contacts
1993 if (empty($fields['failed'])) {
1994 unset($fields['last-update']);
1995 unset($fields['success_update']);
1996 unset($fields['failure_update']);
1999 if (empty($fields)) {
2003 self::update($fields, $condition);
2007 * Remove duplicated contacts
2009 * @param string $nurl Normalised contact url
2010 * @param integer $uid User id
2012 * @throws \Exception
2014 public static function removeDuplicates(string $nurl, int $uid)
2016 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2017 $count = DBA::count('contact', $condition);
2022 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2023 if (!DBA::isResult($first_contact)) {
2024 // Shouldn't happen - so we handle it
2028 $first = $first_contact['id'];
2029 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2030 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2031 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2032 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2036 // Find all duplicates
2037 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2038 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2039 while ($duplicate = DBA::fetch($duplicates)) {
2040 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2044 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2046 DBA::close($duplicates);
2047 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2052 * @param integer $id contact id
2053 * @param string $network Optional network we are probing for
2055 * @throws HTTPException\InternalServerErrorException
2056 * @throws \ImagickException
2058 public static function updateFromProbe(int $id, string $network = '')
2060 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2061 if (!DBA::isResult($contact)) {
2065 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2066 return self::updateFromProbeArray($id, $ret);
2070 * @param integer $id contact id
2071 * @param array $ret Probed data
2073 * @throws HTTPException\InternalServerErrorException
2074 * @throws \ImagickException
2076 private static function updateFromProbeArray(int $id, array $ret)
2079 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2080 This will reliably kill your communication with old Friendica contacts.
2083 // These fields aren't updated by this routine:
2086 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2087 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2088 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix'];
2089 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2090 if (!DBA::isResult($contact)) {
2094 if (self::isLocal($ret['url'])) {
2095 if ($contact['uid'] == 0) {
2096 Logger::info('Local contacts are not updated here.');
2098 self::updateFromPublicContact($id, $contact);
2103 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2104 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2107 // Delete all contacts with the same URL
2108 self::deleteContactByUrl($ret['url']);
2112 $uid = $contact['uid'];
2113 unset($contact['uid']);
2115 $uriid = $contact['uri-id'];
2116 unset($contact['uri-id']);
2118 $pubkey = $contact['pubkey'];
2119 unset($contact['pubkey']);
2121 $contact['photo'] = $contact['avatar'];
2122 unset($contact['avatar']);
2124 $updated = DateTimeFormat::utcNow();
2126 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2127 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2128 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2132 // We must not try to update relay contacts via probe. They are no real contacts.
2133 // We check after the probing to be able to correct falsely detected contact types.
2134 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2135 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2136 self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2137 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2141 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2142 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2143 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2147 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2148 $cid = self::getIdForURL($ret['url'], 0, false);
2149 if (!empty($cid) && ($cid != $id)) {
2150 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2151 return self::updateFromProbeArray($cid, $ret);
2155 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2156 $ret['unsearchable'] = $ret['hide'];
2159 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2160 $ret['forum'] = false;
2161 $ret['prv'] = false;
2162 $ret['contact-type'] = $ret['account-type'];
2163 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2164 $ret['forum'] = (bool)!$ret['manually-approve'];
2165 $ret['prv'] = (bool)!$ret['forum'];
2169 $new_pubkey = $ret['pubkey'] ?? '';
2172 $ret['last-item'] = Probe::getLastUpdate($ret);
2173 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2177 $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
2179 // make sure to not overwrite existing values with blank entries except some technical fields
2180 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2181 foreach ($ret as $key => $val) {
2182 if (!array_key_exists($key, $contact)) {
2184 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2185 $ret[$key] = $contact[$key];
2186 } elseif ($ret[$key] != $contact[$key]) {
2191 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2194 unset($ret['last-item']);
2197 if (empty($uriid)) {
2201 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2202 self::updateAvatar($id, $ret['photo'], $update);
2205 $uriid = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2208 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2210 if (Contact\Relation::isDiscoverable($ret['url'])) {
2211 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2214 // Update the public contact
2216 $contact = self::getByURL($ret['url'], false, ['id']);
2217 if (!empty($contact['id'])) {
2218 self::updateFromProbeArray($contact['id'], $ret);
2225 $ret['uri-id'] = $uriid;
2226 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2227 $ret['updated'] = $updated;
2228 $ret['failed'] = false;
2230 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2231 if (empty($pubkey) && !empty($new_pubkey)) {
2232 $ret['pubkey'] = $new_pubkey;
2235 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2236 $ret['uri-date'] = $updated;
2239 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2240 $ret['name-date'] = $updated;
2243 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2244 $ret['last-update'] = $updated;
2245 $ret['success_update'] = $updated;
2248 unset($ret['photo']);
2250 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2252 if (Contact\Relation::isDiscoverable($ret['url'])) {
2253 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2259 private static function updateFromPublicContact(int $id, array $contact)
2261 $public = self::getByURL($contact['url'], false);
2265 foreach ($contact as $field => $value) {
2266 if ($field == 'uid') {
2269 if ($public[$field] != $value) {
2270 $fields[$field] = $public[$field];
2273 if (!empty($fields)) {
2274 self::update($fields, ['id' => $id, 'self' => false]);
2275 Logger::info('Updating local contact', ['id' => $id]);
2280 * @param integer $url contact url
2281 * @return integer Contact id
2282 * @throws HTTPException\InternalServerErrorException
2283 * @throws \ImagickException
2285 public static function updateFromProbeByURL($url)
2287 $id = self::getIdForURL($url);
2293 self::updateFromProbe($id);
2299 * Detects the communication protocol for a given contact url.
2300 * This is used to detect Friendica contacts that we can communicate via AP.
2302 * @param string $url contact url
2303 * @param string $network Network of that contact
2304 * @return string with protocol
2306 public static function getProtocol($url, $network)
2308 if ($network != Protocol::DFRN) {
2312 $apcontact = APContact::getByURL($url);
2313 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2314 return Protocol::ACTIVITYPUB;
2321 * Takes a $uid and a url/handle and adds a new contact
2323 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2324 * dfrn_request page.
2326 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2329 * $return['success'] boolean true if successful
2330 * $return['message'] error text if success is false.
2332 * Takes a $uid and a url/handle and adds a new contact
2334 * @param int $uid The user id the contact should be created for
2335 * @param string $url The profile URL of the contact
2336 * @param string $network
2338 * @throws HTTPException\InternalServerErrorException
2339 * @throws HTTPException\NotFoundException
2340 * @throws \ImagickException
2342 public static function createFromProbeForUser(int $uid, $url, $network = '')
2344 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2346 // remove ajax junk, e.g. Twitter
2347 $url = str_replace('/#!/', '/', $url);
2349 if (!Network::isUrlAllowed($url)) {
2350 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2354 if (Network::isUrlBlocked($url)) {
2355 $result['message'] = DI::l10n()->t('Blocked domain');
2360 $result['message'] = DI::l10n()->t('Connect URL missing.');
2364 $arr = ['url' => $url, 'contact' => []];
2366 Hook::callAll('follow', $arr);
2369 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2373 if (!empty($arr['contact']['name'])) {
2375 $ret = $arr['contact'];
2378 $ret = Probe::uri($url, $network, $uid);
2381 if (($network != '') && ($ret['network'] != $network)) {
2382 Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2386 // check if we already have a contact
2387 // the poll url is more reliable than the profile url, as we may have
2388 // indirect links or webfinger links
2390 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2391 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2392 if (!DBA::isResult($contact)) {
2393 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2394 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2397 $protocol = self::getProtocol($ret['url'], $ret['network']);
2399 // This extra param just confuses things, remove it
2400 if ($protocol === Protocol::DIASPORA) {
2401 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2404 // do we have enough information?
2405 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2406 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2407 if (empty($ret['poll'])) {
2408 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2410 if (empty($ret['name'])) {
2411 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2413 if (empty($ret['url'])) {
2414 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2416 if (strpos($ret['url'], '@') !== false) {
2417 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2418 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2423 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2424 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2425 $ret['notify'] = '';
2428 if (!$ret['notify']) {
2429 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2432 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2434 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2436 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2439 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2440 $pending = (bool)$ret['manually-approve'];
2443 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2447 if (DBA::isResult($contact)) {
2449 $new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
2451 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2452 self::update($fields, ['id' => $contact['id']]);
2454 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2456 // create contact record
2459 'created' => DateTimeFormat::utcNow(),
2460 'url' => $ret['url'],
2461 'nurl' => Strings::normaliseLink($ret['url']),
2462 'addr' => $ret['addr'],
2463 'alias' => $ret['alias'],
2464 'batch' => $ret['batch'],
2465 'notify' => $ret['notify'],
2466 'poll' => $ret['poll'],
2467 'poco' => $ret['poco'],
2468 'name' => $ret['name'],
2469 'nick' => $ret['nick'],
2470 'network' => $ret['network'],
2471 'baseurl' => $ret['baseurl'],
2472 'gsid' => $ret['gsid'] ?? null,
2473 'protocol' => $protocol,
2474 'pubkey' => $ret['pubkey'],
2475 'rel' => $new_relation,
2476 'priority'=> $ret['priority'],
2477 'writable'=> $writeable,
2478 'hidden' => $hidden,
2481 'pending' => $pending,
2486 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2487 if (!DBA::isResult($contact)) {
2488 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2492 $contact_id = $contact['id'];
2493 $result['cid'] = $contact_id;
2495 Group::addMember(User::getDefaultGroup($uid), $contact_id);
2497 // Update the avatar
2498 self::updateAvatar($contact_id, $ret['photo']);
2500 // pull feed and consume it, which should subscribe to the hub.
2501 if ($contact['network'] == Protocol::OSTATUS) {
2502 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2506 self::updateFromProbeArray($contact_id, $ret);
2508 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2511 $result['success'] = Protocol::follow($uid, $contact, $protocol);
2517 * Unfollow a contact
2519 * @param int $cid Public contact id
2520 * @param int $uid User ID
2522 * @return bool "true" if unfollowing had been successful
2524 public static function unfollow(int $cid, int $uid)
2526 $cdata = self::getPublicAndUserContactID($cid, $uid);
2527 if (empty($cdata['user'])) {
2531 $contact = self::getById($cdata['user']);
2533 self::removeSharer([], $contact);
2539 * @param array $importer Owner (local user) data
2540 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2541 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2542 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2543 * @param string $note Introduction additional message
2544 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2545 * @throws HTTPException\InternalServerErrorException
2546 * @throws \ImagickException
2548 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2550 // Should always be set
2551 if (empty($datarray['author-id'])) {
2555 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2556 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2557 if (!DBA::isResult($pub_contact)) {
2558 // Should never happen
2562 // Contact is blocked at node-level
2563 if (self::isBlocked($datarray['author-id'])) {
2567 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2568 $name = $pub_contact['name'];
2569 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2570 $nick = $pub_contact['nick'];
2571 $network = $pub_contact['network'];
2573 // Ensure that we don't create a new contact when there already is one
2574 $cid = self::getIdForURL($url, $importer['uid']);
2576 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2579 if (!empty($contact)) {
2580 if (!empty($contact['pending'])) {
2581 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2585 // Contact is blocked at user-level
2586 if (!empty($contact['id']) && !empty($importer['id']) &&
2587 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2591 // Make sure that the existing contact isn't archived
2592 self::unmarkForArchival($contact);
2594 if (($contact['rel'] == self::SHARING)
2595 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2596 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2597 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2600 // Ensure to always have the correct network type, independent from the connection request method
2601 self::updateFromProbe($contact['id']);
2603 Post\UserNotification::insertNotification($contact['id'], Activity::FOLLOW, $importer['uid']);
2607 // send email notification to owner?
2608 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2609 Logger::notice('ignoring duplicated connection request from pending contact ' . $url);
2613 // create contact record
2614 $contact_id = self::insert([
2615 'uid' => $importer['uid'],
2616 'created' => DateTimeFormat::utcNow(),
2618 'nurl' => Strings::normaliseLink($url),
2621 'network' => $network,
2622 'rel' => self::FOLLOWER,
2629 // Ensure to always have the correct network type, independent from the connection request method
2630 self::updateFromProbe($contact_id);
2632 self::updateAvatar($contact_id, $photo, true);
2634 Post\UserNotification::insertNotification($contact_id, Activity::FOLLOW, $importer['uid']);
2636 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2638 /// @TODO Encapsulate this into a function/method
2639 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2640 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2641 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2642 // create notification
2643 if (is_array($contact_record)) {
2644 $intro = DI::introFactory()->createNew(
2646 $contact_record['id'],
2649 DI::intro()->save($intro);
2652 Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
2654 if (($user['notify-flags'] & Notification\Type::INTRO) &&
2655 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2657 DI::notify()->createFromArray([
2658 'type' => Notification\Type::INTRO,
2659 'otype' => Notification\ObjectType::INTRO,
2660 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2661 'uid' => $user['uid'],
2662 'cid' => $contact_record['id'],
2663 'link' => DI::baseUrl() . '/notifications/intros',
2666 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2667 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2668 self::createFromProbeForUser($importer['uid'], $url, $network);
2671 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2672 $fields = ['pending' => false];
2673 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2674 $fields['rel'] = self::FRIEND;
2677 self::update($fields, $condition);
2686 public static function removeFollower(array $contact)
2688 if (in_array($contact['rel'] ?? [], [self::FRIEND, self::SHARING])) {
2689 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2690 } elseif (!empty($contact['id'])) {
2691 self::remove($contact['id']);
2693 DI::logger()->info('Couldn\'t remove follower because of invalid contact array', ['contact' => $contact, 'callstack' => System::callstack()]);
2697 public static function removeSharer($importer, $contact)
2699 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2700 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2702 self::remove($contact['id']);
2707 * Create a birthday event.
2709 * Update the year and the birthday.
2711 public static function updateBirthdays()
2715 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2716 AND NOT `contact`.`pending`
2717 AND NOT `contact`.`hidden`
2718 AND NOT `contact`.`blocked`
2719 AND NOT `contact`.`archive`
2720 AND NOT `contact`.`deleted`',
2726 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2728 while ($contact = DBA::fetch($contacts)) {
2729 Logger::notice('update_contact_birthday: ' . $contact['bd']);
2731 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2733 if (Event::createBirthday($contact, $nextbd)) {
2737 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2738 ['id' => $contact['id']]
2742 DBA::close($contacts);
2746 * Remove the unavailable contact ids from the provided list
2748 * @param array $contact_ids Contact id list
2750 * @throws \Exception
2752 public static function pruneUnavailable(array $contact_ids)
2754 if (empty($contact_ids)) {
2758 $contacts = self::selectToArray(['id'], [
2759 'id' => $contact_ids,
2765 return array_column($contacts, 'id');
2769 * Returns a magic link to authenticate remote visitors
2771 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2773 * @param string $contact_url The address of the target contact profile
2774 * @param string $url An url that we will be redirected to after the authentication
2776 * @return string with "redir" link
2777 * @throws HTTPException\InternalServerErrorException
2778 * @throws \ImagickException
2780 public static function magicLink($contact_url, $url = '')
2782 if (!Session::isAuthenticated()) {
2783 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2786 $contact = self::getByURL($contact_url, false);
2787 if (empty($contact)) {
2788 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2791 // Prevents endless loop in case only a non-public contact exists for the contact URL
2792 unset($contact['uid']);
2794 return self::magicLinkByContact($contact, $url ?: $contact_url);
2798 * Returns a magic link to authenticate remote visitors
2800 * @param integer $cid The contact id of the target contact profile
2801 * @param string $url An url that we will be redirected to after the authentication
2803 * @return string with "redir" link
2804 * @throws HTTPException\InternalServerErrorException
2805 * @throws \ImagickException
2807 public static function magicLinkById($cid, $url = '')
2809 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2811 return self::magicLinkByContact($contact, $url);
2815 * Returns a magic link to authenticate remote visitors
2817 * @param array $contact The contact array with "uid", "network" and "url"
2818 * @param string $url An url that we will be redirected to after the authentication
2820 * @return string with "redir" link
2821 * @throws HTTPException\InternalServerErrorException
2822 * @throws \ImagickException
2824 public static function magicLinkByContact($contact, $url = '')
2826 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2828 if (!Session::isAuthenticated()) {
2829 return $destination;
2832 // Only redirections to the same host do make sense
2833 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2837 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2838 return 'contact/' . $contact['id'] . '/conversations';
2841 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
2842 return $destination;
2845 if (empty($contact['id'])) {
2846 return $destination;
2849 $redirect = 'redir/' . $contact['id'];
2851 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2852 $redirect .= '?url=' . $url;
2859 * Is the contact a forum?
2861 * @param integer $contactid ID of the contact
2863 * @return boolean "true" if it is a forum
2865 public static function isForum($contactid)
2867 $fields = ['forum', 'prv'];
2868 $condition = ['id' => $contactid];
2869 $contact = DBA::selectFirst('contact', $fields, $condition);
2870 if (!DBA::isResult($contact)) {
2875 return ($contact['forum'] || $contact['prv']);
2879 * Can the remote contact receive private messages?
2881 * @param array $contact
2884 public static function canReceivePrivateMessages(array $contact)
2886 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2887 $self = $contact['self'] ?? false;
2889 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2893 * Search contact table by nick or name
2895 * @param string $search Name or nick
2896 * @param string $mode Search mode (e.g. "community")
2897 * @param int $uid User ID
2899 * @return array with search results
2900 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2902 public static function searchByName(string $search, string $mode = '', int $uid = 0)
2904 if (empty($search)) {
2908 // check supported networks
2909 $networks = [Protocol::DFRN, Protocol::ACTIVITYPUB];
2910 if (DI::config()->get('system', 'diaspora_enabled')) {
2911 $networks[] = Protocol::DIASPORA;
2914 if (!DI::config()->get('system', 'ostatus_disabled')) {
2915 $networks[] = Protocol::OSTATUS;
2918 $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
2921 $condition['blocked'] = false;
2924 // check if we search only communities or every contact
2925 if ($mode === 'community') {
2926 $condition['contact-type'] = self::TYPE_COMMUNITY;
2931 $condition = DBA::mergeConditions($condition,
2932 ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
2933 AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
2935 $contacts = self::selectToArray([], $condition);
2940 * Add public contacts from an array
2942 * @param array $urls
2943 * @return array result "count", "added" and "updated"
2945 public static function addByUrls(array $urls)
2952 foreach ($urls as $url) {
2953 if (empty($url) || !is_string($url)) {
2956 $contact = self::getByURL($url, false, ['id', 'updated']);
2957 if (empty($contact['id'])) {
2958 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2960 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
2961 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2969 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
2973 * Returns a random, global contact array of the current node
2975 * @return array The profile array
2978 public static function getRandomContact()
2980 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
2981 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2982 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2983 ], ['order' => ['RAND()']]);
2985 if (DBA::isResult($contact)) {