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 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274 * @throws \ImagickException
276 public static function getBasepath($url)
278 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
279 if (!empty($contact['baseurl'])) {
280 return $contact['baseurl'];
283 self::updateFromProbeByURL($url, true);
285 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
286 if (!empty($contact['baseurl'])) {
287 return $contact['baseurl'];
294 * Check if the given contact url is on the same machine
296 * @param string $url The contact link
298 * @return boolean Is it the same machine?
300 public static function isLocal($url)
302 return Strings::compareLink(self::getBasepath($url), System::baseUrl());
307 * Returns the public contact id of the given user id
309 * @param integer $uid User ID
311 * @return integer|boolean Public contact id for given user id
314 public static function getPublicIdByUserId($uid)
316 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
317 if (!DBA::isResult($self)) {
320 return self::getIdForURL($self['url'], 0, true);
324 * @brief Returns the contact id for the user and the public contact id for a given contact id
326 * @param int $cid Either public contact id or user's contact id
327 * @param int $uid User ID
329 * @return array with public and user's contact id
330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 public static function getPublicAndUserContacID($cid, $uid)
335 if (empty($uid) || empty($cid)) {
339 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
340 if (!DBA::isResult($contact)) {
344 // We quit when the user id don't match the user id of the provided contact
345 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
349 if ($contact['uid'] != 0) {
350 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
354 $ucid = $contact['id'];
356 $pcid = $contact['id'];
357 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
360 return ['public' => $pcid, 'user' => $ucid];
364 * Returns contact details for a given contact id in combination with a user id
366 * @param int $cid A contact ID
367 * @param int $uid The User ID
368 * @param array $fields The selected fields for the contact
370 * @return array The contact details
374 public static function getContactForUser($cid, $uid, array $fields = [])
376 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
378 if (!DBA::isResult($contact)) {
386 * @brief Block contact id for user id
388 * @param int $cid Either public contact id or user's contact id
389 * @param int $uid User ID
390 * @param boolean $blocked Is the contact blocked or unblocked?
393 public static function setBlockedForUser($cid, $uid, $blocked)
395 $cdata = self::getPublicAndUserContacID($cid, $uid);
400 if ($cdata['user'] != 0) {
401 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
404 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
407 // Blocked contact can't be in any group
408 self::removeFromGroups($cid);
413 * @brief Returns "block" state for contact id and user id
415 * @param int $cid Either public contact id or user's contact id
416 * @param int $uid User ID
418 * @return boolean is the contact id blocked for the given user?
421 public static function isBlockedByUser($cid, $uid)
423 $cdata = self::getPublicAndUserContacID($cid, $uid);
428 $public_blocked = false;
430 if (!empty($cdata['public'])) {
431 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
432 if (DBA::isResult($public_contact)) {
433 $public_blocked = $public_contact['blocked'];
437 $user_blocked = $public_blocked;
439 if (!empty($cdata['user'])) {
440 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
441 if (DBA::isResult($user_contact)) {
442 $user_blocked = $user_contact['blocked'];
446 if ($user_blocked != $public_blocked) {
447 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
450 return $user_blocked;
454 * @brief Ignore contact id for user id
456 * @param int $cid Either public contact id or user's contact id
457 * @param int $uid User ID
458 * @param boolean $ignored Is the contact ignored or unignored?
461 public static function setIgnoredForUser($cid, $uid, $ignored)
463 $cdata = self::getPublicAndUserContacID($cid, $uid);
468 if ($cdata['user'] != 0) {
469 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
472 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
476 * @brief Returns "ignore" state for contact id and user id
478 * @param int $cid Either public contact id or user's contact id
479 * @param int $uid User ID
481 * @return boolean is the contact id ignored for the given user?
484 public static function isIgnoredByUser($cid, $uid)
486 $cdata = self::getPublicAndUserContacID($cid, $uid);
491 $public_ignored = false;
493 if (!empty($cdata['public'])) {
494 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
495 if (DBA::isResult($public_contact)) {
496 $public_ignored = $public_contact['ignored'];
500 $user_ignored = $public_ignored;
502 if (!empty($cdata['user'])) {
503 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
504 if (DBA::isResult($user_contact)) {
505 $user_ignored = $user_contact['readonly'];
509 if ($user_ignored != $public_ignored) {
510 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
513 return $user_ignored;
517 * @brief Set "collapsed" for contact id and user id
519 * @param int $cid Either public contact id or user's contact id
520 * @param int $uid User ID
521 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
524 public static function setCollapsedForUser($cid, $uid, $collapsed)
526 $cdata = self::getPublicAndUserContacID($cid, $uid);
531 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
535 * @brief Returns "collapsed" state for contact id and user id
537 * @param int $cid Either public contact id or user's contact id
538 * @param int $uid User ID
540 * @return boolean is the contact id blocked for the given user?
541 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
542 * @throws \ImagickException
544 public static function isCollapsedByUser($cid, $uid)
546 $cdata = self::getPublicAndUserContacID($cid, $uid);
553 if (!empty($cdata['public'])) {
554 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
555 if (DBA::isResult($public_contact)) {
556 $collapsed = $public_contact['collapsed'];
564 * @brief Returns a list of contacts belonging in a group
570 public static function getByGroupId($gid)
575 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
577 INNER JOIN `group_member`
578 ON `contact`.`id` = `group_member`.`contact-id`
580 AND `contact`.`uid` = ?
581 AND NOT `contact`.`self`
582 AND NOT `contact`.`deleted`
583 AND NOT `contact`.`blocked`
584 AND NOT `contact`.`pending`
585 ORDER BY `contact`.`name` ASC',
590 if (DBA::isResult($stmt)) {
591 $return = DBA::toArray($stmt);
599 * @brief Returns the count of OStatus contacts in a group
605 public static function getOStatusCountByGroupId($gid)
609 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
611 INNER JOIN `group_member`
612 ON `contact`.`id` = `group_member`.`contact-id`
614 AND `contact`.`uid` = ?
615 AND `contact`.`network` = ?
616 AND `contact`.`notify` != ""',
621 $return = $contacts['count'];
628 * Creates the self-contact for the provided user id
631 * @return bool Operation success
632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
634 public static function createSelfFromUserId($uid)
636 // Only create the entry if it doesn't exist yet
637 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
641 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
642 if (!DBA::isResult($user)) {
646 $return = DBA::insert('contact', [
647 'uid' => $user['uid'],
648 'created' => DateTimeFormat::utcNow(),
650 'name' => $user['username'],
651 'nick' => $user['nickname'],
652 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
653 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
654 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
657 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
658 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
659 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
660 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
661 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
662 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
663 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
664 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
665 'name-date' => DateTimeFormat::utcNow(),
666 'uri-date' => DateTimeFormat::utcNow(),
667 'avatar-date' => DateTimeFormat::utcNow(),
675 * Updates the self-contact for the provided user id
678 * @param boolean $update_avatar Force the avatar update
679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
681 public static function updateSelfFromUserID($uid, $update_avatar = false)
683 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
684 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
685 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
686 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
687 if (!DBA::isResult($self)) {
691 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
692 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
693 if (!DBA::isResult($user)) {
697 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
698 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
699 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
700 if (!DBA::isResult($profile)) {
704 $file_suffix = 'jpg';
706 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
707 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
708 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
709 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
710 'xmpp' => $profile['xmpp']];
712 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
713 if (DBA::isResult($avatar)) {
714 if ($update_avatar) {
715 $fields['avatar-date'] = DateTimeFormat::utcNow();
718 // Creating the path to the avatar, beginning with the file suffix
719 $types = Image::supportedTypes();
720 if (isset($types[$avatar['type']])) {
721 $file_suffix = $types[$avatar['type']];
724 // We are adding a timestamp value so that other systems won't use cached content
725 $timestamp = strtotime($fields['avatar-date']);
727 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
728 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
730 $fields['photo'] = $prefix . '4' . $suffix;
731 $fields['thumb'] = $prefix . '5' . $suffix;
732 $fields['micro'] = $prefix . '6' . $suffix;
734 // We hadn't found a photo entry, so we use the default avatar
735 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
736 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
737 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
740 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
741 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
742 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
743 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
745 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
746 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
747 $fields['nurl'] = Strings::normaliseLink($fields['url']);
748 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
749 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
750 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
751 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
752 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
753 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
757 foreach ($fields as $field => $content) {
758 if ($self[$field] != $content) {
764 if ($fields['name'] != $self['name']) {
765 $fields['name-date'] = DateTimeFormat::utcNow();
767 $fields['updated'] = DateTimeFormat::utcNow();
768 DBA::update('contact', $fields, ['id' => $self['id']]);
770 // Update the public contact as well
771 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
773 // Update the profile
774 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
775 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
776 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
781 * @brief Marks a contact for removal
783 * @param int $id contact id
785 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
787 public static function remove($id)
789 // We want just to make sure that we don't delete our "self" contact
790 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
791 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
795 // Archive the contact
796 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
798 // Delete it in the background
799 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
803 * @brief Sends an unfriend message. Does not remove the contact
805 * @param array $user User unfriending
806 * @param array $contact Contact unfriended
807 * @param boolean $dissolve Remove the contact on the remote side
809 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
810 * @throws \ImagickException
812 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
814 if (empty($contact['network'])) {
818 $protocol = $contact['network'];
819 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
820 $protocol = Protocol::ACTIVITYPUB;
823 if (($protocol == Protocol::DFRN) && $dissolve) {
824 DFRN::deliver($user, $contact, 'placeholder', true);
825 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
826 // create an unfollow slap
828 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
829 $item['follow'] = $contact["url"];
834 $item['attach'] = '';
835 $slap = OStatus::salmon($item, $user);
837 if (!empty($contact['notify'])) {
838 Salmon::slapper($user, $contact['notify'], $slap);
840 } elseif ($protocol == Protocol::DIASPORA) {
841 Diaspora::sendUnshare($user, $contact);
842 } elseif ($protocol == Protocol::ACTIVITYPUB) {
843 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
846 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
852 * @brief Marks a contact for archival after a communication issue delay
854 * Contact has refused to recognise us as a friend. We will start a countdown.
855 * If they still don't recognise us in 32 days, the relationship is over,
856 * and we won't waste any more time trying to communicate with them.
857 * This provides for the possibility that their database is temporarily messed
858 * up or some other transient event and that there's a possibility we could recover from it.
860 * @param array $contact contact to mark for archival
862 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
864 public static function markForArchival(array $contact)
866 if (!isset($contact['url']) && !empty($contact['id'])) {
867 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
868 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
869 if (!DBA::isResult($contact)) {
872 } elseif (!isset($contact['url'])) {
873 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
876 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
878 // Contact already archived or "self" contact? => nothing to do
879 if ($contact['archive'] || $contact['self']) {
883 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
884 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
885 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
888 * We really should send a notification to the owner after 2-3 weeks
889 * so they won't be surprised when the contact vanishes and can take
890 * remedial action if this was a serious mistake or glitch
893 /// @todo Check for contact vitality via probing
894 $archival_days = Config::get('system', 'archival_days', 32);
896 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
897 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
898 /* Relationship is really truly dead. archive them rather than
899 * delete, though if the owner tries to unarchive them we'll start
900 * the whole process over again.
902 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
903 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
904 GContact::updateFromPublicContactURL($contact['url']);
910 * @brief Cancels the archival countdown
912 * @see Contact::markForArchival()
914 * @param array $contact contact to be unmarked for archival
918 public static function unmarkForArchival(array $contact)
920 // Always unarchive the relay contact entry
921 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
922 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
923 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
924 DBA::update('contact', $fields, $condition);
927 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
928 $exists = DBA::exists('contact', $condition);
930 // We don't need to update, we never marked this contact for archival
935 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
937 if (!isset($contact['url']) && !empty($contact['id'])) {
938 $fields = ['id', 'url', 'batch'];
939 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
940 if (!DBA::isResult($contact)) {
945 // It's a miracle. Our dead contact has inexplicably come back to life.
946 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
947 DBA::update('contact', $fields, ['id' => $contact['id']]);
948 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
949 GContact::updateFromPublicContactURL($contact['url']);
953 * @brief Get contact data for a given profile link
955 * The function looks at several places (contact table and gcontact table) for the contact
956 * It caches its result for the same script execution to prevent duplicate calls
958 * @param string $url The profile link
959 * @param int $uid User id
960 * @param array $default If not data was found take this data as default value
962 * @return array Contact data
963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
965 public static function getDetailsByURL($url, $uid = -1, array $default = [])
977 if (isset($cache[$url][$uid])) {
978 return $cache[$url][$uid];
981 $ssl_url = str_replace('http://', 'https://', $url);
983 // Fetch contact data from the contact table for the given user
984 $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`,
985 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
986 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
987 $r = DBA::toArray($s);
989 // Fetch contact data from the contact table for the given user, checking with the alias
990 if (!DBA::isResult($r)) {
991 $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`,
992 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
993 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
994 $r = DBA::toArray($s);
997 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
998 if (!DBA::isResult($r)) {
999 $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`,
1000 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1001 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
1002 $r = DBA::toArray($s);
1005 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1006 if (!DBA::isResult($r)) {
1007 $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`,
1008 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1009 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
1010 $r = DBA::toArray($s);
1013 // Fetch the data from the gcontact table
1014 if (!DBA::isResult($r)) {
1015 $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`,
1016 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1017 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
1018 $r = DBA::toArray($s);
1021 if (DBA::isResult($r)) {
1022 // If there is more than one entry we filter out the connector networks
1023 if (count($r) > 1) {
1024 foreach ($r as $id => $result) {
1025 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1031 $profile = array_shift($r);
1033 // "bd" always contains the upcoming birthday of a contact.
1034 // "birthday" might contain the birthday including the year of birth.
1035 if ($profile["birthday"] > DBA::NULL_DATE) {
1036 $bd_timestamp = strtotime($profile["birthday"]);
1037 $month = date("m", $bd_timestamp);
1038 $day = date("d", $bd_timestamp);
1040 $current_timestamp = time();
1041 $current_year = date("Y", $current_timestamp);
1042 $current_month = date("m", $current_timestamp);
1043 $current_day = date("d", $current_timestamp);
1045 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1046 $current = $current_year . "-" . $current_month . "-" . $current_day;
1048 if ($profile["bd"] < $current) {
1049 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1052 $profile["bd"] = DBA::NULL_DATE;
1055 $profile = $default;
1058 if (empty($profile["photo"]) && isset($default["photo"])) {
1059 $profile["photo"] = $default["photo"];
1062 if (empty($profile["name"]) && isset($default["name"])) {
1063 $profile["name"] = $default["name"];
1066 if (empty($profile["network"]) && isset($default["network"])) {
1067 $profile["network"] = $default["network"];
1070 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1071 $profile["thumb"] = $profile["photo"];
1074 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1075 $profile["micro"] = $profile["thumb"];
1078 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1079 && in_array($profile["network"], Protocol::FEDERATED)
1081 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1084 // Show contact details of Diaspora contacts only if connected
1085 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1086 $profile["location"] = "";
1087 $profile["about"] = "";
1088 $profile["gender"] = "";
1089 $profile["birthday"] = DBA::NULL_DATE;
1092 $cache[$url][$uid] = $profile;
1098 * @brief Get contact data for a given address
1100 * The function looks at several places (contact table and gcontact table) for the contact
1102 * @param string $addr The profile link
1103 * @param int $uid User id
1105 * @return array Contact data
1106 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1107 * @throws \ImagickException
1109 public static function getDetailsByAddr($addr, $uid = -1)
1116 $uid = local_user();
1119 // Fetch contact data from the contact table for the given user
1120 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1121 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1122 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1126 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1127 if (!DBA::isResult($r)) {
1128 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1129 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1130 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1135 // Fetch the data from the gcontact table
1136 if (!DBA::isResult($r)) {
1137 $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`,
1138 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1139 FROM `gcontact` WHERE `addr` = '%s'",
1144 if (!DBA::isResult($r)) {
1145 $data = Probe::uri($addr);
1147 $profile = self::getDetailsByURL($data['url'], $uid);
1156 * @brief Returns the data array for the photo menu of a given contact
1158 * @param array $contact contact
1159 * @param int $uid optional, default 0
1161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1162 * @throws \ImagickException
1164 public static function photoMenu(array $contact, $uid = 0)
1169 $contact_drop_link = '';
1173 $uid = local_user();
1176 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1178 $profile_link = self::magicLink($contact['url']);
1179 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1184 // Look for our own contact if the uid doesn't match and isn't public
1185 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1186 if (DBA::isResult($contact_own)) {
1187 return self::photoMenu($contact_own, $uid);
1192 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1194 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1196 $profile_link = $contact['url'];
1199 if ($profile_link === 'mailbox') {
1204 $status_link = $profile_link . '?tab=status';
1205 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1206 $profile_link = $profile_link . '?tab=profile';
1209 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1210 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1213 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1214 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1217 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1219 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1221 if (!$contact['self']) {
1222 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1227 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1229 if (empty($contact['uid'])) {
1230 $connlnk = 'follow/?url=' . $contact['url'];
1232 'profile' => [L10n::t('View Profile'), $profile_link, true],
1233 'network' => [L10n::t('Network Posts'), $posts_link, false],
1234 'edit' => [L10n::t('View Contact'), $contact_url, false],
1235 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1239 'status' => [L10n::t('View Status'), $status_link, true],
1240 'profile' => [L10n::t('View Profile'), $profile_link, true],
1241 'photos' => [L10n::t('View Photos'), $photos_link, true],
1242 'network' => [L10n::t('Network Posts'), $posts_link, false],
1243 'edit' => [L10n::t('View Contact'), $contact_url, false],
1244 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1245 'pm' => [L10n::t('Send PM'), $pm_url, false],
1246 'poke' => [L10n::t('Poke'), $poke_link, false],
1249 if (!empty($contact['pending'])) {
1250 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1251 if (DBA::isResult($intro)) {
1252 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1257 $args = ['contact' => $contact, 'menu' => &$menu];
1259 Hook::callAll('contact_photo_menu', $args);
1261 $menucondensed = [];
1263 foreach ($menu as $menuname => $menuitem) {
1264 if ($menuitem[1] != '') {
1265 $menucondensed[$menuname] = $menuitem;
1269 return $menucondensed;
1273 * @brief Returns ungrouped contact count or list for user
1275 * Returns either the total number of ungrouped contacts for the given user
1276 * id or a paginated list of ungrouped contacts.
1278 * @param int $uid uid
1280 * @throws \Exception
1282 public static function getUngroupedList($uid)
1292 SELECT DISTINCT(`contact-id`)
1294 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1295 WHERE `group`.`uid` = %d
1296 )", intval($uid), intval($uid));
1300 * Have a look at all contact tables for a given profile url.
1301 * This function works as a replacement for probing the contact.
1303 * @param string $url Contact URL
1304 * @param integer $cid Contact ID
1306 * @return array Contact array in the "probe" structure
1308 private static function getProbeDataFromDatabase($url, $cid = null)
1310 // The link could be provided as http although we stored it as https
1311 $ssl_url = str_replace('http://', 'https://', $url);
1313 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1314 'photo', 'keywords', 'location', 'about', 'network',
1315 'priority', 'batch', 'request', 'confirm', 'poco'];
1318 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1319 if (DBA::isResult($data)) {
1324 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1326 if (!DBA::isResult($data)) {
1327 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1328 $data = DBA::selectFirst('contact', $fields, $condition);
1331 if (DBA::isResult($data)) {
1332 // For security reasons we don't fetch key data from our users
1333 $data["pubkey"] = '';
1337 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1338 'photo', 'keywords', 'location', 'about', 'network'];
1339 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1341 if (!DBA::isResult($data)) {
1342 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1343 $data = DBA::selectFirst('contact', $fields, $condition);
1346 if (DBA::isResult($data)) {
1347 $data["pubkey"] = '';
1349 $data["priority"] = 0;
1350 $data["batch"] = '';
1351 $data["request"] = '';
1352 $data["confirm"] = '';
1357 $data = ActivityPub::probeProfile($url, false);
1358 if (!empty($data)) {
1362 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1363 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1364 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1366 if (!DBA::isResult($data)) {
1367 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1368 $data = DBA::selectFirst('contact', $fields, $condition);
1371 if (DBA::isResult($data)) {
1372 $data["pubkey"] = '';
1373 $data["keywords"] = '';
1374 $data["location"] = '';
1375 $data["about"] = '';
1384 * @brief Fetch the contact id for a given URL and user
1386 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1387 * `addr` or `alias`.
1389 * If there's no record and we aren't looking for a public contact, we quit.
1390 * If there's one, we check that it isn't time to update the picture else we
1391 * directly return the found contact id.
1393 * Second, we probe the provided $url whether it's http://server.tld/profile or
1394 * nick@server.tld. We quit if we can't get any info back.
1396 * Third, we create the contact record if it doesn't exist
1398 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1399 * if there's any updates
1401 * @param string $url Contact URL
1402 * @param integer $uid The user id for the contact (0 = public contact)
1403 * @param boolean $no_update Don't update the contact
1404 * @param array $default Default value for creating the contact when every else fails
1405 * @param boolean $in_loop Internally used variable to prevent an endless loop
1407 * @return integer Contact ID
1408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1409 * @throws \ImagickException
1411 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1413 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1421 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1422 // We first try the nurl (http://server.tld/nick), most common case
1423 $fields = ['id', 'avatar', 'updated', 'network'];
1424 $options = ['order' => ['id']];
1425 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1427 // Then the addr (nick@server.tld)
1428 if (!DBA::isResult($contact)) {
1429 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1432 // Then the alias (which could be anything)
1433 if (!DBA::isResult($contact)) {
1434 // The link could be provided as http although we stored it as https
1435 $ssl_url = str_replace('http://', 'https://', $url);
1436 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1437 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1440 if (DBA::isResult($contact)) {
1441 $contact_id = $contact["id"];
1443 // Update the contact every 7 days
1444 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1446 // We force the update if the avatar is empty
1447 if (empty($contact['avatar'])) {
1448 $update_contact = true;
1451 // Update the contact in the background if needed but it is called by the frontend
1452 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1453 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1456 if (!$update_contact || $no_update) {
1459 } elseif ($uid != 0) {
1460 // Non-existing user-specific contact, exiting
1464 if ($no_update && empty($default)) {
1465 // When we don't want to update, we look if we know this contact in any way
1466 $data = self::getProbeDataFromDatabase($url, $contact_id);
1467 $background_update = true;
1468 } elseif ($no_update && !empty($default['network'])) {
1469 // If there are default values, take these
1471 $background_update = false;
1474 $background_update = false;
1478 $data = Probe::uri($url, "", $uid);
1479 // Ensure that there is a gserver entry
1480 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1481 PortableContact::checkServer($data['baseurl']);
1485 // Take the default values when probing failed
1486 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1487 $data = array_merge($data, $default);
1494 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1495 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1501 'created' => DateTimeFormat::utcNow(),
1502 'url' => $data['url'],
1503 'nurl' => Strings::normaliseLink($data['url']),
1504 'addr' => defaults($data, 'addr', ''),
1505 'alias' => defaults($data, 'alias', ''),
1506 'notify' => defaults($data, 'notify', ''),
1507 'poll' => defaults($data, 'poll', ''),
1508 'name' => defaults($data, 'name', ''),
1509 'nick' => defaults($data, 'nick', ''),
1510 'photo' => defaults($data, 'photo', ''),
1511 'keywords' => defaults($data, 'keywords', ''),
1512 'location' => defaults($data, 'location', ''),
1513 'about' => defaults($data, 'about', ''),
1514 'network' => $data['network'],
1515 'pubkey' => defaults($data, 'pubkey', ''),
1516 'rel' => self::SHARING,
1517 'priority' => defaults($data, 'priority', 0),
1518 'batch' => defaults($data, 'batch', ''),
1519 'request' => defaults($data, 'request', ''),
1520 'confirm' => defaults($data, 'confirm', ''),
1521 'poco' => defaults($data, 'poco', ''),
1522 'baseurl' => defaults($data, 'baseurl', ''),
1523 'name-date' => DateTimeFormat::utcNow(),
1524 'uri-date' => DateTimeFormat::utcNow(),
1525 'avatar-date' => DateTimeFormat::utcNow(),
1531 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1533 // Before inserting we do check if the entry does exist now.
1534 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1535 if (!DBA::isResult($contact)) {
1536 Logger::info('Create new contact', $fields);
1538 self::insert($fields);
1540 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1541 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1542 if (!DBA::isResult($contact)) {
1543 Logger::info('Contact creation failed', $fields);
1548 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1551 $contact_id = $contact["id"];
1554 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1555 self::updateAvatar($data['photo'], $uid, $contact_id);
1558 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1559 if ($background_update) {
1560 // Update in the background when we fetched the data solely from the database
1561 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1563 // Else do a direct update
1564 self::updateFromProbe($contact_id, '', false);
1566 // Update the gcontact entry
1568 GContact::updateFromPublicContactID($contact_id);
1572 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1573 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1575 // This condition should always be true
1576 if (!DBA::isResult($contact)) {
1581 'url' => $data['url'],
1582 'nurl' => Strings::normaliseLink($data['url']),
1583 'updated' => DateTimeFormat::utcNow()
1586 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1588 foreach ($fields as $field) {
1589 $updated[$field] = defaults($data, $field, $contact[$field]);
1592 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1593 $updated['uri-date'] = DateTimeFormat::utcNow();
1596 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1597 $updated['name-date'] = DateTimeFormat::utcNow();
1600 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1607 * @brief Checks if the contact is archived
1609 * @param int $cid contact id
1611 * @return boolean Is the contact archived?
1612 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1614 public static function isArchived(int $cid)
1620 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1621 if (!DBA::isResult($contact)) {
1625 if ($contact['archive']) {
1629 // Check status of ActivityPub endpoints
1630 $apcontact = APContact::getByURL($contact['url'], false);
1631 if (!empty($apcontact)) {
1632 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1636 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1641 // Check status of Diaspora endpoints
1642 if (!empty($contact['batch'])) {
1643 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1644 return DBA::exists('contact', $condition);
1651 * @brief Checks if the contact is blocked
1653 * @param int $cid contact id
1655 * @return boolean Is the contact blocked?
1656 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1658 public static function isBlocked($cid)
1664 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1665 if (!DBA::isResult($blocked)) {
1669 if (Network::isUrlBlocked($blocked['url'])) {
1673 return (bool) $blocked['blocked'];
1677 * @brief Checks if the contact is hidden
1679 * @param int $cid contact id
1681 * @return boolean Is the contact hidden?
1682 * @throws \Exception
1684 public static function isHidden($cid)
1690 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1691 if (!DBA::isResult($hidden)) {
1694 return (bool) $hidden['hidden'];
1698 * @brief Returns posts from a given contact url
1700 * @param string $contact_url Contact URL
1702 * @param bool $thread_mode
1703 * @param int $update
1704 * @return string posts in HTML
1705 * @throws \Exception
1707 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1709 $a = self::getApp();
1711 $cid = self::getIdForURL($contact_url);
1713 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1714 if (!DBA::isResult($contact)) {
1718 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1719 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1721 $sql = "`item`.`uid` = ?";
1724 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1727 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1728 $cid, GRAVITY_PARENT, local_user()];
1730 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1731 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1734 $pager = new Pager($a->query_string);
1736 $params = ['order' => ['received' => true],
1737 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1740 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1742 $items = Item::inArray($r);
1744 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1746 $r = Item::selectForUser(local_user(), [], $condition, $params);
1748 $items = Item::inArray($r);
1750 $o = conversation($a, $items, $pager, 'contact-posts', false);
1754 $o .= $pager->renderMinimal(count($items));
1761 * @brief Returns the account type name
1763 * The function can be called with either the user or the contact array
1765 * @param array $contact contact or user array
1768 public static function getAccountType(array $contact)
1770 // There are several fields that indicate that the contact or user is a forum
1771 // "page-flags" is a field in the user table,
1772 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1773 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1774 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1775 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1776 || (isset($contact['forum']) && intval($contact['forum']))
1777 || (isset($contact['prv']) && intval($contact['prv']))
1778 || (isset($contact['community']) && intval($contact['community']))
1780 $type = self::TYPE_COMMUNITY;
1782 $type = self::TYPE_PERSON;
1785 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1786 if (isset($contact["contact-type"])) {
1787 $type = $contact["contact-type"];
1790 if (isset($contact["account-type"])) {
1791 $type = $contact["account-type"];
1795 case self::TYPE_ORGANISATION:
1796 $account_type = L10n::t("Organisation");
1799 case self::TYPE_NEWS:
1800 $account_type = L10n::t('News');
1803 case self::TYPE_COMMUNITY:
1804 $account_type = L10n::t("Forum");
1812 return $account_type;
1816 * @brief Blocks a contact
1820 * @throws \Exception
1822 public static function block($cid, $reason = null)
1824 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1830 * @brief Unblocks a contact
1834 * @throws \Exception
1836 public static function unblock($cid)
1838 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1844 * @brief Updates the avatar links in a contact only if needed
1846 * @param string $avatar Link to avatar picture
1847 * @param int $uid User id of contact owner
1848 * @param int $cid Contact id
1849 * @param bool $force force picture update
1851 * @return array Returns array of the different avatar sizes
1852 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1853 * @throws \ImagickException
1855 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1857 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1858 if (!DBA::isResult($contact)) {
1861 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1864 if (($contact["avatar"] != $avatar) || $force) {
1865 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1868 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1869 DBA::update('contact', $fields, ['id' => $cid]);
1871 // Update the public contact (contact id = 0)
1873 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1874 if (DBA::isResult($pcontact)) {
1875 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1887 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1889 * @param integer $id contact id
1890 * @param integer $uid user id
1891 * @param string $url The profile URL of the contact
1892 * @param array $fields The fields that are updated
1894 * @throws \Exception
1896 private static function updateContact($id, $uid, $url, array $fields)
1898 if (!DBA::update('contact', $fields, ['id' => $id])) {
1899 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1903 // Search for duplicated contacts and get rid of them
1904 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1908 // Update the corresponding gcontact entry
1909 GContact::updateFromPublicContactID($id);
1911 // Archive or unarchive the contact. We only need to do this for the public contact.
1912 // The archive/unarchive function will update the personal contacts by themselves.
1913 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1914 if (!DBA::isResult($contact)) {
1915 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1919 if (!empty($fields['success_update'])) {
1920 self::unmarkForArchival($contact);
1921 } elseif (!empty($fields['failure_update'])) {
1922 self::markForArchival($contact);
1925 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1927 // These contacts are sharing with us, we don't poll them.
1928 // This means that we don't set the update fields in "OnePoll.php".
1929 $condition['rel'] = self::SHARING;
1930 DBA::update('contact', $fields, $condition);
1932 unset($fields['last-update']);
1933 unset($fields['success_update']);
1934 unset($fields['failure_update']);
1936 if (empty($fields)) {
1940 // We are polling these contacts, so we mustn't set the update fields here.
1941 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1942 DBA::update('contact', $fields, $condition);
1946 * @brief Remove duplicated contacts
1948 * @param string $nurl Normalised contact url
1949 * @param integer $uid User id
1951 * @throws \Exception
1953 public static function removeDuplicates(string $nurl, int $uid)
1955 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1956 $count = DBA::count('contact', $condition);
1961 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1962 if (!DBA::isResult($first_contact)) {
1963 // Shouldn't happen - so we handle it
1967 $first = $first_contact['id'];
1968 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1969 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1970 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1971 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1975 // Find all duplicates
1976 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1977 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1978 while ($duplicate = DBA::fetch($duplicates)) {
1979 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1983 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1985 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1990 * @param integer $id contact id
1991 * @param string $network Optional network we are probing for
1992 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1995 * @throws \ImagickException
1997 public static function updateFromProbe($id, $network = '', $force = false)
2000 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2001 This will reliably kill your communication with old Friendica contacts.
2004 // These fields aren't updated by this routine:
2005 // 'xmpp', 'sensitive'
2007 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2008 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2009 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2010 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2011 if (!DBA::isResult($contact)) {
2015 $uid = $contact['uid'];
2016 unset($contact['uid']);
2018 $pubkey = $contact['pubkey'];
2019 unset($contact['pubkey']);
2021 $contact['photo'] = $contact['avatar'];
2022 unset($contact['avatar']);
2024 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2026 $updated = DateTimeFormat::utcNow();
2028 // We must not try to update relay contacts via probe. They are no real contacts.
2029 // We check after the probing to be able to correct falsely detected contact types.
2030 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2031 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2032 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2033 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2037 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2038 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2039 if ($force && ($uid == 0)) {
2040 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2045 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2046 $ret['unsearchable'] = $ret['hide'];
2049 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2050 $ret['forum'] = false;
2051 $ret['prv'] = false;
2052 $ret['contact-type'] = $ret['account-type'];
2053 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2054 $apcontact = APContact::getByURL($ret['url'], false);
2055 if (isset($apcontact['manually-approve'])) {
2056 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2057 $ret['prv'] = (bool)!$ret['forum'];
2062 $new_pubkey = $ret['pubkey'];
2066 // make sure to not overwrite existing values with blank entries except some technical fields
2067 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2068 foreach ($ret as $key => $val) {
2069 if (!array_key_exists($key, $contact)) {
2071 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2072 $ret[$key] = $contact[$key];
2073 } elseif ($ret[$key] != $contact[$key]) {
2078 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2079 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2084 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2089 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2090 $ret['updated'] = $updated;
2092 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2093 if (empty($pubkey) && !empty($new_pubkey)) {
2094 $ret['pubkey'] = $new_pubkey;
2097 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2098 $ret['uri-date'] = DateTimeFormat::utcNow();
2101 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2102 $ret['name-date'] = $updated;
2105 if ($force && ($uid == 0)) {
2106 $ret['last-update'] = $updated;
2107 $ret['success_update'] = $updated;
2110 unset($ret['photo']);
2112 self::updateContact($id, $uid, $ret['url'], $ret);
2117 public static function updateFromProbeByURL($url, $force = false)
2119 $id = self::getIdForURL($url);
2125 self::updateFromProbe($id, '', $force);
2131 * Detects if a given contact array belongs to a legacy DFRN connection
2133 * @param array $contact
2136 public static function isLegacyDFRNContact($contact)
2138 // Newer Friendica contacts are connected via AP, then these fields aren't set
2139 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2143 * Detects the communication protocol for a given contact url.
2144 * This is used to detect Friendica contacts that we can communicate via AP.
2146 * @param string $url contact url
2147 * @param string $network Network of that contact
2148 * @return string with protocol
2150 public static function getProtocol($url, $network)
2152 if ($network != Protocol::DFRN) {
2156 $apcontact = APContact::getByURL($url);
2157 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2158 return Protocol::ACTIVITYPUB;
2165 * Takes a $uid and a url/handle and adds a new contact
2166 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2167 * dfrn_request page.
2169 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2172 * $return['success'] boolean true if successful
2173 * $return['message'] error text if success is false.
2175 * @brief Takes a $uid and a url/handle and adds a new contact
2177 * @param string $url
2178 * @param bool $interactive
2179 * @param string $network
2181 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2182 * @throws \ImagickException
2184 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2186 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2190 // remove ajax junk, e.g. Twitter
2191 $url = str_replace('/#!/', '/', $url);
2193 if (!Network::isUrlAllowed($url)) {
2194 $result['message'] = L10n::t('Disallowed profile URL.');
2198 if (Network::isUrlBlocked($url)) {
2199 $result['message'] = L10n::t('Blocked domain');
2204 $result['message'] = L10n::t('Connect URL missing.');
2208 $arr = ['url' => $url, 'contact' => []];
2210 Hook::callAll('follow', $arr);
2213 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2217 if (!empty($arr['contact']['name'])) {
2218 $ret = $arr['contact'];
2220 $ret = Probe::uri($url, $network, $uid, false);
2223 if (($network != '') && ($ret['network'] != $network)) {
2224 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2228 // check if we already have a contact
2229 // the poll url is more reliable than the profile url, as we may have
2230 // indirect links or webfinger links
2232 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2233 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2234 if (!DBA::isResult($contact)) {
2235 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2236 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2239 $protocol = self::getProtocol($url, $ret['network']);
2241 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2243 if (strlen($a->getURLPath())) {
2244 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2246 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2249 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2253 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2254 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2255 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2259 // This extra param just confuses things, remove it
2260 if ($protocol === Protocol::DIASPORA) {
2261 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2264 // do we have enough information?
2265 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2266 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2267 if (empty($ret['poll'])) {
2268 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2270 if (empty($ret['name'])) {
2271 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2273 if (empty($ret['url'])) {
2274 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2276 if (strpos($url, '@') !== false) {
2277 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2278 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2283 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2284 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2285 $ret['notify'] = '';
2288 if (!$ret['notify']) {
2289 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2292 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2294 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2296 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2298 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2300 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2304 if (DBA::isResult($contact)) {
2306 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2308 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2309 DBA::update('contact', $fields, ['id' => $contact['id']]);
2311 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2313 // create contact record
2316 'created' => DateTimeFormat::utcNow(),
2317 'url' => $ret['url'],
2318 'nurl' => Strings::normaliseLink($ret['url']),
2319 'addr' => $ret['addr'],
2320 'alias' => $ret['alias'],
2321 'batch' => $ret['batch'],
2322 'notify' => $ret['notify'],
2323 'poll' => $ret['poll'],
2324 'poco' => $ret['poco'],
2325 'name' => $ret['name'],
2326 'nick' => $ret['nick'],
2327 'network' => $ret['network'],
2328 'baseurl' => $ret['baseurl'],
2329 'protocol' => $protocol,
2330 'pubkey' => $ret['pubkey'],
2331 'rel' => $new_relation,
2332 'priority'=> $ret['priority'],
2333 'writable'=> $writeable,
2334 'hidden' => $hidden,
2337 'pending' => $pending,
2342 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2343 if (!DBA::isResult($contact)) {
2344 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2348 $contact_id = $contact['id'];
2349 $result['cid'] = $contact_id;
2351 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2353 // Update the avatar
2354 self::updateAvatar($ret['photo'], $uid, $contact_id);
2356 // pull feed and consume it, which should subscribe to the hub.
2358 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2360 $owner = User::getOwnerDataById($uid);
2362 if (DBA::isResult($owner)) {
2363 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2364 // create a follow slap
2366 $item['verb'] = ACTIVITY_FOLLOW;
2367 $item['follow'] = $contact["url"];
2369 $item['title'] = '';
2372 $item['attach'] = '';
2374 $slap = OStatus::salmon($item, $owner);
2376 if (!empty($contact['notify'])) {
2377 Salmon::slapper($owner, $contact['notify'], $slap);
2379 } elseif ($protocol == Protocol::DIASPORA) {
2380 $ret = Diaspora::sendShare($a->user, $contact);
2381 Logger::log('share returns: ' . $ret);
2382 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2383 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2384 if (empty($activity_id)) {
2385 // This really should never happen
2389 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2390 Logger::log('Follow returns: ' . $ret);
2394 $result['success'] = true;
2399 * @brief Updated contact's SSL policy
2401 * @param array $contact Contact array
2402 * @param string $new_policy New policy, valid: self,full
2404 * @return array Contact array with updated values
2405 * @throws \Exception
2407 public static function updateSslPolicy(array $contact, $new_policy)
2409 $ssl_changed = false;
2410 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2411 $ssl_changed = true;
2412 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2413 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2414 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2415 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2416 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2417 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2420 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2421 $ssl_changed = true;
2422 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2423 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2424 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2425 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2426 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2427 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2431 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2432 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2433 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2434 DBA::update('contact', $fields, ['id' => $contact['id']]);
2441 * @param array $importer Owner (local user) data
2442 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2443 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2444 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2445 * @param string $note Introduction additional message
2446 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2447 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2448 * @throws \ImagickException
2450 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2452 // Should always be set
2453 if (empty($datarray['author-id'])) {
2457 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2458 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2459 if (!DBA::isResult($pub_contact)) {
2460 // Should never happen
2464 // Contact is blocked at node-level
2465 if (self::isBlocked($datarray['author-id'])) {
2469 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2470 $name = $pub_contact['name'];
2471 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2472 $nick = $pub_contact['nick'];
2473 $network = $pub_contact['network'];
2475 // Ensure that we don't create a new contact when there already is one
2476 $cid = self::getIdForURL($url, $importer['uid']);
2478 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2481 if (!empty($contact)) {
2482 if (!empty($contact['pending'])) {
2483 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2487 // Contact is blocked at user-level
2488 if (!empty($contact['id']) && !empty($importer['id']) &&
2489 self::isBlockedByUser($contact['id'], $importer['id'])) {
2493 // Make sure that the existing contact isn't archived
2494 self::unmarkForArchival($contact);
2496 if (($contact['rel'] == self::SHARING)
2497 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2498 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2499 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2502 // Ensure to always have the correct network type, independent from the connection request method
2503 self::updateFromProbe($contact['id'], '', true);
2507 // send email notification to owner?
2508 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2509 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2513 // create contact record
2514 DBA::insert('contact', [
2515 'uid' => $importer['uid'],
2516 'created' => DateTimeFormat::utcNow(),
2518 'nurl' => Strings::normaliseLink($url),
2522 'network' => $network,
2523 'rel' => self::FOLLOWER,
2530 $contact_id = DBA::lastInsertId();
2532 // Ensure to always have the correct network type, independent from the connection request method
2533 self::updateFromProbe($contact_id, '', true);
2535 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2537 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2539 /// @TODO Encapsulate this into a function/method
2540 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2541 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2542 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2543 // create notification
2544 $hash = Strings::getRandomHex();
2546 if (is_array($contact_record)) {
2547 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2548 'blocked' => false, 'knowyou' => false, 'note' => $note,
2549 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2552 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2554 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2555 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2558 'type' => NOTIFY_INTRO,
2559 'notify_flags' => $user['notify-flags'],
2560 'language' => $user['language'],
2561 'to_name' => $user['username'],
2562 'to_email' => $user['email'],
2563 'uid' => $user['uid'],
2564 'link' => System::baseUrl() . '/notifications/intro',
2565 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2566 'source_link' => $contact_record['url'],
2567 'source_photo' => $contact_record['photo'],
2568 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2572 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2573 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2574 DBA::update('contact', ['pending' => false], $condition);
2583 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2585 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2586 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2588 Contact::remove($contact['id']);
2592 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2594 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2595 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2597 Contact::remove($contact['id']);
2602 * @brief Create a birthday event.
2604 * Update the year and the birthday.
2606 public static function updateBirthdays()
2610 AND `bd` > "0001-01-01"
2611 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2612 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2613 AND NOT `contact`.`pending`
2614 AND NOT `contact`.`hidden`
2615 AND NOT `contact`.`blocked`
2616 AND NOT `contact`.`archive`
2617 AND NOT `contact`.`deleted`',
2622 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2624 while ($contact = DBA::fetch($contacts)) {
2625 Logger::log('update_contact_birthday: ' . $contact['bd']);
2627 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2629 if (Event::createBirthday($contact, $nextbd)) {
2633 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2634 ['id' => $contact['id']]
2641 * Remove the unavailable contact ids from the provided list
2643 * @param array $contact_ids Contact id list
2644 * @throws \Exception
2646 public static function pruneUnavailable(array &$contact_ids)
2648 if (empty($contact_ids)) {
2652 $str = DBA::escape(implode(',', $contact_ids));
2654 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2657 while($contact = DBA::fetch($stmt)) {
2658 $return[] = $contact['id'];
2663 $contact_ids = $return;
2667 * @brief Returns a magic link to authenticate remote visitors
2669 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2671 * @param string $contact_url The address of the target contact profile
2672 * @param string $url An url that we will be redirected to after the authentication
2674 * @return string with "redir" link
2675 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2676 * @throws \ImagickException
2678 public static function magicLink($contact_url, $url = '')
2680 if (!local_user() && !remote_user()) {
2681 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2684 $data = self::getProbeDataFromDatabase($contact_url);
2686 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2689 // Prevents endless loop in case only a non-public contact exists for the contact URL
2690 unset($data['uid']);
2692 return self::magicLinkByContact($data, $url ?: $contact_url);
2696 * @brief Returns a magic link to authenticate remote visitors
2698 * @param integer $cid The contact id of the target contact profile
2699 * @param string $url An url that we will be redirected to after the authentication
2701 * @return string with "redir" link
2702 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2703 * @throws \ImagickException
2705 public static function magicLinkbyId($cid, $url = '')
2707 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2709 return self::magicLinkByContact($contact, $url);
2713 * @brief Returns a magic link to authenticate remote visitors
2715 * @param array $contact The contact array with "uid", "network" and "url"
2716 * @param string $url An url that we will be redirected to after the authentication
2718 * @return string with "redir" link
2719 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2720 * @throws \ImagickException
2722 public static function magicLinkByContact($contact, $url = '')
2724 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2726 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2727 return $destination;
2730 // Only redirections to the same host do make sense
2731 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2735 if (!empty($contact['uid'])) {
2736 return self::magicLink($contact['url'], $url);
2739 if (empty($contact['id'])) {
2740 return $destination;
2743 $redirect = 'redir/' . $contact['id'];
2746 $redirect .= '?url=' . $url;
2753 * Remove a contact from all groups
2755 * @param integer $contact_id
2757 * @return boolean Success
2759 public static function removeFromGroups($contact_id)
2761 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2765 * Is the contact a forum?
2767 * @param integer $contactid ID of the contact
2769 * @return boolean "true" if it is a forum
2771 public static function isForum($contactid)
2773 $fields = ['forum', 'prv'];
2774 $condition = ['id' => $contactid];
2775 $contact = DBA::selectFirst('contact', $fields, $condition);
2776 if (!DBA::isResult($contact)) {
2781 return ($contact['forum'] || $contact['prv']);
2785 * Can the remote contact receive private messages?
2787 * @param array $contact
2790 public static function canReceivePrivateMessages(array $contact)
2792 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2793 $self = $contact['self'] ?? false;
2795 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;