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\System;
16 use Friendica\Core\Worker;
17 use Friendica\Database\DBA;
18 use Friendica\Network\Probe;
19 use Friendica\Object\Image;
20 use Friendica\Protocol\ActivityPub;
21 use Friendica\Protocol\DFRN;
22 use Friendica\Protocol\Diaspora;
23 use Friendica\Protocol\OStatus;
24 use Friendica\Protocol\PortableContact;
25 use Friendica\Protocol\Salmon;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Strings;
31 * @brief functions for interacting with a contact
33 class Contact extends BaseObject
36 * @deprecated since version 2019.03
37 * @see User::PAGE_FLAGS_NORMAL
39 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
41 * @deprecated since version 2019.03
42 * @see User::PAGE_FLAGS_SOAPBOX
44 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
46 * @deprecated since version 2019.03
47 * @see User::PAGE_FLAGS_COMMUNITY
49 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
51 * @deprecated since version 2019.03
52 * @see User::PAGE_FLAGS_FREELOVE
54 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
56 * @deprecated since version 2019.03
57 * @see User::PAGE_FLAGS_BLOG
59 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
61 * @deprecated since version 2019.03
62 * @see User::PAGE_FLAGS_PRVGROUP
64 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
72 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
74 * TYPE_PERSON - the account belongs to a person
75 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
77 * TYPE_ORGANISATION - the account belongs to an organisation
78 * Associated page type: PAGE_SOAPBOX
80 * TYPE_NEWS - the account is a news reflector
81 * Associated page type: PAGE_SOAPBOX
83 * TYPE_COMMUNITY - the account is community forum
84 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
86 * TYPE_RELAY - the account is a relay
87 * This will only be assigned to contacts, not to user accounts
90 const TYPE_UNKNOWN = -1;
91 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
92 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
93 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
94 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
95 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
114 * @param array $fields Array of selected fields, empty for all
115 * @param array $condition Array of fields for condition
116 * @param array $params Array of several parameters
120 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
122 return DBA::selectToArray('contact', $fields, $condition, $params);
126 * @param array $fields Array of selected fields, empty for all
127 * @param array $condition Array of fields for condition
128 * @param array $params Array of several parameters
132 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
134 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
140 * Insert a row into the contact table
141 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
143 * @param array $fields field array
144 * @param bool $on_duplicate_update Do an update on a duplicate entry
146 * @return boolean was the insert successful?
149 public static function insert(array $fields, bool $on_duplicate_update = false)
151 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
152 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
153 if (!DBA::isResult($contact)) {
158 // Search for duplicated contacts and get rid of them
159 self::removeDuplicates($contact['nurl'], $contact['uid']);
165 * @param integer $id Contact ID
166 * @param array $fields Array of selected fields, empty for all
167 * @return array|boolean Contact record if it exists, false otherwise
170 public static function getById($id, $fields = [])
172 return DBA::selectFirst('contact', $fields, ['id' => $id]);
176 * @brief Tests if the given contact is a follower
178 * @param int $cid Either public contact id or user's contact id
179 * @param int $uid User ID
181 * @return boolean is the contact id a follower?
182 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
183 * @throws \ImagickException
185 public static function isFollower($cid, $uid)
187 if (self::isBlockedByUser($cid, $uid)) {
191 $cdata = self::getPublicAndUserContacID($cid, $uid);
192 if (empty($cdata['user'])) {
196 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
197 return DBA::exists('contact', $condition);
201 * @brief Tests if the given contact url is a follower
203 * @param string $url Contact URL
204 * @param int $uid User ID
206 * @return boolean is the contact id a follower?
207 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208 * @throws \ImagickException
210 public static function isFollowerByURL($url, $uid)
212 $cid = self::getIdForURL($url, $uid, true);
218 return self::isFollower($cid, $uid);
222 * @brief Tests if the given user follow the given contact
224 * @param int $cid Either public contact id or user's contact id
225 * @param int $uid User ID
227 * @return boolean is the contact url being followed?
228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229 * @throws \ImagickException
231 public static function isSharing($cid, $uid)
233 if (self::isBlockedByUser($cid, $uid)) {
237 $cdata = self::getPublicAndUserContacID($cid, $uid);
238 if (empty($cdata['user'])) {
242 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
243 return DBA::exists('contact', $condition);
247 * @brief Tests if the given user follow the given contact url
249 * @param string $url Contact URL
250 * @param int $uid User ID
252 * @return boolean is the contact url being followed?
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 * @throws \ImagickException
256 public static function isSharingByURL($url, $uid)
258 $cid = self::getIdForURL($url, $uid, true);
264 return self::isSharing($cid, $uid);
268 * @brief Get the basepath for a given contact link
270 * @param string $url The contact link
272 * @return string basepath
273 * @return boolean $dont_update Don't update the contact
274 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
275 * @throws \ImagickException
277 public static function getBasepath($url, $dont_update = false)
279 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
280 if (!empty($contact['baseurl'])) {
281 return $contact['baseurl'];
282 } elseif ($dont_update) {
286 self::updateFromProbeByURL($url, true);
288 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
289 if (!empty($contact['baseurl'])) {
290 return $contact['baseurl'];
297 * Check if the given contact url is on the same machine
299 * @param string $url The contact link
301 * @return boolean Is it the same machine?
303 public static function isLocal($url)
305 return Strings::compareLink(self::getBasepath($url, true), System::baseUrl());
309 * Returns the public contact id of the given user id
311 * @param integer $uid User ID
313 * @return integer|boolean Public contact id for given user id
316 public static function getPublicIdByUserId($uid)
318 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
319 if (!DBA::isResult($self)) {
322 return self::getIdForURL($self['url'], 0, true);
326 * @brief Returns the contact id for the user and the public contact id for a given contact id
328 * @param int $cid Either public contact id or user's contact id
329 * @param int $uid User ID
331 * @return array with public and user's contact id
332 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
333 * @throws \ImagickException
335 public static function getPublicAndUserContacID($cid, $uid)
337 if (empty($uid) || empty($cid)) {
341 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
342 if (!DBA::isResult($contact)) {
346 // We quit when the user id don't match the user id of the provided contact
347 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
351 if ($contact['uid'] != 0) {
352 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
356 $ucid = $contact['id'];
358 $pcid = $contact['id'];
359 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
362 return ['public' => $pcid, 'user' => $ucid];
366 * Returns contact details for a given contact id in combination with a user id
368 * @param int $cid A contact ID
369 * @param int $uid The User ID
370 * @param array $fields The selected fields for the contact
372 * @return array The contact details
376 public static function getContactForUser($cid, $uid, array $fields = [])
378 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
380 if (!DBA::isResult($contact)) {
388 * @brief Block contact id for user id
390 * @param int $cid Either public contact id or user's contact id
391 * @param int $uid User ID
392 * @param boolean $blocked Is the contact blocked or unblocked?
395 public static function setBlockedForUser($cid, $uid, $blocked)
397 $cdata = self::getPublicAndUserContacID($cid, $uid);
402 if ($cdata['user'] != 0) {
403 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
406 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
409 // Blocked contact can't be in any group
410 self::removeFromGroups($cid);
415 * @brief Returns "block" state for contact id and user id
417 * @param int $cid Either public contact id or user's contact id
418 * @param int $uid User ID
420 * @return boolean is the contact id blocked for the given user?
423 public static function isBlockedByUser($cid, $uid)
425 $cdata = self::getPublicAndUserContacID($cid, $uid);
430 $public_blocked = false;
432 if (!empty($cdata['public'])) {
433 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
434 if (DBA::isResult($public_contact)) {
435 $public_blocked = $public_contact['blocked'];
439 $user_blocked = $public_blocked;
441 if (!empty($cdata['user'])) {
442 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
443 if (DBA::isResult($user_contact)) {
444 $user_blocked = $user_contact['blocked'];
448 if ($user_blocked != $public_blocked) {
449 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
452 return $user_blocked;
456 * @brief Ignore contact id for user id
458 * @param int $cid Either public contact id or user's contact id
459 * @param int $uid User ID
460 * @param boolean $ignored Is the contact ignored or unignored?
463 public static function setIgnoredForUser($cid, $uid, $ignored)
465 $cdata = self::getPublicAndUserContacID($cid, $uid);
470 if ($cdata['user'] != 0) {
471 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
474 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
478 * @brief Returns "ignore" state for contact id and user id
480 * @param int $cid Either public contact id or user's contact id
481 * @param int $uid User ID
483 * @return boolean is the contact id ignored for the given user?
486 public static function isIgnoredByUser($cid, $uid)
488 $cdata = self::getPublicAndUserContacID($cid, $uid);
493 $public_ignored = false;
495 if (!empty($cdata['public'])) {
496 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
497 if (DBA::isResult($public_contact)) {
498 $public_ignored = $public_contact['ignored'];
502 $user_ignored = $public_ignored;
504 if (!empty($cdata['user'])) {
505 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
506 if (DBA::isResult($user_contact)) {
507 $user_ignored = $user_contact['readonly'];
511 if ($user_ignored != $public_ignored) {
512 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
515 return $user_ignored;
519 * @brief Set "collapsed" for contact id and user id
521 * @param int $cid Either public contact id or user's contact id
522 * @param int $uid User ID
523 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
526 public static function setCollapsedForUser($cid, $uid, $collapsed)
528 $cdata = self::getPublicAndUserContacID($cid, $uid);
533 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
537 * @brief Returns "collapsed" state for contact id and user id
539 * @param int $cid Either public contact id or user's contact id
540 * @param int $uid User ID
542 * @return boolean is the contact id blocked for the given user?
543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
544 * @throws \ImagickException
546 public static function isCollapsedByUser($cid, $uid)
548 $cdata = self::getPublicAndUserContacID($cid, $uid);
555 if (!empty($cdata['public'])) {
556 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
557 if (DBA::isResult($public_contact)) {
558 $collapsed = $public_contact['collapsed'];
566 * @brief Returns a list of contacts belonging in a group
572 public static function getByGroupId($gid)
577 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
579 INNER JOIN `group_member`
580 ON `contact`.`id` = `group_member`.`contact-id`
582 AND `contact`.`uid` = ?
583 AND NOT `contact`.`self`
584 AND NOT `contact`.`deleted`
585 AND NOT `contact`.`blocked`
586 AND NOT `contact`.`pending`
587 ORDER BY `contact`.`name` ASC',
592 if (DBA::isResult($stmt)) {
593 $return = DBA::toArray($stmt);
601 * @brief Returns the count of OStatus contacts in a group
607 public static function getOStatusCountByGroupId($gid)
611 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
613 INNER JOIN `group_member`
614 ON `contact`.`id` = `group_member`.`contact-id`
616 AND `contact`.`uid` = ?
617 AND `contact`.`network` = ?
618 AND `contact`.`notify` != ""',
623 $return = $contacts['count'];
630 * Creates the self-contact for the provided user id
633 * @return bool Operation success
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
636 public static function createSelfFromUserId($uid)
638 // Only create the entry if it doesn't exist yet
639 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
643 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
644 if (!DBA::isResult($user)) {
648 $return = DBA::insert('contact', [
649 'uid' => $user['uid'],
650 'created' => DateTimeFormat::utcNow(),
652 'name' => $user['username'],
653 'nick' => $user['nickname'],
654 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
655 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
656 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
659 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
660 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
661 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
662 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
663 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
664 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
665 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
666 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
667 'name-date' => DateTimeFormat::utcNow(),
668 'uri-date' => DateTimeFormat::utcNow(),
669 'avatar-date' => DateTimeFormat::utcNow(),
677 * Updates the self-contact for the provided user id
680 * @param boolean $update_avatar Force the avatar update
681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
683 public static function updateSelfFromUserID($uid, $update_avatar = false)
685 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
686 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
687 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
688 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
689 if (!DBA::isResult($self)) {
693 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
694 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
695 if (!DBA::isResult($user)) {
699 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
700 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
701 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
702 if (!DBA::isResult($profile)) {
706 $file_suffix = 'jpg';
708 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
709 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
710 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
711 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
712 'xmpp' => $profile['xmpp']];
714 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
715 if (DBA::isResult($avatar)) {
716 if ($update_avatar) {
717 $fields['avatar-date'] = DateTimeFormat::utcNow();
720 // Creating the path to the avatar, beginning with the file suffix
721 $types = Image::supportedTypes();
722 if (isset($types[$avatar['type']])) {
723 $file_suffix = $types[$avatar['type']];
726 // We are adding a timestamp value so that other systems won't use cached content
727 $timestamp = strtotime($fields['avatar-date']);
729 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
730 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
732 $fields['photo'] = $prefix . '4' . $suffix;
733 $fields['thumb'] = $prefix . '5' . $suffix;
734 $fields['micro'] = $prefix . '6' . $suffix;
736 // We hadn't found a photo entry, so we use the default avatar
737 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
738 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
739 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
742 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
743 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
744 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
745 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
747 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
748 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
749 $fields['nurl'] = Strings::normaliseLink($fields['url']);
750 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
751 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
752 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
753 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
754 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
755 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
759 foreach ($fields as $field => $content) {
760 if ($self[$field] != $content) {
766 if ($fields['name'] != $self['name']) {
767 $fields['name-date'] = DateTimeFormat::utcNow();
769 $fields['updated'] = DateTimeFormat::utcNow();
770 DBA::update('contact', $fields, ['id' => $self['id']]);
772 // Update the public contact as well
773 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
775 // Update the profile
776 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
777 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
778 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
783 * @brief Marks a contact for removal
785 * @param int $id contact id
787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
789 public static function remove($id)
791 // We want just to make sure that we don't delete our "self" contact
792 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
793 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
797 // Archive the contact
798 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
800 // Delete it in the background
801 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
805 * @brief Sends an unfriend message. Does not remove the contact
807 * @param array $user User unfriending
808 * @param array $contact Contact unfriended
809 * @param boolean $dissolve Remove the contact on the remote side
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 * @throws \ImagickException
814 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
816 if (empty($contact['network'])) {
820 $protocol = $contact['network'];
821 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
822 $protocol = Protocol::ACTIVITYPUB;
825 if (($protocol == Protocol::DFRN) && $dissolve) {
826 DFRN::deliver($user, $contact, 'placeholder', true);
827 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
828 // create an unfollow slap
830 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
831 $item['follow'] = $contact["url"];
836 $item['attach'] = '';
837 $slap = OStatus::salmon($item, $user);
839 if (!empty($contact['notify'])) {
840 Salmon::slapper($user, $contact['notify'], $slap);
842 } elseif ($protocol == Protocol::DIASPORA) {
843 Diaspora::sendUnshare($user, $contact);
844 } elseif ($protocol == Protocol::ACTIVITYPUB) {
845 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
848 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
854 * @brief Marks a contact for archival after a communication issue delay
856 * Contact has refused to recognise us as a friend. We will start a countdown.
857 * If they still don't recognise us in 32 days, the relationship is over,
858 * and we won't waste any more time trying to communicate with them.
859 * This provides for the possibility that their database is temporarily messed
860 * up or some other transient event and that there's a possibility we could recover from it.
862 * @param array $contact contact to mark for archival
864 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
866 public static function markForArchival(array $contact)
868 if (!isset($contact['url']) && !empty($contact['id'])) {
869 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
870 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
871 if (!DBA::isResult($contact)) {
874 } elseif (!isset($contact['url'])) {
875 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
878 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
880 // Contact already archived or "self" contact? => nothing to do
881 if ($contact['archive'] || $contact['self']) {
885 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
886 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
887 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
890 * We really should send a notification to the owner after 2-3 weeks
891 * so they won't be surprised when the contact vanishes and can take
892 * remedial action if this was a serious mistake or glitch
895 /// @todo Check for contact vitality via probing
896 $archival_days = Config::get('system', 'archival_days', 32);
898 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
899 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
900 /* Relationship is really truly dead. archive them rather than
901 * delete, though if the owner tries to unarchive them we'll start
902 * the whole process over again.
904 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
905 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
906 GContact::updateFromPublicContactURL($contact['url']);
912 * @brief Cancels the archival countdown
914 * @see Contact::markForArchival()
916 * @param array $contact contact to be unmarked for archival
920 public static function unmarkForArchival(array $contact)
922 // Always unarchive the relay contact entry
923 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
924 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
925 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
926 DBA::update('contact', $fields, $condition);
929 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
930 $exists = DBA::exists('contact', $condition);
932 // We don't need to update, we never marked this contact for archival
937 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
939 if (!isset($contact['url']) && !empty($contact['id'])) {
940 $fields = ['id', 'url', 'batch'];
941 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
942 if (!DBA::isResult($contact)) {
947 // It's a miracle. Our dead contact has inexplicably come back to life.
948 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
949 DBA::update('contact', $fields, ['id' => $contact['id']]);
950 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
951 GContact::updateFromPublicContactURL($contact['url']);
955 * @brief Get contact data for a given profile link
957 * The function looks at several places (contact table and gcontact table) for the contact
958 * It caches its result for the same script execution to prevent duplicate calls
960 * @param string $url The profile link
961 * @param int $uid User id
962 * @param array $default If not data was found take this data as default value
964 * @return array Contact data
965 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967 public static function getDetailsByURL($url, $uid = -1, array $default = [])
979 if (isset($cache[$url][$uid])) {
980 return $cache[$url][$uid];
983 $ssl_url = str_replace('http://', 'https://', $url);
985 // Fetch contact data from the contact table for the given user
986 $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`,
987 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
988 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
989 $r = DBA::toArray($s);
991 // Fetch contact data from the contact table for the given user, checking with the alias
992 if (!DBA::isResult($r)) {
993 $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`,
994 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
995 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
996 $r = DBA::toArray($s);
999 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1000 if (!DBA::isResult($r)) {
1001 $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`,
1002 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1003 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
1004 $r = DBA::toArray($s);
1007 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1008 if (!DBA::isResult($r)) {
1009 $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`,
1010 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1011 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
1012 $r = DBA::toArray($s);
1015 // Fetch the data from the gcontact table
1016 if (!DBA::isResult($r)) {
1017 $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`,
1018 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1019 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
1020 $r = DBA::toArray($s);
1023 if (DBA::isResult($r)) {
1024 // If there is more than one entry we filter out the connector networks
1025 if (count($r) > 1) {
1026 foreach ($r as $id => $result) {
1027 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1033 $profile = array_shift($r);
1035 // "bd" always contains the upcoming birthday of a contact.
1036 // "birthday" might contain the birthday including the year of birth.
1037 if ($profile["birthday"] > DBA::NULL_DATE) {
1038 $bd_timestamp = strtotime($profile["birthday"]);
1039 $month = date("m", $bd_timestamp);
1040 $day = date("d", $bd_timestamp);
1042 $current_timestamp = time();
1043 $current_year = date("Y", $current_timestamp);
1044 $current_month = date("m", $current_timestamp);
1045 $current_day = date("d", $current_timestamp);
1047 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1048 $current = $current_year . "-" . $current_month . "-" . $current_day;
1050 if ($profile["bd"] < $current) {
1051 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1054 $profile["bd"] = DBA::NULL_DATE;
1057 $profile = $default;
1060 if (empty($profile["photo"]) && isset($default["photo"])) {
1061 $profile["photo"] = $default["photo"];
1064 if (empty($profile["name"]) && isset($default["name"])) {
1065 $profile["name"] = $default["name"];
1068 if (empty($profile["network"]) && isset($default["network"])) {
1069 $profile["network"] = $default["network"];
1072 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1073 $profile["thumb"] = $profile["photo"];
1076 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1077 $profile["micro"] = $profile["thumb"];
1080 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1081 && in_array($profile["network"], Protocol::FEDERATED)
1083 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1086 // Show contact details of Diaspora contacts only if connected
1087 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1088 $profile["location"] = "";
1089 $profile["about"] = "";
1090 $profile["gender"] = "";
1091 $profile["birthday"] = DBA::NULL_DATE;
1094 $cache[$url][$uid] = $profile;
1100 * @brief Get contact data for a given address
1102 * The function looks at several places (contact table and gcontact table) for the contact
1104 * @param string $addr The profile link
1105 * @param int $uid User id
1107 * @return array Contact data
1108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1109 * @throws \ImagickException
1111 public static function getDetailsByAddr($addr, $uid = -1)
1118 $uid = local_user();
1121 // Fetch contact data from the contact table for the given user
1122 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1123 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1124 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1128 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1129 if (!DBA::isResult($r)) {
1130 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1131 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1132 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1137 // Fetch the data from the gcontact table
1138 if (!DBA::isResult($r)) {
1139 $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`,
1140 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1141 FROM `gcontact` WHERE `addr` = '%s'",
1146 if (!DBA::isResult($r)) {
1147 $data = Probe::uri($addr);
1149 $profile = self::getDetailsByURL($data['url'], $uid);
1158 * @brief Returns the data array for the photo menu of a given contact
1160 * @param array $contact contact
1161 * @param int $uid optional, default 0
1163 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1164 * @throws \ImagickException
1166 public static function photoMenu(array $contact, $uid = 0)
1171 $contact_drop_link = '';
1175 $uid = local_user();
1178 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1180 $profile_link = self::magicLink($contact['url']);
1181 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1186 // Look for our own contact if the uid doesn't match and isn't public
1187 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1188 if (DBA::isResult($contact_own)) {
1189 return self::photoMenu($contact_own, $uid);
1194 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1196 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1198 $profile_link = $contact['url'];
1201 if ($profile_link === 'mailbox') {
1206 $status_link = $profile_link . '?tab=status';
1207 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1208 $profile_link = $profile_link . '?tab=profile';
1211 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1212 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1215 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1216 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1219 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1221 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1223 if (!$contact['self']) {
1224 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1229 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1231 if (empty($contact['uid'])) {
1232 $connlnk = 'follow/?url=' . $contact['url'];
1234 'profile' => [L10n::t('View Profile'), $profile_link, true],
1235 'network' => [L10n::t('Network Posts'), $posts_link, false],
1236 'edit' => [L10n::t('View Contact'), $contact_url, false],
1237 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1241 'status' => [L10n::t('View Status'), $status_link, true],
1242 'profile' => [L10n::t('View Profile'), $profile_link, true],
1243 'photos' => [L10n::t('View Photos'), $photos_link, true],
1244 'network' => [L10n::t('Network Posts'), $posts_link, false],
1245 'edit' => [L10n::t('View Contact'), $contact_url, false],
1246 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1247 'pm' => [L10n::t('Send PM'), $pm_url, false],
1248 'poke' => [L10n::t('Poke'), $poke_link, false],
1251 if (!empty($contact['pending'])) {
1252 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1253 if (DBA::isResult($intro)) {
1254 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1259 $args = ['contact' => $contact, 'menu' => &$menu];
1261 Hook::callAll('contact_photo_menu', $args);
1263 $menucondensed = [];
1265 foreach ($menu as $menuname => $menuitem) {
1266 if ($menuitem[1] != '') {
1267 $menucondensed[$menuname] = $menuitem;
1271 return $menucondensed;
1275 * @brief Returns ungrouped contact count or list for user
1277 * Returns either the total number of ungrouped contacts for the given user
1278 * id or a paginated list of ungrouped contacts.
1280 * @param int $uid uid
1282 * @throws \Exception
1284 public static function getUngroupedList($uid)
1294 SELECT DISTINCT(`contact-id`)
1296 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1297 WHERE `group`.`uid` = %d
1298 )", intval($uid), intval($uid));
1302 * Have a look at all contact tables for a given profile url.
1303 * This function works as a replacement for probing the contact.
1305 * @param string $url Contact URL
1306 * @param integer $cid Contact ID
1308 * @return array Contact array in the "probe" structure
1310 private static function getProbeDataFromDatabase($url, $cid = null)
1312 // The link could be provided as http although we stored it as https
1313 $ssl_url = str_replace('http://', 'https://', $url);
1315 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1316 'photo', 'keywords', 'location', 'about', 'network',
1317 'priority', 'batch', 'request', 'confirm', 'poco'];
1320 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1321 if (DBA::isResult($data)) {
1326 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1328 if (!DBA::isResult($data)) {
1329 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1330 $data = DBA::selectFirst('contact', $fields, $condition);
1333 if (DBA::isResult($data)) {
1334 // For security reasons we don't fetch key data from our users
1335 $data["pubkey"] = '';
1339 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1340 'photo', 'keywords', 'location', 'about', 'network'];
1341 $data = DBA::selectFirst('gcontact', $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 $data["pubkey"] = '';
1351 $data["priority"] = 0;
1352 $data["batch"] = '';
1353 $data["request"] = '';
1354 $data["confirm"] = '';
1359 $data = ActivityPub::probeProfile($url, false);
1360 if (!empty($data)) {
1364 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1365 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1366 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1368 if (!DBA::isResult($data)) {
1369 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1370 $data = DBA::selectFirst('contact', $fields, $condition);
1373 if (DBA::isResult($data)) {
1374 $data["pubkey"] = '';
1375 $data["keywords"] = '';
1376 $data["location"] = '';
1377 $data["about"] = '';
1386 * @brief Fetch the contact id for a given URL and user
1388 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1389 * `addr` or `alias`.
1391 * If there's no record and we aren't looking for a public contact, we quit.
1392 * If there's one, we check that it isn't time to update the picture else we
1393 * directly return the found contact id.
1395 * Second, we probe the provided $url whether it's http://server.tld/profile or
1396 * nick@server.tld. We quit if we can't get any info back.
1398 * Third, we create the contact record if it doesn't exist
1400 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1401 * if there's any updates
1403 * @param string $url Contact URL
1404 * @param integer $uid The user id for the contact (0 = public contact)
1405 * @param boolean $no_update Don't update the contact
1406 * @param array $default Default value for creating the contact when every else fails
1407 * @param boolean $in_loop Internally used variable to prevent an endless loop
1409 * @return integer Contact ID
1410 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1411 * @throws \ImagickException
1413 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1415 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1423 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1424 // We first try the nurl (http://server.tld/nick), most common case
1425 $fields = ['id', 'avatar', 'updated', 'network'];
1426 $options = ['order' => ['id']];
1427 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1429 // Then the addr (nick@server.tld)
1430 if (!DBA::isResult($contact)) {
1431 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1434 // Then the alias (which could be anything)
1435 if (!DBA::isResult($contact)) {
1436 // The link could be provided as http although we stored it as https
1437 $ssl_url = str_replace('http://', 'https://', $url);
1438 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1439 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1442 if (DBA::isResult($contact)) {
1443 $contact_id = $contact["id"];
1445 // Update the contact every 7 days
1446 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1448 // We force the update if the avatar is empty
1449 if (empty($contact['avatar'])) {
1450 $update_contact = true;
1453 // Update the contact in the background if needed but it is called by the frontend
1454 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1455 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1458 if (!$update_contact || $no_update) {
1461 } elseif ($uid != 0) {
1462 // Non-existing user-specific contact, exiting
1466 if ($no_update && empty($default)) {
1467 // When we don't want to update, we look if we know this contact in any way
1468 $data = self::getProbeDataFromDatabase($url, $contact_id);
1469 $background_update = true;
1470 } elseif ($no_update && !empty($default['network'])) {
1471 // If there are default values, take these
1473 $background_update = false;
1476 $background_update = false;
1480 $data = Probe::uri($url, "", $uid);
1481 // Ensure that there is a gserver entry
1482 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1483 PortableContact::checkServer($data['baseurl']);
1487 // Take the default values when probing failed
1488 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1489 $data = array_merge($data, $default);
1496 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1497 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1503 'created' => DateTimeFormat::utcNow(),
1504 'url' => $data['url'],
1505 'nurl' => Strings::normaliseLink($data['url']),
1506 'addr' => defaults($data, 'addr', ''),
1507 'alias' => defaults($data, 'alias', ''),
1508 'notify' => defaults($data, 'notify', ''),
1509 'poll' => defaults($data, 'poll', ''),
1510 'name' => defaults($data, 'name', ''),
1511 'nick' => defaults($data, 'nick', ''),
1512 'photo' => defaults($data, 'photo', ''),
1513 'keywords' => defaults($data, 'keywords', ''),
1514 'location' => defaults($data, 'location', ''),
1515 'about' => defaults($data, 'about', ''),
1516 'network' => $data['network'],
1517 'pubkey' => defaults($data, 'pubkey', ''),
1518 'rel' => self::SHARING,
1519 'priority' => defaults($data, 'priority', 0),
1520 'batch' => defaults($data, 'batch', ''),
1521 'request' => defaults($data, 'request', ''),
1522 'confirm' => defaults($data, 'confirm', ''),
1523 'poco' => defaults($data, 'poco', ''),
1524 'baseurl' => defaults($data, 'baseurl', ''),
1525 'name-date' => DateTimeFormat::utcNow(),
1526 'uri-date' => DateTimeFormat::utcNow(),
1527 'avatar-date' => DateTimeFormat::utcNow(),
1533 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1535 // Before inserting we do check if the entry does exist now.
1536 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1537 if (!DBA::isResult($contact)) {
1538 Logger::info('Create new contact', $fields);
1540 self::insert($fields);
1542 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1543 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1544 if (!DBA::isResult($contact)) {
1545 Logger::info('Contact creation failed', $fields);
1550 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1553 $contact_id = $contact["id"];
1556 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1557 self::updateAvatar($data['photo'], $uid, $contact_id);
1560 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1561 if ($background_update) {
1562 // Update in the background when we fetched the data solely from the database
1563 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1565 // Else do a direct update
1566 self::updateFromProbe($contact_id, '', false);
1568 // Update the gcontact entry
1570 GContact::updateFromPublicContactID($contact_id);
1574 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1575 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1577 // This condition should always be true
1578 if (!DBA::isResult($contact)) {
1583 'url' => $data['url'],
1584 'nurl' => Strings::normaliseLink($data['url']),
1585 'updated' => DateTimeFormat::utcNow()
1588 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1590 foreach ($fields as $field) {
1591 $updated[$field] = defaults($data, $field, $contact[$field]);
1594 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1595 $updated['uri-date'] = DateTimeFormat::utcNow();
1598 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1599 $updated['name-date'] = DateTimeFormat::utcNow();
1602 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1609 * @brief Checks if the contact is archived
1611 * @param int $cid contact id
1613 * @return boolean Is the contact archived?
1614 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1616 public static function isArchived(int $cid)
1622 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1623 if (!DBA::isResult($contact)) {
1627 if ($contact['archive']) {
1631 // Check status of ActivityPub endpoints
1632 $apcontact = APContact::getByURL($contact['url'], false);
1633 if (!empty($apcontact)) {
1634 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1638 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1643 // Check status of Diaspora endpoints
1644 if (!empty($contact['batch'])) {
1645 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1646 return DBA::exists('contact', $condition);
1653 * @brief Checks if the contact is blocked
1655 * @param int $cid contact id
1657 * @return boolean Is the contact blocked?
1658 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1660 public static function isBlocked($cid)
1666 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1667 if (!DBA::isResult($blocked)) {
1671 if (Network::isUrlBlocked($blocked['url'])) {
1675 return (bool) $blocked['blocked'];
1679 * @brief Checks if the contact is hidden
1681 * @param int $cid contact id
1683 * @return boolean Is the contact hidden?
1684 * @throws \Exception
1686 public static function isHidden($cid)
1692 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1693 if (!DBA::isResult($hidden)) {
1696 return (bool) $hidden['hidden'];
1700 * @brief Returns posts from a given contact url
1702 * @param string $contact_url Contact URL
1704 * @param bool $thread_mode
1705 * @param int $update
1706 * @return string posts in HTML
1707 * @throws \Exception
1709 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1711 $a = self::getApp();
1713 $cid = self::getIdForURL($contact_url);
1715 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1716 if (!DBA::isResult($contact)) {
1720 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1721 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1723 $sql = "`item`.`uid` = ?";
1726 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1729 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1730 $cid, GRAVITY_PARENT, local_user()];
1732 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1733 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1736 $pager = new Pager($a->query_string);
1738 $params = ['order' => ['received' => true],
1739 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1742 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1744 $items = Item::inArray($r);
1746 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1748 $r = Item::selectForUser(local_user(), [], $condition, $params);
1750 $items = Item::inArray($r);
1752 $o = conversation($a, $items, $pager, 'contact-posts', false);
1756 $o .= $pager->renderMinimal(count($items));
1763 * @brief Returns the account type name
1765 * The function can be called with either the user or the contact array
1767 * @param array $contact contact or user array
1770 public static function getAccountType(array $contact)
1772 // There are several fields that indicate that the contact or user is a forum
1773 // "page-flags" is a field in the user table,
1774 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1775 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1776 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1777 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1778 || (isset($contact['forum']) && intval($contact['forum']))
1779 || (isset($contact['prv']) && intval($contact['prv']))
1780 || (isset($contact['community']) && intval($contact['community']))
1782 $type = self::TYPE_COMMUNITY;
1784 $type = self::TYPE_PERSON;
1787 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1788 if (isset($contact["contact-type"])) {
1789 $type = $contact["contact-type"];
1792 if (isset($contact["account-type"])) {
1793 $type = $contact["account-type"];
1797 case self::TYPE_ORGANISATION:
1798 $account_type = L10n::t("Organisation");
1801 case self::TYPE_NEWS:
1802 $account_type = L10n::t('News');
1805 case self::TYPE_COMMUNITY:
1806 $account_type = L10n::t("Forum");
1814 return $account_type;
1818 * @brief Blocks a contact
1822 * @throws \Exception
1824 public static function block($cid, $reason = null)
1826 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1832 * @brief Unblocks a contact
1836 * @throws \Exception
1838 public static function unblock($cid)
1840 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1846 * @brief Updates the avatar links in a contact only if needed
1848 * @param string $avatar Link to avatar picture
1849 * @param int $uid User id of contact owner
1850 * @param int $cid Contact id
1851 * @param bool $force force picture update
1853 * @return array Returns array of the different avatar sizes
1854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1855 * @throws \ImagickException
1857 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1859 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1860 if (!DBA::isResult($contact)) {
1863 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1866 if (($contact["avatar"] != $avatar) || $force) {
1867 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1870 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1871 DBA::update('contact', $fields, ['id' => $cid]);
1873 // Update the public contact (contact id = 0)
1875 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1876 if (DBA::isResult($pcontact)) {
1877 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1889 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1891 * @param integer $id contact id
1892 * @param integer $uid user id
1893 * @param string $url The profile URL of the contact
1894 * @param array $fields The fields that are updated
1896 * @throws \Exception
1898 private static function updateContact($id, $uid, $url, array $fields)
1900 if (!DBA::update('contact', $fields, ['id' => $id])) {
1901 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1905 // Search for duplicated contacts and get rid of them
1906 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1910 // Update the corresponding gcontact entry
1911 GContact::updateFromPublicContactID($id);
1913 // Archive or unarchive the contact. We only need to do this for the public contact.
1914 // The archive/unarchive function will update the personal contacts by themselves.
1915 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1916 if (!DBA::isResult($contact)) {
1917 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1921 if (!empty($fields['success_update'])) {
1922 self::unmarkForArchival($contact);
1923 } elseif (!empty($fields['failure_update'])) {
1924 self::markForArchival($contact);
1927 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1929 // These contacts are sharing with us, we don't poll them.
1930 // This means that we don't set the update fields in "OnePoll.php".
1931 $condition['rel'] = self::SHARING;
1932 DBA::update('contact', $fields, $condition);
1934 unset($fields['last-update']);
1935 unset($fields['success_update']);
1936 unset($fields['failure_update']);
1938 if (empty($fields)) {
1942 // We are polling these contacts, so we mustn't set the update fields here.
1943 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1944 DBA::update('contact', $fields, $condition);
1948 * @brief Remove duplicated contacts
1950 * @param string $nurl Normalised contact url
1951 * @param integer $uid User id
1953 * @throws \Exception
1955 public static function removeDuplicates(string $nurl, int $uid)
1957 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1958 $count = DBA::count('contact', $condition);
1963 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1964 if (!DBA::isResult($first_contact)) {
1965 // Shouldn't happen - so we handle it
1969 $first = $first_contact['id'];
1970 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1971 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1972 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1973 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1977 // Find all duplicates
1978 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1979 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1980 while ($duplicate = DBA::fetch($duplicates)) {
1981 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1985 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1987 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1992 * @param integer $id contact id
1993 * @param string $network Optional network we are probing for
1994 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1997 * @throws \ImagickException
1999 public static function updateFromProbe($id, $network = '', $force = false)
2002 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2003 This will reliably kill your communication with old Friendica contacts.
2006 // These fields aren't updated by this routine:
2007 // 'xmpp', 'sensitive'
2009 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2010 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2011 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2012 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2013 if (!DBA::isResult($contact)) {
2017 $uid = $contact['uid'];
2018 unset($contact['uid']);
2020 $pubkey = $contact['pubkey'];
2021 unset($contact['pubkey']);
2023 $contact['photo'] = $contact['avatar'];
2024 unset($contact['avatar']);
2026 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2028 $updated = DateTimeFormat::utcNow();
2030 // We must not try to update relay contacts via probe. They are no real contacts.
2031 // We check after the probing to be able to correct falsely detected contact types.
2032 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2033 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2034 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2035 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2039 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2040 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2041 if ($force && ($uid == 0)) {
2042 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2047 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2048 $ret['unsearchable'] = $ret['hide'];
2051 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2052 $ret['forum'] = false;
2053 $ret['prv'] = false;
2054 $ret['contact-type'] = $ret['account-type'];
2055 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2056 $apcontact = APContact::getByURL($ret['url'], false);
2057 if (isset($apcontact['manually-approve'])) {
2058 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2059 $ret['prv'] = (bool)!$ret['forum'];
2064 $new_pubkey = $ret['pubkey'];
2068 // make sure to not overwrite existing values with blank entries except some technical fields
2069 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2070 foreach ($ret as $key => $val) {
2071 if (!array_key_exists($key, $contact)) {
2073 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2074 $ret[$key] = $contact[$key];
2075 } elseif ($ret[$key] != $contact[$key]) {
2080 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2081 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2086 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2091 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2092 $ret['updated'] = $updated;
2094 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2095 if (empty($pubkey) && !empty($new_pubkey)) {
2096 $ret['pubkey'] = $new_pubkey;
2099 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2100 $ret['uri-date'] = DateTimeFormat::utcNow();
2103 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2104 $ret['name-date'] = $updated;
2107 if ($force && ($uid == 0)) {
2108 $ret['last-update'] = $updated;
2109 $ret['success_update'] = $updated;
2112 unset($ret['photo']);
2114 self::updateContact($id, $uid, $ret['url'], $ret);
2119 public static function updateFromProbeByURL($url, $force = false)
2121 $id = self::getIdForURL($url);
2127 self::updateFromProbe($id, '', $force);
2133 * Detects if a given contact array belongs to a legacy DFRN connection
2135 * @param array $contact
2138 public static function isLegacyDFRNContact($contact)
2140 // Newer Friendica contacts are connected via AP, then these fields aren't set
2141 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2145 * Detects the communication protocol for a given contact url.
2146 * This is used to detect Friendica contacts that we can communicate via AP.
2148 * @param string $url contact url
2149 * @param string $network Network of that contact
2150 * @return string with protocol
2152 public static function getProtocol($url, $network)
2154 if ($network != Protocol::DFRN) {
2158 $apcontact = APContact::getByURL($url);
2159 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2160 return Protocol::ACTIVITYPUB;
2167 * Takes a $uid and a url/handle and adds a new contact
2168 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2169 * dfrn_request page.
2171 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2174 * $return['success'] boolean true if successful
2175 * $return['message'] error text if success is false.
2177 * @brief Takes a $uid and a url/handle and adds a new contact
2179 * @param string $url
2180 * @param bool $interactive
2181 * @param string $network
2183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2184 * @throws \ImagickException
2186 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2188 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2192 // remove ajax junk, e.g. Twitter
2193 $url = str_replace('/#!/', '/', $url);
2195 if (!Network::isUrlAllowed($url)) {
2196 $result['message'] = L10n::t('Disallowed profile URL.');
2200 if (Network::isUrlBlocked($url)) {
2201 $result['message'] = L10n::t('Blocked domain');
2206 $result['message'] = L10n::t('Connect URL missing.');
2210 $arr = ['url' => $url, 'contact' => []];
2212 Hook::callAll('follow', $arr);
2215 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2219 if (!empty($arr['contact']['name'])) {
2220 $ret = $arr['contact'];
2222 $ret = Probe::uri($url, $network, $uid, false);
2225 if (($network != '') && ($ret['network'] != $network)) {
2226 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2230 // check if we already have a contact
2231 // the poll url is more reliable than the profile url, as we may have
2232 // indirect links or webfinger links
2234 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2235 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2236 if (!DBA::isResult($contact)) {
2237 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2238 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2241 $protocol = self::getProtocol($url, $ret['network']);
2243 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2245 if (strlen($a->getURLPath())) {
2246 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2248 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2251 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2255 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2256 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2257 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2261 // This extra param just confuses things, remove it
2262 if ($protocol === Protocol::DIASPORA) {
2263 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2266 // do we have enough information?
2267 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2268 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2269 if (empty($ret['poll'])) {
2270 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2272 if (empty($ret['name'])) {
2273 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2275 if (empty($ret['url'])) {
2276 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2278 if (strpos($url, '@') !== false) {
2279 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2280 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2285 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2286 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2287 $ret['notify'] = '';
2290 if (!$ret['notify']) {
2291 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2294 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2296 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2298 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2300 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2302 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2306 if (DBA::isResult($contact)) {
2308 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2310 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2311 DBA::update('contact', $fields, ['id' => $contact['id']]);
2313 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2315 // create contact record
2318 'created' => DateTimeFormat::utcNow(),
2319 'url' => $ret['url'],
2320 'nurl' => Strings::normaliseLink($ret['url']),
2321 'addr' => $ret['addr'],
2322 'alias' => $ret['alias'],
2323 'batch' => $ret['batch'],
2324 'notify' => $ret['notify'],
2325 'poll' => $ret['poll'],
2326 'poco' => $ret['poco'],
2327 'name' => $ret['name'],
2328 'nick' => $ret['nick'],
2329 'network' => $ret['network'],
2330 'baseurl' => $ret['baseurl'],
2331 'protocol' => $protocol,
2332 'pubkey' => $ret['pubkey'],
2333 'rel' => $new_relation,
2334 'priority'=> $ret['priority'],
2335 'writable'=> $writeable,
2336 'hidden' => $hidden,
2339 'pending' => $pending,
2344 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2345 if (!DBA::isResult($contact)) {
2346 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2350 $contact_id = $contact['id'];
2351 $result['cid'] = $contact_id;
2353 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2355 // Update the avatar
2356 self::updateAvatar($ret['photo'], $uid, $contact_id);
2358 // pull feed and consume it, which should subscribe to the hub.
2360 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2362 $owner = User::getOwnerDataById($uid);
2364 if (DBA::isResult($owner)) {
2365 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2366 // create a follow slap
2368 $item['verb'] = ACTIVITY_FOLLOW;
2369 $item['follow'] = $contact["url"];
2371 $item['title'] = '';
2374 $item['attach'] = '';
2376 $slap = OStatus::salmon($item, $owner);
2378 if (!empty($contact['notify'])) {
2379 Salmon::slapper($owner, $contact['notify'], $slap);
2381 } elseif ($protocol == Protocol::DIASPORA) {
2382 $ret = Diaspora::sendShare($a->user, $contact);
2383 Logger::log('share returns: ' . $ret);
2384 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2385 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2386 if (empty($activity_id)) {
2387 // This really should never happen
2391 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2392 Logger::log('Follow returns: ' . $ret);
2396 $result['success'] = true;
2401 * @brief Updated contact's SSL policy
2403 * @param array $contact Contact array
2404 * @param string $new_policy New policy, valid: self,full
2406 * @return array Contact array with updated values
2407 * @throws \Exception
2409 public static function updateSslPolicy(array $contact, $new_policy)
2411 $ssl_changed = false;
2412 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2413 $ssl_changed = true;
2414 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2415 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2416 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2417 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2418 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2419 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2422 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2423 $ssl_changed = true;
2424 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2425 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2426 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2427 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2428 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2429 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2433 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2434 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2435 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2436 DBA::update('contact', $fields, ['id' => $contact['id']]);
2443 * @param array $importer Owner (local user) data
2444 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2445 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2446 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2447 * @param string $note Introduction additional message
2448 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2449 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2450 * @throws \ImagickException
2452 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2454 // Should always be set
2455 if (empty($datarray['author-id'])) {
2459 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2460 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2461 if (!DBA::isResult($pub_contact)) {
2462 // Should never happen
2466 // Contact is blocked at node-level
2467 if (self::isBlocked($datarray['author-id'])) {
2471 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2472 $name = $pub_contact['name'];
2473 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2474 $nick = $pub_contact['nick'];
2475 $network = $pub_contact['network'];
2477 // Ensure that we don't create a new contact when there already is one
2478 $cid = self::getIdForURL($url, $importer['uid']);
2480 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2483 if (!empty($contact)) {
2484 if (!empty($contact['pending'])) {
2485 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2489 // Contact is blocked at user-level
2490 if (!empty($contact['id']) && !empty($importer['id']) &&
2491 self::isBlockedByUser($contact['id'], $importer['id'])) {
2495 // Make sure that the existing contact isn't archived
2496 self::unmarkForArchival($contact);
2498 if (($contact['rel'] == self::SHARING)
2499 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2500 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2501 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2504 // Ensure to always have the correct network type, independent from the connection request method
2505 self::updateFromProbe($contact['id'], '', true);
2509 // send email notification to owner?
2510 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2511 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2515 // create contact record
2516 DBA::insert('contact', [
2517 'uid' => $importer['uid'],
2518 'created' => DateTimeFormat::utcNow(),
2520 'nurl' => Strings::normaliseLink($url),
2524 'network' => $network,
2525 'rel' => self::FOLLOWER,
2532 $contact_id = DBA::lastInsertId();
2534 // Ensure to always have the correct network type, independent from the connection request method
2535 self::updateFromProbe($contact_id, '', true);
2537 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2539 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2541 /// @TODO Encapsulate this into a function/method
2542 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2543 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2544 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2545 // create notification
2546 $hash = Strings::getRandomHex();
2548 if (is_array($contact_record)) {
2549 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2550 'blocked' => false, 'knowyou' => false, 'note' => $note,
2551 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2554 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2556 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2557 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2560 'type' => NOTIFY_INTRO,
2561 'notify_flags' => $user['notify-flags'],
2562 'language' => $user['language'],
2563 'to_name' => $user['username'],
2564 'to_email' => $user['email'],
2565 'uid' => $user['uid'],
2566 'link' => System::baseUrl() . '/notifications/intro',
2567 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2568 'source_link' => $contact_record['url'],
2569 'source_photo' => $contact_record['photo'],
2570 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2574 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2575 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2576 DBA::update('contact', ['pending' => false], $condition);
2585 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2587 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2588 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2590 Contact::remove($contact['id']);
2594 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2596 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2597 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2599 Contact::remove($contact['id']);
2604 * @brief Create a birthday event.
2606 * Update the year and the birthday.
2608 public static function updateBirthdays()
2612 AND `bd` > "0001-01-01"
2613 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2614 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2615 AND NOT `contact`.`pending`
2616 AND NOT `contact`.`hidden`
2617 AND NOT `contact`.`blocked`
2618 AND NOT `contact`.`archive`
2619 AND NOT `contact`.`deleted`',
2624 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2626 while ($contact = DBA::fetch($contacts)) {
2627 Logger::log('update_contact_birthday: ' . $contact['bd']);
2629 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2631 if (Event::createBirthday($contact, $nextbd)) {
2635 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2636 ['id' => $contact['id']]
2643 * Remove the unavailable contact ids from the provided list
2645 * @param array $contact_ids Contact id list
2646 * @throws \Exception
2648 public static function pruneUnavailable(array &$contact_ids)
2650 if (empty($contact_ids)) {
2654 $str = DBA::escape(implode(',', $contact_ids));
2656 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2659 while($contact = DBA::fetch($stmt)) {
2660 $return[] = $contact['id'];
2665 $contact_ids = $return;
2669 * @brief Returns a magic link to authenticate remote visitors
2671 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2673 * @param string $contact_url The address of the target contact profile
2674 * @param string $url An url that we will be redirected to after the authentication
2676 * @return string with "redir" link
2677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2678 * @throws \ImagickException
2680 public static function magicLink($contact_url, $url = '')
2682 if (!local_user() && !remote_user()) {
2683 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2686 $data = self::getProbeDataFromDatabase($contact_url);
2688 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2691 // Prevents endless loop in case only a non-public contact exists for the contact URL
2692 unset($data['uid']);
2694 return self::magicLinkByContact($data, $url ?: $contact_url);
2698 * @brief Returns a magic link to authenticate remote visitors
2700 * @param integer $cid The contact id of the target contact profile
2701 * @param string $url An url that we will be redirected to after the authentication
2703 * @return string with "redir" link
2704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2705 * @throws \ImagickException
2707 public static function magicLinkbyId($cid, $url = '')
2709 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2711 return self::magicLinkByContact($contact, $url);
2715 * @brief Returns a magic link to authenticate remote visitors
2717 * @param array $contact The contact array with "uid", "network" and "url"
2718 * @param string $url An url that we will be redirected to after the authentication
2720 * @return string with "redir" link
2721 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2722 * @throws \ImagickException
2724 public static function magicLinkByContact($contact, $url = '')
2726 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2728 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2729 return $destination;
2732 // Only redirections to the same host do make sense
2733 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2737 if (!empty($contact['uid'])) {
2738 return self::magicLink($contact['url'], $url);
2741 if (empty($contact['id'])) {
2742 return $destination;
2745 $redirect = 'redir/' . $contact['id'];
2748 $redirect .= '?url=' . $url;
2755 * Remove a contact from all groups
2757 * @param integer $contact_id
2759 * @return boolean Success
2761 public static function removeFromGroups($contact_id)
2763 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2767 * Is the contact a forum?
2769 * @param integer $contactid ID of the contact
2771 * @return boolean "true" if it is a forum
2773 public static function isForum($contactid)
2775 $fields = ['forum', 'prv'];
2776 $condition = ['id' => $contactid];
2777 $contact = DBA::selectFirst('contact', $fields, $condition);
2778 if (!DBA::isResult($contact)) {
2783 return ($contact['forum'] || $contact['prv']);
2787 * Can the remote contact receive private messages?
2789 * @param array $contact
2792 public static function canReceivePrivateMessages(array $contact)
2794 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2795 $self = $contact['self'] ?? false;
2797 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;