3 * @copyright Copyright (C) 2020, Friendica
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;
26 use Friendica\App\BaseURL;
27 use Friendica\Content\Pager;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Notify\Type;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\DFRN;
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
57 * @deprecated since version 2019.03
58 * @see User::PAGE_FLAGS_NORMAL
60 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_SOAPBOX
65 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
67 * @deprecated since version 2019.03
68 * @see User::PAGE_FLAGS_COMMUNITY
70 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
72 * @deprecated since version 2019.03
73 * @see User::PAGE_FLAGS_FREELOVE
75 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
77 * @deprecated since version 2019.03
78 * @see User::PAGE_FLAGS_BLOG
80 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
82 * @deprecated since version 2019.03
83 * @see User::PAGE_FLAGS_PRVGROUP
85 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
93 * TYPE_UNKNOWN - unknown type
95 * TYPE_PERSON - the account belongs to a person
96 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
98 * TYPE_ORGANISATION - the account belongs to an organisation
99 * Associated page type: PAGE_SOAPBOX
101 * TYPE_NEWS - the account is a news reflector
102 * Associated page type: PAGE_SOAPBOX
104 * TYPE_COMMUNITY - the account is community forum
105 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
107 * TYPE_RELAY - the account is a relay
108 * This will only be assigned to contacts, not to user accounts
111 const TYPE_UNKNOWN = -1;
112 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
113 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
114 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
115 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
116 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
135 * @param array $fields Array of selected fields, empty for all
136 * @param array $condition Array of fields for condition
137 * @param array $params Array of several parameters
141 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
143 return DBA::selectToArray('contact', $fields, $condition, $params);
147 * @param array $fields Array of selected fields, empty for all
148 * @param array $condition Array of fields for condition
149 * @param array $params Array of several parameters
153 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
155 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
161 * Insert a row into the contact table
162 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
164 * @param array $fields field array
165 * @param bool $on_duplicate_update Do an update on a duplicate entry
167 * @return boolean was the insert successful?
170 public static function insert(array $fields, bool $on_duplicate_update = false)
172 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
173 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
174 if (!DBA::isResult($contact)) {
179 // Search for duplicated contacts and get rid of them
180 self::removeDuplicates($contact['nurl'], $contact['uid']);
186 * @param integer $id Contact ID
187 * @param array $fields Array of selected fields, empty for all
188 * @return array|boolean Contact record if it exists, false otherwise
191 public static function getById($id, $fields = [])
193 return DBA::selectFirst('contact', $fields, ['id' => $id]);
197 * Fetches a contact by a given url
199 * @param string $url profile url
200 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
201 * @param array $fields Field list
202 * @param integer $uid User ID of the contact
203 * @return array contact array
205 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
207 if ($update || is_null($update)) {
208 $cid = self::getIdForURL($url, $uid, $update);
213 $contact = self::getById($cid, $fields);
214 if (empty($contact)) {
220 // Add internal fields
222 if (!empty($fields)) {
223 foreach (['id', 'avatar', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
224 if (!in_array($internal, $fields)) {
225 $fields[] = $internal;
226 $removal[] = $internal;
231 // We first try the nurl (http://server.tld/nick), most common case
232 $options = ['order' => ['id']];
233 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
235 // Then the addr (nick@server.tld)
236 if (!DBA::isResult($contact)) {
237 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
240 // Then the alias (which could be anything)
241 if (!DBA::isResult($contact)) {
242 // The link could be provided as http although we stored it as https
243 $ssl_url = str_replace('http://', 'https://', $url);
244 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
245 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
248 if (!DBA::isResult($contact)) {
252 // Update the contact in the background if needed
253 $updated = max($contact['success_update'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
254 if ((($updated < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
255 in_array($contact['network'], Protocol::FEDERATED)) {
256 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
259 // Remove the internal fields
260 foreach ($removal as $internal) {
261 unset($contact[$internal]);
268 * Fetches a contact for a given user by a given url.
269 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
271 * @param string $url profile url
272 * @param integer $uid User ID of the contact
273 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
274 * @param array $fields Field list
275 * @return array contact array
277 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
280 $contact = self::getByURL($url, $update, $fields, $uid);
281 if (!empty($contact)) {
282 if (!empty($contact['id'])) {
283 $contact['cid'] = $contact['id'];
290 $contact = self::getByURL($url, $update, $fields);
291 if (!empty($contact['id'])) {
293 $contact['zid'] = $contact['id'];
299 * Tests if the given contact is a follower
301 * @param int $cid Either public contact id or user's contact id
302 * @param int $uid User ID
304 * @return boolean is the contact id a follower?
305 * @throws HTTPException\InternalServerErrorException
306 * @throws \ImagickException
308 public static function isFollower($cid, $uid)
310 if (Contact\User::isBlocked($cid, $uid)) {
314 $cdata = self::getPublicAndUserContacID($cid, $uid);
315 if (empty($cdata['user'])) {
319 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
320 return DBA::exists('contact', $condition);
324 * Tests if the given contact url is a follower
326 * @param string $url Contact URL
327 * @param int $uid User ID
329 * @return boolean is the contact id a follower?
330 * @throws HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 public static function isFollowerByURL($url, $uid)
335 $cid = self::getIdForURL($url, $uid, false);
341 return self::isFollower($cid, $uid);
345 * Tests if the given user follow the given contact
347 * @param int $cid Either public contact id or user's contact id
348 * @param int $uid User ID
350 * @return boolean is the contact url being followed?
351 * @throws HTTPException\InternalServerErrorException
352 * @throws \ImagickException
354 public static function isSharing($cid, $uid)
356 if (Contact\User::isBlocked($cid, $uid)) {
360 $cdata = self::getPublicAndUserContacID($cid, $uid);
361 if (empty($cdata['user'])) {
365 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
366 return DBA::exists('contact', $condition);
370 * Tests if the given user follow the given contact url
372 * @param string $url Contact URL
373 * @param int $uid User ID
375 * @return boolean is the contact url being followed?
376 * @throws HTTPException\InternalServerErrorException
377 * @throws \ImagickException
379 public static function isSharingByURL($url, $uid)
381 $cid = self::getIdForURL($url, $uid, false);
387 return self::isSharing($cid, $uid);
391 * Get the basepath for a given contact link
393 * @param string $url The contact link
394 * @param boolean $dont_update Don't update the contact
396 * @return string basepath
397 * @throws HTTPException\InternalServerErrorException
398 * @throws \ImagickException
400 public static function getBasepath($url, $dont_update = false)
402 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
403 if (!DBA::isResult($contact)) {
407 if (!empty($contact['baseurl'])) {
408 return $contact['baseurl'];
409 } elseif ($dont_update) {
413 // Update the existing contact
414 self::updateFromProbe($contact['id'], '', true);
416 // And fetch the result
417 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
418 if (empty($contact['baseurl'])) {
419 Logger::info('No baseurl for contact', ['url' => $url]);
423 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
424 return $contact['baseurl'];
428 * Check if the given contact url is on the same server
430 * @param string $url The contact link
432 * @return boolean Is it the same server?
434 public static function isLocal($url)
436 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
440 * Check if the given contact ID is on the same server
442 * @param string $url The contact link
444 * @return boolean Is it the same server?
446 public static function isLocalById(int $cid)
448 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
449 if (!DBA::isResult($contact)) {
453 if (empty($contact['baseurl'])) {
454 $baseurl = self::getBasepath($contact['url'], true);
456 $baseurl = $contact['baseurl'];
459 return Strings::compareLink($baseurl, DI::baseUrl());
463 * Returns the public contact id of the given user id
465 * @param integer $uid User ID
467 * @return integer|boolean Public contact id for given user id
470 public static function getPublicIdByUserId($uid)
472 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
473 if (!DBA::isResult($self)) {
476 return self::getIdForURL($self['url'], 0, false);
480 * Returns the contact id for the user and the public contact id for a given contact id
482 * @param int $cid Either public contact id or user's contact id
483 * @param int $uid User ID
485 * @return array with public and user's contact id
486 * @throws HTTPException\InternalServerErrorException
487 * @throws \ImagickException
489 public static function getPublicAndUserContacID($cid, $uid)
491 if (empty($uid) || empty($cid)) {
495 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
496 if (!DBA::isResult($contact)) {
500 // We quit when the user id don't match the user id of the provided contact
501 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
505 if ($contact['uid'] != 0) {
506 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
510 $ucid = $contact['id'];
512 $pcid = $contact['id'];
513 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
516 return ['public' => $pcid, 'user' => $ucid];
520 * Returns contact details for a given contact id in combination with a user id
522 * @param int $cid A contact ID
523 * @param int $uid The User ID
524 * @param array $fields The selected fields for the contact
526 * @return array The contact details
530 public static function getContactForUser($cid, $uid, array $fields = [])
532 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
534 if (!DBA::isResult($contact)) {
542 * Creates the self-contact for the provided user id
545 * @return bool Operation success
546 * @throws HTTPException\InternalServerErrorException
548 public static function createSelfFromUserId($uid)
550 // Only create the entry if it doesn't exist yet
551 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
555 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
556 if (!DBA::isResult($user)) {
560 $return = DBA::insert('contact', [
561 'uid' => $user['uid'],
562 'created' => DateTimeFormat::utcNow(),
564 'name' => $user['username'],
565 'nick' => $user['nickname'],
566 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
567 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
568 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
571 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
572 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
573 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
574 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
575 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
576 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
577 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
578 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
579 'name-date' => DateTimeFormat::utcNow(),
580 'uri-date' => DateTimeFormat::utcNow(),
581 'avatar-date' => DateTimeFormat::utcNow(),
589 * Updates the self-contact for the provided user id
592 * @param boolean $update_avatar Force the avatar update
593 * @throws HTTPException\InternalServerErrorException
595 public static function updateSelfFromUserID($uid, $update_avatar = false)
597 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
598 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
599 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
600 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
601 if (!DBA::isResult($self)) {
605 $fields = ['nickname', 'page-flags', 'account-type'];
606 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
607 if (!DBA::isResult($user)) {
611 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
612 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
613 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
614 if (!DBA::isResult($profile)) {
618 $file_suffix = 'jpg';
620 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
621 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
622 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
623 'contact-type' => $user['account-type'],
624 'xmpp' => $profile['xmpp']];
626 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
627 if (DBA::isResult($avatar)) {
628 if ($update_avatar) {
629 $fields['avatar-date'] = DateTimeFormat::utcNow();
632 // Creating the path to the avatar, beginning with the file suffix
633 $types = Images::supportedTypes();
634 if (isset($types[$avatar['type']])) {
635 $file_suffix = $types[$avatar['type']];
638 // We are adding a timestamp value so that other systems won't use cached content
639 $timestamp = strtotime($fields['avatar-date']);
641 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
642 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
644 $fields['photo'] = $prefix . '4' . $suffix;
645 $fields['thumb'] = $prefix . '5' . $suffix;
646 $fields['micro'] = $prefix . '6' . $suffix;
648 // We hadn't found a photo entry, so we use the default avatar
649 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
650 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
651 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
654 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
655 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
656 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
657 $fields['unsearchable'] = !$profile['net-publish'];
659 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
660 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
661 $fields['nurl'] = Strings::normaliseLink($fields['url']);
662 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
663 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
664 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
665 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
666 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
667 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
671 foreach ($fields as $field => $content) {
672 if ($self[$field] != $content) {
678 if ($fields['name'] != $self['name']) {
679 $fields['name-date'] = DateTimeFormat::utcNow();
681 $fields['updated'] = DateTimeFormat::utcNow();
682 DBA::update('contact', $fields, ['id' => $self['id']]);
684 // Update the public contact as well
685 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
687 // Update the profile
688 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
689 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
690 DBA::update('profile', $fields, ['uid' => $uid]);
695 * Marks a contact for removal
697 * @param int $id contact id
699 * @throws HTTPException\InternalServerErrorException
701 public static function remove($id)
703 // We want just to make sure that we don't delete our "self" contact
704 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
705 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
709 // Archive the contact
710 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
712 // Delete it in the background
713 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
717 * Sends an unfriend message. Does not remove the contact
719 * @param array $user User unfriending
720 * @param array $contact Contact unfriended
721 * @param boolean $dissolve Remove the contact on the remote side
723 * @throws HTTPException\InternalServerErrorException
724 * @throws \ImagickException
726 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
728 if (empty($contact['network'])) {
732 $protocol = $contact['network'];
733 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
734 $protocol = Protocol::ACTIVITYPUB;
737 if (($protocol == Protocol::DFRN) && $dissolve) {
738 DFRN::deliver($user, $contact, 'placeholder', true);
739 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
740 // create an unfollow slap
742 $item['verb'] = Activity::O_UNFOLLOW;
743 $item['gravity'] = GRAVITY_ACTIVITY;
744 $item['follow'] = $contact["url"];
749 $item['attach'] = '';
750 $slap = OStatus::salmon($item, $user);
752 if (!empty($contact['notify'])) {
753 Salmon::slapper($user, $contact['notify'], $slap);
755 } elseif ($protocol == Protocol::DIASPORA) {
756 Diaspora::sendUnshare($user, $contact);
757 } elseif ($protocol == Protocol::ACTIVITYPUB) {
758 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
761 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
767 * Marks a contact for archival after a communication issue delay
769 * Contact has refused to recognise us as a friend. We will start a countdown.
770 * If they still don't recognise us in 32 days, the relationship is over,
771 * and we won't waste any more time trying to communicate with them.
772 * This provides for the possibility that their database is temporarily messed
773 * up or some other transient event and that there's a possibility we could recover from it.
775 * @param array $contact contact to mark for archival
777 * @throws HTTPException\InternalServerErrorException
779 public static function markForArchival(array $contact)
781 if (!isset($contact['url']) && !empty($contact['id'])) {
782 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
783 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
784 if (!DBA::isResult($contact)) {
787 } elseif (!isset($contact['url'])) {
788 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
791 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
793 // Contact already archived or "self" contact? => nothing to do
794 if ($contact['archive'] || $contact['self']) {
798 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
799 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
800 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
803 * We really should send a notification to the owner after 2-3 weeks
804 * so they won't be surprised when the contact vanishes and can take
805 * remedial action if this was a serious mistake or glitch
808 /// @todo Check for contact vitality via probing
809 $archival_days = DI::config()->get('system', 'archival_days', 32);
811 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
812 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
813 /* Relationship is really truly dead. archive them rather than
814 * delete, though if the owner tries to unarchive them we'll start
815 * the whole process over again.
817 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
818 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
824 * Cancels the archival countdown
826 * @see Contact::markForArchival()
828 * @param array $contact contact to be unmarked for archival
832 public static function unmarkForArchival(array $contact)
834 // Always unarchive the relay contact entry
835 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
836 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
837 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
838 DBA::update('contact', $fields, $condition);
841 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
842 $exists = DBA::exists('contact', $condition);
844 // We don't need to update, we never marked this contact for archival
849 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
851 if (!isset($contact['url']) && !empty($contact['id'])) {
852 $fields = ['id', 'url', 'batch'];
853 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
854 if (!DBA::isResult($contact)) {
859 // It's a miracle. Our dead contact has inexplicably come back to life.
860 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
861 DBA::update('contact', $fields, ['id' => $contact['id']]);
862 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
866 * Returns the data array for the photo menu of a given contact
868 * @param array $contact contact
869 * @param int $uid optional, default 0
871 * @throws HTTPException\InternalServerErrorException
872 * @throws \ImagickException
874 public static function photoMenu(array $contact, $uid = 0)
879 $contact_drop_link = '';
886 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
888 $profile_link = self::magicLink($contact['url']);
889 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
894 // Look for our own contact if the uid doesn't match and isn't public
895 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
896 if (DBA::isResult($contact_own)) {
897 return self::photoMenu($contact_own, $uid);
902 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
904 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
906 $profile_link = $contact['url'];
909 if ($profile_link === 'mailbox') {
914 $status_link = $profile_link . '/status';
915 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
916 $profile_link = $profile_link . '/profile';
919 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
920 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
923 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
924 $poke_link = 'contact/' . $contact['id'] . '/poke';
927 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
929 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
931 if (!$contact['self']) {
932 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
937 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
938 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
939 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
940 } elseif(!$contact['pending']) {
941 $follow_link = 'follow?url=' . urlencode($contact['url']);
945 if (!empty($follow_link) || !empty($unfollow_link)) {
946 $contact_drop_link = '';
951 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
953 if (empty($contact['uid'])) {
955 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
956 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
957 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
958 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
959 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
963 'status' => [DI::l10n()->t('View Status') , $status_link , true],
964 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
965 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
966 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
967 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
968 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
969 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
970 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
971 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
972 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
975 if (!empty($contact['pending'])) {
976 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
977 if (DBA::isResult($intro)) {
978 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
983 $args = ['contact' => $contact, 'menu' => &$menu];
985 Hook::callAll('contact_photo_menu', $args);
989 foreach ($menu as $menuname => $menuitem) {
990 if ($menuitem[1] != '') {
991 $menucondensed[$menuname] = $menuitem;
995 return $menucondensed;
999 * Have a look at all contact tables for a given profile url.
1000 * This function works as a replacement for probing the contact.
1002 * @param string $url Contact URL
1003 * @param integer $cid Contact ID
1005 * @return array Contact array in the "probe" structure
1007 private static function getProbeDataFromDatabase($url, $cid = null)
1009 // The link could be provided as http although we stored it as https
1010 $ssl_url = str_replace('http://', 'https://', $url);
1012 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1013 'photo', 'keywords', 'location', 'about', 'network',
1014 'priority', 'batch', 'request', 'confirm', 'poco'];
1017 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1018 if (DBA::isResult($data)) {
1023 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1025 if (!DBA::isResult($data)) {
1026 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1027 $data = DBA::selectFirst('contact', $fields, $condition);
1030 if (DBA::isResult($data)) {
1031 // For security reasons we don't fetch key data from our users
1032 $data["pubkey"] = '';
1036 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1037 'photo', 'keywords', 'location', 'about', 'network'];
1038 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1039 $data = DBA::selectFirst('contact', $fields, $condition);
1041 if (DBA::isResult($data)) {
1042 $data["pubkey"] = '';
1044 $data["priority"] = 0;
1045 $data["batch"] = '';
1046 $data["request"] = '';
1047 $data["confirm"] = '';
1052 $data = ActivityPub::probeProfile($url, false);
1053 if (!empty($data)) {
1057 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1058 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1059 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1061 if (!DBA::isResult($data)) {
1062 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1063 $data = DBA::selectFirst('contact', $fields, $condition);
1066 if (DBA::isResult($data)) {
1067 $data["pubkey"] = '';
1068 $data["keywords"] = '';
1069 $data["location"] = '';
1070 $data["about"] = '';
1079 * Fetch the contact id for a given URL and user
1081 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1082 * `addr` or `alias`.
1084 * If there's no record and we aren't looking for a public contact, we quit.
1085 * If there's one, we check that it isn't time to update the picture else we
1086 * directly return the found contact id.
1088 * Second, we probe the provided $url whether it's http://server.tld/profile or
1089 * nick@server.tld. We quit if we can't get any info back.
1091 * Third, we create the contact record if it doesn't exist
1093 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1094 * if there's any updates
1096 * @param string $url Contact URL
1097 * @param integer $uid The user id for the contact (0 = public contact)
1098 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1099 * @param array $default Default value for creating the contact when every else fails
1101 * @return integer Contact ID
1102 * @throws HTTPException\InternalServerErrorException
1103 * @throws \ImagickException
1105 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1107 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1115 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1117 if (!empty($contact)) {
1118 $contact_id = $contact["id"];
1120 if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1121 // Update public mail accounts via their user's accounts
1122 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1123 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1124 if (!DBA::isResult($mailcontact)) {
1125 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1128 if (DBA::isResult($mailcontact)) {
1129 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1133 if (empty($update)) {
1136 } elseif ($uid != 0) {
1137 // Non-existing user-specific contact, exiting
1141 if (!$update && empty($default)) {
1142 // When we don't want to update, we look if we know this contact in any way
1143 $data = self::getProbeDataFromDatabase($url, $contact_id);
1144 $background_update = true;
1145 } elseif (!$update && !empty($default['network'])) {
1146 // If there are default values, take these
1148 $background_update = false;
1151 $background_update = false;
1154 if ((empty($data) && is_null($update)) || $update) {
1155 $data = Probe::uri($url, "", $uid);
1156 $probed = !empty($data['network']) && ($data['network'] != Protocol::PHANTOM);
1161 // Take the default values when probing failed
1162 if (!empty($default) && (empty($data['network']) || !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO])))) {
1163 $data = array_merge($data, $default);
1166 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1167 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1171 if (!empty($data['baseurl'])) {
1172 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1175 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1176 $data['gsid'] = GServer::getID($data['baseurl']);
1180 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1181 if (!empty($data['alias'])) {
1182 $urls[] = Strings::normaliseLink($data['alias']);
1184 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1185 if (!empty($contact['id'])) {
1186 $contact_id = $contact['id'];
1187 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'probed_url' => $data['url'], 'alias' => $data['alias'], 'addr' => $data['addr']]);
1194 'created' => DateTimeFormat::utcNow(),
1195 'url' => $data['url'],
1196 'nurl' => Strings::normaliseLink($data['url']),
1197 'addr' => $data['addr'] ?? '',
1198 'alias' => $data['alias'] ?? '',
1199 'notify' => $data['notify'] ?? '',
1200 'poll' => $data['poll'] ?? '',
1201 'name' => $data['name'] ?? '',
1202 'nick' => $data['nick'] ?? '',
1203 'keywords' => $data['keywords'] ?? '',
1204 'location' => $data['location'] ?? '',
1205 'about' => $data['about'] ?? '',
1206 'network' => $data['network'],
1207 'pubkey' => $data['pubkey'] ?? '',
1208 'rel' => self::SHARING,
1209 'priority' => $data['priority'] ?? 0,
1210 'batch' => $data['batch'] ?? '',
1211 'request' => $data['request'] ?? '',
1212 'confirm' => $data['confirm'] ?? '',
1213 'poco' => $data['poco'] ?? '',
1214 'baseurl' => $data['baseurl'] ?? '',
1215 'gsid' => $data['gsid'] ?? null,
1216 'name-date' => DateTimeFormat::utcNow(),
1217 'uri-date' => DateTimeFormat::utcNow(),
1218 'avatar-date' => DateTimeFormat::utcNow(),
1224 if (($uid == 0) && $probed) {
1225 $fields['last-item'] = Probe::getLastUpdate($data);
1226 Logger::info('Fetched last item', ['url' => $url, 'probed_url' => $data['url'], 'last-item' => $fields['last-item'], 'callstack' => System::callstack(20)]);
1229 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1231 // Before inserting we do check if the entry does exist now.
1232 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1233 if (!DBA::isResult($contact)) {
1234 Logger::info('Create new contact', $fields);
1236 self::insert($fields);
1238 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1239 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1240 if (!DBA::isResult($contact)) {
1241 Logger::info('Contact creation failed', $fields);
1246 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1249 $contact_id = $contact["id"];
1252 if ($background_update && !$probed && in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1253 // Update in the background when we fetched the data solely from the database
1254 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1255 } elseif (!empty($data['network'])) {
1256 self::updateFromProbeArray($contact_id, $data, false);
1258 Logger::info('Invalid data', ['url' => $url, 'data' => $data]);
1265 * Checks if the contact is archived
1267 * @param int $cid contact id
1269 * @return boolean Is the contact archived?
1270 * @throws HTTPException\InternalServerErrorException
1272 public static function isArchived(int $cid)
1278 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1279 if (!DBA::isResult($contact)) {
1283 if ($contact['archive']) {
1287 // Check status of ActivityPub endpoints
1288 $apcontact = APContact::getByURL($contact['url'], false);
1289 if (!empty($apcontact)) {
1290 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1294 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1299 // Check status of Diaspora endpoints
1300 if (!empty($contact['batch'])) {
1301 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1302 return DBA::exists('contact', $condition);
1309 * Checks if the contact is blocked
1311 * @param int $cid contact id
1313 * @return boolean Is the contact blocked?
1314 * @throws HTTPException\InternalServerErrorException
1316 public static function isBlocked($cid)
1322 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1323 if (!DBA::isResult($blocked)) {
1327 if (Network::isUrlBlocked($blocked['url'])) {
1331 return (bool) $blocked['blocked'];
1335 * Checks if the contact is hidden
1337 * @param int $cid contact id
1339 * @return boolean Is the contact hidden?
1340 * @throws \Exception
1342 public static function isHidden($cid)
1348 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1349 if (!DBA::isResult($hidden)) {
1352 return (bool) $hidden['hidden'];
1356 * Returns posts from a given contact url
1358 * @param string $contact_url Contact URL
1359 * @param bool $thread_mode
1360 * @param int $update
1361 * @return string posts in HTML
1362 * @throws \Exception
1364 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1366 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1370 * Returns posts from a given contact id
1372 * @param integer $cid
1373 * @param bool $thread_mode
1374 * @param integer $update
1375 * @return string posts in HTML
1376 * @throws \Exception
1378 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1382 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1383 if (!DBA::isResult($contact)) {
1387 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1388 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1390 $sql = "`item`.`uid` = ?";
1393 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1396 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1397 $cid, GRAVITY_PARENT, local_user()];
1399 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1400 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1403 if (DI::mode()->isMobile()) {
1404 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1405 DI::config()->get('system', 'itemspage_network_mobile'));
1407 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1408 DI::config()->get('system', 'itemspage_network'));
1411 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1413 $params = ['order' => ['received' => true],
1414 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1417 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1419 $items = Item::inArray($r);
1421 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1423 $r = Item::selectForUser(local_user(), [], $condition, $params);
1425 $items = Item::inArray($r);
1427 $o = conversation($a, $items, 'contact-posts', false);
1431 $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 = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1506 * Unblocks a contact
1510 * @throws \Exception
1512 public static function unblock($cid)
1514 $return = DBA::update('contact', ['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', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1527 if (!DBA::isResult($contact)) {
1531 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1535 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1537 self::updateAvatar($cid, $contact['avatar'], true);
1541 * Return the photo path for a given contact array in the given size
1543 * @param array $contact contact array
1544 * @param string $field Fieldname of the photo in the contact array
1545 * @param string $default Default path when no picture had been found
1546 * @param string $size Size of the avatar picture
1547 * @param string $avatar Avatar path that is displayed when no photo had been found
1548 * @return string photo path
1550 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1552 if (!empty($contact)) {
1553 $contact = self::checkAvatarCacheByArray($contact);
1554 if (!empty($contact[$field])) {
1555 $avatar = $contact[$field];
1559 if (empty($avatar)) {
1563 if (Proxy::isLocalImage($avatar)) {
1566 return Proxy::proxifyUrl($avatar, false, $size);
1571 * Return the photo path for a given contact array
1573 * @param array $contact Contact array
1574 * @param string $avatar Avatar path that is displayed when no photo had been found
1575 * @return string photo path
1577 public static function getPhoto(array $contact, string $avatar = '')
1579 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1583 * Return the photo path (thumb size) for a given contact array
1585 * @param array $contact Contact array
1586 * @param string $avatar Avatar path that is displayed when no photo had been found
1587 * @return string photo path
1589 public static function getThumb(array $contact, string $avatar = '')
1591 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1595 * Return the photo path (micro size) for a given contact array
1597 * @param array $contact Contact array
1598 * @param string $avatar Avatar path that is displayed when no photo had been found
1599 * @return string photo path
1601 public static function getMicro(array $contact, string $avatar = '')
1603 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1607 * Check the given contact array for avatar cache fields
1609 * @param array $contact
1610 * @return array contact array with avatar cache fields
1612 private static function checkAvatarCacheByArray(array $contact)
1615 $contact_fields = [];
1616 $fields = ['photo', 'thumb', 'micro'];
1617 foreach ($fields as $field) {
1618 if (isset($contact[$field])) {
1619 $contact_fields[] = $field;
1621 if (isset($contact[$field]) && empty($contact[$field])) {
1630 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1631 self::updateAvatar($contact['id'], $contact['avatar'], true);
1633 $new_contact = self::getById($contact['id'], $contact_fields);
1634 if (DBA::isResult($new_contact)) {
1635 // We only update the cache fields
1636 $contact = array_merge($contact, $new_contact);
1640 /// add the default avatars if the fields aren't filled
1641 if (isset($contact['photo']) && empty($contact['photo'])) {
1642 $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1644 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1645 $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1647 if (isset($contact['micro']) && empty($contact['micro'])) {
1648 $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1655 * Updates the avatar links in a contact only if needed
1657 * @param int $cid Contact id
1658 * @param string $avatar Link to avatar picture
1659 * @param bool $force force picture update
1662 * @throws HTTPException\InternalServerErrorException
1663 * @throws HTTPException\NotFoundException
1664 * @throws \ImagickException
1666 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1668 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1669 if (!DBA::isResult($contact)) {
1673 $uid = $contact['uid'];
1675 // Only update the cached photo links of public contacts when they already are cached
1676 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1677 if ($contact['avatar'] != $avatar) {
1678 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1679 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1685 $contact['photo'] ?? '',
1686 $contact['thumb'] ?? '',
1687 $contact['micro'] ?? '',
1690 $update = ($contact['avatar'] != $avatar) || $force;
1693 foreach ($data as $image_uri) {
1694 $image_rid = Photo::ridFromURI($image_uri);
1695 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1696 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1703 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1705 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1706 DBA::update('contact', $fields, ['id' => $cid]);
1707 } elseif (empty($contact['avatar'])) {
1708 // Ensure that the avatar field is set
1709 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1710 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1716 * Helper function for "updateFromProbe". Updates personal and public contact
1718 * @param integer $id contact id
1719 * @param integer $uid user id
1720 * @param string $url The profile URL of the contact
1721 * @param array $fields The fields that are updated
1723 * @throws \Exception
1725 private static function updateContact($id, $uid, $url, array $fields)
1727 if (!DBA::update('contact', $fields, ['id' => $id])) {
1728 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1732 // Search for duplicated contacts and get rid of them
1733 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1737 // Archive or unarchive the contact. We only need to do this for the public contact.
1738 // The archive/unarchive function will update the personal contacts by themselves.
1739 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1740 if (!DBA::isResult($contact)) {
1741 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1745 if (!empty($fields['success_update'])) {
1746 self::unmarkForArchival($contact);
1747 } elseif (!empty($fields['failure_update'])) {
1748 self::markForArchival($contact);
1751 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1753 // These contacts are sharing with us, we don't poll them.
1754 // This means that we don't set the update fields in "OnePoll.php".
1755 $condition['rel'] = self::SHARING;
1756 DBA::update('contact', $fields, $condition);
1758 unset($fields['last-update']);
1759 unset($fields['success_update']);
1760 unset($fields['failure_update']);
1762 if (empty($fields)) {
1766 // We are polling these contacts, so we mustn't set the update fields here.
1767 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1768 DBA::update('contact', $fields, $condition);
1772 * Remove duplicated contacts
1774 * @param string $nurl Normalised contact url
1775 * @param integer $uid User id
1777 * @throws \Exception
1779 public static function removeDuplicates(string $nurl, int $uid)
1781 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1782 $count = DBA::count('contact', $condition);
1787 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1788 if (!DBA::isResult($first_contact)) {
1789 // Shouldn't happen - so we handle it
1793 $first = $first_contact['id'];
1794 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1795 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1796 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1797 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1801 // Find all duplicates
1802 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1803 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1804 while ($duplicate = DBA::fetch($duplicates)) {
1805 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1809 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1811 DBA::close($duplicates);
1812 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1817 * @param integer $id contact id
1818 * @param string $network Optional network we are probing for
1819 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1821 * @throws HTTPException\InternalServerErrorException
1822 * @throws \ImagickException
1824 public static function updateFromProbe(int $id, string $network = '', bool $force = false)
1826 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1827 if (!DBA::isResult($contact)) {
1831 $ret = Probe::uri($contact['url'], $network, $contact['uid'], !$force);
1832 return self::updateFromProbeArray($id, $ret, $force);
1836 * @param integer $id contact id
1837 * @param array $ret Probed data
1838 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1840 * @throws HTTPException\InternalServerErrorException
1841 * @throws \ImagickException
1843 private static function updateFromProbeArray(int $id, array $ret, bool $force = false)
1846 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1847 This will reliably kill your communication with old Friendica contacts.
1850 // These fields aren't updated by this routine:
1851 // 'xmpp', 'sensitive'
1853 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
1854 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1855 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1856 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1857 if (!DBA::isResult($contact)) {
1861 $uid = $contact['uid'];
1862 unset($contact['uid']);
1864 $pubkey = $contact['pubkey'];
1865 unset($contact['pubkey']);
1867 $contact['photo'] = $contact['avatar'];
1868 unset($contact['avatar']);
1870 $updated = DateTimeFormat::utcNow();
1872 // We must not try to update relay contacts via probe. They are no real contacts.
1873 // We check after the probing to be able to correct falsely detected contact types.
1874 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1875 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1876 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1877 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1881 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1882 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1883 if ($force && ($uid == 0)) {
1884 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1889 if (Contact\Relation::isDiscoverable($ret['url'])) {
1890 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1893 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1894 $ret['unsearchable'] = $ret['hide'];
1897 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1898 $ret['forum'] = false;
1899 $ret['prv'] = false;
1900 $ret['contact-type'] = $ret['account-type'];
1901 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1902 $apcontact = APContact::getByURL($ret['url'], false);
1903 if (isset($apcontact['manually-approve'])) {
1904 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1905 $ret['prv'] = (bool)!$ret['forum'];
1910 $new_pubkey = $ret['pubkey'] ?? '';
1913 $ret['last-item'] = Probe::getLastUpdate($ret);
1914 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1919 // make sure to not overwrite existing values with blank entries except some technical fields
1920 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1921 foreach ($ret as $key => $val) {
1922 if (!array_key_exists($key, $contact)) {
1924 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1925 $ret[$key] = $contact[$key];
1926 } elseif ($ret[$key] != $contact[$key]) {
1931 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1934 unset($ret['last-item']);
1937 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1938 self::updateAvatar($id, $ret['photo'], $update || $force);
1942 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1944 // Update the public contact
1946 self::updateFromProbeByURL($ret['url']);
1952 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1953 $ret['updated'] = $updated;
1955 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1956 if (empty($pubkey) && !empty($new_pubkey)) {
1957 $ret['pubkey'] = $new_pubkey;
1960 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1961 $ret['uri-date'] = DateTimeFormat::utcNow();
1964 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1965 $ret['name-date'] = $updated;
1968 if ($force && ($uid == 0)) {
1969 $ret['last-update'] = $updated;
1970 $ret['success_update'] = $updated;
1971 $ret['failed'] = false;
1974 unset($ret['photo']);
1976 self::updateContact($id, $uid, $ret['url'], $ret);
1981 public static function updateFromProbeByURL($url, $force = false)
1983 $id = self::getIdForURL($url);
1989 self::updateFromProbe($id, '', $force);
1995 * Detects if a given contact array belongs to a legacy DFRN connection
1997 * @param array $contact
2000 public static function isLegacyDFRNContact($contact)
2002 // Newer Friendica contacts are connected via AP, then these fields aren't set
2003 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2007 * Detects the communication protocol for a given contact url.
2008 * This is used to detect Friendica contacts that we can communicate via AP.
2010 * @param string $url contact url
2011 * @param string $network Network of that contact
2012 * @return string with protocol
2014 public static function getProtocol($url, $network)
2016 if ($network != Protocol::DFRN) {
2020 $apcontact = APContact::getByURL($url);
2021 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2022 return Protocol::ACTIVITYPUB;
2029 * Takes a $uid and a url/handle and adds a new contact
2031 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2032 * dfrn_request page.
2034 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2037 * $return['success'] boolean true if successful
2038 * $return['message'] error text if success is false.
2040 * Takes a $uid and a url/handle and adds a new contact
2042 * @param array $user The user the contact should be created for
2043 * @param string $url The profile URL of the contact
2044 * @param bool $interactive
2045 * @param string $network
2047 * @throws HTTPException\InternalServerErrorException
2048 * @throws HTTPException\NotFoundException
2049 * @throws \ImagickException
2051 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2053 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2055 // remove ajax junk, e.g. Twitter
2056 $url = str_replace('/#!/', '/', $url);
2058 if (!Network::isUrlAllowed($url)) {
2059 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2063 if (Network::isUrlBlocked($url)) {
2064 $result['message'] = DI::l10n()->t('Blocked domain');
2069 $result['message'] = DI::l10n()->t('Connect URL missing.');
2073 $arr = ['url' => $url, 'contact' => []];
2075 Hook::callAll('follow', $arr);
2078 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2082 if (!empty($arr['contact']['name'])) {
2083 $ret = $arr['contact'];
2085 $ret = Probe::uri($url, $network, $user['uid'], false);
2088 if (($network != '') && ($ret['network'] != $network)) {
2089 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2093 // check if we already have a contact
2094 // the poll url is more reliable than the profile url, as we may have
2095 // indirect links or webfinger links
2097 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2098 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2099 if (!DBA::isResult($contact)) {
2100 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2101 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2104 $protocol = self::getProtocol($ret['url'], $ret['network']);
2106 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2108 if (strlen(DI::baseUrl()->getUrlPath())) {
2109 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2111 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2114 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2118 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2119 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2120 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2124 // This extra param just confuses things, remove it
2125 if ($protocol === Protocol::DIASPORA) {
2126 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2129 // do we have enough information?
2130 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2131 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2132 if (empty($ret['poll'])) {
2133 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2135 if (empty($ret['name'])) {
2136 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2138 if (empty($ret['url'])) {
2139 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2141 if (strpos($ret['url'], '@') !== false) {
2142 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2143 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2148 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2149 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2150 $ret['notify'] = '';
2153 if (!$ret['notify']) {
2154 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2157 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2159 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2161 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2164 if ($protocol == Protocol::ACTIVITYPUB) {
2165 $apcontact = APContact::getByURL($ret['url'], false);
2166 if (isset($apcontact['manually-approve'])) {
2167 $pending = (bool)$apcontact['manually-approve'];
2171 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2175 if (DBA::isResult($contact)) {
2177 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2179 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2180 DBA::update('contact', $fields, ['id' => $contact['id']]);
2182 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2184 // create contact record
2186 'uid' => $user['uid'],
2187 'created' => DateTimeFormat::utcNow(),
2188 'url' => $ret['url'],
2189 'nurl' => Strings::normaliseLink($ret['url']),
2190 'addr' => $ret['addr'],
2191 'alias' => $ret['alias'],
2192 'batch' => $ret['batch'],
2193 'notify' => $ret['notify'],
2194 'poll' => $ret['poll'],
2195 'poco' => $ret['poco'],
2196 'name' => $ret['name'],
2197 'nick' => $ret['nick'],
2198 'network' => $ret['network'],
2199 'baseurl' => $ret['baseurl'],
2200 'gsid' => $ret['gsid'] ?? null,
2201 'protocol' => $protocol,
2202 'pubkey' => $ret['pubkey'],
2203 'rel' => $new_relation,
2204 'priority'=> $ret['priority'],
2205 'writable'=> $writeable,
2206 'hidden' => $hidden,
2209 'pending' => $pending,
2214 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2215 if (!DBA::isResult($contact)) {
2216 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2220 $contact_id = $contact['id'];
2221 $result['cid'] = $contact_id;
2223 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2225 // Update the avatar
2226 self::updateAvatar($contact_id, $ret['photo']);
2228 // pull feed and consume it, which should subscribe to the hub.
2230 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2232 $owner = User::getOwnerDataById($user['uid']);
2234 if (DBA::isResult($owner)) {
2235 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2236 // create a follow slap
2238 $item['verb'] = Activity::FOLLOW;
2239 $item['gravity'] = GRAVITY_ACTIVITY;
2240 $item['follow'] = $contact["url"];
2242 $item['title'] = '';
2244 $item['uri-id'] = 0;
2245 $item['attach'] = '';
2247 $slap = OStatus::salmon($item, $owner);
2249 if (!empty($contact['notify'])) {
2250 Salmon::slapper($owner, $contact['notify'], $slap);
2252 } elseif ($protocol == Protocol::DIASPORA) {
2253 $ret = Diaspora::sendShare($owner, $contact);
2254 Logger::log('share returns: ' . $ret);
2255 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2256 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2257 if (empty($activity_id)) {
2258 // This really should never happen
2262 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2263 Logger::log('Follow returns: ' . $ret);
2267 $result['success'] = true;
2272 * Updated contact's SSL policy
2274 * @param array $contact Contact array
2275 * @param string $new_policy New policy, valid: self,full
2277 * @return array Contact array with updated values
2278 * @throws \Exception
2280 public static function updateSslPolicy(array $contact, $new_policy)
2282 $ssl_changed = false;
2283 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2284 $ssl_changed = true;
2285 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2286 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2287 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2288 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2289 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2290 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2293 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2294 $ssl_changed = true;
2295 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2296 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2297 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2298 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2299 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2300 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2304 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2305 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2306 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2307 DBA::update('contact', $fields, ['id' => $contact['id']]);
2314 * @param array $importer Owner (local user) data
2315 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2316 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2317 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2318 * @param string $note Introduction additional message
2319 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2320 * @throws HTTPException\InternalServerErrorException
2321 * @throws \ImagickException
2323 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2325 // Should always be set
2326 if (empty($datarray['author-id'])) {
2330 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2331 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2332 if (!DBA::isResult($pub_contact)) {
2333 // Should never happen
2337 // Contact is blocked at node-level
2338 if (self::isBlocked($datarray['author-id'])) {
2342 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2343 $name = $pub_contact['name'];
2344 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2345 $nick = $pub_contact['nick'];
2346 $network = $pub_contact['network'];
2348 // Ensure that we don't create a new contact when there already is one
2349 $cid = self::getIdForURL($url, $importer['uid']);
2351 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2354 if (!empty($contact)) {
2355 if (!empty($contact['pending'])) {
2356 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2360 // Contact is blocked at user-level
2361 if (!empty($contact['id']) && !empty($importer['id']) &&
2362 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2366 // Make sure that the existing contact isn't archived
2367 self::unmarkForArchival($contact);
2369 if (($contact['rel'] == self::SHARING)
2370 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2371 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2372 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2375 // Ensure to always have the correct network type, independent from the connection request method
2376 self::updateFromProbe($contact['id'], '', true);
2380 // send email notification to owner?
2381 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2382 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2386 // create contact record
2387 DBA::insert('contact', [
2388 'uid' => $importer['uid'],
2389 'created' => DateTimeFormat::utcNow(),
2391 'nurl' => Strings::normaliseLink($url),
2394 'network' => $network,
2395 'rel' => self::FOLLOWER,
2402 $contact_id = DBA::lastInsertId();
2404 // Ensure to always have the correct network type, independent from the connection request method
2405 self::updateFromProbe($contact_id, '', true);
2407 self::updateAvatar($contact_id, $photo, true);
2409 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2411 /// @TODO Encapsulate this into a function/method
2412 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2413 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2414 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2415 // create notification
2416 $hash = Strings::getRandomHex();
2418 if (is_array($contact_record)) {
2419 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2420 'blocked' => false, 'knowyou' => false, 'note' => $note,
2421 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2424 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2426 if (($user['notify-flags'] & Type::INTRO) &&
2427 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2430 'type' => Type::INTRO,
2431 'notify_flags' => $user['notify-flags'],
2432 'language' => $user['language'],
2433 'to_name' => $user['username'],
2434 'to_email' => $user['email'],
2435 'uid' => $user['uid'],
2436 'link' => DI::baseUrl() . '/notifications/intros',
2437 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2438 'source_link' => $contact_record['url'],
2439 'source_photo' => $contact_record['photo'],
2440 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2444 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2445 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2446 self::createFromProbe($importer, $url, false, $network);
2449 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2450 $fields = ['pending' => false];
2451 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2452 $fields['rel'] = Contact::FRIEND;
2455 DBA::update('contact', $fields, $condition);
2464 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2466 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2467 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2469 Contact::remove($contact['id']);
2473 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2475 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2476 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2478 Contact::remove($contact['id']);
2483 * Create a birthday event.
2485 * Update the year and the birthday.
2487 public static function updateBirthdays()
2491 AND `bd` > "0001-01-01"
2492 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2493 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2494 AND NOT `contact`.`pending`
2495 AND NOT `contact`.`hidden`
2496 AND NOT `contact`.`blocked`
2497 AND NOT `contact`.`archive`
2498 AND NOT `contact`.`deleted`',
2503 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2505 while ($contact = DBA::fetch($contacts)) {
2506 Logger::log('update_contact_birthday: ' . $contact['bd']);
2508 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2510 if (Event::createBirthday($contact, $nextbd)) {
2514 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2515 ['id' => $contact['id']]
2519 DBA::close($contacts);
2523 * Remove the unavailable contact ids from the provided list
2525 * @param array $contact_ids Contact id list
2527 * @throws \Exception
2529 public static function pruneUnavailable(array $contact_ids)
2531 if (empty($contact_ids)) {
2535 $contacts = Contact::selectToArray(['id'], [
2536 'id' => $contact_ids,
2542 return array_column($contacts, 'id');
2546 * Returns a magic link to authenticate remote visitors
2548 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2550 * @param string $contact_url The address of the target contact profile
2551 * @param string $url An url that we will be redirected to after the authentication
2553 * @return string with "redir" link
2554 * @throws HTTPException\InternalServerErrorException
2555 * @throws \ImagickException
2557 public static function magicLink($contact_url, $url = '')
2559 if (!Session::isAuthenticated()) {
2560 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2563 $data = self::getProbeDataFromDatabase($contact_url);
2565 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2568 // Prevents endless loop in case only a non-public contact exists for the contact URL
2569 unset($data['uid']);
2571 return self::magicLinkByContact($data, $url ?: $contact_url);
2575 * Returns a magic link to authenticate remote visitors
2577 * @param integer $cid The contact id of the target contact profile
2578 * @param string $url An url that we will be redirected to after the authentication
2580 * @return string with "redir" link
2581 * @throws HTTPException\InternalServerErrorException
2582 * @throws \ImagickException
2584 public static function magicLinkbyId($cid, $url = '')
2586 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2588 return self::magicLinkByContact($contact, $url);
2592 * Returns a magic link to authenticate remote visitors
2594 * @param array $contact The contact array with "uid", "network" and "url"
2595 * @param string $url An url that we will be redirected to after the authentication
2597 * @return string with "redir" link
2598 * @throws HTTPException\InternalServerErrorException
2599 * @throws \ImagickException
2601 public static function magicLinkByContact($contact, $url = '')
2603 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2605 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2606 return $destination;
2609 // Only redirections to the same host do make sense
2610 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2614 if (!empty($contact['uid'])) {
2615 return self::magicLink($contact['url'], $url);
2618 if (empty($contact['id'])) {
2619 return $destination;
2622 $redirect = 'redir/' . $contact['id'];
2624 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2625 $redirect .= '?url=' . $url;
2632 * Is the contact a forum?
2634 * @param integer $contactid ID of the contact
2636 * @return boolean "true" if it is a forum
2638 public static function isForum($contactid)
2640 $fields = ['forum', 'prv'];
2641 $condition = ['id' => $contactid];
2642 $contact = DBA::selectFirst('contact', $fields, $condition);
2643 if (!DBA::isResult($contact)) {
2648 return ($contact['forum'] || $contact['prv']);
2652 * Can the remote contact receive private messages?
2654 * @param array $contact
2657 public static function canReceivePrivateMessages(array $contact)
2659 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2660 $self = $contact['self'] ?? false;
2662 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2666 * Search contact table by nick or name
2668 * @param string $search Name or nick
2669 * @param string $mode Search mode (e.g. "community")
2671 * @return array with search results
2672 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2674 public static function searchByName($search, $mode = '')
2676 if (empty($search)) {
2680 // check supported networks
2681 if (DI::config()->get('system', 'diaspora_enabled')) {
2682 $diaspora = Protocol::DIASPORA;
2684 $diaspora = Protocol::DFRN;
2687 if (!DI::config()->get('system', 'ostatus_disabled')) {
2688 $ostatus = Protocol::OSTATUS;
2690 $ostatus = Protocol::DFRN;
2693 // check if we search only communities or every contact
2694 if ($mode === 'community') {
2695 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2702 $results = DBA::p("SELECT * FROM `contact`
2703 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2704 NOT `failed` AND `uid` = ? AND
2705 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2706 ORDER BY `nurl` DESC LIMIT 1000",
2707 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2710 $contacts = DBA::toArray($results);
2715 * Add public contacts from an array
2717 * @param array $urls
2718 * @return array result "count", "added" and "updated"
2720 public static function addByUrls(array $urls)
2726 foreach ($urls as $url) {
2727 $contact = Contact::getByURL($url, false, ['id']);
2728 if (empty($contact['id'])) {
2729 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2732 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2738 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2742 * Returns a random, global contact of the current node
2744 * @return string The profile URL
2747 public static function getRandomUrl()
2749 $r = DBA::selectFirst('contact', ['url'], [
2750 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2751 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2752 ], ['order' => ['RAND()']]);
2754 if (DBA::isResult($r)) {