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\Session;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBA;
19 use Friendica\Network\Probe;
20 use Friendica\Object\Image;
21 use Friendica\Protocol\ActivityPub;
22 use Friendica\Protocol\DFRN;
23 use Friendica\Protocol\Diaspora;
24 use Friendica\Protocol\OStatus;
25 use Friendica\Protocol\PortableContact;
26 use Friendica\Protocol\Salmon;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\Network;
29 use Friendica\Util\Strings;
32 * @brief functions for interacting with a contact
34 class Contact extends BaseObject
37 * @deprecated since version 2019.03
38 * @see User::PAGE_FLAGS_NORMAL
40 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
42 * @deprecated since version 2019.03
43 * @see User::PAGE_FLAGS_SOAPBOX
45 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
47 * @deprecated since version 2019.03
48 * @see User::PAGE_FLAGS_COMMUNITY
50 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
52 * @deprecated since version 2019.03
53 * @see User::PAGE_FLAGS_FREELOVE
55 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
57 * @deprecated since version 2019.03
58 * @see User::PAGE_FLAGS_BLOG
60 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_PRVGROUP
65 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
73 * TYPE_UNKNOWN - the account has been imported from gcontact where this is the default type value
75 * TYPE_PERSON - the account belongs to a person
76 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
78 * TYPE_ORGANISATION - the account belongs to an organisation
79 * Associated page type: PAGE_SOAPBOX
81 * TYPE_NEWS - the account is a news reflector
82 * Associated page type: PAGE_SOAPBOX
84 * TYPE_COMMUNITY - the account is community forum
85 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
87 * TYPE_RELAY - the account is a relay
88 * This will only be assigned to contacts, not to user accounts
91 const TYPE_UNKNOWN = -1;
92 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
93 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
94 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
95 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
96 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
115 * @param array $fields Array of selected fields, empty for all
116 * @param array $condition Array of fields for condition
117 * @param array $params Array of several parameters
121 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
123 return DBA::selectToArray('contact', $fields, $condition, $params);
127 * @param array $fields Array of selected fields, empty for all
128 * @param array $condition Array of fields for condition
129 * @param array $params Array of several parameters
133 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
135 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
141 * Insert a row into the contact table
142 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
144 * @param array $fields field array
145 * @param bool $on_duplicate_update Do an update on a duplicate entry
147 * @return boolean was the insert successful?
150 public static function insert(array $fields, bool $on_duplicate_update = false)
152 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
153 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
154 if (!DBA::isResult($contact)) {
159 // Search for duplicated contacts and get rid of them
160 self::removeDuplicates($contact['nurl'], $contact['uid']);
166 * @param integer $id Contact ID
167 * @param array $fields Array of selected fields, empty for all
168 * @return array|boolean Contact record if it exists, false otherwise
171 public static function getById($id, $fields = [])
173 return DBA::selectFirst('contact', $fields, ['id' => $id]);
177 * @brief Tests if the given contact is a follower
179 * @param int $cid Either public contact id or user's contact id
180 * @param int $uid User ID
182 * @return boolean is the contact id a follower?
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 public static function isFollower($cid, $uid)
188 if (self::isBlockedByUser($cid, $uid)) {
192 $cdata = self::getPublicAndUserContacID($cid, $uid);
193 if (empty($cdata['user'])) {
197 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
198 return DBA::exists('contact', $condition);
202 * @brief Tests if the given contact url is a follower
204 * @param string $url Contact URL
205 * @param int $uid User ID
207 * @return boolean is the contact id a follower?
208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
209 * @throws \ImagickException
211 public static function isFollowerByURL($url, $uid)
213 $cid = self::getIdForURL($url, $uid, true);
219 return self::isFollower($cid, $uid);
223 * @brief Tests if the given user follow the given contact
225 * @param int $cid Either public contact id or user's contact id
226 * @param int $uid User ID
228 * @return boolean is the contact url being followed?
229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 * @throws \ImagickException
232 public static function isSharing($cid, $uid)
234 if (self::isBlockedByUser($cid, $uid)) {
238 $cdata = self::getPublicAndUserContacID($cid, $uid);
239 if (empty($cdata['user'])) {
243 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
244 return DBA::exists('contact', $condition);
248 * @brief Tests if the given user follow the given contact url
250 * @param string $url Contact URL
251 * @param int $uid User ID
253 * @return boolean is the contact url being followed?
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 public static function isSharingByURL($url, $uid)
259 $cid = self::getIdForURL($url, $uid, true);
265 return self::isSharing($cid, $uid);
269 * @brief Get the basepath for a given contact link
271 * @param string $url The contact link
273 * @return string basepath
274 * @return boolean $dont_update Don't update the contact
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
278 public static function getBasepath($url, $dont_update = false)
280 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
281 if (!empty($contact['baseurl'])) {
282 return $contact['baseurl'];
283 } elseif ($dont_update) {
287 self::updateFromProbeByURL($url, true);
289 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
290 if (!empty($contact['baseurl'])) {
291 return $contact['baseurl'];
298 * Check if the given contact url is on the same server
300 * @param string $url The contact link
302 * @return boolean Is it the same server?
304 public static function isLocal($url)
306 return Strings::compareLink(self::getBasepath($url, true), System::baseUrl());
310 * Returns the public contact id of the given user id
312 * @param integer $uid User ID
314 * @return integer|boolean Public contact id for given user id
317 public static function getPublicIdByUserId($uid)
319 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
320 if (!DBA::isResult($self)) {
323 return self::getIdForURL($self['url'], 0, true);
327 * @brief Returns the contact id for the user and the public contact id for a given contact id
329 * @param int $cid Either public contact id or user's contact id
330 * @param int $uid User ID
332 * @return array with public and user's contact id
333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
334 * @throws \ImagickException
336 public static function getPublicAndUserContacID($cid, $uid)
338 if (empty($uid) || empty($cid)) {
342 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
343 if (!DBA::isResult($contact)) {
347 // We quit when the user id don't match the user id of the provided contact
348 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
352 if ($contact['uid'] != 0) {
353 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
357 $ucid = $contact['id'];
359 $pcid = $contact['id'];
360 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
363 return ['public' => $pcid, 'user' => $ucid];
367 * Returns contact details for a given contact id in combination with a user id
369 * @param int $cid A contact ID
370 * @param int $uid The User ID
371 * @param array $fields The selected fields for the contact
373 * @return array The contact details
377 public static function getContactForUser($cid, $uid, array $fields = [])
379 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
381 if (!DBA::isResult($contact)) {
389 * @brief Block contact id for user id
391 * @param int $cid Either public contact id or user's contact id
392 * @param int $uid User ID
393 * @param boolean $blocked Is the contact blocked or unblocked?
396 public static function setBlockedForUser($cid, $uid, $blocked)
398 $cdata = self::getPublicAndUserContacID($cid, $uid);
403 if ($cdata['user'] != 0) {
404 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
407 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
410 // Blocked contact can't be in any group
411 self::removeFromGroups($cid);
416 * @brief Returns "block" state for contact id and user id
418 * @param int $cid Either public contact id or user's contact id
419 * @param int $uid User ID
421 * @return boolean is the contact id blocked for the given user?
424 public static function isBlockedByUser($cid, $uid)
426 $cdata = self::getPublicAndUserContacID($cid, $uid);
431 $public_blocked = false;
433 if (!empty($cdata['public'])) {
434 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
435 if (DBA::isResult($public_contact)) {
436 $public_blocked = $public_contact['blocked'];
440 $user_blocked = $public_blocked;
442 if (!empty($cdata['user'])) {
443 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
444 if (DBA::isResult($user_contact)) {
445 $user_blocked = $user_contact['blocked'];
449 if ($user_blocked != $public_blocked) {
450 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
453 return $user_blocked;
457 * @brief Ignore contact id for user id
459 * @param int $cid Either public contact id or user's contact id
460 * @param int $uid User ID
461 * @param boolean $ignored Is the contact ignored or unignored?
464 public static function setIgnoredForUser($cid, $uid, $ignored)
466 $cdata = self::getPublicAndUserContacID($cid, $uid);
471 if ($cdata['user'] != 0) {
472 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
475 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
479 * @brief Returns "ignore" state for contact id and user id
481 * @param int $cid Either public contact id or user's contact id
482 * @param int $uid User ID
484 * @return boolean is the contact id ignored for the given user?
487 public static function isIgnoredByUser($cid, $uid)
489 $cdata = self::getPublicAndUserContacID($cid, $uid);
494 $public_ignored = false;
496 if (!empty($cdata['public'])) {
497 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
498 if (DBA::isResult($public_contact)) {
499 $public_ignored = $public_contact['ignored'];
503 $user_ignored = $public_ignored;
505 if (!empty($cdata['user'])) {
506 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
507 if (DBA::isResult($user_contact)) {
508 $user_ignored = $user_contact['readonly'];
512 if ($user_ignored != $public_ignored) {
513 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
516 return $user_ignored;
520 * @brief Set "collapsed" for contact id and user id
522 * @param int $cid Either public contact id or user's contact id
523 * @param int $uid User ID
524 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
527 public static function setCollapsedForUser($cid, $uid, $collapsed)
529 $cdata = self::getPublicAndUserContacID($cid, $uid);
534 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
538 * @brief Returns "collapsed" state for contact id and user id
540 * @param int $cid Either public contact id or user's contact id
541 * @param int $uid User ID
543 * @return boolean is the contact id blocked for the given user?
544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
545 * @throws \ImagickException
547 public static function isCollapsedByUser($cid, $uid)
549 $cdata = self::getPublicAndUserContacID($cid, $uid);
556 if (!empty($cdata['public'])) {
557 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
558 if (DBA::isResult($public_contact)) {
559 $collapsed = $public_contact['collapsed'];
567 * @brief Returns a list of contacts belonging in a group
573 public static function getByGroupId($gid)
578 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
580 INNER JOIN `group_member`
581 ON `contact`.`id` = `group_member`.`contact-id`
583 AND `contact`.`uid` = ?
584 AND NOT `contact`.`self`
585 AND NOT `contact`.`deleted`
586 AND NOT `contact`.`blocked`
587 AND NOT `contact`.`pending`
588 ORDER BY `contact`.`name` ASC',
593 if (DBA::isResult($stmt)) {
594 $return = DBA::toArray($stmt);
602 * @brief Returns the count of OStatus contacts in a group
608 public static function getOStatusCountByGroupId($gid)
612 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
614 INNER JOIN `group_member`
615 ON `contact`.`id` = `group_member`.`contact-id`
617 AND `contact`.`uid` = ?
618 AND `contact`.`network` = ?
619 AND `contact`.`notify` != ""',
624 $return = $contacts['count'];
631 * Creates the self-contact for the provided user id
634 * @return bool Operation success
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 public static function createSelfFromUserId($uid)
639 // Only create the entry if it doesn't exist yet
640 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
644 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
645 if (!DBA::isResult($user)) {
649 $return = DBA::insert('contact', [
650 'uid' => $user['uid'],
651 'created' => DateTimeFormat::utcNow(),
653 'name' => $user['username'],
654 'nick' => $user['nickname'],
655 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
656 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
657 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
660 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
661 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
662 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
663 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
664 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
665 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
666 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
667 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
668 'name-date' => DateTimeFormat::utcNow(),
669 'uri-date' => DateTimeFormat::utcNow(),
670 'avatar-date' => DateTimeFormat::utcNow(),
678 * Updates the self-contact for the provided user id
681 * @param boolean $update_avatar Force the avatar update
682 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684 public static function updateSelfFromUserID($uid, $update_avatar = false)
686 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
687 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
688 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
689 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
690 if (!DBA::isResult($self)) {
694 $fields = ['nickname', 'page-flags', 'account-type', 'hidewall'];
695 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
696 if (!DBA::isResult($user)) {
700 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
701 'country-name', 'gender', 'pub_keywords', 'xmpp', 'net-publish'];
702 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
703 if (!DBA::isResult($profile)) {
707 $file_suffix = 'jpg';
709 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
710 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
711 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
712 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
713 'xmpp' => $profile['xmpp']];
715 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
716 if (DBA::isResult($avatar)) {
717 if ($update_avatar) {
718 $fields['avatar-date'] = DateTimeFormat::utcNow();
721 // Creating the path to the avatar, beginning with the file suffix
722 $types = Image::supportedTypes();
723 if (isset($types[$avatar['type']])) {
724 $file_suffix = $types[$avatar['type']];
727 // We are adding a timestamp value so that other systems won't use cached content
728 $timestamp = strtotime($fields['avatar-date']);
730 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
731 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
733 $fields['photo'] = $prefix . '4' . $suffix;
734 $fields['thumb'] = $prefix . '5' . $suffix;
735 $fields['micro'] = $prefix . '6' . $suffix;
737 // We hadn't found a photo entry, so we use the default avatar
738 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
739 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
740 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
743 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
744 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
745 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
746 $fields['unsearchable'] = $user['hidewall'] || !$profile['net-publish'];
748 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
749 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
750 $fields['nurl'] = Strings::normaliseLink($fields['url']);
751 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
752 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
753 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
754 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
755 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
756 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
760 foreach ($fields as $field => $content) {
761 if ($self[$field] != $content) {
767 if ($fields['name'] != $self['name']) {
768 $fields['name-date'] = DateTimeFormat::utcNow();
770 $fields['updated'] = DateTimeFormat::utcNow();
771 DBA::update('contact', $fields, ['id' => $self['id']]);
773 // Update the public contact as well
774 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
776 // Update the profile
777 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
778 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
779 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
784 * @brief Marks a contact for removal
786 * @param int $id contact id
788 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
790 public static function remove($id)
792 // We want just to make sure that we don't delete our "self" contact
793 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
794 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
798 // Archive the contact
799 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
801 // Delete it in the background
802 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
806 * @brief Sends an unfriend message. Does not remove the contact
808 * @param array $user User unfriending
809 * @param array $contact Contact unfriended
810 * @param boolean $dissolve Remove the contact on the remote side
812 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 * @throws \ImagickException
815 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
817 if (empty($contact['network'])) {
821 $protocol = $contact['network'];
822 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
823 $protocol = Protocol::ACTIVITYPUB;
826 if (($protocol == Protocol::DFRN) && $dissolve) {
827 DFRN::deliver($user, $contact, 'placeholder', true);
828 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
829 // create an unfollow slap
831 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
832 $item['follow'] = $contact["url"];
837 $item['attach'] = '';
838 $slap = OStatus::salmon($item, $user);
840 if (!empty($contact['notify'])) {
841 Salmon::slapper($user, $contact['notify'], $slap);
843 } elseif ($protocol == Protocol::DIASPORA) {
844 Diaspora::sendUnshare($user, $contact);
845 } elseif ($protocol == Protocol::ACTIVITYPUB) {
846 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
849 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
855 * @brief Marks a contact for archival after a communication issue delay
857 * Contact has refused to recognise us as a friend. We will start a countdown.
858 * If they still don't recognise us in 32 days, the relationship is over,
859 * and we won't waste any more time trying to communicate with them.
860 * This provides for the possibility that their database is temporarily messed
861 * up or some other transient event and that there's a possibility we could recover from it.
863 * @param array $contact contact to mark for archival
865 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
867 public static function markForArchival(array $contact)
869 if (!isset($contact['url']) && !empty($contact['id'])) {
870 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
871 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
872 if (!DBA::isResult($contact)) {
875 } elseif (!isset($contact['url'])) {
876 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
879 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
881 // Contact already archived or "self" contact? => nothing to do
882 if ($contact['archive'] || $contact['self']) {
886 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
887 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
888 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
891 * We really should send a notification to the owner after 2-3 weeks
892 * so they won't be surprised when the contact vanishes and can take
893 * remedial action if this was a serious mistake or glitch
896 /// @todo Check for contact vitality via probing
897 $archival_days = Config::get('system', 'archival_days', 32);
899 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
900 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
901 /* Relationship is really truly dead. archive them rather than
902 * delete, though if the owner tries to unarchive them we'll start
903 * the whole process over again.
905 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
906 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
907 GContact::updateFromPublicContactURL($contact['url']);
913 * @brief Cancels the archival countdown
915 * @see Contact::markForArchival()
917 * @param array $contact contact to be unmarked for archival
921 public static function unmarkForArchival(array $contact)
923 // Always unarchive the relay contact entry
924 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
925 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
926 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
927 DBA::update('contact', $fields, $condition);
930 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
931 $exists = DBA::exists('contact', $condition);
933 // We don't need to update, we never marked this contact for archival
938 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
940 if (!isset($contact['url']) && !empty($contact['id'])) {
941 $fields = ['id', 'url', 'batch'];
942 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
943 if (!DBA::isResult($contact)) {
948 // It's a miracle. Our dead contact has inexplicably come back to life.
949 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
950 DBA::update('contact', $fields, ['id' => $contact['id']]);
951 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
952 GContact::updateFromPublicContactURL($contact['url']);
956 * @brief Get contact data for a given profile link
958 * The function looks at several places (contact table and gcontact table) for the contact
959 * It caches its result for the same script execution to prevent duplicate calls
961 * @param string $url The profile link
962 * @param int $uid User id
963 * @param array $default If not data was found take this data as default value
965 * @return array Contact data
966 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
968 public static function getDetailsByURL($url, $uid = -1, array $default = [])
980 if (isset($cache[$url][$uid])) {
981 return $cache[$url][$uid];
984 $ssl_url = str_replace('http://', 'https://', $url);
986 // Fetch contact data from the contact table for the given user
987 $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`,
988 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
989 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
990 $r = DBA::toArray($s);
992 // Fetch contact data from the contact table for the given user, checking with the alias
993 if (!DBA::isResult($r)) {
994 $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`,
995 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
996 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
997 $r = DBA::toArray($s);
1000 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1001 if (!DBA::isResult($r)) {
1002 $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`,
1003 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1004 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
1005 $r = DBA::toArray($s);
1008 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1009 if (!DBA::isResult($r)) {
1010 $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`,
1011 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1012 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
1013 $r = DBA::toArray($s);
1016 // Fetch the data from the gcontact table
1017 if (!DBA::isResult($r)) {
1018 $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`,
1019 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1020 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
1021 $r = DBA::toArray($s);
1024 if (DBA::isResult($r)) {
1025 // If there is more than one entry we filter out the connector networks
1026 if (count($r) > 1) {
1027 foreach ($r as $id => $result) {
1028 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1034 $profile = array_shift($r);
1036 // "bd" always contains the upcoming birthday of a contact.
1037 // "birthday" might contain the birthday including the year of birth.
1038 if ($profile["birthday"] > DBA::NULL_DATE) {
1039 $bd_timestamp = strtotime($profile["birthday"]);
1040 $month = date("m", $bd_timestamp);
1041 $day = date("d", $bd_timestamp);
1043 $current_timestamp = time();
1044 $current_year = date("Y", $current_timestamp);
1045 $current_month = date("m", $current_timestamp);
1046 $current_day = date("d", $current_timestamp);
1048 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1049 $current = $current_year . "-" . $current_month . "-" . $current_day;
1051 if ($profile["bd"] < $current) {
1052 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1055 $profile["bd"] = DBA::NULL_DATE;
1058 $profile = $default;
1061 if (empty($profile["photo"]) && isset($default["photo"])) {
1062 $profile["photo"] = $default["photo"];
1065 if (empty($profile["name"]) && isset($default["name"])) {
1066 $profile["name"] = $default["name"];
1069 if (empty($profile["network"]) && isset($default["network"])) {
1070 $profile["network"] = $default["network"];
1073 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1074 $profile["thumb"] = $profile["photo"];
1077 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1078 $profile["micro"] = $profile["thumb"];
1081 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1082 && in_array($profile["network"], Protocol::FEDERATED)
1084 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1087 // Show contact details of Diaspora contacts only if connected
1088 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1089 $profile["location"] = "";
1090 $profile["about"] = "";
1091 $profile["gender"] = "";
1092 $profile["birthday"] = DBA::NULL_DATE;
1095 $cache[$url][$uid] = $profile;
1101 * @brief Get contact data for a given address
1103 * The function looks at several places (contact table and gcontact table) for the contact
1105 * @param string $addr The profile link
1106 * @param int $uid User id
1108 * @return array Contact data
1109 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1110 * @throws \ImagickException
1112 public static function getDetailsByAddr($addr, $uid = -1)
1119 $uid = local_user();
1122 // Fetch contact data from the contact table for the given user
1123 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1124 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1125 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1129 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1130 if (!DBA::isResult($r)) {
1131 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1132 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1133 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1138 // Fetch the data from the gcontact table
1139 if (!DBA::isResult($r)) {
1140 $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`,
1141 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1142 FROM `gcontact` WHERE `addr` = '%s'",
1147 if (!DBA::isResult($r)) {
1148 $data = Probe::uri($addr);
1150 $profile = self::getDetailsByURL($data['url'], $uid);
1159 * @brief Returns the data array for the photo menu of a given contact
1161 * @param array $contact contact
1162 * @param int $uid optional, default 0
1164 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1165 * @throws \ImagickException
1167 public static function photoMenu(array $contact, $uid = 0)
1172 $contact_drop_link = '';
1176 $uid = local_user();
1179 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1181 $profile_link = self::magicLink($contact['url']);
1182 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1187 // Look for our own contact if the uid doesn't match and isn't public
1188 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1189 if (DBA::isResult($contact_own)) {
1190 return self::photoMenu($contact_own, $uid);
1195 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1197 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
1199 $profile_link = $contact['url'];
1202 if ($profile_link === 'mailbox') {
1207 $status_link = $profile_link . '?tab=status';
1208 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1209 $profile_link = $profile_link . '?tab=profile';
1212 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1213 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1216 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1217 $poke_link = System::baseUrl() . '/poke/?c=' . $contact['id'];
1220 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1222 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1224 if (!$contact['self']) {
1225 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1230 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1232 if (empty($contact['uid'])) {
1233 $connlnk = 'follow/?url=' . $contact['url'];
1235 'profile' => [L10n::t('View Profile'), $profile_link, true],
1236 'network' => [L10n::t('Network Posts'), $posts_link, false],
1237 'edit' => [L10n::t('View Contact'), $contact_url, false],
1238 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1242 'status' => [L10n::t('View Status'), $status_link, true],
1243 'profile' => [L10n::t('View Profile'), $profile_link, true],
1244 'photos' => [L10n::t('View Photos'), $photos_link, true],
1245 'network' => [L10n::t('Network Posts'), $posts_link, false],
1246 'edit' => [L10n::t('View Contact'), $contact_url, false],
1247 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1248 'pm' => [L10n::t('Send PM'), $pm_url, false],
1249 'poke' => [L10n::t('Poke'), $poke_link, false],
1252 if (!empty($contact['pending'])) {
1253 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1254 if (DBA::isResult($intro)) {
1255 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1260 $args = ['contact' => $contact, 'menu' => &$menu];
1262 Hook::callAll('contact_photo_menu', $args);
1264 $menucondensed = [];
1266 foreach ($menu as $menuname => $menuitem) {
1267 if ($menuitem[1] != '') {
1268 $menucondensed[$menuname] = $menuitem;
1272 return $menucondensed;
1276 * @brief Returns ungrouped contact count or list for user
1278 * Returns either the total number of ungrouped contacts for the given user
1279 * id or a paginated list of ungrouped contacts.
1281 * @param int $uid uid
1283 * @throws \Exception
1285 public static function getUngroupedList($uid)
1295 SELECT DISTINCT(`contact-id`)
1297 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1298 WHERE `group`.`uid` = %d
1299 )", intval($uid), intval($uid));
1303 * Have a look at all contact tables for a given profile url.
1304 * This function works as a replacement for probing the contact.
1306 * @param string $url Contact URL
1307 * @param integer $cid Contact ID
1309 * @return array Contact array in the "probe" structure
1311 private static function getProbeDataFromDatabase($url, $cid = null)
1313 // The link could be provided as http although we stored it as https
1314 $ssl_url = str_replace('http://', 'https://', $url);
1316 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1317 'photo', 'keywords', 'location', 'about', 'network',
1318 'priority', 'batch', 'request', 'confirm', 'poco'];
1321 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1322 if (DBA::isResult($data)) {
1327 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1329 if (!DBA::isResult($data)) {
1330 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1331 $data = DBA::selectFirst('contact', $fields, $condition);
1334 if (DBA::isResult($data)) {
1335 // For security reasons we don't fetch key data from our users
1336 $data["pubkey"] = '';
1340 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1341 'photo', 'keywords', 'location', 'about', 'network'];
1342 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1344 if (!DBA::isResult($data)) {
1345 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1346 $data = DBA::selectFirst('contact', $fields, $condition);
1349 if (DBA::isResult($data)) {
1350 $data["pubkey"] = '';
1352 $data["priority"] = 0;
1353 $data["batch"] = '';
1354 $data["request"] = '';
1355 $data["confirm"] = '';
1360 $data = ActivityPub::probeProfile($url, false);
1361 if (!empty($data)) {
1365 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1366 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1367 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1369 if (!DBA::isResult($data)) {
1370 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1371 $data = DBA::selectFirst('contact', $fields, $condition);
1374 if (DBA::isResult($data)) {
1375 $data["pubkey"] = '';
1376 $data["keywords"] = '';
1377 $data["location"] = '';
1378 $data["about"] = '';
1387 * @brief Fetch the contact id for a given URL and user
1389 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1390 * `addr` or `alias`.
1392 * If there's no record and we aren't looking for a public contact, we quit.
1393 * If there's one, we check that it isn't time to update the picture else we
1394 * directly return the found contact id.
1396 * Second, we probe the provided $url whether it's http://server.tld/profile or
1397 * nick@server.tld. We quit if we can't get any info back.
1399 * Third, we create the contact record if it doesn't exist
1401 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1402 * if there's any updates
1404 * @param string $url Contact URL
1405 * @param integer $uid The user id for the contact (0 = public contact)
1406 * @param boolean $no_update Don't update the contact
1407 * @param array $default Default value for creating the contact when every else fails
1408 * @param boolean $in_loop Internally used variable to prevent an endless loop
1410 * @return integer Contact ID
1411 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1412 * @throws \ImagickException
1414 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1416 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1424 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1425 // We first try the nurl (http://server.tld/nick), most common case
1426 $fields = ['id', 'avatar', 'updated', 'network'];
1427 $options = ['order' => ['id']];
1428 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1430 // Then the addr (nick@server.tld)
1431 if (!DBA::isResult($contact)) {
1432 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1435 // Then the alias (which could be anything)
1436 if (!DBA::isResult($contact)) {
1437 // The link could be provided as http although we stored it as https
1438 $ssl_url = str_replace('http://', 'https://', $url);
1439 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1440 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1443 if (DBA::isResult($contact)) {
1444 $contact_id = $contact["id"];
1446 // Update the contact every 7 days
1447 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1449 // We force the update if the avatar is empty
1450 if (empty($contact['avatar'])) {
1451 $update_contact = true;
1454 // Update the contact in the background if needed but it is called by the frontend
1455 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1456 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1459 if (!$update_contact || $no_update) {
1462 } elseif ($uid != 0) {
1463 // Non-existing user-specific contact, exiting
1467 if ($no_update && empty($default)) {
1468 // When we don't want to update, we look if we know this contact in any way
1469 $data = self::getProbeDataFromDatabase($url, $contact_id);
1470 $background_update = true;
1471 } elseif ($no_update && !empty($default['network'])) {
1472 // If there are default values, take these
1474 $background_update = false;
1477 $background_update = false;
1481 $data = Probe::uri($url, "", $uid);
1482 // Ensure that there is a gserver entry
1483 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1484 GServer::check($data['baseurl']);
1488 // Take the default values when probing failed
1489 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1490 $data = array_merge($data, $default);
1497 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1498 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1504 'created' => DateTimeFormat::utcNow(),
1505 'url' => $data['url'],
1506 'nurl' => Strings::normaliseLink($data['url']),
1507 'addr' => defaults($data, 'addr', ''),
1508 'alias' => defaults($data, 'alias', ''),
1509 'notify' => defaults($data, 'notify', ''),
1510 'poll' => defaults($data, 'poll', ''),
1511 'name' => defaults($data, 'name', ''),
1512 'nick' => defaults($data, 'nick', ''),
1513 'photo' => defaults($data, 'photo', ''),
1514 'keywords' => defaults($data, 'keywords', ''),
1515 'location' => defaults($data, 'location', ''),
1516 'about' => defaults($data, 'about', ''),
1517 'network' => $data['network'],
1518 'pubkey' => defaults($data, 'pubkey', ''),
1519 'rel' => self::SHARING,
1520 'priority' => defaults($data, 'priority', 0),
1521 'batch' => defaults($data, 'batch', ''),
1522 'request' => defaults($data, 'request', ''),
1523 'confirm' => defaults($data, 'confirm', ''),
1524 'poco' => defaults($data, 'poco', ''),
1525 'baseurl' => defaults($data, 'baseurl', ''),
1526 'name-date' => DateTimeFormat::utcNow(),
1527 'uri-date' => DateTimeFormat::utcNow(),
1528 'avatar-date' => DateTimeFormat::utcNow(),
1534 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1536 // Before inserting we do check if the entry does exist now.
1537 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1538 if (!DBA::isResult($contact)) {
1539 Logger::info('Create new contact', $fields);
1541 self::insert($fields);
1543 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1544 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1545 if (!DBA::isResult($contact)) {
1546 Logger::info('Contact creation failed', $fields);
1551 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1554 $contact_id = $contact["id"];
1557 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1558 self::updateAvatar($data['photo'], $uid, $contact_id);
1561 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1562 if ($background_update) {
1563 // Update in the background when we fetched the data solely from the database
1564 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1566 // Else do a direct update
1567 self::updateFromProbe($contact_id, '', false);
1569 // Update the gcontact entry
1571 GContact::updateFromPublicContactID($contact_id);
1575 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1576 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1578 // This condition should always be true
1579 if (!DBA::isResult($contact)) {
1584 'url' => $data['url'],
1585 'nurl' => Strings::normaliseLink($data['url']),
1586 'updated' => DateTimeFormat::utcNow()
1589 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1591 foreach ($fields as $field) {
1592 $updated[$field] = defaults($data, $field, $contact[$field]);
1595 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1596 $updated['uri-date'] = DateTimeFormat::utcNow();
1599 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1600 $updated['name-date'] = DateTimeFormat::utcNow();
1603 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1610 * @brief Checks if the contact is archived
1612 * @param int $cid contact id
1614 * @return boolean Is the contact archived?
1615 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1617 public static function isArchived(int $cid)
1623 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1624 if (!DBA::isResult($contact)) {
1628 if ($contact['archive']) {
1632 // Check status of ActivityPub endpoints
1633 $apcontact = APContact::getByURL($contact['url'], false);
1634 if (!empty($apcontact)) {
1635 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1639 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1644 // Check status of Diaspora endpoints
1645 if (!empty($contact['batch'])) {
1646 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1647 return DBA::exists('contact', $condition);
1654 * @brief Checks if the contact is blocked
1656 * @param int $cid contact id
1658 * @return boolean Is the contact blocked?
1659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1661 public static function isBlocked($cid)
1667 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1668 if (!DBA::isResult($blocked)) {
1672 if (Network::isUrlBlocked($blocked['url'])) {
1676 return (bool) $blocked['blocked'];
1680 * @brief Checks if the contact is hidden
1682 * @param int $cid contact id
1684 * @return boolean Is the contact hidden?
1685 * @throws \Exception
1687 public static function isHidden($cid)
1693 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1694 if (!DBA::isResult($hidden)) {
1697 return (bool) $hidden['hidden'];
1701 * @brief Returns posts from a given contact url
1703 * @param string $contact_url Contact URL
1705 * @param bool $thread_mode
1706 * @param int $update
1707 * @return string posts in HTML
1708 * @throws \Exception
1710 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1712 $a = self::getApp();
1714 $cid = self::getIdForURL($contact_url);
1716 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1717 if (!DBA::isResult($contact)) {
1721 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1722 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1724 $sql = "`item`.`uid` = ?";
1727 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1730 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1731 $cid, GRAVITY_PARENT, local_user()];
1733 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1734 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1737 $pager = new Pager($a->query_string);
1739 $params = ['order' => ['received' => true],
1740 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1743 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1745 $items = Item::inArray($r);
1747 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1749 $r = Item::selectForUser(local_user(), [], $condition, $params);
1751 $items = Item::inArray($r);
1753 $o = conversation($a, $items, $pager, 'contact-posts', false);
1757 $o .= $pager->renderMinimal(count($items));
1764 * @brief Returns the account type name
1766 * The function can be called with either the user or the contact array
1768 * @param array $contact contact or user array
1771 public static function getAccountType(array $contact)
1773 // There are several fields that indicate that the contact or user is a forum
1774 // "page-flags" is a field in the user table,
1775 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1776 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1777 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1778 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1779 || (isset($contact['forum']) && intval($contact['forum']))
1780 || (isset($contact['prv']) && intval($contact['prv']))
1781 || (isset($contact['community']) && intval($contact['community']))
1783 $type = self::TYPE_COMMUNITY;
1785 $type = self::TYPE_PERSON;
1788 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1789 if (isset($contact["contact-type"])) {
1790 $type = $contact["contact-type"];
1793 if (isset($contact["account-type"])) {
1794 $type = $contact["account-type"];
1798 case self::TYPE_ORGANISATION:
1799 $account_type = L10n::t("Organisation");
1802 case self::TYPE_NEWS:
1803 $account_type = L10n::t('News');
1806 case self::TYPE_COMMUNITY:
1807 $account_type = L10n::t("Forum");
1815 return $account_type;
1819 * @brief Blocks a contact
1823 * @throws \Exception
1825 public static function block($cid, $reason = null)
1827 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1833 * @brief Unblocks a contact
1837 * @throws \Exception
1839 public static function unblock($cid)
1841 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1847 * @brief Updates the avatar links in a contact only if needed
1849 * @param string $avatar Link to avatar picture
1850 * @param int $uid User id of contact owner
1851 * @param int $cid Contact id
1852 * @param bool $force force picture update
1854 * @return array Returns array of the different avatar sizes
1855 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1856 * @throws \ImagickException
1858 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1860 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1861 if (!DBA::isResult($contact)) {
1864 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1867 if (($contact["avatar"] != $avatar) || $force) {
1868 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1871 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1872 DBA::update('contact', $fields, ['id' => $cid]);
1874 // Update the public contact (contact id = 0)
1876 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1877 if (DBA::isResult($pcontact)) {
1878 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1890 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1892 * @param integer $id contact id
1893 * @param integer $uid user id
1894 * @param string $url The profile URL of the contact
1895 * @param array $fields The fields that are updated
1897 * @throws \Exception
1899 private static function updateContact($id, $uid, $url, array $fields)
1901 if (!DBA::update('contact', $fields, ['id' => $id])) {
1902 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1906 // Search for duplicated contacts and get rid of them
1907 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1911 // Update the corresponding gcontact entry
1912 GContact::updateFromPublicContactID($id);
1914 // Archive or unarchive the contact. We only need to do this for the public contact.
1915 // The archive/unarchive function will update the personal contacts by themselves.
1916 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1917 if (!DBA::isResult($contact)) {
1918 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1922 if (!empty($fields['success_update'])) {
1923 self::unmarkForArchival($contact);
1924 } elseif (!empty($fields['failure_update'])) {
1925 self::markForArchival($contact);
1928 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1930 // These contacts are sharing with us, we don't poll them.
1931 // This means that we don't set the update fields in "OnePoll.php".
1932 $condition['rel'] = self::SHARING;
1933 DBA::update('contact', $fields, $condition);
1935 unset($fields['last-update']);
1936 unset($fields['success_update']);
1937 unset($fields['failure_update']);
1939 if (empty($fields)) {
1943 // We are polling these contacts, so we mustn't set the update fields here.
1944 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1945 DBA::update('contact', $fields, $condition);
1949 * @brief Remove duplicated contacts
1951 * @param string $nurl Normalised contact url
1952 * @param integer $uid User id
1954 * @throws \Exception
1956 public static function removeDuplicates(string $nurl, int $uid)
1958 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1959 $count = DBA::count('contact', $condition);
1964 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1965 if (!DBA::isResult($first_contact)) {
1966 // Shouldn't happen - so we handle it
1970 $first = $first_contact['id'];
1971 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1972 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1973 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1974 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1978 // Find all duplicates
1979 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1980 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1981 while ($duplicate = DBA::fetch($duplicates)) {
1982 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1986 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1988 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1993 * @param integer $id contact id
1994 * @param string $network Optional network we are probing for
1995 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1997 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1998 * @throws \ImagickException
2000 public static function updateFromProbe($id, $network = '', $force = false)
2003 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2004 This will reliably kill your communication with old Friendica contacts.
2007 // These fields aren't updated by this routine:
2008 // 'xmpp', 'sensitive'
2010 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2011 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2012 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2013 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2014 if (!DBA::isResult($contact)) {
2018 $uid = $contact['uid'];
2019 unset($contact['uid']);
2021 $pubkey = $contact['pubkey'];
2022 unset($contact['pubkey']);
2024 $contact['photo'] = $contact['avatar'];
2025 unset($contact['avatar']);
2027 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2029 $updated = DateTimeFormat::utcNow();
2031 // We must not try to update relay contacts via probe. They are no real contacts.
2032 // We check after the probing to be able to correct falsely detected contact types.
2033 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2034 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2035 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2036 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2040 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2041 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
2042 if ($force && ($uid == 0)) {
2043 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2048 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2049 $ret['unsearchable'] = $ret['hide'];
2052 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2053 $ret['forum'] = false;
2054 $ret['prv'] = false;
2055 $ret['contact-type'] = $ret['account-type'];
2056 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2057 $apcontact = APContact::getByURL($ret['url'], false);
2058 if (isset($apcontact['manually-approve'])) {
2059 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2060 $ret['prv'] = (bool)!$ret['forum'];
2065 $new_pubkey = $ret['pubkey'];
2069 // make sure to not overwrite existing values with blank entries except some technical fields
2070 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2071 foreach ($ret as $key => $val) {
2072 if (!array_key_exists($key, $contact)) {
2074 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2075 $ret[$key] = $contact[$key];
2076 } elseif ($ret[$key] != $contact[$key]) {
2081 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2082 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2087 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2092 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2093 $ret['updated'] = $updated;
2095 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2096 if (empty($pubkey) && !empty($new_pubkey)) {
2097 $ret['pubkey'] = $new_pubkey;
2100 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2101 $ret['uri-date'] = DateTimeFormat::utcNow();
2104 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2105 $ret['name-date'] = $updated;
2108 if ($force && ($uid == 0)) {
2109 $ret['last-update'] = $updated;
2110 $ret['success_update'] = $updated;
2113 unset($ret['photo']);
2115 self::updateContact($id, $uid, $ret['url'], $ret);
2120 public static function updateFromProbeByURL($url, $force = false)
2122 $id = self::getIdForURL($url);
2128 self::updateFromProbe($id, '', $force);
2134 * Detects if a given contact array belongs to a legacy DFRN connection
2136 * @param array $contact
2139 public static function isLegacyDFRNContact($contact)
2141 // Newer Friendica contacts are connected via AP, then these fields aren't set
2142 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2146 * Detects the communication protocol for a given contact url.
2147 * This is used to detect Friendica contacts that we can communicate via AP.
2149 * @param string $url contact url
2150 * @param string $network Network of that contact
2151 * @return string with protocol
2153 public static function getProtocol($url, $network)
2155 if ($network != Protocol::DFRN) {
2159 $apcontact = APContact::getByURL($url);
2160 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2161 return Protocol::ACTIVITYPUB;
2168 * Takes a $uid and a url/handle and adds a new contact
2169 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2170 * dfrn_request page.
2172 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2175 * $return['success'] boolean true if successful
2176 * $return['message'] error text if success is false.
2178 * @brief Takes a $uid and a url/handle and adds a new contact
2180 * @param string $url
2181 * @param bool $interactive
2182 * @param string $network
2184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2185 * @throws \ImagickException
2187 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2189 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2193 // remove ajax junk, e.g. Twitter
2194 $url = str_replace('/#!/', '/', $url);
2196 if (!Network::isUrlAllowed($url)) {
2197 $result['message'] = L10n::t('Disallowed profile URL.');
2201 if (Network::isUrlBlocked($url)) {
2202 $result['message'] = L10n::t('Blocked domain');
2207 $result['message'] = L10n::t('Connect URL missing.');
2211 $arr = ['url' => $url, 'contact' => []];
2213 Hook::callAll('follow', $arr);
2216 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2220 if (!empty($arr['contact']['name'])) {
2221 $ret = $arr['contact'];
2223 $ret = Probe::uri($url, $network, $uid, false);
2226 if (($network != '') && ($ret['network'] != $network)) {
2227 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2231 // check if we already have a contact
2232 // the poll url is more reliable than the profile url, as we may have
2233 // indirect links or webfinger links
2235 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2236 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2237 if (!DBA::isResult($contact)) {
2238 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2239 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2242 $protocol = self::getProtocol($url, $ret['network']);
2244 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2246 if (strlen($a->getURLPath())) {
2247 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2249 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2252 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2256 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2257 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2258 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2262 // This extra param just confuses things, remove it
2263 if ($protocol === Protocol::DIASPORA) {
2264 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2267 // do we have enough information?
2268 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2269 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2270 if (empty($ret['poll'])) {
2271 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2273 if (empty($ret['name'])) {
2274 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2276 if (empty($ret['url'])) {
2277 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2279 if (strpos($url, '@') !== false) {
2280 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2281 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2286 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2287 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2288 $ret['notify'] = '';
2291 if (!$ret['notify']) {
2292 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2295 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2297 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2299 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2301 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2303 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2307 if (DBA::isResult($contact)) {
2309 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2311 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2312 DBA::update('contact', $fields, ['id' => $contact['id']]);
2314 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2316 // create contact record
2319 'created' => DateTimeFormat::utcNow(),
2320 'url' => $ret['url'],
2321 'nurl' => Strings::normaliseLink($ret['url']),
2322 'addr' => $ret['addr'],
2323 'alias' => $ret['alias'],
2324 'batch' => $ret['batch'],
2325 'notify' => $ret['notify'],
2326 'poll' => $ret['poll'],
2327 'poco' => $ret['poco'],
2328 'name' => $ret['name'],
2329 'nick' => $ret['nick'],
2330 'network' => $ret['network'],
2331 'baseurl' => $ret['baseurl'],
2332 'protocol' => $protocol,
2333 'pubkey' => $ret['pubkey'],
2334 'rel' => $new_relation,
2335 'priority'=> $ret['priority'],
2336 'writable'=> $writeable,
2337 'hidden' => $hidden,
2340 'pending' => $pending,
2345 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2346 if (!DBA::isResult($contact)) {
2347 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2351 $contact_id = $contact['id'];
2352 $result['cid'] = $contact_id;
2354 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2356 // Update the avatar
2357 self::updateAvatar($ret['photo'], $uid, $contact_id);
2359 // pull feed and consume it, which should subscribe to the hub.
2361 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2363 $owner = User::getOwnerDataById($uid);
2365 if (DBA::isResult($owner)) {
2366 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2367 // create a follow slap
2369 $item['verb'] = ACTIVITY_FOLLOW;
2370 $item['follow'] = $contact["url"];
2372 $item['title'] = '';
2375 $item['attach'] = '';
2377 $slap = OStatus::salmon($item, $owner);
2379 if (!empty($contact['notify'])) {
2380 Salmon::slapper($owner, $contact['notify'], $slap);
2382 } elseif ($protocol == Protocol::DIASPORA) {
2383 $ret = Diaspora::sendShare($a->user, $contact);
2384 Logger::log('share returns: ' . $ret);
2385 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2386 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2387 if (empty($activity_id)) {
2388 // This really should never happen
2392 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2393 Logger::log('Follow returns: ' . $ret);
2397 $result['success'] = true;
2402 * @brief Updated contact's SSL policy
2404 * @param array $contact Contact array
2405 * @param string $new_policy New policy, valid: self,full
2407 * @return array Contact array with updated values
2408 * @throws \Exception
2410 public static function updateSslPolicy(array $contact, $new_policy)
2412 $ssl_changed = false;
2413 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2414 $ssl_changed = true;
2415 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2416 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2417 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2418 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2419 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2420 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2423 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2424 $ssl_changed = true;
2425 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2426 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2427 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2428 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2429 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2430 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2434 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2435 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2436 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2437 DBA::update('contact', $fields, ['id' => $contact['id']]);
2444 * @param array $importer Owner (local user) data
2445 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2446 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2447 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2448 * @param string $note Introduction additional message
2449 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2451 * @throws \ImagickException
2453 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2455 // Should always be set
2456 if (empty($datarray['author-id'])) {
2460 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2461 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2462 if (!DBA::isResult($pub_contact)) {
2463 // Should never happen
2467 // Contact is blocked at node-level
2468 if (self::isBlocked($datarray['author-id'])) {
2472 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2473 $name = $pub_contact['name'];
2474 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2475 $nick = $pub_contact['nick'];
2476 $network = $pub_contact['network'];
2478 // Ensure that we don't create a new contact when there already is one
2479 $cid = self::getIdForURL($url, $importer['uid']);
2481 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2484 if (!empty($contact)) {
2485 if (!empty($contact['pending'])) {
2486 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2490 // Contact is blocked at user-level
2491 if (!empty($contact['id']) && !empty($importer['id']) &&
2492 self::isBlockedByUser($contact['id'], $importer['id'])) {
2496 // Make sure that the existing contact isn't archived
2497 self::unmarkForArchival($contact);
2499 if (($contact['rel'] == self::SHARING)
2500 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2501 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2502 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2505 // Ensure to always have the correct network type, independent from the connection request method
2506 self::updateFromProbe($contact['id'], '', true);
2510 // send email notification to owner?
2511 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2512 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2516 // create contact record
2517 DBA::insert('contact', [
2518 'uid' => $importer['uid'],
2519 'created' => DateTimeFormat::utcNow(),
2521 'nurl' => Strings::normaliseLink($url),
2525 'network' => $network,
2526 'rel' => self::FOLLOWER,
2533 $contact_id = DBA::lastInsertId();
2535 // Ensure to always have the correct network type, independent from the connection request method
2536 self::updateFromProbe($contact_id, '', true);
2538 Contact::updateAvatar($photo, $importer["uid"], $contact_id, true);
2540 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2542 /// @TODO Encapsulate this into a function/method
2543 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2544 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2545 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2546 // create notification
2547 $hash = Strings::getRandomHex();
2549 if (is_array($contact_record)) {
2550 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2551 'blocked' => false, 'knowyou' => false, 'note' => $note,
2552 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2555 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2557 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2558 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2561 'type' => NOTIFY_INTRO,
2562 'notify_flags' => $user['notify-flags'],
2563 'language' => $user['language'],
2564 'to_name' => $user['username'],
2565 'to_email' => $user['email'],
2566 'uid' => $user['uid'],
2567 'link' => System::baseUrl() . '/notifications/intro',
2568 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2569 'source_link' => $contact_record['url'],
2570 'source_photo' => $contact_record['photo'],
2571 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2575 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2576 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2577 DBA::update('contact', ['pending' => false], $condition);
2586 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2588 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2589 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2591 Contact::remove($contact['id']);
2595 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2597 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2598 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2600 Contact::remove($contact['id']);
2605 * @brief Create a birthday event.
2607 * Update the year and the birthday.
2609 public static function updateBirthdays()
2613 AND `bd` > "0001-01-01"
2614 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2615 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2616 AND NOT `contact`.`pending`
2617 AND NOT `contact`.`hidden`
2618 AND NOT `contact`.`blocked`
2619 AND NOT `contact`.`archive`
2620 AND NOT `contact`.`deleted`',
2625 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2627 while ($contact = DBA::fetch($contacts)) {
2628 Logger::log('update_contact_birthday: ' . $contact['bd']);
2630 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2632 if (Event::createBirthday($contact, $nextbd)) {
2636 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2637 ['id' => $contact['id']]
2644 * Remove the unavailable contact ids from the provided list
2646 * @param array $contact_ids Contact id list
2647 * @throws \Exception
2649 public static function pruneUnavailable(array &$contact_ids)
2651 if (empty($contact_ids)) {
2655 $str = DBA::escape(implode(',', $contact_ids));
2657 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2660 while($contact = DBA::fetch($stmt)) {
2661 $return[] = $contact['id'];
2666 $contact_ids = $return;
2670 * @brief Returns a magic link to authenticate remote visitors
2672 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2674 * @param string $contact_url The address of the target contact profile
2675 * @param string $url An url that we will be redirected to after the authentication
2677 * @return string with "redir" link
2678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2679 * @throws \ImagickException
2681 public static function magicLink($contact_url, $url = '')
2683 if (!Session::isAuthenticated()) {
2684 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2687 $data = self::getProbeDataFromDatabase($contact_url);
2689 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2692 // Prevents endless loop in case only a non-public contact exists for the contact URL
2693 unset($data['uid']);
2695 return self::magicLinkByContact($data, $url ?: $contact_url);
2699 * @brief Returns a magic link to authenticate remote visitors
2701 * @param integer $cid The contact id of the target contact profile
2702 * @param string $url An url that we will be redirected to after the authentication
2704 * @return string with "redir" link
2705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2706 * @throws \ImagickException
2708 public static function magicLinkbyId($cid, $url = '')
2710 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2712 return self::magicLinkByContact($contact, $url);
2716 * @brief Returns a magic link to authenticate remote visitors
2718 * @param array $contact The contact array with "uid", "network" and "url"
2719 * @param string $url An url that we will be redirected to after the authentication
2721 * @return string with "redir" link
2722 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2723 * @throws \ImagickException
2725 public static function magicLinkByContact($contact, $url = '')
2727 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2729 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2730 return $destination;
2733 // Only redirections to the same host do make sense
2734 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2738 if (!empty($contact['uid'])) {
2739 return self::magicLink($contact['url'], $url);
2742 if (empty($contact['id'])) {
2743 return $destination;
2746 $redirect = 'redir/' . $contact['id'];
2748 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2749 $redirect .= '?url=' . $url;
2756 * Remove a contact from all groups
2758 * @param integer $contact_id
2760 * @return boolean Success
2762 public static function removeFromGroups($contact_id)
2764 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2768 * Is the contact a forum?
2770 * @param integer $contactid ID of the contact
2772 * @return boolean "true" if it is a forum
2774 public static function isForum($contactid)
2776 $fields = ['forum', 'prv'];
2777 $condition = ['id' => $contactid];
2778 $contact = DBA::selectFirst('contact', $fields, $condition);
2779 if (!DBA::isResult($contact)) {
2784 return ($contact['forum'] || $contact['prv']);
2788 * Can the remote contact receive private messages?
2790 * @param array $contact
2793 public static function canReceivePrivateMessages(array $contact)
2795 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2796 $self = $contact['self'] ?? false;
2798 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;