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;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Session;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Notify\Type;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\Probe;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\DFRN;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\OStatus;
42 use Friendica\Protocol\Salmon;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
50 * functions for interacting with a contact
54 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
55 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
56 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
59 * @deprecated since version 2019.03
60 * @see User::PAGE_FLAGS_NORMAL
62 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
64 * @deprecated since version 2019.03
65 * @see User::PAGE_FLAGS_SOAPBOX
67 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
69 * @deprecated since version 2019.03
70 * @see User::PAGE_FLAGS_COMMUNITY
72 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
74 * @deprecated since version 2019.03
75 * @see User::PAGE_FLAGS_FREELOVE
77 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
79 * @deprecated since version 2019.03
80 * @see User::PAGE_FLAGS_BLOG
82 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
84 * @deprecated since version 2019.03
85 * @see User::PAGE_FLAGS_PRVGROUP
87 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
95 * TYPE_UNKNOWN - unknown type
97 * TYPE_PERSON - the account belongs to a person
98 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
100 * TYPE_ORGANISATION - the account belongs to an organisation
101 * Associated page type: PAGE_SOAPBOX
103 * TYPE_NEWS - the account is a news reflector
104 * Associated page type: PAGE_SOAPBOX
106 * TYPE_COMMUNITY - the account is community forum
107 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
109 * TYPE_RELAY - the account is a relay
110 * This will only be assigned to contacts, not to user accounts
113 const TYPE_UNKNOWN = -1;
114 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
115 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
116 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
117 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
118 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
138 * @param array $fields Array of selected fields, empty for all
139 * @param array $condition Array of fields for condition
140 * @param array $params Array of several parameters
144 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
146 return DBA::selectToArray('contact', $fields, $condition, $params);
150 * @param array $fields Array of selected fields, empty for all
151 * @param array $condition Array of fields for condition
152 * @param array $params Array of several parameters
156 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
158 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
164 * Insert a row into the contact table
165 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
167 * @param array $fields field array
168 * @param bool $on_duplicate_update Do an update on a duplicate entry
170 * @return boolean was the insert successful?
173 public static function insert(array $fields, bool $on_duplicate_update = false)
175 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
176 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
177 if (!DBA::isResult($contact)) {
182 // Search for duplicated contacts and get rid of them
183 self::removeDuplicates($contact['nurl'], $contact['uid']);
189 * @param integer $id Contact ID
190 * @param array $fields Array of selected fields, empty for all
191 * @return array|boolean Contact record if it exists, false otherwise
194 public static function getById($id, $fields = [])
196 return DBA::selectFirst('contact', $fields, ['id' => $id]);
200 * Fetches a contact by a given url
202 * @param string $url profile url
203 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
204 * @param array $fields Field list
205 * @param integer $uid User ID of the contact
206 * @return array contact array
208 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
210 if ($update || is_null($update)) {
211 $cid = self::getIdForURL($url, $uid, $update);
216 $contact = self::getById($cid, $fields);
217 if (empty($contact)) {
223 // Add internal fields
225 if (!empty($fields)) {
226 foreach (['id', 'avatar', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
227 if (!in_array($internal, $fields)) {
228 $fields[] = $internal;
229 $removal[] = $internal;
234 // We first try the nurl (http://server.tld/nick), most common case
235 $options = ['order' => ['id']];
236 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
238 // Then the addr (nick@server.tld)
239 if (!DBA::isResult($contact)) {
240 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
243 // Then the alias (which could be anything)
244 if (!DBA::isResult($contact)) {
245 // The link could be provided as http although we stored it as https
246 $ssl_url = str_replace('http://', 'https://', $url);
247 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
248 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
251 if (!DBA::isResult($contact)) {
255 // Update the contact in the background if needed
256 $updated = max($contact['success_update'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
257 if ((($updated < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
258 in_array($contact['network'], Protocol::FEDERATED)) {
259 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
262 // Remove the internal fields
263 foreach ($removal as $internal) {
264 unset($contact[$internal]);
271 * Fetches a contact for a given user by a given url.
272 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
274 * @param string $url profile url
275 * @param integer $uid User ID of the contact
276 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
277 * @param array $fields Field list
278 * @return array contact array
280 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
283 $contact = self::getByURL($url, $update, $fields, $uid);
284 if (!empty($contact)) {
285 if (!empty($contact['id'])) {
286 $contact['cid'] = $contact['id'];
293 $contact = self::getByURL($url, $update, $fields);
294 if (!empty($contact['id'])) {
296 $contact['zid'] = $contact['id'];
302 * Tests if the given contact is a follower
304 * @param int $cid Either public contact id or user's contact id
305 * @param int $uid User ID
307 * @return boolean is the contact id a follower?
308 * @throws HTTPException\InternalServerErrorException
309 * @throws \ImagickException
311 public static function isFollower($cid, $uid)
313 if (Contact\User::isBlocked($cid, $uid)) {
317 $cdata = self::getPublicAndUserContacID($cid, $uid);
318 if (empty($cdata['user'])) {
322 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
323 return DBA::exists('contact', $condition);
327 * Tests if the given contact url is a follower
329 * @param string $url Contact URL
330 * @param int $uid User ID
332 * @return boolean is the contact id a follower?
333 * @throws HTTPException\InternalServerErrorException
334 * @throws \ImagickException
336 public static function isFollowerByURL($url, $uid)
338 $cid = self::getIdForURL($url, $uid);
344 return self::isFollower($cid, $uid);
348 * Tests if the given user follow the given contact
350 * @param int $cid Either public contact id or user's contact id
351 * @param int $uid User ID
353 * @return boolean is the contact url being followed?
354 * @throws HTTPException\InternalServerErrorException
355 * @throws \ImagickException
357 public static function isSharing($cid, $uid)
359 if (Contact\User::isBlocked($cid, $uid)) {
363 $cdata = self::getPublicAndUserContacID($cid, $uid);
364 if (empty($cdata['user'])) {
368 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
369 return DBA::exists('contact', $condition);
373 * Tests if the given user follow the given contact url
375 * @param string $url Contact URL
376 * @param int $uid User ID
378 * @return boolean is the contact url being followed?
379 * @throws HTTPException\InternalServerErrorException
380 * @throws \ImagickException
382 public static function isSharingByURL($url, $uid)
384 $cid = self::getIdForURL($url, $uid);
390 return self::isSharing($cid, $uid);
394 * Get the basepath for a given contact link
396 * @param string $url The contact link
397 * @param boolean $dont_update Don't update the contact
399 * @return string basepath
400 * @throws HTTPException\InternalServerErrorException
401 * @throws \ImagickException
403 public static function getBasepath($url, $dont_update = false)
405 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
406 if (!DBA::isResult($contact)) {
410 if (!empty($contact['baseurl'])) {
411 return $contact['baseurl'];
412 } elseif ($dont_update) {
416 // Update the existing contact
417 self::updateFromProbe($contact['id']);
419 // And fetch the result
420 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
421 if (empty($contact['baseurl'])) {
422 Logger::info('No baseurl for contact', ['url' => $url]);
426 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
427 return $contact['baseurl'];
431 * Check if the given contact url is on the same server
433 * @param string $url The contact link
435 * @return boolean Is it the same server?
437 public static function isLocal($url)
439 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
443 * Check if the given contact ID is on the same server
445 * @param string $url The contact link
447 * @return boolean Is it the same server?
449 public static function isLocalById(int $cid)
451 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
452 if (!DBA::isResult($contact)) {
456 if (empty($contact['baseurl'])) {
457 $baseurl = self::getBasepath($contact['url'], true);
459 $baseurl = $contact['baseurl'];
462 return Strings::compareLink($baseurl, DI::baseUrl());
466 * Returns the public contact id of the given user id
468 * @param integer $uid User ID
470 * @return integer|boolean Public contact id for given user id
473 public static function getPublicIdByUserId($uid)
475 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
476 if (!DBA::isResult($self)) {
479 return self::getIdForURL($self['url']);
483 * Returns the contact id for the user and the public contact id for a given contact id
485 * @param int $cid Either public contact id or user's contact id
486 * @param int $uid User ID
488 * @return array with public and user's contact id
489 * @throws HTTPException\InternalServerErrorException
490 * @throws \ImagickException
492 public static function getPublicAndUserContacID($cid, $uid)
494 if (empty($uid) || empty($cid)) {
498 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
499 if (!DBA::isResult($contact)) {
503 // We quit when the user id don't match the user id of the provided contact
504 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
508 if ($contact['uid'] != 0) {
509 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
513 $ucid = $contact['id'];
515 $pcid = $contact['id'];
516 $ucid = Contact::getIdForURL($contact['url'], $uid);
519 return ['public' => $pcid, 'user' => $ucid];
523 * Returns contact details for a given contact id in combination with a user id
525 * @param int $cid A contact ID
526 * @param int $uid The User ID
527 * @param array $fields The selected fields for the contact
529 * @return array The contact details
533 public static function getContactForUser($cid, $uid, array $fields = [])
535 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
537 if (!DBA::isResult($contact)) {
545 * Creates the self-contact for the provided user id
548 * @return bool Operation success
549 * @throws HTTPException\InternalServerErrorException
551 public static function createSelfFromUserId($uid)
553 // Only create the entry if it doesn't exist yet
554 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
558 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'], ['uid' => $uid]);
559 if (!DBA::isResult($user)) {
563 $return = DBA::insert('contact', [
564 'uid' => $user['uid'],
565 'created' => DateTimeFormat::utcNow(),
567 'name' => $user['username'],
568 'nick' => $user['nickname'],
569 'pubkey' => $user['pubkey'],
570 'prvkey' => $user['prvkey'],
571 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
572 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
573 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
576 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
577 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
578 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
579 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
580 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
581 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
582 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
583 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
584 'name-date' => DateTimeFormat::utcNow(),
585 'uri-date' => DateTimeFormat::utcNow(),
586 'avatar-date' => DateTimeFormat::utcNow(),
594 * Updates the self-contact for the provided user id
597 * @param boolean $update_avatar Force the avatar update
598 * @throws HTTPException\InternalServerErrorException
600 public static function updateSelfFromUserID($uid, $update_avatar = false)
602 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
603 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
604 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
605 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
606 if (!DBA::isResult($self)) {
610 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
611 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
612 if (!DBA::isResult($user)) {
616 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
617 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
618 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
619 if (!DBA::isResult($profile)) {
623 $file_suffix = 'jpg';
625 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
626 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
627 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
628 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
629 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp']];
631 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
632 if (DBA::isResult($avatar)) {
633 if ($update_avatar) {
634 $fields['avatar-date'] = DateTimeFormat::utcNow();
637 // Creating the path to the avatar, beginning with the file suffix
638 $types = Images::supportedTypes();
639 if (isset($types[$avatar['type']])) {
640 $file_suffix = $types[$avatar['type']];
643 // We are adding a timestamp value so that other systems won't use cached content
644 $timestamp = strtotime($fields['avatar-date']);
646 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
647 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
649 $fields['photo'] = $prefix . '4' . $suffix;
650 $fields['thumb'] = $prefix . '5' . $suffix;
651 $fields['micro'] = $prefix . '6' . $suffix;
653 // We hadn't found a photo entry, so we use the default avatar
654 $fields['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
655 $fields['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
656 $fields['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
659 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
660 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
661 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
662 $fields['unsearchable'] = !$profile['net-publish'];
664 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
665 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
666 $fields['nurl'] = Strings::normaliseLink($fields['url']);
667 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
668 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
669 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
670 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
671 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
672 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
676 foreach ($fields as $field => $content) {
677 if ($self[$field] != $content) {
683 if ($fields['name'] != $self['name']) {
684 $fields['name-date'] = DateTimeFormat::utcNow();
686 $fields['updated'] = DateTimeFormat::utcNow();
687 DBA::update('contact', $fields, ['id' => $self['id']]);
689 // Update the public contact as well
690 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
692 // Update the profile
693 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
694 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
695 DBA::update('profile', $fields, ['uid' => $uid]);
700 * Marks a contact for removal
702 * @param int $id contact id
704 * @throws HTTPException\InternalServerErrorException
706 public static function remove($id)
708 // We want just to make sure that we don't delete our "self" contact
709 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
710 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
714 // Archive the contact
715 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
717 // Delete it in the background
718 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
722 * Sends an unfriend message. Does not remove the contact
724 * @param array $user User unfriending
725 * @param array $contact Contact unfriended
726 * @param boolean $dissolve Remove the contact on the remote side
728 * @throws HTTPException\InternalServerErrorException
729 * @throws \ImagickException
731 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
733 if (empty($contact['network'])) {
737 $protocol = $contact['network'];
738 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
739 $protocol = Protocol::ACTIVITYPUB;
742 if (($protocol == Protocol::DFRN) && $dissolve) {
743 DFRN::deliver($user, $contact, 'placeholder', true);
744 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
745 // create an unfollow slap
747 $item['verb'] = Activity::O_UNFOLLOW;
748 $item['gravity'] = GRAVITY_ACTIVITY;
749 $item['follow'] = $contact["url"];
754 $item['attach'] = '';
755 $slap = OStatus::salmon($item, $user);
757 if (!empty($contact['notify'])) {
758 Salmon::slapper($user, $contact['notify'], $slap);
760 } elseif ($protocol == Protocol::DIASPORA) {
761 Diaspora::sendUnshare($user, $contact);
762 } elseif ($protocol == Protocol::ACTIVITYPUB) {
763 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
766 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
772 * Marks a contact for archival after a communication issue delay
774 * Contact has refused to recognise us as a friend. We will start a countdown.
775 * If they still don't recognise us in 32 days, the relationship is over,
776 * and we won't waste any more time trying to communicate with them.
777 * This provides for the possibility that their database is temporarily messed
778 * up or some other transient event and that there's a possibility we could recover from it.
780 * @param array $contact contact to mark for archival
782 * @throws HTTPException\InternalServerErrorException
784 public static function markForArchival(array $contact)
786 if (!isset($contact['url']) && !empty($contact['id'])) {
787 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
788 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
789 if (!DBA::isResult($contact)) {
792 } elseif (!isset($contact['url'])) {
793 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
796 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
798 // Contact already archived or "self" contact? => nothing to do
799 if ($contact['archive'] || $contact['self']) {
803 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
804 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
805 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
808 * We really should send a notification to the owner after 2-3 weeks
809 * so they won't be surprised when the contact vanishes and can take
810 * remedial action if this was a serious mistake or glitch
813 /// @todo Check for contact vitality via probing
814 $archival_days = DI::config()->get('system', 'archival_days', 32);
816 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
817 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
818 /* Relationship is really truly dead. archive them rather than
819 * delete, though if the owner tries to unarchive them we'll start
820 * the whole process over again.
822 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
823 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
829 * Cancels the archival countdown
831 * @see Contact::markForArchival()
833 * @param array $contact contact to be unmarked for archival
837 public static function unmarkForArchival(array $contact)
839 // Always unarchive the relay contact entry
840 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
841 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
842 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
843 DBA::update('contact', $fields, $condition);
846 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
847 $exists = DBA::exists('contact', $condition);
849 // We don't need to update, we never marked this contact for archival
854 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
856 if (!isset($contact['url']) && !empty($contact['id'])) {
857 $fields = ['id', 'url', 'batch'];
858 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
859 if (!DBA::isResult($contact)) {
864 // It's a miracle. Our dead contact has inexplicably come back to life.
865 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
866 DBA::update('contact', $fields, ['id' => $contact['id']]);
867 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
871 * Returns the data array for the photo menu of a given contact
873 * @param array $contact contact
874 * @param int $uid optional, default 0
876 * @throws HTTPException\InternalServerErrorException
877 * @throws \ImagickException
879 public static function photoMenu(array $contact, $uid = 0)
884 $contact_drop_link = '';
891 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
893 $profile_link = self::magicLink($contact['url']);
894 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
899 // Look for our own contact if the uid doesn't match and isn't public
900 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
901 if (DBA::isResult($contact_own)) {
902 return self::photoMenu($contact_own, $uid);
907 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
909 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
911 $profile_link = $contact['url'];
914 if ($profile_link === 'mailbox') {
919 $status_link = $profile_link . '/status';
920 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
921 $profile_link = $profile_link . '/profile';
924 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
925 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
928 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
929 $poke_link = 'contact/' . $contact['id'] . '/poke';
932 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
934 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
936 if (!$contact['self']) {
937 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
942 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
943 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
944 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
945 } elseif(!$contact['pending']) {
946 $follow_link = 'follow?url=' . urlencode($contact['url']);
950 if (!empty($follow_link) || !empty($unfollow_link)) {
951 $contact_drop_link = '';
956 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
958 if (empty($contact['uid'])) {
960 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
961 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
962 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
963 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
964 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
968 'status' => [DI::l10n()->t('View Status') , $status_link , true],
969 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
970 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
971 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
972 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
973 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
974 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
975 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
976 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
977 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
980 if (!empty($contact['pending'])) {
981 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
982 if (DBA::isResult($intro)) {
983 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
988 $args = ['contact' => $contact, 'menu' => &$menu];
990 Hook::callAll('contact_photo_menu', $args);
994 foreach ($menu as $menuname => $menuitem) {
995 if ($menuitem[1] != '') {
996 $menucondensed[$menuname] = $menuitem;
1000 return $menucondensed;
1004 * Fetch the contact id for a given URL and user
1006 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1007 * `addr` or `alias`.
1009 * If there's no record and we aren't looking for a public contact, we quit.
1010 * If there's one, we check that it isn't time to update the picture else we
1011 * directly return the found contact id.
1013 * Second, we probe the provided $url whether it's http://server.tld/profile or
1014 * nick@server.tld. We quit if we can't get any info back.
1016 * Third, we create the contact record if it doesn't exist
1018 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1019 * if there's any updates
1021 * @param string $url Contact URL
1022 * @param integer $uid The user id for the contact (0 = public contact)
1023 * @param boolean $update true = always update, false = never update, null = update when not found
1024 * @param array $default Default value for creating the contact when everything else fails
1026 * @return integer Contact ID
1027 * @throws HTTPException\InternalServerErrorException
1028 * @throws \ImagickException
1030 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1035 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1039 $contact = self::getByURL($url, false, ['id', 'network'], $uid);
1041 if (!empty($contact)) {
1042 $contact_id = $contact["id"];
1044 if (empty($update)) {
1045 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1048 } elseif ($uid != 0) {
1049 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1051 } elseif (empty($default) && !is_null($update) && !$update) {
1052 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1058 if (empty($default['network']) || $update) {
1059 $data = Probe::uri($url, "", $uid);
1061 // Take the default values when probing failed
1062 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1063 $data = array_merge($data, $default);
1065 } elseif (!empty($default['network'])) {
1069 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1070 // Fetch data for the public contact via the first found personal contact
1071 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1072 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'contact-type',
1073 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1074 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1076 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1077 if (!DBA::isResult($personal_contact)) {
1078 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1081 if (DBA::isResult($personal_contact)) {
1082 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1083 $data = $personal_contact;
1084 $data['photo'] = $personal_contact['avatar'];
1085 $data['account-type'] = $personal_contact['contact-type'];
1086 $data['hide'] = $personal_contact['unsearchable'];
1087 unset($data['avatar']);
1088 unset($data['contact-type']);
1089 unset($data['unsearchable']);
1093 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1094 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1099 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1100 if (!empty($data['alias'])) {
1101 $urls[] = Strings::normaliseLink($data['alias']);
1103 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1104 if (!empty($contact['id'])) {
1105 $contact_id = $contact['id'];
1106 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'probed_url' => $data['url'], 'alias' => $data['alias'], 'addr' => $data['addr']]);
1111 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1114 'url' => $data['url'],
1115 'nurl' => Strings::normaliseLink($data['url']),
1116 'network' => $data['network'],
1117 'created' => DateTimeFormat::utcNow(),
1118 'rel' => self::SHARING,
1124 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1126 // Before inserting we do check if the entry does exist now.
1127 DBA::lock('contact');
1128 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1129 if (DBA::isResult($contact)) {
1130 $contact_id = $contact['id'];
1131 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1133 DBA::insert('contact', $fields);
1134 $contact_id = DBA::lastInsertId();
1136 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1141 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1145 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1148 self::updateFromProbeArray($contact_id, $data);
1154 * Checks if the contact is archived
1156 * @param int $cid contact id
1158 * @return boolean Is the contact archived?
1159 * @throws HTTPException\InternalServerErrorException
1161 public static function isArchived(int $cid)
1167 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1168 if (!DBA::isResult($contact)) {
1172 if ($contact['archive']) {
1176 // Check status of ActivityPub endpoints
1177 $apcontact = APContact::getByURL($contact['url'], false);
1178 if (!empty($apcontact)) {
1179 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1183 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1188 // Check status of Diaspora endpoints
1189 if (!empty($contact['batch'])) {
1190 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1191 return DBA::exists('contact', $condition);
1198 * Checks if the contact is blocked
1200 * @param int $cid contact id
1202 * @return boolean Is the contact blocked?
1203 * @throws HTTPException\InternalServerErrorException
1205 public static function isBlocked($cid)
1211 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1212 if (!DBA::isResult($blocked)) {
1216 if (Network::isUrlBlocked($blocked['url'])) {
1220 return (bool) $blocked['blocked'];
1224 * Checks if the contact is hidden
1226 * @param int $cid contact id
1228 * @return boolean Is the contact hidden?
1229 * @throws \Exception
1231 public static function isHidden($cid)
1237 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1238 if (!DBA::isResult($hidden)) {
1241 return (bool) $hidden['hidden'];
1245 * Returns posts from a given contact url
1247 * @param string $contact_url Contact URL
1248 * @param bool $thread_mode
1249 * @param int $update
1250 * @return string posts in HTML
1251 * @throws \Exception
1253 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1255 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1259 * Returns posts from a given contact id
1261 * @param integer $cid
1262 * @param bool $thread_mode
1263 * @param integer $update
1264 * @return string posts in HTML
1265 * @throws \Exception
1267 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1271 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1272 if (!DBA::isResult($contact)) {
1276 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1277 $sql = "`item`.`uid` IN (0, ?)";
1279 $sql = "`item`.`uid` = ?";
1282 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1285 $condition = ["(`$contact_field` = ? OR (`causer-id` = ? AND `post-type` = ?)) AND `gravity` = ? AND " . $sql,
1286 $cid, $cid, Item::PT_ANNOUNCEMENT, GRAVITY_PARENT, local_user()];
1288 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1289 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1292 if (DI::mode()->isMobile()) {
1293 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1294 DI::config()->get('system', 'itemspage_network_mobile'));
1296 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1297 DI::config()->get('system', 'itemspage_network'));
1300 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1302 $params = ['order' => ['received' => true], 'group_by' => ['uri-id'],
1303 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1306 $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1308 while ($item = DBA::fetch($r)) {
1309 if ($item['gravity'] != GRAVITY_PARENT) {
1310 $item['uri'] = $item['parent-uri'];
1312 unset($item['parent-uri']);
1313 unset($item['gravity']);
1319 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1321 $r = Item::selectForUser(local_user(), [], $condition, $params);
1323 $items = Item::inArray($r);
1325 $o = conversation($a, $items, 'contact-posts', false);
1329 $o .= $pager->renderMinimal(count($items));
1336 * Returns the account type name
1338 * The function can be called with either the user or the contact array
1340 * @param array $contact contact or user array
1343 public static function getAccountType(array $contact)
1345 // There are several fields that indicate that the contact or user is a forum
1346 // "page-flags" is a field in the user table,
1347 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1348 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1349 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1350 || (isset($contact['forum']) && intval($contact['forum']))
1351 || (isset($contact['prv']) && intval($contact['prv']))
1352 || (isset($contact['community']) && intval($contact['community']))
1354 $type = self::TYPE_COMMUNITY;
1356 $type = self::TYPE_PERSON;
1359 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1360 if (isset($contact["contact-type"])) {
1361 $type = $contact["contact-type"];
1364 if (isset($contact["account-type"])) {
1365 $type = $contact["account-type"];
1369 case self::TYPE_ORGANISATION:
1370 $account_type = DI::l10n()->t("Organisation");
1373 case self::TYPE_NEWS:
1374 $account_type = DI::l10n()->t('News');
1377 case self::TYPE_COMMUNITY:
1378 $account_type = DI::l10n()->t("Forum");
1386 return $account_type;
1394 * @throws \Exception
1396 public static function block($cid, $reason = null)
1398 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1404 * Unblocks a contact
1408 * @throws \Exception
1410 public static function unblock($cid)
1412 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1418 * Ensure that cached avatar exist
1420 * @param integer $cid
1422 public static function checkAvatarCache(int $cid)
1424 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1425 if (!DBA::isResult($contact)) {
1429 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1433 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1435 self::updateAvatar($cid, $contact['avatar'], true);
1439 * Return the photo path for a given contact array in the given size
1441 * @param array $contact contact array
1442 * @param string $field Fieldname of the photo in the contact array
1443 * @param string $default Default path when no picture had been found
1444 * @param string $size Size of the avatar picture
1445 * @param string $avatar Avatar path that is displayed when no photo had been found
1446 * @return string photo path
1448 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1450 if (!empty($contact)) {
1451 $contact = self::checkAvatarCacheByArray($contact);
1452 if (!empty($contact[$field])) {
1453 $avatar = $contact[$field];
1457 if (empty($avatar)) {
1461 if (Proxy::isLocalImage($avatar)) {
1464 return Proxy::proxifyUrl($avatar, false, $size);
1469 * Return the photo path for a given contact array
1471 * @param array $contact Contact array
1472 * @param string $avatar Avatar path that is displayed when no photo had been found
1473 * @return string photo path
1475 public static function getPhoto(array $contact, string $avatar = '')
1477 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO, Proxy::SIZE_SMALL, $avatar);
1481 * Return the photo path (thumb size) for a given contact array
1483 * @param array $contact Contact array
1484 * @param string $avatar Avatar path that is displayed when no photo had been found
1485 * @return string photo path
1487 public static function getThumb(array $contact, string $avatar = '')
1489 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . self::DEFAULT_AVATAR_THUMB, Proxy::SIZE_THUMB, $avatar);
1493 * Return the photo path (micro size) for a given contact array
1495 * @param array $contact Contact array
1496 * @param string $avatar Avatar path that is displayed when no photo had been found
1497 * @return string photo path
1499 public static function getMicro(array $contact, string $avatar = '')
1501 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . self::DEFAULT_AVATAR_MICRO, Proxy::SIZE_MICRO, $avatar);
1505 * Check the given contact array for avatar cache fields
1507 * @param array $contact
1508 * @return array contact array with avatar cache fields
1510 private static function checkAvatarCacheByArray(array $contact)
1513 $contact_fields = [];
1514 $fields = ['photo', 'thumb', 'micro'];
1515 foreach ($fields as $field) {
1516 if (isset($contact[$field])) {
1517 $contact_fields[] = $field;
1519 if (isset($contact[$field]) && empty($contact[$field])) {
1528 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1529 self::updateAvatar($contact['id'], $contact['avatar'], true);
1531 $new_contact = self::getById($contact['id'], $contact_fields);
1532 if (DBA::isResult($new_contact)) {
1533 // We only update the cache fields
1534 $contact = array_merge($contact, $new_contact);
1538 /// add the default avatars if the fields aren't filled
1539 if (isset($contact['photo']) && empty($contact['photo'])) {
1540 $contact['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
1542 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1543 $contact['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
1545 if (isset($contact['micro']) && empty($contact['micro'])) {
1546 $contact['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
1553 * Updates the avatar links in a contact only if needed
1555 * @param int $cid Contact id
1556 * @param string $avatar Link to avatar picture
1557 * @param bool $force force picture update
1558 * @param bool $create_cache Enforces the creation of cached avatar fields
1561 * @throws HTTPException\InternalServerErrorException
1562 * @throws HTTPException\NotFoundException
1563 * @throws \ImagickException
1565 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1567 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl', 'url', 'network'], ['id' => $cid, 'self' => false]);
1568 if (!DBA::isResult($contact)) {
1572 $uid = $contact['uid'];
1574 // Only update the cached photo links of public contacts when they already are cached
1575 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1576 if ($contact['avatar'] != $avatar) {
1577 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1578 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1583 // User contacts use are updated through the public contacts
1584 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1585 $pcid = self::getIdForURL($contact['url'], false);
1586 if (!empty($pcid)) {
1587 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1588 self::updateAvatar($pcid, $avatar, $force, true);
1593 // Replace cached avatar pictures from the default avatar with the default avatars in different sizes
1594 if (strpos($avatar, self::DEFAULT_AVATAR_PHOTO)) {
1595 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1596 'photo' => DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO,
1597 'thumb' => DI::baseUrl() . self::DEFAULT_AVATAR_THUMB,
1598 'micro' => DI::baseUrl() . self::DEFAULT_AVATAR_MICRO];
1599 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1602 // Use the data from the self account
1603 if (empty($fields)) {
1604 $local_uid = User::getIdForURL($contact['url']);
1605 if (!empty($local_uid)) {
1606 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1607 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1611 if (empty($fields)) {
1612 $update = ($contact['avatar'] != $avatar) || $force;
1616 $contact['photo'] ?? '',
1617 $contact['thumb'] ?? '',
1618 $contact['micro'] ?? '',
1621 foreach ($data as $image_uri) {
1622 $image_rid = Photo::ridFromURI($image_uri);
1623 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1624 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1631 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1633 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1634 $update = !empty($fields);
1635 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1641 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1650 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1651 // Collect all user contacts of the given public contact
1652 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1653 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1654 while ($personal_contact = DBA::fetch($personal_contacts)) {
1655 $cids[] = $personal_contact['id'];
1656 $uids[] = $personal_contact['uid'];
1658 DBA::close($personal_contacts);
1660 if (!empty($cids)) {
1661 // Delete possibly existing cached user contact avatars
1662 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1668 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1669 DBA::update('contact', $fields, ['id' => $cids]);
1673 * Helper function for "updateFromProbe". Updates personal and public contact
1675 * @param integer $id contact id
1676 * @param integer $uid user id
1677 * @param string $url The profile URL of the contact
1678 * @param array $fields The fields that are updated
1680 * @throws \Exception
1682 private static function updateContact($id, $uid, $url, array $fields)
1684 if (!DBA::update('contact', $fields, ['id' => $id])) {
1685 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1689 // Search for duplicated contacts and get rid of them
1690 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1694 // Archive or unarchive the contact. We only need to do this for the public contact.
1695 // The archive/unarchive function will update the personal contacts by themselves.
1696 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1697 if (!DBA::isResult($contact)) {
1698 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1702 if (!empty($fields['success_update'])) {
1703 self::unmarkForArchival($contact);
1704 } elseif (!empty($fields['failure_update'])) {
1705 self::markForArchival($contact);
1708 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1710 // These contacts are sharing with us, we don't poll them.
1711 // This means that we don't set the update fields in "OnePoll.php".
1712 $condition['rel'] = self::SHARING;
1713 DBA::update('contact', $fields, $condition);
1715 unset($fields['last-update']);
1716 unset($fields['success_update']);
1717 unset($fields['failure_update']);
1719 if (empty($fields)) {
1723 // We are polling these contacts, so we mustn't set the update fields here.
1724 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1725 DBA::update('contact', $fields, $condition);
1729 * Remove duplicated contacts
1731 * @param string $nurl Normalised contact url
1732 * @param integer $uid User id
1734 * @throws \Exception
1736 public static function removeDuplicates(string $nurl, int $uid)
1738 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1739 $count = DBA::count('contact', $condition);
1744 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1745 if (!DBA::isResult($first_contact)) {
1746 // Shouldn't happen - so we handle it
1750 $first = $first_contact['id'];
1751 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1752 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1753 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1754 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1758 // Find all duplicates
1759 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1760 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1761 while ($duplicate = DBA::fetch($duplicates)) {
1762 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1766 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1768 DBA::close($duplicates);
1769 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1774 * @param integer $id contact id
1775 * @param string $network Optional network we are probing for
1777 * @throws HTTPException\InternalServerErrorException
1778 * @throws \ImagickException
1780 public static function updateFromProbe(int $id, string $network = '')
1782 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1783 if (!DBA::isResult($contact)) {
1787 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1788 return self::updateFromProbeArray($id, $ret);
1792 * @param integer $id contact id
1793 * @param array $ret Probed data
1795 * @throws HTTPException\InternalServerErrorException
1796 * @throws \ImagickException
1798 private static function updateFromProbeArray(int $id, array $ret)
1801 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1802 This will reliably kill your communication with old Friendica contacts.
1805 // These fields aren't updated by this routine:
1806 // 'xmpp', 'sensitive'
1808 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe', 'manually-approve',
1809 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1810 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1811 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1812 if (!DBA::isResult($contact)) {
1816 $uid = $contact['uid'];
1817 unset($contact['uid']);
1819 $pubkey = $contact['pubkey'];
1820 unset($contact['pubkey']);
1822 $contact['photo'] = $contact['avatar'];
1823 unset($contact['avatar']);
1825 $updated = DateTimeFormat::utcNow();
1827 // We must not try to update relay contacts via probe. They are no real contacts.
1828 // We check after the probing to be able to correct falsely detected contact types.
1829 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1830 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1831 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1832 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1836 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1837 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1839 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1844 if (Contact\Relation::isDiscoverable($ret['url'])) {
1845 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1848 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1849 $ret['unsearchable'] = $ret['hide'];
1852 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1853 $ret['forum'] = false;
1854 $ret['prv'] = false;
1855 $ret['contact-type'] = $ret['account-type'];
1856 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1857 $ret['forum'] = (bool)!$ret['manually-approve'];
1858 $ret['prv'] = (bool)!$ret['forum'];
1862 $new_pubkey = $ret['pubkey'] ?? '';
1865 $ret['last-item'] = Probe::getLastUpdate($ret);
1866 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1871 // make sure to not overwrite existing values with blank entries except some technical fields
1872 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1873 foreach ($ret as $key => $val) {
1874 if (!array_key_exists($key, $contact)) {
1876 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1877 $ret[$key] = $contact[$key];
1878 } elseif ($ret[$key] != $contact[$key]) {
1883 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1886 unset($ret['last-item']);
1889 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1890 self::updateAvatar($id, $ret['photo'], $update);
1894 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1896 // Update the public contact
1898 $contact = self::getByURL($ret['url'], false, ['id']);
1899 if (!empty($contact['id'])) {
1900 self::updateFromProbeArray($contact['id'], $ret);
1907 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1908 $ret['updated'] = $updated;
1910 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1911 if (empty($pubkey) && !empty($new_pubkey)) {
1912 $ret['pubkey'] = $new_pubkey;
1915 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1916 $ret['uri-date'] = DateTimeFormat::utcNow();
1919 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1920 $ret['name-date'] = $updated;
1924 $ret['last-update'] = $updated;
1925 $ret['success_update'] = $updated;
1926 $ret['failed'] = false;
1929 unset($ret['photo']);
1931 self::updateContact($id, $uid, $ret['url'], $ret);
1937 * @param integer $url contact url
1938 * @return integer Contact id
1939 * @throws HTTPException\InternalServerErrorException
1940 * @throws \ImagickException
1942 public static function updateFromProbeByURL($url)
1944 $id = self::getIdForURL($url);
1950 self::updateFromProbe($id);
1956 * Detects if a given contact array belongs to a legacy DFRN connection
1958 * @param array $contact
1961 public static function isLegacyDFRNContact($contact)
1963 // Newer Friendica contacts are connected via AP, then these fields aren't set
1964 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1968 * Detects the communication protocol for a given contact url.
1969 * This is used to detect Friendica contacts that we can communicate via AP.
1971 * @param string $url contact url
1972 * @param string $network Network of that contact
1973 * @return string with protocol
1975 public static function getProtocol($url, $network)
1977 if ($network != Protocol::DFRN) {
1981 $apcontact = APContact::getByURL($url);
1982 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1983 return Protocol::ACTIVITYPUB;
1990 * Takes a $uid and a url/handle and adds a new contact
1992 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1993 * dfrn_request page.
1995 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1998 * $return['success'] boolean true if successful
1999 * $return['message'] error text if success is false.
2001 * Takes a $uid and a url/handle and adds a new contact
2003 * @param array $user The user the contact should be created for
2004 * @param string $url The profile URL of the contact
2005 * @param bool $interactive
2006 * @param string $network
2008 * @throws HTTPException\InternalServerErrorException
2009 * @throws HTTPException\NotFoundException
2010 * @throws \ImagickException
2012 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2014 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2016 // remove ajax junk, e.g. Twitter
2017 $url = str_replace('/#!/', '/', $url);
2019 if (!Network::isUrlAllowed($url)) {
2020 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2024 if (Network::isUrlBlocked($url)) {
2025 $result['message'] = DI::l10n()->t('Blocked domain');
2030 $result['message'] = DI::l10n()->t('Connect URL missing.');
2034 $arr = ['url' => $url, 'contact' => []];
2036 Hook::callAll('follow', $arr);
2039 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2043 if (!empty($arr['contact']['name'])) {
2044 $ret = $arr['contact'];
2046 $ret = Probe::uri($url, $network, $user['uid']);
2049 if (($network != '') && ($ret['network'] != $network)) {
2050 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2054 // check if we already have a contact
2055 // the poll url is more reliable than the profile url, as we may have
2056 // indirect links or webfinger links
2058 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2059 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2060 if (!DBA::isResult($contact)) {
2061 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2062 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2065 $protocol = self::getProtocol($ret['url'], $ret['network']);
2067 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2069 if (strlen(DI::baseUrl()->getUrlPath())) {
2070 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2072 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2075 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2079 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2080 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2081 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2085 // This extra param just confuses things, remove it
2086 if ($protocol === Protocol::DIASPORA) {
2087 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2090 // do we have enough information?
2091 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2092 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2093 if (empty($ret['poll'])) {
2094 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2096 if (empty($ret['name'])) {
2097 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2099 if (empty($ret['url'])) {
2100 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2102 if (strpos($ret['url'], '@') !== false) {
2103 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2104 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2109 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2110 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2111 $ret['notify'] = '';
2114 if (!$ret['notify']) {
2115 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2118 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2120 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2122 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2125 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2126 $pending = (bool)$ret['manually-approve'];
2129 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2133 if (DBA::isResult($contact)) {
2135 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2137 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2138 DBA::update('contact', $fields, ['id' => $contact['id']]);
2140 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2142 // create contact record
2144 'uid' => $user['uid'],
2145 'created' => DateTimeFormat::utcNow(),
2146 'url' => $ret['url'],
2147 'nurl' => Strings::normaliseLink($ret['url']),
2148 'addr' => $ret['addr'],
2149 'alias' => $ret['alias'],
2150 'batch' => $ret['batch'],
2151 'notify' => $ret['notify'],
2152 'poll' => $ret['poll'],
2153 'poco' => $ret['poco'],
2154 'name' => $ret['name'],
2155 'nick' => $ret['nick'],
2156 'network' => $ret['network'],
2157 'baseurl' => $ret['baseurl'],
2158 'gsid' => $ret['gsid'] ?? null,
2159 'protocol' => $protocol,
2160 'pubkey' => $ret['pubkey'],
2161 'rel' => $new_relation,
2162 'priority'=> $ret['priority'],
2163 'writable'=> $writeable,
2164 'hidden' => $hidden,
2167 'pending' => $pending,
2172 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2173 if (!DBA::isResult($contact)) {
2174 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2178 $contact_id = $contact['id'];
2179 $result['cid'] = $contact_id;
2181 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2183 // Update the avatar
2184 self::updateAvatar($contact_id, $ret['photo']);
2186 // pull feed and consume it, which should subscribe to the hub.
2188 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2190 $owner = User::getOwnerDataById($user['uid']);
2192 if (DBA::isResult($owner)) {
2193 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2194 // create a follow slap
2196 $item['verb'] = Activity::FOLLOW;
2197 $item['gravity'] = GRAVITY_ACTIVITY;
2198 $item['follow'] = $contact["url"];
2200 $item['title'] = '';
2202 $item['uri-id'] = 0;
2203 $item['attach'] = '';
2205 $slap = OStatus::salmon($item, $owner);
2207 if (!empty($contact['notify'])) {
2208 Salmon::slapper($owner, $contact['notify'], $slap);
2210 } elseif ($protocol == Protocol::DIASPORA) {
2211 $ret = Diaspora::sendShare($owner, $contact);
2212 Logger::log('share returns: ' . $ret);
2213 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2214 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2215 if (empty($activity_id)) {
2216 // This really should never happen
2220 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2221 Logger::log('Follow returns: ' . $ret);
2225 $result['success'] = true;
2230 * Updated contact's SSL policy
2232 * @param array $contact Contact array
2233 * @param string $new_policy New policy, valid: self,full
2235 * @return array Contact array with updated values
2236 * @throws \Exception
2238 public static function updateSslPolicy(array $contact, $new_policy)
2240 $ssl_changed = false;
2241 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2242 $ssl_changed = true;
2243 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2244 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2245 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2246 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2247 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2248 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2251 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2252 $ssl_changed = true;
2253 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2254 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2255 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2256 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2257 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2258 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2262 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2263 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2264 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2265 DBA::update('contact', $fields, ['id' => $contact['id']]);
2272 * @param array $importer Owner (local user) data
2273 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2274 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2275 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2276 * @param string $note Introduction additional message
2277 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2278 * @throws HTTPException\InternalServerErrorException
2279 * @throws \ImagickException
2281 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2283 // Should always be set
2284 if (empty($datarray['author-id'])) {
2288 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2289 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2290 if (!DBA::isResult($pub_contact)) {
2291 // Should never happen
2295 // Contact is blocked at node-level
2296 if (self::isBlocked($datarray['author-id'])) {
2300 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2301 $name = $pub_contact['name'];
2302 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2303 $nick = $pub_contact['nick'];
2304 $network = $pub_contact['network'];
2306 // Ensure that we don't create a new contact when there already is one
2307 $cid = self::getIdForURL($url, $importer['uid']);
2309 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2312 if (!empty($contact)) {
2313 if (!empty($contact['pending'])) {
2314 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2318 // Contact is blocked at user-level
2319 if (!empty($contact['id']) && !empty($importer['id']) &&
2320 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2324 // Make sure that the existing contact isn't archived
2325 self::unmarkForArchival($contact);
2327 if (($contact['rel'] == self::SHARING)
2328 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2329 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2330 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2333 // Ensure to always have the correct network type, independent from the connection request method
2334 self::updateFromProbe($contact['id']);
2338 // send email notification to owner?
2339 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2340 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2344 // create contact record
2345 DBA::insert('contact', [
2346 'uid' => $importer['uid'],
2347 'created' => DateTimeFormat::utcNow(),
2349 'nurl' => Strings::normaliseLink($url),
2352 'network' => $network,
2353 'rel' => self::FOLLOWER,
2360 $contact_id = DBA::lastInsertId();
2362 // Ensure to always have the correct network type, independent from the connection request method
2363 self::updateFromProbe($contact_id);
2365 self::updateAvatar($contact_id, $photo, true);
2367 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2369 /// @TODO Encapsulate this into a function/method
2370 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2371 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2372 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2373 // create notification
2374 $hash = Strings::getRandomHex();
2376 if (is_array($contact_record)) {
2377 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2378 'blocked' => false, 'knowyou' => false, 'note' => $note,
2379 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2382 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2384 if (($user['notify-flags'] & Type::INTRO) &&
2385 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2388 'type' => Type::INTRO,
2389 'notify_flags' => $user['notify-flags'],
2390 'language' => $user['language'],
2391 'to_name' => $user['username'],
2392 'to_email' => $user['email'],
2393 'uid' => $user['uid'],
2394 'link' => DI::baseUrl() . '/notifications/intros',
2395 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2396 'source_link' => $contact_record['url'],
2397 'source_photo' => $contact_record['photo'],
2398 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2402 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2403 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2404 self::createFromProbe($importer, $url, false, $network);
2407 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2408 $fields = ['pending' => false];
2409 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2410 $fields['rel'] = Contact::FRIEND;
2413 DBA::update('contact', $fields, $condition);
2422 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2424 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2425 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2427 Contact::remove($contact['id']);
2431 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2433 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2434 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2436 Contact::remove($contact['id']);
2441 * Create a birthday event.
2443 * Update the year and the birthday.
2445 public static function updateBirthdays()
2449 AND `bd` > "0001-01-01"
2450 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2451 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2452 AND NOT `contact`.`pending`
2453 AND NOT `contact`.`hidden`
2454 AND NOT `contact`.`blocked`
2455 AND NOT `contact`.`archive`
2456 AND NOT `contact`.`deleted`',
2461 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2463 while ($contact = DBA::fetch($contacts)) {
2464 Logger::log('update_contact_birthday: ' . $contact['bd']);
2466 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2468 if (Event::createBirthday($contact, $nextbd)) {
2472 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2473 ['id' => $contact['id']]
2477 DBA::close($contacts);
2481 * Remove the unavailable contact ids from the provided list
2483 * @param array $contact_ids Contact id list
2485 * @throws \Exception
2487 public static function pruneUnavailable(array $contact_ids)
2489 if (empty($contact_ids)) {
2493 $contacts = Contact::selectToArray(['id'], [
2494 'id' => $contact_ids,
2500 return array_column($contacts, 'id');
2504 * Returns a magic link to authenticate remote visitors
2506 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2508 * @param string $contact_url The address of the target contact profile
2509 * @param string $url An url that we will be redirected to after the authentication
2511 * @return string with "redir" link
2512 * @throws HTTPException\InternalServerErrorException
2513 * @throws \ImagickException
2515 public static function magicLink($contact_url, $url = '')
2517 if (!Session::isAuthenticated()) {
2518 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2521 $contact = self::getByURL($contact_url, false);
2522 if (empty($contact)) {
2523 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2526 // Prevents endless loop in case only a non-public contact exists for the contact URL
2527 unset($contact['uid']);
2529 return self::magicLinkByContact($contact, $url ?: $contact_url);
2533 * Returns a magic link to authenticate remote visitors
2535 * @param integer $cid The contact id of the target contact profile
2536 * @param string $url An url that we will be redirected to after the authentication
2538 * @return string with "redir" link
2539 * @throws HTTPException\InternalServerErrorException
2540 * @throws \ImagickException
2542 public static function magicLinkbyId($cid, $url = '')
2544 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2546 return self::magicLinkByContact($contact, $url);
2550 * Returns a magic link to authenticate remote visitors
2552 * @param array $contact The contact array with "uid", "network" and "url"
2553 * @param string $url An url that we will be redirected to after the authentication
2555 * @return string with "redir" link
2556 * @throws HTTPException\InternalServerErrorException
2557 * @throws \ImagickException
2559 public static function magicLinkByContact($contact, $url = '')
2561 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2563 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2564 return $destination;
2567 // Only redirections to the same host do make sense
2568 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2572 if (!empty($contact['uid'])) {
2573 return self::magicLink($contact['url'], $url);
2576 if (empty($contact['id'])) {
2577 return $destination;
2580 $redirect = 'redir/' . $contact['id'];
2582 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2583 $redirect .= '?url=' . $url;
2590 * Is the contact a forum?
2592 * @param integer $contactid ID of the contact
2594 * @return boolean "true" if it is a forum
2596 public static function isForum($contactid)
2598 $fields = ['forum', 'prv'];
2599 $condition = ['id' => $contactid];
2600 $contact = DBA::selectFirst('contact', $fields, $condition);
2601 if (!DBA::isResult($contact)) {
2606 return ($contact['forum'] || $contact['prv']);
2610 * Can the remote contact receive private messages?
2612 * @param array $contact
2615 public static function canReceivePrivateMessages(array $contact)
2617 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2618 $self = $contact['self'] ?? false;
2620 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2624 * Search contact table by nick or name
2626 * @param string $search Name or nick
2627 * @param string $mode Search mode (e.g. "community")
2629 * @return array with search results
2630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2632 public static function searchByName($search, $mode = '')
2634 if (empty($search)) {
2638 // check supported networks
2639 if (DI::config()->get('system', 'diaspora_enabled')) {
2640 $diaspora = Protocol::DIASPORA;
2642 $diaspora = Protocol::DFRN;
2645 if (!DI::config()->get('system', 'ostatus_disabled')) {
2646 $ostatus = Protocol::OSTATUS;
2648 $ostatus = Protocol::DFRN;
2651 // check if we search only communities or every contact
2652 if ($mode === 'community') {
2653 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2660 $results = DBA::p("SELECT * FROM `contact`
2661 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2662 NOT `failed` AND `uid` = ? AND
2663 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2664 ORDER BY `nurl` DESC LIMIT 1000",
2665 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2668 $contacts = DBA::toArray($results);
2673 * Add public contacts from an array
2675 * @param array $urls
2676 * @return array result "count", "added" and "updated"
2678 public static function addByUrls(array $urls)
2684 foreach ($urls as $url) {
2685 $contact = Contact::getByURL($url, false, ['id']);
2686 if (empty($contact['id'])) {
2687 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2690 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2696 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2700 * Returns a random, global contact of the current node
2702 * @return string The profile URL
2705 public static function getRandomUrl()
2707 $r = DBA::selectFirst('contact', ['url'], [
2708 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2709 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2710 ], ['order' => ['RAND()']]);
2712 if (DBA::isResult($r)) {