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', 'updated', '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 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
254 in_array($contact['network'], Protocol::FEDERATED)) {
255 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
258 // Remove the internal fields
259 foreach ($removal as $internal) {
260 unset($contact[$internal]);
267 * Fetches a contact for a given user by a given url.
268 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
270 * @param string $url profile url
271 * @param integer $uid User ID of the contact
272 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
273 * @param array $fields Field list
274 * @return array contact array
276 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
279 $contact = self::getByURL($url, $update, $fields, $uid);
280 if (!empty($contact)) {
281 if (!empty($contact['id'])) {
282 $contact['cid'] = $contact['id'];
289 $contact = self::getByURL($url, $update, $fields);
290 if (!empty($contact['id'])) {
292 $contact['zid'] = $contact['id'];
298 * Tests if the given contact is a follower
300 * @param int $cid Either public contact id or user's contact id
301 * @param int $uid User ID
303 * @return boolean is the contact id a follower?
304 * @throws HTTPException\InternalServerErrorException
305 * @throws \ImagickException
307 public static function isFollower($cid, $uid)
309 if (Contact\User::isBlocked($cid, $uid)) {
313 $cdata = self::getPublicAndUserContacID($cid, $uid);
314 if (empty($cdata['user'])) {
318 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
319 return DBA::exists('contact', $condition);
323 * Tests if the given contact url is a follower
325 * @param string $url Contact URL
326 * @param int $uid User ID
328 * @return boolean is the contact id a follower?
329 * @throws HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 public static function isFollowerByURL($url, $uid)
334 $cid = self::getIdForURL($url, $uid, false);
340 return self::isFollower($cid, $uid);
344 * Tests if the given user follow the given contact
346 * @param int $cid Either public contact id or user's contact id
347 * @param int $uid User ID
349 * @return boolean is the contact url being followed?
350 * @throws HTTPException\InternalServerErrorException
351 * @throws \ImagickException
353 public static function isSharing($cid, $uid)
355 if (Contact\User::isBlocked($cid, $uid)) {
359 $cdata = self::getPublicAndUserContacID($cid, $uid);
360 if (empty($cdata['user'])) {
364 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
365 return DBA::exists('contact', $condition);
369 * Tests if the given user follow the given contact url
371 * @param string $url Contact URL
372 * @param int $uid User ID
374 * @return boolean is the contact url being followed?
375 * @throws HTTPException\InternalServerErrorException
376 * @throws \ImagickException
378 public static function isSharingByURL($url, $uid)
380 $cid = self::getIdForURL($url, $uid, false);
386 return self::isSharing($cid, $uid);
390 * Get the basepath for a given contact link
392 * @param string $url The contact link
393 * @param boolean $dont_update Don't update the contact
395 * @return string basepath
396 * @throws HTTPException\InternalServerErrorException
397 * @throws \ImagickException
399 public static function getBasepath($url, $dont_update = false)
401 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
402 if (!DBA::isResult($contact)) {
406 if (!empty($contact['baseurl'])) {
407 return $contact['baseurl'];
408 } elseif ($dont_update) {
412 // Update the existing contact
413 self::updateFromProbe($contact['id'], '', true);
415 // And fetch the result
416 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
417 if (empty($contact['baseurl'])) {
418 Logger::info('No baseurl for contact', ['url' => $url]);
422 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
423 return $contact['baseurl'];
427 * Check if the given contact url is on the same server
429 * @param string $url The contact link
431 * @return boolean Is it the same server?
433 public static function isLocal($url)
435 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
439 * Check if the given contact ID is on the same server
441 * @param string $url The contact link
443 * @return boolean Is it the same server?
445 public static function isLocalById(int $cid)
447 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
448 if (!DBA::isResult($contact)) {
452 if (empty($contact['baseurl'])) {
453 $baseurl = self::getBasepath($contact['url'], true);
455 $baseurl = $contact['baseurl'];
458 return Strings::compareLink($baseurl, DI::baseUrl());
462 * Returns the public contact id of the given user id
464 * @param integer $uid User ID
466 * @return integer|boolean Public contact id for given user id
469 public static function getPublicIdByUserId($uid)
471 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
472 if (!DBA::isResult($self)) {
475 return self::getIdForURL($self['url'], 0, false);
479 * Returns the contact id for the user and the public contact id for a given contact id
481 * @param int $cid Either public contact id or user's contact id
482 * @param int $uid User ID
484 * @return array with public and user's contact id
485 * @throws HTTPException\InternalServerErrorException
486 * @throws \ImagickException
488 public static function getPublicAndUserContacID($cid, $uid)
490 if (empty($uid) || empty($cid)) {
494 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
495 if (!DBA::isResult($contact)) {
499 // We quit when the user id don't match the user id of the provided contact
500 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
504 if ($contact['uid'] != 0) {
505 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
509 $ucid = $contact['id'];
511 $pcid = $contact['id'];
512 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
515 return ['public' => $pcid, 'user' => $ucid];
519 * Returns contact details for a given contact id in combination with a user id
521 * @param int $cid A contact ID
522 * @param int $uid The User ID
523 * @param array $fields The selected fields for the contact
525 * @return array The contact details
529 public static function getContactForUser($cid, $uid, array $fields = [])
531 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
533 if (!DBA::isResult($contact)) {
541 * Creates the self-contact for the provided user id
544 * @return bool Operation success
545 * @throws HTTPException\InternalServerErrorException
547 public static function createSelfFromUserId($uid)
549 // Only create the entry if it doesn't exist yet
550 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
554 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
555 if (!DBA::isResult($user)) {
559 $return = DBA::insert('contact', [
560 'uid' => $user['uid'],
561 'created' => DateTimeFormat::utcNow(),
563 'name' => $user['username'],
564 'nick' => $user['nickname'],
565 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
566 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
567 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
570 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
571 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
572 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
573 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
574 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
575 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
576 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
577 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
578 'name-date' => DateTimeFormat::utcNow(),
579 'uri-date' => DateTimeFormat::utcNow(),
580 'avatar-date' => DateTimeFormat::utcNow(),
588 * Updates the self-contact for the provided user id
591 * @param boolean $update_avatar Force the avatar update
592 * @throws HTTPException\InternalServerErrorException
594 public static function updateSelfFromUserID($uid, $update_avatar = false)
596 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
597 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
598 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
599 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
600 if (!DBA::isResult($self)) {
604 $fields = ['nickname', 'page-flags', 'account-type'];
605 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
606 if (!DBA::isResult($user)) {
610 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
611 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
612 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
613 if (!DBA::isResult($profile)) {
617 $file_suffix = 'jpg';
619 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
620 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
621 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
622 'contact-type' => $user['account-type'],
623 'xmpp' => $profile['xmpp']];
625 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
626 if (DBA::isResult($avatar)) {
627 if ($update_avatar) {
628 $fields['avatar-date'] = DateTimeFormat::utcNow();
631 // Creating the path to the avatar, beginning with the file suffix
632 $types = Images::supportedTypes();
633 if (isset($types[$avatar['type']])) {
634 $file_suffix = $types[$avatar['type']];
637 // We are adding a timestamp value so that other systems won't use cached content
638 $timestamp = strtotime($fields['avatar-date']);
640 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
641 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
643 $fields['photo'] = $prefix . '4' . $suffix;
644 $fields['thumb'] = $prefix . '5' . $suffix;
645 $fields['micro'] = $prefix . '6' . $suffix;
647 // We hadn't found a photo entry, so we use the default avatar
648 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
649 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
650 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
653 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
654 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
655 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
656 $fields['unsearchable'] = !$profile['net-publish'];
658 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
659 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
660 $fields['nurl'] = Strings::normaliseLink($fields['url']);
661 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
662 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
663 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
664 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
665 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
666 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
670 foreach ($fields as $field => $content) {
671 if ($self[$field] != $content) {
677 if ($fields['name'] != $self['name']) {
678 $fields['name-date'] = DateTimeFormat::utcNow();
680 $fields['updated'] = DateTimeFormat::utcNow();
681 DBA::update('contact', $fields, ['id' => $self['id']]);
683 // Update the public contact as well
684 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
686 // Update the profile
687 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
688 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
689 DBA::update('profile', $fields, ['uid' => $uid]);
694 * Marks a contact for removal
696 * @param int $id contact id
698 * @throws HTTPException\InternalServerErrorException
700 public static function remove($id)
702 // We want just to make sure that we don't delete our "self" contact
703 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
704 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
708 // Archive the contact
709 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
711 // Delete it in the background
712 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
716 * Sends an unfriend message. Does not remove the contact
718 * @param array $user User unfriending
719 * @param array $contact Contact unfriended
720 * @param boolean $dissolve Remove the contact on the remote side
722 * @throws HTTPException\InternalServerErrorException
723 * @throws \ImagickException
725 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
727 if (empty($contact['network'])) {
731 $protocol = $contact['network'];
732 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
733 $protocol = Protocol::ACTIVITYPUB;
736 if (($protocol == Protocol::DFRN) && $dissolve) {
737 DFRN::deliver($user, $contact, 'placeholder', true);
738 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
739 // create an unfollow slap
741 $item['verb'] = Activity::O_UNFOLLOW;
742 $item['gravity'] = GRAVITY_ACTIVITY;
743 $item['follow'] = $contact["url"];
748 $item['attach'] = '';
749 $slap = OStatus::salmon($item, $user);
751 if (!empty($contact['notify'])) {
752 Salmon::slapper($user, $contact['notify'], $slap);
754 } elseif ($protocol == Protocol::DIASPORA) {
755 Diaspora::sendUnshare($user, $contact);
756 } elseif ($protocol == Protocol::ACTIVITYPUB) {
757 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
760 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
766 * Marks a contact for archival after a communication issue delay
768 * Contact has refused to recognise us as a friend. We will start a countdown.
769 * If they still don't recognise us in 32 days, the relationship is over,
770 * and we won't waste any more time trying to communicate with them.
771 * This provides for the possibility that their database is temporarily messed
772 * up or some other transient event and that there's a possibility we could recover from it.
774 * @param array $contact contact to mark for archival
776 * @throws HTTPException\InternalServerErrorException
778 public static function markForArchival(array $contact)
780 if (!isset($contact['url']) && !empty($contact['id'])) {
781 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
782 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
783 if (!DBA::isResult($contact)) {
786 } elseif (!isset($contact['url'])) {
787 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
790 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
792 // Contact already archived or "self" contact? => nothing to do
793 if ($contact['archive'] || $contact['self']) {
797 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
798 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
799 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
802 * We really should send a notification to the owner after 2-3 weeks
803 * so they won't be surprised when the contact vanishes and can take
804 * remedial action if this was a serious mistake or glitch
807 /// @todo Check for contact vitality via probing
808 $archival_days = DI::config()->get('system', 'archival_days', 32);
810 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
811 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
812 /* Relationship is really truly dead. archive them rather than
813 * delete, though if the owner tries to unarchive them we'll start
814 * the whole process over again.
816 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
817 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
823 * Cancels the archival countdown
825 * @see Contact::markForArchival()
827 * @param array $contact contact to be unmarked for archival
831 public static function unmarkForArchival(array $contact)
833 // Always unarchive the relay contact entry
834 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
835 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
836 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
837 DBA::update('contact', $fields, $condition);
840 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
841 $exists = DBA::exists('contact', $condition);
843 // We don't need to update, we never marked this contact for archival
848 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
850 if (!isset($contact['url']) && !empty($contact['id'])) {
851 $fields = ['id', 'url', 'batch'];
852 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
853 if (!DBA::isResult($contact)) {
858 // It's a miracle. Our dead contact has inexplicably come back to life.
859 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
860 DBA::update('contact', $fields, ['id' => $contact['id']]);
861 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
865 * Returns the data array for the photo menu of a given contact
867 * @param array $contact contact
868 * @param int $uid optional, default 0
870 * @throws HTTPException\InternalServerErrorException
871 * @throws \ImagickException
873 public static function photoMenu(array $contact, $uid = 0)
878 $contact_drop_link = '';
885 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
887 $profile_link = self::magicLink($contact['url']);
888 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
893 // Look for our own contact if the uid doesn't match and isn't public
894 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
895 if (DBA::isResult($contact_own)) {
896 return self::photoMenu($contact_own, $uid);
901 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
903 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
905 $profile_link = $contact['url'];
908 if ($profile_link === 'mailbox') {
913 $status_link = $profile_link . '/status';
914 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
915 $profile_link = $profile_link . '/profile';
918 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
919 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
922 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
923 $poke_link = 'contact/' . $contact['id'] . '/poke';
926 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
928 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
930 if (!$contact['self']) {
931 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
936 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
937 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
938 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
939 } elseif(!$contact['pending']) {
940 $follow_link = 'follow?url=' . urlencode($contact['url']);
944 if (!empty($follow_link) || !empty($unfollow_link)) {
945 $contact_drop_link = '';
950 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
952 if (empty($contact['uid'])) {
954 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
955 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
956 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
957 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
958 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
962 'status' => [DI::l10n()->t('View Status') , $status_link , true],
963 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
964 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
965 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
966 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
967 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
968 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
969 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
970 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
971 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
974 if (!empty($contact['pending'])) {
975 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
976 if (DBA::isResult($intro)) {
977 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
982 $args = ['contact' => $contact, 'menu' => &$menu];
984 Hook::callAll('contact_photo_menu', $args);
988 foreach ($menu as $menuname => $menuitem) {
989 if ($menuitem[1] != '') {
990 $menucondensed[$menuname] = $menuitem;
994 return $menucondensed;
998 * Have a look at all contact tables for a given profile url.
999 * This function works as a replacement for probing the contact.
1001 * @param string $url Contact URL
1002 * @param integer $cid Contact ID
1004 * @return array Contact array in the "probe" structure
1006 private static function getProbeDataFromDatabase($url, $cid = null)
1008 // The link could be provided as http although we stored it as https
1009 $ssl_url = str_replace('http://', 'https://', $url);
1011 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1012 'photo', 'keywords', 'location', 'about', 'network',
1013 'priority', 'batch', 'request', 'confirm', 'poco'];
1016 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1017 if (DBA::isResult($data)) {
1022 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1024 if (!DBA::isResult($data)) {
1025 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1026 $data = DBA::selectFirst('contact', $fields, $condition);
1029 if (DBA::isResult($data)) {
1030 // For security reasons we don't fetch key data from our users
1031 $data["pubkey"] = '';
1035 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1036 'photo', 'keywords', 'location', 'about', 'network'];
1037 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1038 $data = DBA::selectFirst('contact', $fields, $condition);
1040 if (DBA::isResult($data)) {
1041 $data["pubkey"] = '';
1043 $data["priority"] = 0;
1044 $data["batch"] = '';
1045 $data["request"] = '';
1046 $data["confirm"] = '';
1051 $data = ActivityPub::probeProfile($url, false);
1052 if (!empty($data)) {
1056 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1057 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1058 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1060 if (!DBA::isResult($data)) {
1061 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1062 $data = DBA::selectFirst('contact', $fields, $condition);
1065 if (DBA::isResult($data)) {
1066 $data["pubkey"] = '';
1067 $data["keywords"] = '';
1068 $data["location"] = '';
1069 $data["about"] = '';
1078 * Fetch the contact id for a given URL and user
1080 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1081 * `addr` or `alias`.
1083 * If there's no record and we aren't looking for a public contact, we quit.
1084 * If there's one, we check that it isn't time to update the picture else we
1085 * directly return the found contact id.
1087 * Second, we probe the provided $url whether it's http://server.tld/profile or
1088 * nick@server.tld. We quit if we can't get any info back.
1090 * Third, we create the contact record if it doesn't exist
1092 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1093 * if there's any updates
1095 * @param string $url Contact URL
1096 * @param integer $uid The user id for the contact (0 = public contact)
1097 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1098 * @param array $default Default value for creating the contact when every else fails
1099 * @param boolean $in_loop Internally used variable to prevent an endless loop
1101 * @return integer Contact ID
1102 * @throws HTTPException\InternalServerErrorException
1103 * @throws \ImagickException
1105 public static function getIdForURL($url, $uid = 0, $update = null, $default = [], $in_loop = false)
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);
1158 // Take the default values when probing failed
1159 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1160 $data = array_merge($data, $default);
1163 if (empty($data) || ($data['network'] == Protocol::PHANTOM)) {
1164 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1168 if (!empty($data['baseurl'])) {
1169 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1172 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1173 $data['gsid'] = GServer::getID($data['baseurl']);
1176 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url']) && !$in_loop) {
1177 $contact_id = self::getIdForURL($data["alias"], $uid, false, $default, true);
1183 'created' => DateTimeFormat::utcNow(),
1184 'url' => $data['url'],
1185 'nurl' => Strings::normaliseLink($data['url']),
1186 'addr' => $data['addr'] ?? '',
1187 'alias' => $data['alias'] ?? '',
1188 'notify' => $data['notify'] ?? '',
1189 'poll' => $data['poll'] ?? '',
1190 'name' => $data['name'] ?? '',
1191 'nick' => $data['nick'] ?? '',
1192 'keywords' => $data['keywords'] ?? '',
1193 'location' => $data['location'] ?? '',
1194 'about' => $data['about'] ?? '',
1195 'network' => $data['network'],
1196 'pubkey' => $data['pubkey'] ?? '',
1197 'rel' => self::SHARING,
1198 'priority' => $data['priority'] ?? 0,
1199 'batch' => $data['batch'] ?? '',
1200 'request' => $data['request'] ?? '',
1201 'confirm' => $data['confirm'] ?? '',
1202 'poco' => $data['poco'] ?? '',
1203 'baseurl' => $data['baseurl'] ?? '',
1204 'gsid' => $data['gsid'] ?? null,
1205 'name-date' => DateTimeFormat::utcNow(),
1206 'uri-date' => DateTimeFormat::utcNow(),
1207 'avatar-date' => DateTimeFormat::utcNow(),
1213 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1215 // Before inserting we do check if the entry does exist now.
1216 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1217 if (!DBA::isResult($contact)) {
1218 Logger::info('Create new contact', $fields);
1220 self::insert($fields);
1222 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1223 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1224 if (!DBA::isResult($contact)) {
1225 Logger::info('Contact creation failed', $fields);
1230 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1233 $contact_id = $contact["id"];
1236 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1237 self::updateAvatar($contact_id, $data['photo']);
1240 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1241 if ($background_update) {
1242 // Update in the background when we fetched the data solely from the database
1243 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1245 // Else do a direct update
1246 self::updateFromProbe($contact_id, '', false);
1249 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid'];
1250 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1252 // This condition should always be true
1253 if (!DBA::isResult($contact)) {
1258 'url' => $data['url'],
1259 'nurl' => Strings::normaliseLink($data['url']),
1260 'updated' => DateTimeFormat::utcNow(),
1264 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1266 foreach ($fields as $field) {
1267 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1270 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1271 $updated['uri-date'] = DateTimeFormat::utcNow();
1274 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1275 $updated['name-date'] = DateTimeFormat::utcNow();
1278 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1285 * Checks if the contact is archived
1287 * @param int $cid contact id
1289 * @return boolean Is the contact archived?
1290 * @throws HTTPException\InternalServerErrorException
1292 public static function isArchived(int $cid)
1298 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1299 if (!DBA::isResult($contact)) {
1303 if ($contact['archive']) {
1307 // Check status of ActivityPub endpoints
1308 $apcontact = APContact::getByURL($contact['url'], false);
1309 if (!empty($apcontact)) {
1310 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1314 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1319 // Check status of Diaspora endpoints
1320 if (!empty($contact['batch'])) {
1321 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1322 return DBA::exists('contact', $condition);
1329 * Checks if the contact is blocked
1331 * @param int $cid contact id
1333 * @return boolean Is the contact blocked?
1334 * @throws HTTPException\InternalServerErrorException
1336 public static function isBlocked($cid)
1342 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1343 if (!DBA::isResult($blocked)) {
1347 if (Network::isUrlBlocked($blocked['url'])) {
1351 return (bool) $blocked['blocked'];
1355 * Checks if the contact is hidden
1357 * @param int $cid contact id
1359 * @return boolean Is the contact hidden?
1360 * @throws \Exception
1362 public static function isHidden($cid)
1368 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1369 if (!DBA::isResult($hidden)) {
1372 return (bool) $hidden['hidden'];
1376 * Returns posts from a given contact url
1378 * @param string $contact_url Contact URL
1379 * @param bool $thread_mode
1380 * @param int $update
1381 * @return string posts in HTML
1382 * @throws \Exception
1384 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1386 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1390 * Returns posts from a given contact id
1392 * @param integer $cid
1393 * @param bool $thread_mode
1394 * @param integer $update
1395 * @return string posts in HTML
1396 * @throws \Exception
1398 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1402 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1403 if (!DBA::isResult($contact)) {
1407 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1408 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1410 $sql = "`item`.`uid` = ?";
1413 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1416 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1417 $cid, GRAVITY_PARENT, local_user()];
1419 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1420 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1423 if (DI::mode()->isMobile()) {
1424 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1425 DI::config()->get('system', 'itemspage_network_mobile'));
1427 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1428 DI::config()->get('system', 'itemspage_network'));
1431 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1433 $params = ['order' => ['received' => true],
1434 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1437 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1439 $items = Item::inArray($r);
1441 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1443 $r = Item::selectForUser(local_user(), [], $condition, $params);
1445 $items = Item::inArray($r);
1447 $o = conversation($a, $items, 'contact-posts', false);
1451 $o .= $pager->renderMinimal(count($items));
1458 * Returns the account type name
1460 * The function can be called with either the user or the contact array
1462 * @param array $contact contact or user array
1465 public static function getAccountType(array $contact)
1467 // There are several fields that indicate that the contact or user is a forum
1468 // "page-flags" is a field in the user table,
1469 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1470 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1471 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1472 || (isset($contact['forum']) && intval($contact['forum']))
1473 || (isset($contact['prv']) && intval($contact['prv']))
1474 || (isset($contact['community']) && intval($contact['community']))
1476 $type = self::TYPE_COMMUNITY;
1478 $type = self::TYPE_PERSON;
1481 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1482 if (isset($contact["contact-type"])) {
1483 $type = $contact["contact-type"];
1486 if (isset($contact["account-type"])) {
1487 $type = $contact["account-type"];
1491 case self::TYPE_ORGANISATION:
1492 $account_type = DI::l10n()->t("Organisation");
1495 case self::TYPE_NEWS:
1496 $account_type = DI::l10n()->t('News');
1499 case self::TYPE_COMMUNITY:
1500 $account_type = DI::l10n()->t("Forum");
1508 return $account_type;
1516 * @throws \Exception
1518 public static function block($cid, $reason = null)
1520 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1526 * Unblocks a contact
1530 * @throws \Exception
1532 public static function unblock($cid)
1534 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1540 * Ensure that cached avatar exist
1542 * @param integer $cid
1544 public static function checkAvatarCache(int $cid)
1546 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1547 if (!DBA::isResult($contact)) {
1551 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1555 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1557 self::updateAvatar($cid, $contact['avatar'], true);
1561 * Return the photo path for a given contact array in the given size
1563 * @param array $contact contact array
1564 * @param string $field Fieldname of the photo in the contact array
1565 * @param string $default Default path when no picture had been found
1566 * @param string $size Size of the avatar picture
1567 * @param string $avatar Avatar path that is displayed when no photo had been found
1568 * @return string photo path
1570 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1572 if (!empty($contact)) {
1573 $contact = self::checkAvatarCacheByArray($contact);
1574 if (!empty($contact[$field])) {
1575 $avatar = $contact[$field];
1579 if (empty($avatar)) {
1583 if (Proxy::isLocalImage($avatar)) {
1586 return Proxy::proxifyUrl($avatar, false, $size);
1591 * Return the photo path for a given contact array
1593 * @param array $contact Contact array
1594 * @param string $avatar Avatar path that is displayed when no photo had been found
1595 * @return string photo path
1597 public static function getPhoto(array $contact, string $avatar = '')
1599 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1603 * Return the photo path (thumb size) for a given contact array
1605 * @param array $contact Contact array
1606 * @param string $avatar Avatar path that is displayed when no photo had been found
1607 * @return string photo path
1609 public static function getThumb(array $contact, string $avatar = '')
1611 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1615 * Return the photo path (micro size) for a given contact array
1617 * @param array $contact Contact array
1618 * @param string $avatar Avatar path that is displayed when no photo had been found
1619 * @return string photo path
1621 public static function getMicro(array $contact, string $avatar = '')
1623 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1627 * Check the given contact array for avatar cache fields
1629 * @param array $contact
1630 * @return array contact array with avatar cache fields
1632 private static function checkAvatarCacheByArray(array $contact)
1635 $contact_fields = [];
1636 $fields = ['photo', 'thumb', 'micro'];
1637 foreach ($fields as $field) {
1638 if (isset($contact[$field])) {
1639 $contact_fields[] = $field;
1641 if (isset($contact[$field]) && empty($contact[$field])) {
1650 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1651 self::updateAvatar($contact['id'], $contact['avatar'], true);
1653 $new_contact = self::getById($contact['id'], $contact_fields);
1654 if (DBA::isResult($new_contact)) {
1655 // We only update the cache fields
1656 $contact = array_merge($contact, $new_contact);
1660 /// add the default avatars if the fields aren't filled
1661 if (isset($contact['photo']) && empty($contact['photo'])) {
1662 $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1664 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1665 $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1667 if (isset($contact['micro']) && empty($contact['micro'])) {
1668 $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1675 * Updates the avatar links in a contact only if needed
1677 * @param int $cid Contact id
1678 * @param string $avatar Link to avatar picture
1679 * @param bool $force force picture update
1682 * @throws HTTPException\InternalServerErrorException
1683 * @throws HTTPException\NotFoundException
1684 * @throws \ImagickException
1686 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1688 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1689 if (!DBA::isResult($contact)) {
1693 $uid = $contact['uid'];
1695 // Only update the cached photo links of public contacts when they already are cached
1696 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1697 if ($contact['avatar'] != $avatar) {
1698 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1699 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1705 $contact['photo'] ?? '',
1706 $contact['thumb'] ?? '',
1707 $contact['micro'] ?? '',
1710 $update = ($contact['avatar'] != $avatar) || $force;
1713 foreach ($data as $image_uri) {
1714 $image_rid = Photo::ridFromURI($image_uri);
1715 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1716 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1723 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1725 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1726 DBA::update('contact', $fields, ['id' => $cid]);
1727 } elseif (empty($contact['avatar'])) {
1728 // Ensure that the avatar field is set
1729 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1730 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1736 * Helper function for "updateFromProbe". Updates personal and public contact
1738 * @param integer $id contact id
1739 * @param integer $uid user id
1740 * @param string $url The profile URL of the contact
1741 * @param array $fields The fields that are updated
1743 * @throws \Exception
1745 private static function updateContact($id, $uid, $url, array $fields)
1747 if (!DBA::update('contact', $fields, ['id' => $id])) {
1748 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1752 // Search for duplicated contacts and get rid of them
1753 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1757 // Archive or unarchive the contact. We only need to do this for the public contact.
1758 // The archive/unarchive function will update the personal contacts by themselves.
1759 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1760 if (!DBA::isResult($contact)) {
1761 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1765 if (!empty($fields['success_update'])) {
1766 self::unmarkForArchival($contact);
1767 } elseif (!empty($fields['failure_update'])) {
1768 self::markForArchival($contact);
1771 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1773 // These contacts are sharing with us, we don't poll them.
1774 // This means that we don't set the update fields in "OnePoll.php".
1775 $condition['rel'] = self::SHARING;
1776 DBA::update('contact', $fields, $condition);
1778 unset($fields['last-update']);
1779 unset($fields['success_update']);
1780 unset($fields['failure_update']);
1782 if (empty($fields)) {
1786 // We are polling these contacts, so we mustn't set the update fields here.
1787 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1788 DBA::update('contact', $fields, $condition);
1792 * Remove duplicated contacts
1794 * @param string $nurl Normalised contact url
1795 * @param integer $uid User id
1797 * @throws \Exception
1799 public static function removeDuplicates(string $nurl, int $uid)
1801 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1802 $count = DBA::count('contact', $condition);
1807 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1808 if (!DBA::isResult($first_contact)) {
1809 // Shouldn't happen - so we handle it
1813 $first = $first_contact['id'];
1814 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1815 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1816 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1817 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1821 // Find all duplicates
1822 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1823 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1824 while ($duplicate = DBA::fetch($duplicates)) {
1825 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1829 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1831 DBA::close($duplicates);
1832 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1837 * @param integer $id contact id
1838 * @param string $network Optional network we are probing for
1839 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1841 * @throws HTTPException\InternalServerErrorException
1842 * @throws \ImagickException
1844 public static function updateFromProbe(int $id, string $network = '', bool $force = false)
1847 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1848 This will reliably kill your communication with old Friendica contacts.
1851 // These fields aren't updated by this routine:
1852 // 'xmpp', 'sensitive'
1854 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
1855 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1856 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
1857 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1858 if (!DBA::isResult($contact)) {
1862 $uid = $contact['uid'];
1863 unset($contact['uid']);
1865 $pubkey = $contact['pubkey'];
1866 unset($contact['pubkey']);
1868 $contact['photo'] = $contact['avatar'];
1869 unset($contact['avatar']);
1871 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1873 $updated = DateTimeFormat::utcNow();
1875 // We must not try to update relay contacts via probe. They are no real contacts.
1876 // We check after the probing to be able to correct falsely detected contact types.
1877 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1878 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1879 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1880 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1884 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1885 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1886 if ($force && ($uid == 0)) {
1887 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1892 if (Contact\Relation::isDiscoverable($ret['url'])) {
1893 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1896 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1897 $ret['unsearchable'] = $ret['hide'];
1900 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1901 $ret['forum'] = false;
1902 $ret['prv'] = false;
1903 $ret['contact-type'] = $ret['account-type'];
1904 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1905 $apcontact = APContact::getByURL($ret['url'], false);
1906 if (isset($apcontact['manually-approve'])) {
1907 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1908 $ret['prv'] = (bool)!$ret['forum'];
1913 $new_pubkey = $ret['pubkey'];
1917 // make sure to not overwrite existing values with blank entries except some technical fields
1918 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1919 foreach ($ret as $key => $val) {
1920 if (!array_key_exists($key, $contact)) {
1922 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1923 $ret[$key] = $contact[$key];
1924 } elseif ($ret[$key] != $contact[$key]) {
1929 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1930 self::updateAvatar($id, $ret['photo'], $update || $force);
1935 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1938 // Update the public contact
1940 self::updateFromProbeByURL($ret['url']);
1946 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1947 $ret['updated'] = $updated;
1949 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1950 if (empty($pubkey) && !empty($new_pubkey)) {
1951 $ret['pubkey'] = $new_pubkey;
1954 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1955 $ret['uri-date'] = DateTimeFormat::utcNow();
1958 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1959 $ret['name-date'] = $updated;
1962 if ($force && ($uid == 0)) {
1963 $ret['last-update'] = $updated;
1964 $ret['success_update'] = $updated;
1965 $ret['failed'] = false;
1968 unset($ret['photo']);
1970 self::updateContact($id, $uid, $ret['url'], $ret);
1975 public static function updateFromProbeByURL($url, $force = false)
1977 $id = self::getIdForURL($url);
1983 self::updateFromProbe($id, '', $force);
1989 * Detects if a given contact array belongs to a legacy DFRN connection
1991 * @param array $contact
1994 public static function isLegacyDFRNContact($contact)
1996 // Newer Friendica contacts are connected via AP, then these fields aren't set
1997 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2001 * Detects the communication protocol for a given contact url.
2002 * This is used to detect Friendica contacts that we can communicate via AP.
2004 * @param string $url contact url
2005 * @param string $network Network of that contact
2006 * @return string with protocol
2008 public static function getProtocol($url, $network)
2010 if ($network != Protocol::DFRN) {
2014 $apcontact = APContact::getByURL($url);
2015 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2016 return Protocol::ACTIVITYPUB;
2023 * Takes a $uid and a url/handle and adds a new contact
2025 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2026 * dfrn_request page.
2028 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2031 * $return['success'] boolean true if successful
2032 * $return['message'] error text if success is false.
2034 * Takes a $uid and a url/handle and adds a new contact
2036 * @param array $user The user the contact should be created for
2037 * @param string $url The profile URL of the contact
2038 * @param bool $interactive
2039 * @param string $network
2041 * @throws HTTPException\InternalServerErrorException
2042 * @throws HTTPException\NotFoundException
2043 * @throws \ImagickException
2045 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2047 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2049 // remove ajax junk, e.g. Twitter
2050 $url = str_replace('/#!/', '/', $url);
2052 if (!Network::isUrlAllowed($url)) {
2053 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2057 if (Network::isUrlBlocked($url)) {
2058 $result['message'] = DI::l10n()->t('Blocked domain');
2063 $result['message'] = DI::l10n()->t('Connect URL missing.');
2067 $arr = ['url' => $url, 'contact' => []];
2069 Hook::callAll('follow', $arr);
2072 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2076 if (!empty($arr['contact']['name'])) {
2077 $ret = $arr['contact'];
2079 $ret = Probe::uri($url, $network, $user['uid'], false);
2082 if (($network != '') && ($ret['network'] != $network)) {
2083 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2087 // check if we already have a contact
2088 // the poll url is more reliable than the profile url, as we may have
2089 // indirect links or webfinger links
2091 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2092 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2093 if (!DBA::isResult($contact)) {
2094 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2095 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2098 $protocol = self::getProtocol($ret['url'], $ret['network']);
2100 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2102 if (strlen(DI::baseUrl()->getUrlPath())) {
2103 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2105 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2108 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2112 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2113 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2114 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2118 // This extra param just confuses things, remove it
2119 if ($protocol === Protocol::DIASPORA) {
2120 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2123 // do we have enough information?
2124 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2125 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2126 if (empty($ret['poll'])) {
2127 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2129 if (empty($ret['name'])) {
2130 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2132 if (empty($ret['url'])) {
2133 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2135 if (strpos($ret['url'], '@') !== false) {
2136 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2137 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2142 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2143 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2144 $ret['notify'] = '';
2147 if (!$ret['notify']) {
2148 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2151 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2153 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2155 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2158 if ($protocol == Protocol::ACTIVITYPUB) {
2159 $apcontact = APContact::getByURL($ret['url'], false);
2160 if (isset($apcontact['manually-approve'])) {
2161 $pending = (bool)$apcontact['manually-approve'];
2165 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2169 if (DBA::isResult($contact)) {
2171 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2173 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2174 DBA::update('contact', $fields, ['id' => $contact['id']]);
2176 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2178 // create contact record
2180 'uid' => $user['uid'],
2181 'created' => DateTimeFormat::utcNow(),
2182 'url' => $ret['url'],
2183 'nurl' => Strings::normaliseLink($ret['url']),
2184 'addr' => $ret['addr'],
2185 'alias' => $ret['alias'],
2186 'batch' => $ret['batch'],
2187 'notify' => $ret['notify'],
2188 'poll' => $ret['poll'],
2189 'poco' => $ret['poco'],
2190 'name' => $ret['name'],
2191 'nick' => $ret['nick'],
2192 'network' => $ret['network'],
2193 'baseurl' => $ret['baseurl'],
2194 'gsid' => $ret['gsid'] ?? null,
2195 'protocol' => $protocol,
2196 'pubkey' => $ret['pubkey'],
2197 'rel' => $new_relation,
2198 'priority'=> $ret['priority'],
2199 'writable'=> $writeable,
2200 'hidden' => $hidden,
2203 'pending' => $pending,
2208 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2209 if (!DBA::isResult($contact)) {
2210 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2214 $contact_id = $contact['id'];
2215 $result['cid'] = $contact_id;
2217 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2219 // Update the avatar
2220 self::updateAvatar($contact_id, $ret['photo']);
2222 // pull feed and consume it, which should subscribe to the hub.
2224 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2226 $owner = User::getOwnerDataById($user['uid']);
2228 if (DBA::isResult($owner)) {
2229 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2230 // create a follow slap
2232 $item['verb'] = Activity::FOLLOW;
2233 $item['gravity'] = GRAVITY_ACTIVITY;
2234 $item['follow'] = $contact["url"];
2236 $item['title'] = '';
2238 $item['uri-id'] = 0;
2239 $item['attach'] = '';
2241 $slap = OStatus::salmon($item, $owner);
2243 if (!empty($contact['notify'])) {
2244 Salmon::slapper($owner, $contact['notify'], $slap);
2246 } elseif ($protocol == Protocol::DIASPORA) {
2247 $ret = Diaspora::sendShare($owner, $contact);
2248 Logger::log('share returns: ' . $ret);
2249 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2250 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2251 if (empty($activity_id)) {
2252 // This really should never happen
2256 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2257 Logger::log('Follow returns: ' . $ret);
2261 $result['success'] = true;
2266 * Updated contact's SSL policy
2268 * @param array $contact Contact array
2269 * @param string $new_policy New policy, valid: self,full
2271 * @return array Contact array with updated values
2272 * @throws \Exception
2274 public static function updateSslPolicy(array $contact, $new_policy)
2276 $ssl_changed = false;
2277 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2278 $ssl_changed = true;
2279 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2280 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2281 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2282 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2283 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2284 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2287 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2288 $ssl_changed = true;
2289 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2290 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2291 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2292 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2293 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2294 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2298 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2299 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2300 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2301 DBA::update('contact', $fields, ['id' => $contact['id']]);
2308 * @param array $importer Owner (local user) data
2309 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2310 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2311 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2312 * @param string $note Introduction additional message
2313 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2314 * @throws HTTPException\InternalServerErrorException
2315 * @throws \ImagickException
2317 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2319 // Should always be set
2320 if (empty($datarray['author-id'])) {
2324 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2325 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2326 if (!DBA::isResult($pub_contact)) {
2327 // Should never happen
2331 // Contact is blocked at node-level
2332 if (self::isBlocked($datarray['author-id'])) {
2336 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2337 $name = $pub_contact['name'];
2338 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2339 $nick = $pub_contact['nick'];
2340 $network = $pub_contact['network'];
2342 // Ensure that we don't create a new contact when there already is one
2343 $cid = self::getIdForURL($url, $importer['uid']);
2345 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2348 if (!empty($contact)) {
2349 if (!empty($contact['pending'])) {
2350 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2354 // Contact is blocked at user-level
2355 if (!empty($contact['id']) && !empty($importer['id']) &&
2356 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2360 // Make sure that the existing contact isn't archived
2361 self::unmarkForArchival($contact);
2363 if (($contact['rel'] == self::SHARING)
2364 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2365 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2366 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2369 // Ensure to always have the correct network type, independent from the connection request method
2370 self::updateFromProbe($contact['id'], '', true);
2374 // send email notification to owner?
2375 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2376 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2380 // create contact record
2381 DBA::insert('contact', [
2382 'uid' => $importer['uid'],
2383 'created' => DateTimeFormat::utcNow(),
2385 'nurl' => Strings::normaliseLink($url),
2388 'network' => $network,
2389 'rel' => self::FOLLOWER,
2396 $contact_id = DBA::lastInsertId();
2398 // Ensure to always have the correct network type, independent from the connection request method
2399 self::updateFromProbe($contact_id, '', true);
2401 self::updateAvatar($contact_id, $photo, true);
2403 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2405 /// @TODO Encapsulate this into a function/method
2406 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2407 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2408 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2409 // create notification
2410 $hash = Strings::getRandomHex();
2412 if (is_array($contact_record)) {
2413 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2414 'blocked' => false, 'knowyou' => false, 'note' => $note,
2415 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2418 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2420 if (($user['notify-flags'] & Type::INTRO) &&
2421 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2424 'type' => Type::INTRO,
2425 'notify_flags' => $user['notify-flags'],
2426 'language' => $user['language'],
2427 'to_name' => $user['username'],
2428 'to_email' => $user['email'],
2429 'uid' => $user['uid'],
2430 'link' => DI::baseUrl() . '/notifications/intros',
2431 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2432 'source_link' => $contact_record['url'],
2433 'source_photo' => $contact_record['photo'],
2434 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2438 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2439 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2440 self::createFromProbe($importer, $url, false, $network);
2443 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2444 $fields = ['pending' => false];
2445 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2446 $fields['rel'] = Contact::FRIEND;
2449 DBA::update('contact', $fields, $condition);
2458 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2460 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2461 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2463 Contact::remove($contact['id']);
2467 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2469 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2470 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2472 Contact::remove($contact['id']);
2477 * Create a birthday event.
2479 * Update the year and the birthday.
2481 public static function updateBirthdays()
2485 AND `bd` > "0001-01-01"
2486 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2487 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2488 AND NOT `contact`.`pending`
2489 AND NOT `contact`.`hidden`
2490 AND NOT `contact`.`blocked`
2491 AND NOT `contact`.`archive`
2492 AND NOT `contact`.`deleted`',
2497 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2499 while ($contact = DBA::fetch($contacts)) {
2500 Logger::log('update_contact_birthday: ' . $contact['bd']);
2502 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2504 if (Event::createBirthday($contact, $nextbd)) {
2508 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2509 ['id' => $contact['id']]
2513 DBA::close($contacts);
2517 * Remove the unavailable contact ids from the provided list
2519 * @param array $contact_ids Contact id list
2521 * @throws \Exception
2523 public static function pruneUnavailable(array $contact_ids)
2525 if (empty($contact_ids)) {
2529 $contacts = Contact::selectToArray(['id'], [
2530 'id' => $contact_ids,
2536 return array_column($contacts, 'id');
2540 * Returns a magic link to authenticate remote visitors
2542 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2544 * @param string $contact_url The address of the target contact profile
2545 * @param string $url An url that we will be redirected to after the authentication
2547 * @return string with "redir" link
2548 * @throws HTTPException\InternalServerErrorException
2549 * @throws \ImagickException
2551 public static function magicLink($contact_url, $url = '')
2553 if (!Session::isAuthenticated()) {
2554 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2557 $data = self::getProbeDataFromDatabase($contact_url);
2559 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2562 // Prevents endless loop in case only a non-public contact exists for the contact URL
2563 unset($data['uid']);
2565 return self::magicLinkByContact($data, $url ?: $contact_url);
2569 * Returns a magic link to authenticate remote visitors
2571 * @param integer $cid The contact id of the target contact profile
2572 * @param string $url An url that we will be redirected to after the authentication
2574 * @return string with "redir" link
2575 * @throws HTTPException\InternalServerErrorException
2576 * @throws \ImagickException
2578 public static function magicLinkbyId($cid, $url = '')
2580 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2582 return self::magicLinkByContact($contact, $url);
2586 * Returns a magic link to authenticate remote visitors
2588 * @param array $contact The contact array with "uid", "network" and "url"
2589 * @param string $url An url that we will be redirected to after the authentication
2591 * @return string with "redir" link
2592 * @throws HTTPException\InternalServerErrorException
2593 * @throws \ImagickException
2595 public static function magicLinkByContact($contact, $url = '')
2597 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2599 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2600 return $destination;
2603 // Only redirections to the same host do make sense
2604 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2608 if (!empty($contact['uid'])) {
2609 return self::magicLink($contact['url'], $url);
2612 if (empty($contact['id'])) {
2613 return $destination;
2616 $redirect = 'redir/' . $contact['id'];
2618 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2619 $redirect .= '?url=' . $url;
2626 * Is the contact a forum?
2628 * @param integer $contactid ID of the contact
2630 * @return boolean "true" if it is a forum
2632 public static function isForum($contactid)
2634 $fields = ['forum', 'prv'];
2635 $condition = ['id' => $contactid];
2636 $contact = DBA::selectFirst('contact', $fields, $condition);
2637 if (!DBA::isResult($contact)) {
2642 return ($contact['forum'] || $contact['prv']);
2646 * Can the remote contact receive private messages?
2648 * @param array $contact
2651 public static function canReceivePrivateMessages(array $contact)
2653 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2654 $self = $contact['self'] ?? false;
2656 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2660 * Search contact table by nick or name
2662 * @param string $search Name or nick
2663 * @param string $mode Search mode (e.g. "community")
2665 * @return array with search results
2666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2668 public static function searchByName($search, $mode = '')
2670 if (empty($search)) {
2674 // check supported networks
2675 if (DI::config()->get('system', 'diaspora_enabled')) {
2676 $diaspora = Protocol::DIASPORA;
2678 $diaspora = Protocol::DFRN;
2681 if (!DI::config()->get('system', 'ostatus_disabled')) {
2682 $ostatus = Protocol::OSTATUS;
2684 $ostatus = Protocol::DFRN;
2687 // check if we search only communities or every contact
2688 if ($mode === 'community') {
2689 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2696 $results = DBA::p("SELECT * FROM `contact`
2697 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2698 NOT `failed` AND `uid` = ? AND
2699 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2700 ORDER BY `nurl` DESC LIMIT 1000",
2701 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2704 $contacts = DBA::toArray($results);
2709 * Add public contacts from an array
2711 * @param array $urls
2712 * @return array result "count", "added" and "updated"
2714 public static function addByUrls(array $urls)
2720 foreach ($urls as $url) {
2721 $contact = Contact::getByURL($url, false, ['id']);
2722 if (empty($contact['id'])) {
2723 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2726 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2732 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2736 * Set the last date that the contact had posted something
2738 * This functionality is currently unused
2740 * @param string $data probing result
2741 * @param bool $force force updating
2743 private static function setLastUpdate(array $data, bool $force = false)
2745 $contact = self::getByURL($data['url'], false, []);
2746 if (empty($contact)) {
2749 if (!$force && !GServer::updateNeeded($contact['created'], $contact['updated'], $contact['last_failure'], $contact['last_contact'])) {
2750 Logger::info("Don't update profile", ['url' => $data['url'], 'updated' => $contact['updated']]);
2754 if (self::updateFromNoScrape($data)) {
2758 if (!empty($data['outbox'])) {
2759 self::updateFromOutbox($data['outbox'], $data);
2760 } elseif (!empty($data['poll']) && ($data['network'] == Protocol::ACTIVITYPUB)) {
2761 self::updateFromOutbox($data['poll'], $data);
2762 } elseif (!empty($data['poll'])) {
2763 self::updateFromFeed($data);
2768 * Update a global contact via the "noscrape" endpoint
2770 * @param string $data Probing result
2772 * @return bool 'true' if update was successful or the server was unreachable
2774 private static function updateFromNoScrape(array $data)
2776 // Check the 'noscrape' endpoint when it is a Friendica server
2777 $gserver = DBA::selectFirst('gserver', ['noscrape'], ["`nurl` = ? AND `noscrape` != ''",
2778 Strings::normaliseLink($data['baseurl'])]);
2779 if (!DBA::isResult($gserver)) {
2783 $curlResult = DI::httpRequest()->get($gserver['noscrape'] . '/' . $data['nick']);
2785 if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
2786 $noscrape = json_decode($curlResult->getBody(), true);
2787 if (!empty($noscrape) && !empty($noscrape['updated'])) {
2788 $noscrape['updated'] = DateTimeFormat::utc($noscrape['updated'], DateTimeFormat::MYSQL);
2789 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $noscrape['updated']];
2790 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2793 } elseif ($curlResult->isTimeout()) {
2794 // On a timeout return the existing value, but mark the contact as failure
2795 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
2796 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2803 * Update a global contact via an ActivityPub Outbox
2805 * @param string $feed
2806 * @param array $data Probing result
2807 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2809 private static function updateFromOutbox(string $feed, array $data)
2811 $outbox = ActivityPub::fetchContent($feed);
2812 if (empty($outbox)) {
2816 if (!empty($outbox['orderedItems'])) {
2817 $items = $outbox['orderedItems'];
2818 } elseif (!empty($outbox['first']['orderedItems'])) {
2819 $items = $outbox['first']['orderedItems'];
2820 } elseif (!empty($outbox['first']['href']) && ($outbox['first']['href'] != $feed)) {
2821 self::updateFromOutbox($outbox['first']['href'], $data);
2823 } elseif (!empty($outbox['first'])) {
2824 if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
2825 self::updateFromOutbox($outbox['first'], $data);
2827 Logger::warning('Unexpected data', ['outbox' => $outbox]);
2835 foreach ($items as $activity) {
2836 if (!empty($activity['published'])) {
2837 $published = DateTimeFormat::utc($activity['published']);
2838 } elseif (!empty($activity['object']['published'])) {
2839 $published = DateTimeFormat::utc($activity['object']['published']);
2844 if ($last_updated < $published) {
2845 $last_updated = $published;
2849 if (empty($last_updated)) {
2853 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
2854 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2858 * Update a global contact via an XML feed
2860 * @param string $data Probing result
2862 private static function updateFromFeed(array $data)
2864 // Search for the newest entry in the feed
2865 $curlResult = DI::httpRequest()->get($data['poll']);
2866 if (!$curlResult->isSuccess()) {
2867 $fields = ['failed' => true, 'last_failure' => DateTimeFormat::utcNow()];
2868 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2870 Logger::info("Profile wasn't reachable (no feed)", ['url' => $data['url']]);
2874 $doc = new DOMDocument();
2875 @$doc->loadXML($curlResult->getBody());
2877 $xpath = new DOMXPath($doc);
2878 $xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
2880 $entries = $xpath->query('/atom:feed/atom:entry');
2884 foreach ($entries as $entry) {
2885 $published_item = $xpath->query('atom:published/text()', $entry)->item(0);
2886 $updated_item = $xpath->query('atom:updated/text()' , $entry)->item(0);
2887 $published = !empty($published_item->nodeValue) ? DateTimeFormat::utc($published_item->nodeValue) : null;
2888 $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
2890 if (empty($published) || empty($updated)) {
2891 Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
2895 if ($last_updated < $published) {
2896 $last_updated = $published;
2899 if ($last_updated < $updated) {
2900 $last_updated = $updated;
2904 if (empty($last_updated)) {
2908 $fields = ['failed' => false, 'last_contact' => DateTimeFormat::utcNow(), 'updated' => $last_updated];
2909 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($data['url'])]);
2913 * Returns a random, global contact of the current node
2915 * @return string The profile URL
2918 public static function getRandomUrl()
2920 $r = DBA::selectFirst('contact', ['url'], [
2921 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2922 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2923 ], ['order' => ['RAND()']]);
2925 if (DBA::isResult($r)) {