3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\App\BaseURL;
8 use Friendica\BaseObject;
9 use Friendica\Content\Pager;
10 use Friendica\Core\Config;
11 use Friendica\Core\Hook;
12 use Friendica\Core\L10n;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\Session;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Network\Probe;
20 use Friendica\Object\Image;
21 use Friendica\Protocol\Activity;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Protocol\DFRN;
24 use Friendica\Protocol\Diaspora;
25 use Friendica\Protocol\OStatus;
26 use Friendica\Protocol\Salmon;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Network;
29 use Friendica\Util\Strings;
32 * @brief functions for interacting with a contact
34 class Contact extends BaseObject
37 * @deprecated since version 2019.03
38 * @see User::PAGE_FLAGS_NORMAL
40 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
42 * @deprecated since version 2019.03
43 * @see User::PAGE_FLAGS_SOAPBOX
45 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
47 * @deprecated since version 2019.03
48 * @see User::PAGE_FLAGS_COMMUNITY
50 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
52 * @deprecated since version 2019.03
53 * @see User::PAGE_FLAGS_FREELOVE
55 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
57 * @deprecated since version 2019.03
58 * @see User::PAGE_FLAGS_BLOG
60 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_PRVGROUP
65 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
73 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
75 * TYPE_PERSON - the account belongs to a person
76 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
78 * TYPE_ORGANISATION - the account belongs to an organisation
79 * Associated page type: PAGE_SOAPBOX
81 * TYPE_NEWS - the account is a news reflector
82 * Associated page type: PAGE_SOAPBOX
84 * TYPE_COMMUNITY - the account is community forum
85 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
87 * TYPE_RELAY - the account is a relay
88 * This will only be assigned to contacts, not to user accounts
91 const TYPE_UNKNOWN = -1;
92 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
93 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
94 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
95 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
96 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
115 * @param array $fields Array of selected fields, empty for all
116 * @param array $condition Array of fields for condition
117 * @param array $params Array of several parameters
121 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
123 return DBA::selectToArray('contact', $fields, $condition, $params);
127 * @param array $fields Array of selected fields, empty for all
128 * @param array $condition Array of fields for condition
129 * @param array $params Array of several parameters
133 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
135 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
141 * Insert a row into the contact table
142 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
144 * @param array $fields field array
145 * @param bool $on_duplicate_update Do an update on a duplicate entry
147 * @return boolean was the insert successful?
150 public static function insert(array $fields, bool $on_duplicate_update = false)
152 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
153 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
154 if (!DBA::isResult($contact)) {
159 // Search for duplicated contacts and get rid of them
160 self::removeDuplicates($contact['nurl'], $contact['uid']);
166 * @param integer $id Contact ID
167 * @param array $fields Array of selected fields, empty for all
168 * @return array|boolean Contact record if it exists, false otherwise
171 public static function getById($id, $fields = [])
173 return DBA::selectFirst('contact', $fields, ['id' => $id]);
177 * @brief Tests if the given contact is a follower
179 * @param int $cid Either public contact id or user's contact id
180 * @param int $uid User ID
182 * @return boolean is the contact id a follower?
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 public static function isFollower($cid, $uid)
188 if (self::isBlockedByUser($cid, $uid)) {
192 $cdata = self::getPublicAndUserContacID($cid, $uid);
193 if (empty($cdata['user'])) {
197 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
198 return DBA::exists('contact', $condition);
202 * @brief Tests if the given contact url is a follower
204 * @param string $url Contact URL
205 * @param int $uid User ID
207 * @return boolean is the contact id a follower?
208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
209 * @throws \ImagickException
211 public static function isFollowerByURL($url, $uid)
213 $cid = self::getIdForURL($url, $uid, true);
219 return self::isFollower($cid, $uid);
223 * @brief Tests if the given user follow the given contact
225 * @param int $cid Either public contact id or user's contact id
226 * @param int $uid User ID
228 * @return boolean is the contact url being followed?
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function isSharing($cid, $uid)
234 if (self::isBlockedByUser($cid, $uid)) {
238 $cdata = self::getPublicAndUserContacID($cid, $uid);
239 if (empty($cdata['user'])) {
243 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
244 return DBA::exists('contact', $condition);
248 * @brief Tests if the given user follow the given contact url
250 * @param string $url Contact URL
251 * @param int $uid User ID
253 * @return boolean is the contact url being followed?
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 public static function isSharingByURL($url, $uid)
259 $cid = self::getIdForURL($url, $uid, true);
265 return self::isSharing($cid, $uid);
269 * @brief Get the basepath for a given contact link
271 * @param string $url The contact link
273 * @return string basepath
274 * @return boolean $dont_update Don't update the contact
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
278 public static function getBasepath($url, $dont_update = false)
280 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
281 if (!empty($contact['baseurl'])) {
282 return $contact['baseurl'];
283 } elseif ($dont_update) {
287 self::updateFromProbeByURL($url, true);
289 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
290 if (!empty($contact['baseurl'])) {
291 return $contact['baseurl'];
298 * Check if the given contact url is on the same server
300 * @param string $url The contact link
302 * @return boolean Is it the same server?
304 public static function isLocal($url)
306 return Strings::compareLink(self::getBasepath($url, true), System::baseUrl());
310 * Returns the public contact id of the given user id
312 * @param integer $uid User ID
314 * @return integer|boolean Public contact id for given user id
317 public static function getPublicIdByUserId($uid)
319 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
320 if (!DBA::isResult($self)) {
323 return self::getIdForURL($self['url'], 0, true);
327 * @brief Returns the contact id for the user and the public contact id for a given contact id
329 * @param int $cid Either public contact id or user's contact id
330 * @param int $uid User ID
332 * @return array with public and user's contact id
333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
334 * @throws \ImagickException
336 public static function getPublicAndUserContacID($cid, $uid)
338 if (empty($uid) || empty($cid)) {
342 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
343 if (!DBA::isResult($contact)) {
347 // We quit when the user id don't match the user id of the provided contact
348 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
352 if ($contact['uid'] != 0) {
353 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
357 $ucid = $contact['id'];
359 $pcid = $contact['id'];
360 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
363 return ['public' => $pcid, 'user' => $ucid];
367 * Returns contact details for a given contact id in combination with a user id
369 * @param int $cid A contact ID
370 * @param int $uid The User ID
371 * @param array $fields The selected fields for the contact
373 * @return array The contact details
377 public static function getContactForUser($cid, $uid, array $fields = [])
379 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
381 if (!DBA::isResult($contact)) {
389 * @brief Block contact id for user id
391 * @param int $cid Either public contact id or user's contact id
392 * @param int $uid User ID
393 * @param boolean $blocked Is the contact blocked or unblocked?
396 public static function setBlockedForUser($cid, $uid, $blocked)
398 $cdata = self::getPublicAndUserContacID($cid, $uid);
403 if ($cdata['user'] != 0) {
404 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
407 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
410 // Blocked contact can't be in any group
411 self::removeFromGroups($cid);
416 * @brief Returns "block" state for contact id and user id
418 * @param int $cid Either public contact id or user's contact id
419 * @param int $uid User ID
421 * @return boolean is the contact id blocked for the given user?
424 public static function isBlockedByUser($cid, $uid)
426 $cdata = self::getPublicAndUserContacID($cid, $uid);
431 $public_blocked = false;
433 if (!empty($cdata['public'])) {
434 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
435 if (DBA::isResult($public_contact)) {
436 $public_blocked = $public_contact['blocked'];
440 $user_blocked = $public_blocked;
442 if (!empty($cdata['user'])) {
443 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
444 if (DBA::isResult($user_contact)) {
445 $user_blocked = $user_contact['blocked'];
449 if ($user_blocked != $public_blocked) {
450 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
453 return $user_blocked;
457 * @brief Ignore contact id for user id
459 * @param int $cid Either public contact id or user's contact id
460 * @param int $uid User ID
461 * @param boolean $ignored Is the contact ignored or unignored?
464 public static function setIgnoredForUser($cid, $uid, $ignored)
466 $cdata = self::getPublicAndUserContacID($cid, $uid);
471 if ($cdata['user'] != 0) {
472 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
475 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
479 * @brief Returns "ignore" state for contact id and user id
481 * @param int $cid Either public contact id or user's contact id
482 * @param int $uid User ID
484 * @return boolean is the contact id ignored for the given user?
487 public static function isIgnoredByUser($cid, $uid)
489 $cdata = self::getPublicAndUserContacID($cid, $uid);
494 $public_ignored = false;
496 if (!empty($cdata['public'])) {
497 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
498 if (DBA::isResult($public_contact)) {
499 $public_ignored = $public_contact['ignored'];
503 $user_ignored = $public_ignored;
505 if (!empty($cdata['user'])) {
506 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
507 if (DBA::isResult($user_contact)) {
508 $user_ignored = $user_contact['readonly'];
512 if ($user_ignored != $public_ignored) {
513 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
516 return $user_ignored;
520 * @brief Set "collapsed" for contact id and user id
522 * @param int $cid Either public contact id or user's contact id
523 * @param int $uid User ID
524 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
527 public static function setCollapsedForUser($cid, $uid, $collapsed)
529 $cdata = self::getPublicAndUserContacID($cid, $uid);
534 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
538 * @brief Returns "collapsed" state for contact id and user id
540 * @param int $cid Either public contact id or user's contact id
541 * @param int $uid User ID
543 * @return boolean is the contact id blocked for the given user?
544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
545 * @throws \ImagickException
547 public static function isCollapsedByUser($cid, $uid)
549 $cdata = self::getPublicAndUserContacID($cid, $uid);
556 if (!empty($cdata['public'])) {
557 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
558 if (DBA::isResult($public_contact)) {
559 $collapsed = $public_contact['collapsed'];
567 * @brief Returns a list of contacts belonging in a group
573 public static function getByGroupId($gid)
578 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
580 INNER JOIN `group_member`
581 ON `contact`.`id` = `group_member`.`contact-id`
583 AND `contact`.`uid` = ?
584 AND NOT `contact`.`self`
585 AND NOT `contact`.`deleted`
586 AND NOT `contact`.`blocked`
587 AND NOT `contact`.`pending`
588 ORDER BY `contact`.`name` ASC',
593 if (DBA::isResult($stmt)) {
594 $return = DBA::toArray($stmt);
602 * @brief Returns the count of OStatus contacts in a group
608 public static function getOStatusCountByGroupId($gid)
612 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
614 INNER JOIN `group_member`
615 ON `contact`.`id` = `group_member`.`contact-id`
617 AND `contact`.`uid` = ?
618 AND `contact`.`network` = ?
619 AND `contact`.`notify` != ""',
624 $return = $contacts['count'];
631 * Creates the self-contact for the provided user id
634 * @return bool Operation success
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 public static function createSelfFromUserId($uid)
639 // Only create the entry if it doesn't exist yet
640 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
644 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
645 if (!DBA::isResult($user)) {
649 $return = DBA::insert('contact', [
650 'uid' => $user['uid'],
651 'created' => DateTimeFormat::utcNow(),
653 'name' => $user['username'],
654 'nick' => $user['nickname'],
655 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
656 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
657 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
660 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
661 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
662 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
663 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
664 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
665 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
666 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
667 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
668 'name-date' => DateTimeFormat::utcNow(),
669 'uri-date' => DateTimeFormat::utcNow(),
670 'avatar-date' => DateTimeFormat::utcNow(),
678 * Updates the self-contact for the provided user id
681 * @param boolean $update_avatar Force the avatar update
682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684 public static function updateSelfFromUserID($uid, $update_avatar = false)
686 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
687 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
688 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
689 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
690 if (!DBA::isResult($self)) {
694 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
695 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
696 if (!DBA::isResult($user)) {
700 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
701 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
702 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
703 if (!DBA::isResult($profile)) {
707 $file_suffix = 'jpg';
709 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
710 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
711 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
712 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
713 'xmpp' => $profile['xmpp']];
715 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
716 if (DBA::isResult($avatar)) {
717 if ($update_avatar) {
718 $fields['avatar-date'] = DateTimeFormat::utcNow();
721 // Creating the path to the avatar, beginning with the file suffix
722 $types = Image::supportedTypes();
723 if (isset($types[$avatar['type']])) {
724 $file_suffix = $types[$avatar['type']];
727 // We are adding a timestamp value so that other systems won't use cached content
728 $timestamp = strtotime($fields['avatar-date']);
730 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
731 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
733 $fields['photo'] = $prefix . '4' . $suffix;
734 $fields['thumb'] = $prefix . '5' . $suffix;
735 $fields['micro'] = $prefix . '6' . $suffix;
737 // We hadn't found a photo entry, so we use the default avatar
738 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
739 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
740 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
743 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
744 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
745 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
746 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
748 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
749 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
750 $fields['nurl'] = Strings::normaliseLink($fields['url']);
751 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
752 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
753 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
754 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
755 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
756 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
760 foreach ($fields as $field => $content) {
761 if ($self[$field] != $content) {
767 if ($fields['name'] != $self['name']) {
768 $fields['name-date'] = DateTimeFormat::utcNow();
770 $fields['updated'] = DateTimeFormat::utcNow();
771 DBA::update('contact', $fields, ['id' => $self['id']]);
773 // Update the public contact as well
774 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
776 // Update the profile
777 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
778 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
779 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
784 * @brief Marks a contact for removal
786 * @param int $id contact id
788 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
790 public static function remove($id)
792 // We want just to make sure that we don't delete our "self" contact
793 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
794 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
798 // Archive the contact
799 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
801 // Delete it in the background
802 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
806 * @brief Sends an unfriend message. Does not remove the contact
808 * @param array $user User unfriending
809 * @param array $contact Contact unfriended
810 * @param boolean $dissolve Remove the contact on the remote side
812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 * @throws \ImagickException
815 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
817 if (empty($contact['network'])) {
821 $protocol = $contact['network'];
822 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
823 $protocol = Protocol::ACTIVITYPUB;
826 if (($protocol == Protocol::DFRN) && $dissolve) {
827 DFRN::deliver($user, $contact, 'placeholder', true);
828 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
829 // create an unfollow slap
831 $item['verb'] = Activity::O_UNFOLLOW;
832 $item['follow'] = $contact["url"];
837 $item['attach'] = '';
838 $slap = OStatus::salmon($item, $user);
840 if (!empty($contact['notify'])) {
841 Salmon::slapper($user, $contact['notify'], $slap);
843 } elseif ($protocol == Protocol::DIASPORA) {
844 Diaspora::sendUnshare($user, $contact);
845 } elseif ($protocol == Protocol::ACTIVITYPUB) {
846 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
849 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
855 * @brief Marks a contact for archival after a communication issue delay
857 * Contact has refused to recognise us as a friend. We will start a countdown.
858 * If they still don't recognise us in 32 days, the relationship is over,
859 * and we won't waste any more time trying to communicate with them.
860 * This provides for the possibility that their database is temporarily messed
861 * up or some other transient event and that there's a possibility we could recover from it.
863 * @param array $contact contact to mark for archival
865 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
867 public static function markForArchival(array $contact)
869 if (!isset($contact['url']) && !empty($contact['id'])) {
870 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
871 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
872 if (!DBA::isResult($contact)) {
875 } elseif (!isset($contact['url'])) {
876 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
879 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
881 // Contact already archived or "self" contact? => nothing to do
882 if ($contact['archive'] || $contact['self']) {
886 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
887 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
888 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
891 * We really should send a notification to the owner after 2-3 weeks
892 * so they won't be surprised when the contact vanishes and can take
893 * remedial action if this was a serious mistake or glitch
896 /// @todo Check for contact vitality via probing
897 $archival_days = Config::get('system', 'archival_days', 32);
899 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
900 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
901 /* Relationship is really truly dead. archive them rather than
902 * delete, though if the owner tries to unarchive them we'll start
903 * the whole process over again.
905 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
906 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
907 GContact::updateFromPublicContactURL($contact['url']);
913 * @brief Cancels the archival countdown
915 * @see Contact::markForArchival()
917 * @param array $contact contact to be unmarked for archival
921 public static function unmarkForArchival(array $contact)
923 // Always unarchive the relay contact entry
924 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
925 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
926 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
927 DBA::update('contact', $fields, $condition);
930 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
931 $exists = DBA::exists('contact', $condition);
933 // We don't need to update, we never marked this contact for archival
938 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
940 if (!isset($contact['url']) && !empty($contact['id'])) {
941 $fields = ['id', 'url', 'batch'];
942 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
943 if (!DBA::isResult($contact)) {
948 // It's a miracle. Our dead contact has inexplicably come back to life.
949 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
950 DBA::update('contact', $fields, ['id' => $contact['id']]);
951 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
952 GContact::updateFromPublicContactURL($contact['url']);
956 * @brief Get contact data for a given profile link
958 * The function looks at several places (contact table and gcontact table) for the contact
959 * It caches its result for the same script execution to prevent duplicate calls
961 * @param string $url The profile link
962 * @param int $uid User id
963 * @param array $default If not data was found take this data as default value
965 * @return array Contact data
966 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
968 public static function getDetailsByURL($url, $uid = -1, array $default = [])
980 if (isset($cache[$url][$uid])) {
981 return $cache[$url][$uid];
984 $ssl_url = str_replace('http://', 'https://', $url);
986 $nurl = Strings::normaliseLink($url);
988 // Fetch contact data from the contact table for the given user
989 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
990 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
991 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", $nurl, $uid);
992 $r = DBA::toArray($s);
994 // Fetch contact data from the contact table for the given user, checking with the alias
995 if (!DBA::isResult($r)) {
996 $s = DBA::p("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
997 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
998 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", $nurl, $url, $ssl_url, $uid);
999 $r = DBA::toArray($s);
1002 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1003 if (!DBA::isResult($r)) {
1004 $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1005 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1006 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", $nurl);
1007 $r = DBA::toArray($s);
1010 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1011 if (!DBA::isResult($r)) {
1012 $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1013 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1014 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", $nurl, $url, $ssl_url);
1015 $r = DBA::toArray($s);
1018 // Fetch the data from the gcontact table
1019 if (!DBA::isResult($r)) {
1020 $s = DBA::p("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
1021 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`, 2 AS `rel`, 0 AS `pending`
1022 FROM `gcontact` WHERE `nurl` = ?", $nurl);
1023 $r = DBA::toArray($s);
1026 if (DBA::isResult($r)) {
1027 // If there is more than one entry we filter out the connector networks
1028 if (count($r) > 1) {
1029 foreach ($r as $id => $result) {
1030 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1036 $profile = array_shift($r);
1038 // "bd" always contains the upcoming birthday of a contact.
1039 // "birthday" might contain the birthday including the year of birth.
1040 if ($profile["birthday"] > DBA::NULL_DATE) {
1041 $bd_timestamp = strtotime($profile["birthday"]);
1042 $month = date("m", $bd_timestamp);
1043 $day = date("d", $bd_timestamp);
1045 $current_timestamp = time();
1046 $current_year = date("Y", $current_timestamp);
1047 $current_month = date("m", $current_timestamp);
1048 $current_day = date("d", $current_timestamp);
1050 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1051 $current = $current_year . "-" . $current_month . "-" . $current_day;
1053 if ($profile["bd"] < $current) {
1054 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1057 $profile["bd"] = DBA::NULL_DATE;
1060 $profile = $default;
1063 if (empty($profile["photo"]) && isset($default["photo"])) {
1064 $profile["photo"] = $default["photo"];
1067 if (empty($profile["name"]) && isset($default["name"])) {
1068 $profile["name"] = $default["name"];
1071 if (empty($profile["network"]) && isset($default["network"])) {
1072 $profile["network"] = $default["network"];
1075 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1076 $profile["thumb"] = $profile["photo"];
1079 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1080 $profile["micro"] = $profile["thumb"];
1083 if ((empty($profile["addr"]) || empty($profile["name"])) && !empty($profile["gid"])
1084 && in_array($profile["network"], Protocol::FEDERATED)
1086 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1089 // Show contact details of Diaspora contacts only if connected
1090 if (empty($profile["cid"]) && ($profile["network"] ?? "") == Protocol::DIASPORA) {
1091 $profile["location"] = "";
1092 $profile["about"] = "";
1093 $profile["gender"] = "";
1094 $profile["birthday"] = DBA::NULL_DATE;
1097 $cache[$url][$uid] = $profile;
1103 * @brief Get contact data for a given address
1105 * The function looks at several places (contact table and gcontact table) for the contact
1107 * @param string $addr The profile link
1108 * @param int $uid User id
1110 * @return array Contact data
1111 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1112 * @throws \ImagickException
1114 public static function getDetailsByAddr($addr, $uid = -1)
1121 $uid = local_user();
1124 // Fetch contact data from the contact table for the given user
1125 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1126 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`, `rel`, `pending`
1127 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1131 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1132 if (!DBA::isResult($r)) {
1133 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1134 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`, `rel`, `pending`
1135 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1140 // Fetch the data from the gcontact table
1141 if (!DBA::isResult($r)) {
1142 $r = q("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
1143 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`, 2 AS `rel`, 0 AS `pending`
1144 FROM `gcontact` WHERE `addr` = '%s'",
1149 if (!DBA::isResult($r)) {
1150 $data = Probe::uri($addr);
1152 $profile = self::getDetailsByURL($data['url'], $uid);
1161 * @brief Returns the data array for the photo menu of a given contact
1163 * @param array $contact contact
1164 * @param int $uid optional, default 0
1166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1167 * @throws \ImagickException
1169 public static function photoMenu(array $contact, $uid = 0)
1174 $contact_drop_link = '';
1178 $uid = local_user();
1181 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1183 $profile_link = self::magicLink($contact['url']);
1184 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1189 // Look for our own contact if the uid doesn't match and isn't public
1190 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1191 if (DBA::isResult($contact_own)) {
1192 return self::photoMenu($contact_own, $uid);
1197 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1199 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
1201 $profile_link = $contact['url'];
1204 if ($profile_link === 'mailbox') {
1209 $status_link = $profile_link . '?tab=status';
1210 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1211 $profile_link = $profile_link . '?tab=profile';
1214 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1215 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1218 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1219 $poke_link = System::baseUrl() . '/poke/?c=' . $contact['id'];
1222 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1224 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1226 if (!$contact['self']) {
1227 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1231 $unfollow_link = '';
1232 if (in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1233 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1234 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
1235 } elseif(!$contact['pending']) {
1236 $follow_link = 'follow?url=' . urlencode($contact['url']);
1242 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1244 if (empty($contact['uid'])) {
1246 'profile' => [L10n::t('View Profile') , $profile_link , true],
1247 'network' => [L10n::t('Network Posts') , $posts_link , false],
1248 'edit' => [L10n::t('View Contact') , $contact_url , false],
1249 'follow' => [L10n::t('Connect/Follow'), $follow_link , true],
1250 'unfollow'=> [L10n::t('UnFollow') , $unfollow_link, true],
1254 'status' => [L10n::t('View Status') , $status_link , true],
1255 'profile' => [L10n::t('View Profile') , $profile_link , true],
1256 'photos' => [L10n::t('View Photos') , $photos_link , true],
1257 'network' => [L10n::t('Network Posts') , $posts_link , false],
1258 'edit' => [L10n::t('View Contact') , $contact_url , false],
1259 'drop' => [L10n::t('Drop Contact') , $contact_drop_link, false],
1260 'pm' => [L10n::t('Send PM') , $pm_url , false],
1261 'poke' => [L10n::t('Poke') , $poke_link , false],
1262 'follow' => [L10n::t('Connect/Follow'), $follow_link , true],
1263 'unfollow'=> [L10n::t('UnFollow') , $unfollow_link , true],
1266 if (!empty($contact['pending'])) {
1267 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1268 if (DBA::isResult($intro)) {
1269 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1274 $args = ['contact' => $contact, 'menu' => &$menu];
1276 Hook::callAll('contact_photo_menu', $args);
1278 $menucondensed = [];
1280 foreach ($menu as $menuname => $menuitem) {
1281 if ($menuitem[1] != '') {
1282 $menucondensed[$menuname] = $menuitem;
1286 return $menucondensed;
1290 * @brief Returns ungrouped contact count or list for user
1292 * Returns either the total number of ungrouped contacts for the given user
1293 * id or a paginated list of ungrouped contacts.
1295 * @param int $uid uid
1297 * @throws \Exception
1299 public static function getUngroupedList($uid)
1309 SELECT DISTINCT(`contact-id`)
1311 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1312 WHERE `group`.`uid` = %d
1313 )", intval($uid), intval($uid));
1317 * Have a look at all contact tables for a given profile url.
1318 * This function works as a replacement for probing the contact.
1320 * @param string $url Contact URL
1321 * @param integer $cid Contact ID
1323 * @return array Contact array in the "probe" structure
1325 private static function getProbeDataFromDatabase($url, $cid = null)
1327 // The link could be provided as http although we stored it as https
1328 $ssl_url = str_replace('http://', 'https://', $url);
1330 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1331 'photo', 'keywords', 'location', 'about', 'network',
1332 'priority', 'batch', 'request', 'confirm', 'poco'];
1335 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1336 if (DBA::isResult($data)) {
1341 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1343 if (!DBA::isResult($data)) {
1344 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1345 $data = DBA::selectFirst('contact', $fields, $condition);
1348 if (DBA::isResult($data)) {
1349 // For security reasons we don't fetch key data from our users
1350 $data["pubkey"] = '';
1354 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1355 'photo', 'keywords', 'location', 'about', 'network'];
1356 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1358 if (!DBA::isResult($data)) {
1359 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1360 $data = DBA::selectFirst('contact', $fields, $condition);
1363 if (DBA::isResult($data)) {
1364 $data["pubkey"] = '';
1366 $data["priority"] = 0;
1367 $data["batch"] = '';
1368 $data["request"] = '';
1369 $data["confirm"] = '';
1374 $data = ActivityPub::probeProfile($url, false);
1375 if (!empty($data)) {
1379 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1380 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1381 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1383 if (!DBA::isResult($data)) {
1384 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1385 $data = DBA::selectFirst('contact', $fields, $condition);
1388 if (DBA::isResult($data)) {
1389 $data["pubkey"] = '';
1390 $data["keywords"] = '';
1391 $data["location"] = '';
1392 $data["about"] = '';
1401 * @brief Fetch the contact id for a given URL and user
1403 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1404 * `addr` or `alias`.
1406 * If there's no record and we aren't looking for a public contact, we quit.
1407 * If there's one, we check that it isn't time to update the picture else we
1408 * directly return the found contact id.
1410 * Second, we probe the provided $url whether it's http://server.tld/profile or
1411 * nick@server.tld. We quit if we can't get any info back.
1413 * Third, we create the contact record if it doesn't exist
1415 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1416 * if there's any updates
1418 * @param string $url Contact URL
1419 * @param integer $uid The user id for the contact (0 = public contact)
1420 * @param boolean $no_update Don't update the contact
1421 * @param array $default Default value for creating the contact when every else fails
1422 * @param boolean $in_loop Internally used variable to prevent an endless loop
1424 * @return integer Contact ID
1425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1426 * @throws \ImagickException
1428 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1430 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1438 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1439 // We first try the nurl (http://server.tld/nick), most common case
1440 $fields = ['id', 'avatar', 'updated', 'network'];
1441 $options = ['order' => ['id']];
1442 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1444 // Then the addr (nick@server.tld)
1445 if (!DBA::isResult($contact)) {
1446 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1449 // Then the alias (which could be anything)
1450 if (!DBA::isResult($contact)) {
1451 // The link could be provided as http although we stored it as https
1452 $ssl_url = str_replace('http://', 'https://', $url);
1453 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1454 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1457 if (DBA::isResult($contact)) {
1458 $contact_id = $contact["id"];
1460 // Update the contact every 7 days
1461 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1463 // We force the update if the avatar is empty
1464 if (empty($contact['avatar'])) {
1465 $update_contact = true;
1468 // Update the contact in the background if needed but it is called by the frontend
1469 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1470 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1473 if (!$update_contact || $no_update) {
1476 } elseif ($uid != 0) {
1477 // Non-existing user-specific contact, exiting
1481 if ($no_update && empty($default)) {
1482 // When we don't want to update, we look if we know this contact in any way
1483 $data = self::getProbeDataFromDatabase($url, $contact_id);
1484 $background_update = true;
1485 } elseif ($no_update && !empty($default['network'])) {
1486 // If there are default values, take these
1488 $background_update = false;
1491 $background_update = false;
1495 $data = Probe::uri($url, "", $uid);
1496 // Ensure that there is a gserver entry
1497 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1498 GServer::check($data['baseurl']);
1502 // Take the default values when probing failed
1503 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1504 $data = array_merge($data, $default);
1511 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1512 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1518 'created' => DateTimeFormat::utcNow(),
1519 'url' => $data['url'],
1520 'nurl' => Strings::normaliseLink($data['url']),
1521 'addr' => $data['addr'] ?? '',
1522 'alias' => $data['alias'] ?? '',
1523 'notify' => $data['notify'] ?? '',
1524 'poll' => $data['poll'] ?? '',
1525 'name' => $data['name'] ?? '',
1526 'nick' => $data['nick'] ?? '',
1527 'photo' => $data['photo'] ?? '',
1528 'keywords' => $data['keywords'] ?? '',
1529 'location' => $data['location'] ?? '',
1530 'about' => $data['about'] ?? '',
1531 'network' => $data['network'],
1532 'pubkey' => $data['pubkey'] ?? '',
1533 'rel' => self::SHARING,
1534 'priority' => $data['priority'] ?? 0,
1535 'batch' => $data['batch'] ?? '',
1536 'request' => $data['request'] ?? '',
1537 'confirm' => $data['confirm'] ?? '',
1538 'poco' => $data['poco'] ?? '',
1539 'baseurl' => $data['baseurl'] ?? '',
1540 'name-date' => DateTimeFormat::utcNow(),
1541 'uri-date' => DateTimeFormat::utcNow(),
1542 'avatar-date' => DateTimeFormat::utcNow(),
1548 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1550 // Before inserting we do check if the entry does exist now.
1551 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1552 if (!DBA::isResult($contact)) {
1553 Logger::info('Create new contact', $fields);
1555 self::insert($fields);
1557 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1558 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1559 if (!DBA::isResult($contact)) {
1560 Logger::info('Contact creation failed', $fields);
1565 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1568 $contact_id = $contact["id"];
1571 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1572 self::updateAvatar($data['photo'], $uid, $contact_id);
1575 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1576 if ($background_update) {
1577 // Update in the background when we fetched the data solely from the database
1578 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1580 // Else do a direct update
1581 self::updateFromProbe($contact_id, '', false);
1583 // Update the gcontact entry
1585 GContact::updateFromPublicContactID($contact_id);
1589 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1590 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1592 // This condition should always be true
1593 if (!DBA::isResult($contact)) {
1598 'url' => $data['url'],
1599 'nurl' => Strings::normaliseLink($data['url']),
1600 'updated' => DateTimeFormat::utcNow()
1603 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1605 foreach ($fields as $field) {
1606 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1609 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1610 $updated['uri-date'] = DateTimeFormat::utcNow();
1613 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1614 $updated['name-date'] = DateTimeFormat::utcNow();
1617 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1624 * @brief Checks if the contact is archived
1626 * @param int $cid contact id
1628 * @return boolean Is the contact archived?
1629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1631 public static function isArchived(int $cid)
1637 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1638 if (!DBA::isResult($contact)) {
1642 if ($contact['archive']) {
1646 // Check status of ActivityPub endpoints
1647 $apcontact = APContact::getByURL($contact['url'], false);
1648 if (!empty($apcontact)) {
1649 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1653 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1658 // Check status of Diaspora endpoints
1659 if (!empty($contact['batch'])) {
1660 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1661 return DBA::exists('contact', $condition);
1668 * @brief Checks if the contact is blocked
1670 * @param int $cid contact id
1672 * @return boolean Is the contact blocked?
1673 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1675 public static function isBlocked($cid)
1681 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1682 if (!DBA::isResult($blocked)) {
1686 if (Network::isUrlBlocked($blocked['url'])) {
1690 return (bool) $blocked['blocked'];
1694 * @brief Checks if the contact is hidden
1696 * @param int $cid contact id
1698 * @return boolean Is the contact hidden?
1699 * @throws \Exception
1701 public static function isHidden($cid)
1707 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1708 if (!DBA::isResult($hidden)) {
1711 return (bool) $hidden['hidden'];
1715 * @brief Returns posts from a given contact url
1717 * @param string $contact_url Contact URL
1719 * @param bool $thread_mode
1720 * @param int $update
1721 * @return string posts in HTML
1722 * @throws \Exception
1724 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1726 $a = self::getApp();
1728 $cid = self::getIdForURL($contact_url);
1730 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1731 if (!DBA::isResult($contact)) {
1735 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1736 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1738 $sql = "`item`.`uid` = ?";
1741 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1744 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1745 $cid, GRAVITY_PARENT, local_user()];
1747 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1748 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1751 $pager = new Pager($a->query_string);
1753 $params = ['order' => ['received' => true],
1754 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1757 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1759 $items = Item::inArray($r);
1761 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1763 $r = Item::selectForUser(local_user(), [], $condition, $params);
1765 $items = Item::inArray($r);
1767 $o = conversation($a, $items, $pager, 'contact-posts', false);
1771 $o .= $pager->renderMinimal(count($items));
1778 * @brief Returns the account type name
1780 * The function can be called with either the user or the contact array
1782 * @param array $contact contact or user array
1785 public static function getAccountType(array $contact)
1787 // There are several fields that indicate that the contact or user is a forum
1788 // "page-flags" is a field in the user table,
1789 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1790 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1791 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1792 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1793 || (isset($contact['forum']) && intval($contact['forum']))
1794 || (isset($contact['prv']) && intval($contact['prv']))
1795 || (isset($contact['community']) && intval($contact['community']))
1797 $type = self::TYPE_COMMUNITY;
1799 $type = self::TYPE_PERSON;
1802 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1803 if (isset($contact["contact-type"])) {
1804 $type = $contact["contact-type"];
1807 if (isset($contact["account-type"])) {
1808 $type = $contact["account-type"];
1812 case self::TYPE_ORGANISATION:
1813 $account_type = L10n::t("Organisation");
1816 case self::TYPE_NEWS:
1817 $account_type = L10n::t('News');
1820 case self::TYPE_COMMUNITY:
1821 $account_type = L10n::t("Forum");
1829 return $account_type;
1833 * @brief Blocks a contact
1837 * @throws \Exception
1839 public static function block($cid, $reason = null)
1841 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1847 * @brief Unblocks a contact
1851 * @throws \Exception
1853 public static function unblock($cid)
1855 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1861 * @brief Updates the avatar links in a contact only if needed
1863 * @param string $avatar Link to avatar picture
1864 * @param int $uid User id of contact owner
1865 * @param int $cid Contact id
1866 * @param bool $force force picture update
1868 * @return array Returns array of the different avatar sizes
1869 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1870 * @throws \ImagickException
1872 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1874 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1875 if (!DBA::isResult($contact)) {
1878 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1881 if (($contact["avatar"] != $avatar) || $force) {
1882 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1885 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1886 DBA::update('contact', $fields, ['id' => $cid]);
1888 // Update the public contact (contact id = 0)
1890 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1891 if (DBA::isResult($pcontact)) {
1892 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1904 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1906 * @param integer $id contact id
1907 * @param integer $uid user id
1908 * @param string $url The profile URL of the contact
1909 * @param array $fields The fields that are updated
1911 * @throws \Exception
1913 private static function updateContact($id, $uid, $url, array $fields)
1915 if (!DBA::update('contact', $fields, ['id' => $id])) {
1916 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1920 // Search for duplicated contacts and get rid of them
1921 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1925 // Update the corresponding gcontact entry
1926 GContact::updateFromPublicContactID($id);
1928 // Archive or unarchive the contact. We only need to do this for the public contact.
1929 // The archive/unarchive function will update the personal contacts by themselves.
1930 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1931 if (!DBA::isResult($contact)) {
1932 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1936 if (!empty($fields['success_update'])) {
1937 self::unmarkForArchival($contact);
1938 } elseif (!empty($fields['failure_update'])) {
1939 self::markForArchival($contact);
1942 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1944 // These contacts are sharing with us, we don't poll them.
1945 // This means that we don't set the update fields in "OnePoll.php".
1946 $condition['rel'] = self::SHARING;
1947 DBA::update('contact', $fields, $condition);
1949 unset($fields['last-update']);
1950 unset($fields['success_update']);
1951 unset($fields['failure_update']);
1953 if (empty($fields)) {
1957 // We are polling these contacts, so we mustn't set the update fields here.
1958 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1959 DBA::update('contact', $fields, $condition);
1963 * @brief Remove duplicated contacts
1965 * @param string $nurl Normalised contact url
1966 * @param integer $uid User id
1968 * @throws \Exception
1970 public static function removeDuplicates(string $nurl, int $uid)
1972 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1973 $count = DBA::count('contact', $condition);
1978 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1979 if (!DBA::isResult($first_contact)) {
1980 // Shouldn't happen - so we handle it
1984 $first = $first_contact['id'];
1985 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1986 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1987 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1988 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1992 // Find all duplicates
1993 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1994 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1995 while ($duplicate = DBA::fetch($duplicates)) {
1996 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2000 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2002 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2007 * @param integer $id contact id
2008 * @param string $network Optional network we are probing for
2009 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2011 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2012 * @throws \ImagickException
2014 public static function updateFromProbe($id, $network = '', $force = false)
2017 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2018 This will reliably kill your communication with old Friendica contacts.
2021 // These fields aren't updated by this routine:
2022 // 'xmpp', 'sensitive'
2024 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2025 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2026 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2027 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2028 if (!DBA::isResult($contact)) {
2032 $uid = $contact['uid'];
2033 unset($contact['uid']);
2035 $pubkey = $contact['pubkey'];
2036 unset($contact['pubkey']);
2038 $contact['photo'] = $contact['avatar'];
2039 unset($contact['avatar']);
2041 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2043 $updated = DateTimeFormat::utcNow();
2045 // We must not try to update relay contacts via probe. They are no real contacts.
2046 // We check after the probing to be able to correct falsely detected contact types.
2047 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2048 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2049 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2050 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2054 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2055 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2056 if ($force && ($uid == 0)) {
2057 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2062 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2063 $ret['unsearchable'] = $ret['hide'];
2066 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2067 $ret['forum'] = false;
2068 $ret['prv'] = false;
2069 $ret['contact-type'] = $ret['account-type'];
2070 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2071 $apcontact = APContact::getByURL($ret['url'], false);
2072 if (isset($apcontact['manually-approve'])) {
2073 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2074 $ret['prv'] = (bool)!$ret['forum'];
2079 $new_pubkey = $ret['pubkey'];
2083 // make sure to not overwrite existing values with blank entries except some technical fields
2084 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2085 foreach ($ret as $key => $val) {
2086 if (!array_key_exists($key, $contact)) {
2088 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2089 $ret[$key] = $contact[$key];
2090 } elseif ($ret[$key] != $contact[$key]) {
2095 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2096 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2101 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2106 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2107 $ret['updated'] = $updated;
2109 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2110 if (empty($pubkey) && !empty($new_pubkey)) {
2111 $ret['pubkey'] = $new_pubkey;
2114 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2115 $ret['uri-date'] = DateTimeFormat::utcNow();
2118 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2119 $ret['name-date'] = $updated;
2122 if ($force && ($uid == 0)) {
2123 $ret['last-update'] = $updated;
2124 $ret['success_update'] = $updated;
2127 unset($ret['photo']);
2129 self::updateContact($id, $uid, $ret['url'], $ret);
2134 public static function updateFromProbeByURL($url, $force = false)
2136 $id = self::getIdForURL($url);
2142 self::updateFromProbe($id, '', $force);
2148 * Detects if a given contact array belongs to a legacy DFRN connection
2150 * @param array $contact
2153 public static function isLegacyDFRNContact($contact)
2155 // Newer Friendica contacts are connected via AP, then these fields aren't set
2156 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2160 * Detects the communication protocol for a given contact url.
2161 * This is used to detect Friendica contacts that we can communicate via AP.
2163 * @param string $url contact url
2164 * @param string $network Network of that contact
2165 * @return string with protocol
2167 public static function getProtocol($url, $network)
2169 if ($network != Protocol::DFRN) {
2173 $apcontact = APContact::getByURL($url);
2174 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2175 return Protocol::ACTIVITYPUB;
2182 * Takes a $uid and a url/handle and adds a new contact
2183 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2184 * dfrn_request page.
2186 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2189 * $return['success'] boolean true if successful
2190 * $return['message'] error text if success is false.
2192 * @brief Takes a $uid and a url/handle and adds a new contact
2194 * @param string $url
2195 * @param bool $interactive
2196 * @param string $network
2198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2199 * @throws \ImagickException
2201 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2203 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2207 // remove ajax junk, e.g. Twitter
2208 $url = str_replace('/#!/', '/', $url);
2210 if (!Network::isUrlAllowed($url)) {
2211 $result['message'] = L10n::t('Disallowed profile URL.');
2215 if (Network::isUrlBlocked($url)) {
2216 $result['message'] = L10n::t('Blocked domain');
2221 $result['message'] = L10n::t('Connect URL missing.');
2225 $arr = ['url' => $url, 'contact' => []];
2227 Hook::callAll('follow', $arr);
2230 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2234 if (!empty($arr['contact']['name'])) {
2235 $ret = $arr['contact'];
2237 $ret = Probe::uri($url, $network, $uid, false);
2240 if (($network != '') && ($ret['network'] != $network)) {
2241 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2245 // check if we already have a contact
2246 // the poll url is more reliable than the profile url, as we may have
2247 // indirect links or webfinger links
2249 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2250 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2251 if (!DBA::isResult($contact)) {
2252 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2253 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2256 $protocol = self::getProtocol($url, $ret['network']);
2258 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2260 if (strlen($a->getURLPath())) {
2261 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2263 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2266 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2270 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2271 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2272 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2276 // This extra param just confuses things, remove it
2277 if ($protocol === Protocol::DIASPORA) {
2278 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2281 // do we have enough information?
2282 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2283 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2284 if (empty($ret['poll'])) {
2285 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2287 if (empty($ret['name'])) {
2288 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2290 if (empty($ret['url'])) {
2291 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2293 if (strpos($url, '@') !== false) {
2294 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2295 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2300 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2301 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2302 $ret['notify'] = '';
2305 if (!$ret['notify']) {
2306 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2309 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2311 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2313 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2316 if ($protocol == Protocol::ACTIVITYPUB) {
2317 $apcontact = APContact::getByURL($url, false);
2318 if (isset($apcontact['manually-approve'])) {
2319 $pending = (bool)$apcontact['manually-approve'];
2323 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2327 if (DBA::isResult($contact)) {
2329 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2331 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2332 DBA::update('contact', $fields, ['id' => $contact['id']]);
2334 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2336 // create contact record
2339 'created' => DateTimeFormat::utcNow(),
2340 'url' => $ret['url'],
2341 'nurl' => Strings::normaliseLink($ret['url']),
2342 'addr' => $ret['addr'],
2343 'alias' => $ret['alias'],
2344 'batch' => $ret['batch'],
2345 'notify' => $ret['notify'],
2346 'poll' => $ret['poll'],
2347 'poco' => $ret['poco'],
2348 'name' => $ret['name'],
2349 'nick' => $ret['nick'],
2350 'network' => $ret['network'],
2351 'baseurl' => $ret['baseurl'],
2352 'protocol' => $protocol,
2353 'pubkey' => $ret['pubkey'],
2354 'rel' => $new_relation,
2355 'priority'=> $ret['priority'],
2356 'writable'=> $writeable,
2357 'hidden' => $hidden,
2360 'pending' => $pending,
2365 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2366 if (!DBA::isResult($contact)) {
2367 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2371 $contact_id = $contact['id'];
2372 $result['cid'] = $contact_id;
2374 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2376 // Update the avatar
2377 self::updateAvatar($ret['photo'], $uid, $contact_id);
2379 // pull feed and consume it, which should subscribe to the hub.
2381 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2383 $owner = User::getOwnerDataById($uid);
2385 if (DBA::isResult($owner)) {
2386 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2387 // create a follow slap
2389 $item['verb'] = Activity::FOLLOW;
2390 $item['follow'] = $contact["url"];
2392 $item['title'] = '';
2395 $item['attach'] = '';
2397 $slap = OStatus::salmon($item, $owner);
2399 if (!empty($contact['notify'])) {
2400 Salmon::slapper($owner, $contact['notify'], $slap);
2402 } elseif ($protocol == Protocol::DIASPORA) {
2403 $ret = Diaspora::sendShare($a->user, $contact);
2404 Logger::log('share returns: ' . $ret);
2405 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2406 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2407 if (empty($activity_id)) {
2408 // This really should never happen
2412 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2413 Logger::log('Follow returns: ' . $ret);
2417 $result['success'] = true;
2422 * @brief Updated contact's SSL policy
2424 * @param array $contact Contact array
2425 * @param string $new_policy New policy, valid: self,full
2427 * @return array Contact array with updated values
2428 * @throws \Exception
2430 public static function updateSslPolicy(array $contact, $new_policy)
2432 $ssl_changed = false;
2433 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2434 $ssl_changed = true;
2435 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2436 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2437 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2438 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2439 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2440 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2443 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2444 $ssl_changed = true;
2445 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2446 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2447 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2448 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2449 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2450 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2454 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2455 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2456 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2457 DBA::update('contact', $fields, ['id' => $contact['id']]);
2464 * @param array $importer Owner (local user) data
2465 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2466 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2467 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2468 * @param string $note Introduction additional message
2469 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2470 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2471 * @throws \ImagickException
2473 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2475 // Should always be set
2476 if (empty($datarray['author-id'])) {
2480 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2481 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2482 if (!DBA::isResult($pub_contact)) {
2483 // Should never happen
2487 // Contact is blocked at node-level
2488 if (self::isBlocked($datarray['author-id'])) {
2492 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2493 $name = $pub_contact['name'];
2494 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2495 $nick = $pub_contact['nick'];
2496 $network = $pub_contact['network'];
2498 // Ensure that we don't create a new contact when there already is one
2499 $cid = self::getIdForURL($url, $importer['uid']);
2501 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2504 if (!empty($contact)) {
2505 if (!empty($contact['pending'])) {
2506 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2510 // Contact is blocked at user-level
2511 if (!empty($contact['id']) && !empty($importer['id']) &&
2512 self::isBlockedByUser($contact['id'], $importer['id'])) {
2516 // Make sure that the existing contact isn't archived
2517 self::unmarkForArchival($contact);
2519 if (($contact['rel'] == self::SHARING)
2520 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2521 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2522 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2525 // Ensure to always have the correct network type, independent from the connection request method
2526 self::updateFromProbe($contact['id'], '', true);
2530 // send email notification to owner?
2531 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2532 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2536 // create contact record
2537 DBA::insert('contact', [
2538 'uid' => $importer['uid'],
2539 'created' => DateTimeFormat::utcNow(),
2541 'nurl' => Strings::normaliseLink($url),
2545 'network' => $network,
2546 'rel' => self::FOLLOWER,
2553 $contact_id = DBA::lastInsertId();
2555 // Ensure to always have the correct network type, independent from the connection request method
2556 self::updateFromProbe($contact_id, '', true);
2558 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2560 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2562 /// @TODO Encapsulate this into a function/method
2563 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2564 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2565 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2566 // create notification
2567 $hash = Strings::getRandomHex();
2569 if (is_array($contact_record)) {
2570 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2571 'blocked' => false, 'knowyou' => false, 'note' => $note,
2572 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2575 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2577 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2578 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2581 'type' => NOTIFY_INTRO,
2582 'notify_flags' => $user['notify-flags'],
2583 'language' => $user['language'],
2584 'to_name' => $user['username'],
2585 'to_email' => $user['email'],
2586 'uid' => $user['uid'],
2587 'link' => System::baseUrl() . '/notifications/intro',
2588 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2589 'source_link' => $contact_record['url'],
2590 'source_photo' => $contact_record['photo'],
2591 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2595 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2596 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2597 DBA::update('contact', ['pending' => false], $condition);
2606 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2608 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2609 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2611 Contact::remove($contact['id']);
2615 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2617 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2618 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2620 Contact::remove($contact['id']);
2625 * @brief Create a birthday event.
2627 * Update the year and the birthday.
2629 public static function updateBirthdays()
2633 AND `bd` > "0001-01-01"
2634 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2635 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2636 AND NOT `contact`.`pending`
2637 AND NOT `contact`.`hidden`
2638 AND NOT `contact`.`blocked`
2639 AND NOT `contact`.`archive`
2640 AND NOT `contact`.`deleted`',
2645 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2647 while ($contact = DBA::fetch($contacts)) {
2648 Logger::log('update_contact_birthday: ' . $contact['bd']);
2650 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2652 if (Event::createBirthday($contact, $nextbd)) {
2656 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2657 ['id' => $contact['id']]
2664 * Remove the unavailable contact ids from the provided list
2666 * @param array $contact_ids Contact id list
2667 * @throws \Exception
2669 public static function pruneUnavailable(array &$contact_ids)
2671 if (empty($contact_ids)) {
2675 $str = DBA::escape(implode(',', $contact_ids));
2677 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2680 while($contact = DBA::fetch($stmt)) {
2681 $return[] = $contact['id'];
2686 $contact_ids = $return;
2690 * @brief Returns a magic link to authenticate remote visitors
2692 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2694 * @param string $contact_url The address of the target contact profile
2695 * @param string $url An url that we will be redirected to after the authentication
2697 * @return string with "redir" link
2698 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2699 * @throws \ImagickException
2701 public static function magicLink($contact_url, $url = '')
2703 if (!Session::isAuthenticated()) {
2704 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2707 $data = self::getProbeDataFromDatabase($contact_url);
2709 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2712 // Prevents endless loop in case only a non-public contact exists for the contact URL
2713 unset($data['uid']);
2715 return self::magicLinkByContact($data, $url ?: $contact_url);
2719 * @brief Returns a magic link to authenticate remote visitors
2721 * @param integer $cid The contact id of the target contact profile
2722 * @param string $url An url that we will be redirected to after the authentication
2724 * @return string with "redir" link
2725 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2726 * @throws \ImagickException
2728 public static function magicLinkbyId($cid, $url = '')
2730 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2732 return self::magicLinkByContact($contact, $url);
2736 * @brief Returns a magic link to authenticate remote visitors
2738 * @param array $contact The contact array with "uid", "network" and "url"
2739 * @param string $url An url that we will be redirected to after the authentication
2741 * @return string with "redir" link
2742 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2743 * @throws \ImagickException
2745 public static function magicLinkByContact($contact, $url = '')
2747 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2749 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2750 return $destination;
2753 // Only redirections to the same host do make sense
2754 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2758 if (!empty($contact['uid'])) {
2759 return self::magicLink($contact['url'], $url);
2762 if (empty($contact['id'])) {
2763 return $destination;
2766 $redirect = 'redir/' . $contact['id'];
2768 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2769 $redirect .= '?url=' . $url;
2776 * Remove a contact from all groups
2778 * @param integer $contact_id
2780 * @return boolean Success
2782 public static function removeFromGroups($contact_id)
2784 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2788 * Is the contact a forum?
2790 * @param integer $contactid ID of the contact
2792 * @return boolean "true" if it is a forum
2794 public static function isForum($contactid)
2796 $fields = ['forum', 'prv'];
2797 $condition = ['id' => $contactid];
2798 $contact = DBA::selectFirst('contact', $fields, $condition);
2799 if (!DBA::isResult($contact)) {
2804 return ($contact['forum'] || $contact['prv']);
2808 * Can the remote contact receive private messages?
2810 * @param array $contact
2813 public static function canReceivePrivateMessages(array $contact)
2815 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2816 $self = $contact['self'] ?? false;
2818 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;