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 * Returns the public contact id of the given user id
296 * @param integer $uid User ID
298 * @return integer|boolean Public contact id for given user id
301 public static function getPublicIdByUserId($uid)
303 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
304 if (!DBA::isResult($self)) {
307 return self::getIdForURL($self['url'], 0, true);
311 * @brief Returns the contact id for the user and the public contact id for a given contact id
313 * @param int $cid Either public contact id or user's contact id
314 * @param int $uid User ID
316 * @return array with public and user's contact id
317 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
318 * @throws \ImagickException
320 public static function getPublicAndUserContacID($cid, $uid)
322 if (empty($uid) || empty($cid)) {
326 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
327 if (!DBA::isResult($contact)) {
331 // We quit when the user id don't match the user id of the provided contact
332 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
336 if ($contact['uid'] != 0) {
337 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
341 $ucid = $contact['id'];
343 $pcid = $contact['id'];
344 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
347 return ['public' => $pcid, 'user' => $ucid];
351 * Returns contact details for a given contact id in combination with a user id
353 * @param int $cid A contact ID
354 * @param int $uid The User ID
355 * @param array $fields The selected fields for the contact
357 * @return array The contact details
361 public static function getContactForUser($cid, $uid, array $fields = [])
363 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
365 if (!DBA::isResult($contact)) {
373 * @brief Block contact id for user id
375 * @param int $cid Either public contact id or user's contact id
376 * @param int $uid User ID
377 * @param boolean $blocked Is the contact blocked or unblocked?
380 public static function setBlockedForUser($cid, $uid, $blocked)
382 $cdata = self::getPublicAndUserContacID($cid, $uid);
387 if ($cdata['user'] != 0) {
388 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
391 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
394 // Blocked contact can't be in any group
395 self::removeFromGroups($cid);
400 * @brief Returns "block" state for contact id and user id
402 * @param int $cid Either public contact id or user's contact id
403 * @param int $uid User ID
405 * @return boolean is the contact id blocked for the given user?
408 public static function isBlockedByUser($cid, $uid)
410 $cdata = self::getPublicAndUserContacID($cid, $uid);
415 $public_blocked = false;
417 if (!empty($cdata['public'])) {
418 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
419 if (DBA::isResult($public_contact)) {
420 $public_blocked = $public_contact['blocked'];
424 $user_blocked = $public_blocked;
426 if (!empty($cdata['user'])) {
427 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
428 if (DBA::isResult($user_contact)) {
429 $user_blocked = $user_contact['blocked'];
433 if ($user_blocked != $public_blocked) {
434 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
437 return $user_blocked;
441 * @brief Ignore contact id for user id
443 * @param int $cid Either public contact id or user's contact id
444 * @param int $uid User ID
445 * @param boolean $ignored Is the contact ignored or unignored?
448 public static function setIgnoredForUser($cid, $uid, $ignored)
450 $cdata = self::getPublicAndUserContacID($cid, $uid);
455 if ($cdata['user'] != 0) {
456 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
459 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
463 * @brief Returns "ignore" state for contact id and user id
465 * @param int $cid Either public contact id or user's contact id
466 * @param int $uid User ID
468 * @return boolean is the contact id ignored for the given user?
471 public static function isIgnoredByUser($cid, $uid)
473 $cdata = self::getPublicAndUserContacID($cid, $uid);
478 $public_ignored = false;
480 if (!empty($cdata['public'])) {
481 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
482 if (DBA::isResult($public_contact)) {
483 $public_ignored = $public_contact['ignored'];
487 $user_ignored = $public_ignored;
489 if (!empty($cdata['user'])) {
490 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
491 if (DBA::isResult($user_contact)) {
492 $user_ignored = $user_contact['readonly'];
496 if ($user_ignored != $public_ignored) {
497 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
500 return $user_ignored;
504 * @brief Set "collapsed" for contact id and user id
506 * @param int $cid Either public contact id or user's contact id
507 * @param int $uid User ID
508 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
511 public static function setCollapsedForUser($cid, $uid, $collapsed)
513 $cdata = self::getPublicAndUserContacID($cid, $uid);
518 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
522 * @brief Returns "collapsed" state for contact id and user id
524 * @param int $cid Either public contact id or user's contact id
525 * @param int $uid User ID
527 * @return boolean is the contact id blocked for the given user?
528 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529 * @throws \ImagickException
531 public static function isCollapsedByUser($cid, $uid)
533 $cdata = self::getPublicAndUserContacID($cid, $uid);
540 if (!empty($cdata['public'])) {
541 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
542 if (DBA::isResult($public_contact)) {
543 $collapsed = $public_contact['collapsed'];
551 * @brief Returns a list of contacts belonging in a group
557 public static function getByGroupId($gid)
562 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
564 INNER JOIN `group_member`
565 ON `contact`.`id` = `group_member`.`contact-id`
567 AND `contact`.`uid` = ?
568 AND NOT `contact`.`self`
569 AND NOT `contact`.`deleted`
570 AND NOT `contact`.`blocked`
571 AND NOT `contact`.`pending`
572 ORDER BY `contact`.`name` ASC',
577 if (DBA::isResult($stmt)) {
578 $return = DBA::toArray($stmt);
586 * @brief Returns the count of OStatus contacts in a group
592 public static function getOStatusCountByGroupId($gid)
596 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
598 INNER JOIN `group_member`
599 ON `contact`.`id` = `group_member`.`contact-id`
601 AND `contact`.`uid` = ?
602 AND `contact`.`network` = ?
603 AND `contact`.`notify` != ""',
608 $return = $contacts['count'];
615 * Creates the self-contact for the provided user id
618 * @return bool Operation success
619 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
621 public static function createSelfFromUserId($uid)
623 // Only create the entry if it doesn't exist yet
624 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
628 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
629 if (!DBA::isResult($user)) {
633 $return = DBA::insert('contact', [
634 'uid' => $user['uid'],
635 'created' => DateTimeFormat::utcNow(),
637 'name' => $user['username'],
638 'nick' => $user['nickname'],
639 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
640 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
641 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
644 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
645 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
646 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
647 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
648 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
649 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
650 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
651 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
652 'name-date' => DateTimeFormat::utcNow(),
653 'uri-date' => DateTimeFormat::utcNow(),
654 'avatar-date' => DateTimeFormat::utcNow(),
662 * Updates the self-contact for the provided user id
665 * @param boolean $update_avatar Force the avatar update
666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
668 public static function updateSelfFromUserID($uid, $update_avatar = false)
670 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
671 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
672 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
673 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
674 if (!DBA::isResult($self)) {
678 $fields = ['nickname', 'page-flags', 'account-type'];
679 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
680 if (!DBA::isResult($user)) {
684 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
685 'country-name', 'gender', 'pub_keywords', 'xmpp'];
686 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
687 if (!DBA::isResult($profile)) {
691 $file_suffix = 'jpg';
693 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
694 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
695 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
696 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
697 'xmpp' => $profile['xmpp']];
699 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
700 if (DBA::isResult($avatar)) {
701 if ($update_avatar) {
702 $fields['avatar-date'] = DateTimeFormat::utcNow();
705 // Creating the path to the avatar, beginning with the file suffix
706 $types = Image::supportedTypes();
707 if (isset($types[$avatar['type']])) {
708 $file_suffix = $types[$avatar['type']];
711 // We are adding a timestamp value so that other systems won't use cached content
712 $timestamp = strtotime($fields['avatar-date']);
714 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
715 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
717 $fields['photo'] = $prefix . '4' . $suffix;
718 $fields['thumb'] = $prefix . '5' . $suffix;
719 $fields['micro'] = $prefix . '6' . $suffix;
721 // We hadn't found a photo entry, so we use the default avatar
722 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
723 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
724 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
727 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
728 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
729 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
731 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
732 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
733 $fields['nurl'] = Strings::normaliseLink($fields['url']);
734 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
735 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
736 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
737 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
738 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
739 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
743 foreach ($fields as $field => $content) {
744 if ($self[$field] != $content) {
750 if ($fields['name'] != $self['name']) {
751 $fields['name-date'] = DateTimeFormat::utcNow();
753 $fields['updated'] = DateTimeFormat::utcNow();
754 DBA::update('contact', $fields, ['id' => $self['id']]);
756 // Update the public contact as well
757 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
759 // Update the profile
760 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
761 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
762 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
767 * @brief Marks a contact for removal
769 * @param int $id contact id
771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
773 public static function remove($id)
775 // We want just to make sure that we don't delete our "self" contact
776 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
777 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
781 // Archive the contact
782 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
784 // Delete it in the background
785 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
789 * @brief Sends an unfriend message. Does not remove the contact
791 * @param array $user User unfriending
792 * @param array $contact Contact unfriended
793 * @param boolean $dissolve Remove the contact on the remote side
795 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
796 * @throws \ImagickException
798 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
800 if (empty($contact['network'])) {
804 $protocol = $contact['network'];
805 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
806 $protocol = Protocol::ACTIVITYPUB;
809 if (($protocol == Protocol::DFRN) && $dissolve) {
810 DFRN::deliver($user, $contact, 'placeholder', true);
811 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
812 // create an unfollow slap
814 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
815 $item['follow'] = $contact["url"];
820 $item['attach'] = '';
821 $slap = OStatus::salmon($item, $user);
823 if (!empty($contact['notify'])) {
824 Salmon::slapper($user, $contact['notify'], $slap);
826 } elseif ($protocol == Protocol::DIASPORA) {
827 Diaspora::sendUnshare($user, $contact);
828 } elseif ($protocol == Protocol::ACTIVITYPUB) {
829 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
832 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
838 * @brief Marks a contact for archival after a communication issue delay
840 * Contact has refused to recognise us as a friend. We will start a countdown.
841 * If they still don't recognise us in 32 days, the relationship is over,
842 * and we won't waste any more time trying to communicate with them.
843 * This provides for the possibility that their database is temporarily messed
844 * up or some other transient event and that there's a possibility we could recover from it.
846 * @param array $contact contact to mark for archival
848 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
850 public static function markForArchival(array $contact)
852 if (!isset($contact['url']) && !empty($contact['id'])) {
853 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
854 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
855 if (!DBA::isResult($contact)) {
858 } elseif (!isset($contact['url'])) {
859 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
862 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
864 // Contact already archived or "self" contact? => nothing to do
865 if ($contact['archive'] || $contact['self']) {
869 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
870 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
871 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
874 * We really should send a notification to the owner after 2-3 weeks
875 * so they won't be surprised when the contact vanishes and can take
876 * remedial action if this was a serious mistake or glitch
879 /// @todo Check for contact vitality via probing
880 $archival_days = Config::get('system', 'archival_days', 32);
882 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
883 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
884 /* Relationship is really truly dead. archive them rather than
885 * delete, though if the owner tries to unarchive them we'll start
886 * the whole process over again.
888 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
889 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
890 GContact::updateFromPublicContactURL($contact['url']);
896 * @brief Cancels the archival countdown
898 * @see Contact::markForArchival()
900 * @param array $contact contact to be unmarked for archival
904 public static function unmarkForArchival(array $contact)
906 // Always unarchive the relay contact entry
907 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
908 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
909 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
910 DBA::update('contact', $fields, $condition);
913 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
914 $exists = DBA::exists('contact', $condition);
916 // We don't need to update, we never marked this contact for archival
921 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
923 if (!isset($contact['url']) && !empty($contact['id'])) {
924 $fields = ['id', 'url', 'batch'];
925 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
926 if (!DBA::isResult($contact)) {
931 // It's a miracle. Our dead contact has inexplicably come back to life.
932 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
933 DBA::update('contact', $fields, ['id' => $contact['id']]);
934 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
935 GContact::updateFromPublicContactURL($contact['url']);
939 * @brief Get contact data for a given profile link
941 * The function looks at several places (contact table and gcontact table) for the contact
942 * It caches its result for the same script execution to prevent duplicate calls
944 * @param string $url The profile link
945 * @param int $uid User id
946 * @param array $default If not data was found take this data as default value
948 * @return array Contact data
949 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
951 public static function getDetailsByURL($url, $uid = -1, array $default = [])
963 if (isset($cache[$url][$uid])) {
964 return $cache[$url][$uid];
967 $ssl_url = str_replace('http://', 'https://', $url);
969 // Fetch contact data from the contact table for the given user
970 $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`,
971 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
972 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
973 $r = DBA::toArray($s);
975 // Fetch contact data from the contact table for the given user, checking with the alias
976 if (!DBA::isResult($r)) {
977 $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`,
978 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
979 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
980 $r = DBA::toArray($s);
983 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
984 if (!DBA::isResult($r)) {
985 $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`,
986 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
987 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
988 $r = DBA::toArray($s);
991 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
992 if (!DBA::isResult($r)) {
993 $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`,
994 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
995 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
996 $r = DBA::toArray($s);
999 // Fetch the data from the gcontact table
1000 if (!DBA::isResult($r)) {
1001 $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`,
1002 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1003 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
1004 $r = DBA::toArray($s);
1007 if (DBA::isResult($r)) {
1008 // If there is more than one entry we filter out the connector networks
1009 if (count($r) > 1) {
1010 foreach ($r as $id => $result) {
1011 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1017 $profile = array_shift($r);
1019 // "bd" always contains the upcoming birthday of a contact.
1020 // "birthday" might contain the birthday including the year of birth.
1021 if ($profile["birthday"] > DBA::NULL_DATE) {
1022 $bd_timestamp = strtotime($profile["birthday"]);
1023 $month = date("m", $bd_timestamp);
1024 $day = date("d", $bd_timestamp);
1026 $current_timestamp = time();
1027 $current_year = date("Y", $current_timestamp);
1028 $current_month = date("m", $current_timestamp);
1029 $current_day = date("d", $current_timestamp);
1031 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1032 $current = $current_year . "-" . $current_month . "-" . $current_day;
1034 if ($profile["bd"] < $current) {
1035 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1038 $profile["bd"] = DBA::NULL_DATE;
1041 $profile = $default;
1044 if (empty($profile["photo"]) && isset($default["photo"])) {
1045 $profile["photo"] = $default["photo"];
1048 if (empty($profile["name"]) && isset($default["name"])) {
1049 $profile["name"] = $default["name"];
1052 if (empty($profile["network"]) && isset($default["network"])) {
1053 $profile["network"] = $default["network"];
1056 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1057 $profile["thumb"] = $profile["photo"];
1060 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1061 $profile["micro"] = $profile["thumb"];
1064 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1065 && in_array($profile["network"], Protocol::FEDERATED)
1067 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1070 // Show contact details of Diaspora contacts only if connected
1071 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1072 $profile["location"] = "";
1073 $profile["about"] = "";
1074 $profile["gender"] = "";
1075 $profile["birthday"] = DBA::NULL_DATE;
1078 $cache[$url][$uid] = $profile;
1084 * @brief Get contact data for a given address
1086 * The function looks at several places (contact table and gcontact table) for the contact
1088 * @param string $addr The profile link
1089 * @param int $uid User id
1091 * @return array Contact data
1092 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1093 * @throws \ImagickException
1095 public static function getDetailsByAddr($addr, $uid = -1)
1102 $uid = local_user();
1105 // Fetch contact data from the contact table for the given user
1106 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1107 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1108 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1112 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1113 if (!DBA::isResult($r)) {
1114 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1115 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1116 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1121 // Fetch the data from the gcontact table
1122 if (!DBA::isResult($r)) {
1123 $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`,
1124 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1125 FROM `gcontact` WHERE `addr` = '%s'",
1130 if (!DBA::isResult($r)) {
1131 $data = Probe::uri($addr);
1133 $profile = self::getDetailsByURL($data['url'], $uid);
1142 * @brief Returns the data array for the photo menu of a given contact
1144 * @param array $contact contact
1145 * @param int $uid optional, default 0
1147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1148 * @throws \ImagickException
1150 public static function photoMenu(array $contact, $uid = 0)
1155 $contact_drop_link = '';
1159 $uid = local_user();
1162 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1164 $profile_link = self::magicLink($contact['url']);
1165 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1170 // Look for our own contact if the uid doesn't match and isn't public
1171 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1172 if (DBA::isResult($contact_own)) {
1173 return self::photoMenu($contact_own, $uid);
1178 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && !$contact['pending']) {
1180 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1182 $profile_link = $contact['url'];
1185 if ($profile_link === 'mailbox') {
1190 $status_link = $profile_link . '?tab=status';
1191 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1192 $profile_link = $profile_link . '?tab=profile';
1195 if (self::canReceivePrivateMessages($contact) && !$contact['pending']) {
1196 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1199 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && !$contact['pending']) {
1200 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1203 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1205 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1207 if (!$contact['self']) {
1208 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1213 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1215 if (empty($contact['uid'])) {
1216 $connlnk = 'follow/?url=' . $contact['url'];
1218 'profile' => [L10n::t('View Profile'), $profile_link, true],
1219 'network' => [L10n::t('Network Posts'), $posts_link, false],
1220 'edit' => [L10n::t('View Contact'), $contact_url, false],
1221 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1225 'status' => [L10n::t('View Status'), $status_link, true],
1226 'profile' => [L10n::t('View Profile'), $profile_link, true],
1227 'photos' => [L10n::t('View Photos'), $photos_link, true],
1228 'network' => [L10n::t('Network Posts'), $posts_link, false],
1229 'edit' => [L10n::t('View Contact'), $contact_url, false],
1230 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1231 'pm' => [L10n::t('Send PM'), $pm_url, false],
1232 'poke' => [L10n::t('Poke'), $poke_link, false],
1235 if ($contact['pending']) {
1236 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1237 if (DBA::isResult($intro)) {
1238 $menu['follow'] = [L10n::t('Approve'), 'notifications/intros/' . $intro['id'], true];
1243 $args = ['contact' => $contact, 'menu' => &$menu];
1245 Hook::callAll('contact_photo_menu', $args);
1247 $menucondensed = [];
1249 foreach ($menu as $menuname => $menuitem) {
1250 if ($menuitem[1] != '') {
1251 $menucondensed[$menuname] = $menuitem;
1255 return $menucondensed;
1259 * @brief Returns ungrouped contact count or list for user
1261 * Returns either the total number of ungrouped contacts for the given user
1262 * id or a paginated list of ungrouped contacts.
1264 * @param int $uid uid
1266 * @throws \Exception
1268 public static function getUngroupedList($uid)
1278 SELECT DISTINCT(`contact-id`)
1280 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1281 WHERE `group`.`uid` = %d
1282 )", intval($uid), intval($uid));
1286 * Have a look at all contact tables for a given profile url.
1287 * This function works as a replacement for probing the contact.
1289 * @param string $url Contact URL
1290 * @param integer $cid Contact ID
1292 * @return array Contact array in the "probe" structure
1294 private static function getProbeDataFromDatabase($url, $cid = null)
1296 // The link could be provided as http although we stored it as https
1297 $ssl_url = str_replace('http://', 'https://', $url);
1299 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1300 'photo', 'keywords', 'location', 'about', 'network',
1301 'priority', 'batch', 'request', 'confirm', 'poco'];
1304 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1305 if (DBA::isResult($data)) {
1310 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1312 if (!DBA::isResult($data)) {
1313 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1314 $data = DBA::selectFirst('contact', $fields, $condition);
1317 if (DBA::isResult($data)) {
1318 // For security reasons we don't fetch key data from our users
1319 $data["pubkey"] = '';
1323 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1324 'photo', 'keywords', 'location', 'about', 'network'];
1325 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1327 if (!DBA::isResult($data)) {
1328 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1329 $data = DBA::selectFirst('contact', $fields, $condition);
1332 if (DBA::isResult($data)) {
1333 $data["pubkey"] = '';
1335 $data["priority"] = 0;
1336 $data["batch"] = '';
1337 $data["request"] = '';
1338 $data["confirm"] = '';
1343 $data = ActivityPub::probeProfile($url, false);
1344 if (!empty($data)) {
1348 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1349 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1350 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1352 if (!DBA::isResult($data)) {
1353 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1354 $data = DBA::selectFirst('contact', $fields, $condition);
1357 if (DBA::isResult($data)) {
1358 $data["pubkey"] = '';
1359 $data["keywords"] = '';
1360 $data["location"] = '';
1361 $data["about"] = '';
1370 * @brief Fetch the contact id for a given URL and user
1372 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1373 * `addr` or `alias`.
1375 * If there's no record and we aren't looking for a public contact, we quit.
1376 * If there's one, we check that it isn't time to update the picture else we
1377 * directly return the found contact id.
1379 * Second, we probe the provided $url whether it's http://server.tld/profile or
1380 * nick@server.tld. We quit if we can't get any info back.
1382 * Third, we create the contact record if it doesn't exist
1384 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1385 * if there's any updates
1387 * @param string $url Contact URL
1388 * @param integer $uid The user id for the contact (0 = public contact)
1389 * @param boolean $no_update Don't update the contact
1390 * @param array $default Default value for creating the contact when every else fails
1391 * @param boolean $in_loop Internally used variable to prevent an endless loop
1393 * @return integer Contact ID
1394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1395 * @throws \ImagickException
1397 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1399 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1407 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1408 // We first try the nurl (http://server.tld/nick), most common case
1409 $fields = ['id', 'avatar', 'updated', 'network'];
1410 $options = ['order' => ['id']];
1411 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1413 // Then the addr (nick@server.tld)
1414 if (!DBA::isResult($contact)) {
1415 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1418 // Then the alias (which could be anything)
1419 if (!DBA::isResult($contact)) {
1420 // The link could be provided as http although we stored it as https
1421 $ssl_url = str_replace('http://', 'https://', $url);
1422 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1423 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1426 if (DBA::isResult($contact)) {
1427 $contact_id = $contact["id"];
1429 // Update the contact every 7 days
1430 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1432 // We force the update if the avatar is empty
1433 if (empty($contact['avatar'])) {
1434 $update_contact = true;
1437 // Update the contact in the background if needed but it is called by the frontend
1438 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1439 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1442 if (!$update_contact || $no_update) {
1445 } elseif ($uid != 0) {
1446 // Non-existing user-specific contact, exiting
1450 if ($no_update && empty($default)) {
1451 // When we don't want to update, we look if we know this contact in any way
1452 $data = self::getProbeDataFromDatabase($url, $contact_id);
1453 $background_update = true;
1454 } elseif ($no_update && !empty($default['network'])) {
1455 // If there are default values, take these
1457 $background_update = false;
1460 $background_update = false;
1464 $data = Probe::uri($url, "", $uid);
1466 // Ensure that there is a gserver entry
1467 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1468 PortableContact::checkServer($data['baseurl']);
1472 // Take the default values when probing failed
1473 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1474 $data = array_merge($data, $default);
1481 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1482 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1488 'created' => DateTimeFormat::utcNow(),
1489 'url' => $data['url'],
1490 'nurl' => Strings::normaliseLink($data['url']),
1491 'addr' => defaults($data, 'addr', ''),
1492 'alias' => defaults($data, 'alias', ''),
1493 'notify' => defaults($data, 'notify', ''),
1494 'poll' => defaults($data, 'poll', ''),
1495 'name' => defaults($data, 'name', ''),
1496 'nick' => defaults($data, 'nick', ''),
1497 'photo' => defaults($data, 'photo', ''),
1498 'keywords' => defaults($data, 'keywords', ''),
1499 'location' => defaults($data, 'location', ''),
1500 'about' => defaults($data, 'about', ''),
1501 'network' => $data['network'],
1502 'pubkey' => defaults($data, 'pubkey', ''),
1503 'rel' => self::SHARING,
1504 'priority' => defaults($data, 'priority', 0),
1505 'batch' => defaults($data, 'batch', ''),
1506 'request' => defaults($data, 'request', ''),
1507 'confirm' => defaults($data, 'confirm', ''),
1508 'poco' => defaults($data, 'poco', ''),
1509 'baseurl' => defaults($data, 'baseurl', ''),
1510 'name-date' => DateTimeFormat::utcNow(),
1511 'uri-date' => DateTimeFormat::utcNow(),
1512 'avatar-date' => DateTimeFormat::utcNow(),
1518 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1520 // Before inserting we do check if the entry does exist now.
1521 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1522 if (!DBA::isResult($contact)) {
1523 Logger::info('Create new contact', $fields);
1525 self::insert($fields);
1527 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1528 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1529 if (!DBA::isResult($contact)) {
1530 Logger::info('Contact creation failed', $fields);
1535 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1538 $contact_id = $contact["id"];
1541 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1542 self::updateAvatar($data['photo'], $uid, $contact_id);
1545 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1546 if ($background_update) {
1547 // Update in the background when we fetched the data solely from the database
1548 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1550 // Else do a direct update
1551 self::updateFromProbe($contact_id, '', false);
1553 // Update the gcontact entry
1555 GContact::updateFromPublicContactID($contact_id);
1559 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1560 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1562 // This condition should always be true
1563 if (!DBA::isResult($contact)) {
1568 'url' => $data['url'],
1569 'nurl' => Strings::normaliseLink($data['url']),
1570 'updated' => DateTimeFormat::utcNow()
1573 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1575 foreach ($fields as $field) {
1576 $updated[$field] = defaults($data, $field, $contact[$field]);
1579 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1580 $updated['uri-date'] = DateTimeFormat::utcNow();
1583 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1584 $updated['name-date'] = DateTimeFormat::utcNow();
1587 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1594 * @brief Checks if the contact is archived
1596 * @param int $cid contact id
1598 * @return boolean Is the contact archived?
1599 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1601 public static function isArchived(int $cid)
1607 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1608 if (!DBA::isResult($contact)) {
1612 if ($contact['archive']) {
1616 // Check status of ActivityPub endpoints
1617 $apcontact = APContact::getByURL($contact['url'], false);
1618 if (!empty($apcontact)) {
1619 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1623 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1628 // Check status of Diaspora endpoints
1629 if (!empty($contact['batch'])) {
1630 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1631 return DBA::exists('contact', $condition);
1638 * @brief Checks if the contact is blocked
1640 * @param int $cid contact id
1642 * @return boolean Is the contact blocked?
1643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1645 public static function isBlocked($cid)
1651 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1652 if (!DBA::isResult($blocked)) {
1656 if (Network::isUrlBlocked($blocked['url'])) {
1660 return (bool) $blocked['blocked'];
1664 * @brief Checks if the contact is hidden
1666 * @param int $cid contact id
1668 * @return boolean Is the contact hidden?
1669 * @throws \Exception
1671 public static function isHidden($cid)
1677 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1678 if (!DBA::isResult($hidden)) {
1681 return (bool) $hidden['hidden'];
1685 * @brief Returns posts from a given contact url
1687 * @param string $contact_url Contact URL
1689 * @param bool $thread_mode
1690 * @param int $update
1691 * @return string posts in HTML
1692 * @throws \Exception
1694 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1696 $a = self::getApp();
1698 $cid = self::getIdForURL($contact_url);
1700 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1701 if (!DBA::isResult($contact)) {
1705 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1706 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1708 $sql = "`item`.`uid` = ?";
1711 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1714 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1715 $cid, GRAVITY_PARENT, local_user()];
1717 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1718 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1721 $pager = new Pager($a->query_string);
1723 $params = ['order' => ['received' => true],
1724 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1727 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1729 $items = Item::inArray($r);
1731 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1733 $r = Item::selectForUser(local_user(), [], $condition, $params);
1735 $items = Item::inArray($r);
1737 $o = conversation($a, $items, $pager, 'contact-posts', false);
1741 $o .= $pager->renderMinimal(count($items));
1748 * @brief Returns the account type name
1750 * The function can be called with either the user or the contact array
1752 * @param array $contact contact or user array
1755 public static function getAccountType(array $contact)
1757 // There are several fields that indicate that the contact or user is a forum
1758 // "page-flags" is a field in the user table,
1759 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1760 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1761 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1762 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1763 || (isset($contact['forum']) && intval($contact['forum']))
1764 || (isset($contact['prv']) && intval($contact['prv']))
1765 || (isset($contact['community']) && intval($contact['community']))
1767 $type = self::TYPE_COMMUNITY;
1769 $type = self::TYPE_PERSON;
1772 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1773 if (isset($contact["contact-type"])) {
1774 $type = $contact["contact-type"];
1777 if (isset($contact["account-type"])) {
1778 $type = $contact["account-type"];
1782 case self::TYPE_ORGANISATION:
1783 $account_type = L10n::t("Organisation");
1786 case self::TYPE_NEWS:
1787 $account_type = L10n::t('News');
1790 case self::TYPE_COMMUNITY:
1791 $account_type = L10n::t("Forum");
1799 return $account_type;
1803 * @brief Blocks a contact
1807 * @throws \Exception
1809 public static function block($cid, $reason = null)
1811 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1817 * @brief Unblocks a contact
1821 * @throws \Exception
1823 public static function unblock($cid)
1825 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1831 * @brief Updates the avatar links in a contact only if needed
1833 * @param string $avatar Link to avatar picture
1834 * @param int $uid User id of contact owner
1835 * @param int $cid Contact id
1836 * @param bool $force force picture update
1838 * @return array Returns array of the different avatar sizes
1839 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1840 * @throws \ImagickException
1842 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1844 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1845 if (!DBA::isResult($contact)) {
1848 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1851 if (($contact["avatar"] != $avatar) || $force) {
1852 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1855 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1856 DBA::update('contact', $fields, ['id' => $cid]);
1858 // Update the public contact (contact id = 0)
1860 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1861 if (DBA::isResult($pcontact)) {
1862 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1874 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1876 * @param integer $id contact id
1877 * @param integer $uid user id
1878 * @param string $url The profile URL of the contact
1879 * @param array $fields The fields that are updated
1881 * @throws \Exception
1883 private static function updateContact($id, $uid, $url, array $fields)
1885 if (!DBA::update('contact', $fields, ['id' => $id])) {
1886 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1890 // Search for duplicated contacts and get rid of them
1891 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1895 // Update the corresponding gcontact entry
1896 GContact::updateFromPublicContactID($id);
1898 // Archive or unarchive the contact. We only need to do this for the public contact.
1899 // The archive/unarchive function will update the personal contacts by themselves.
1900 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1901 if (!DBA::isResult($contact)) {
1902 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1906 if (!empty($fields['success_update'])) {
1907 self::unmarkForArchival($contact);
1908 } elseif (!empty($fields['failure_update'])) {
1909 self::markForArchival($contact);
1912 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1914 // These contacts are sharing with us, we don't poll them.
1915 // This means that we don't set the update fields in "OnePoll.php".
1916 $condition['rel'] = self::SHARING;
1917 DBA::update('contact', $fields, $condition);
1919 unset($fields['last-update']);
1920 unset($fields['success_update']);
1921 unset($fields['failure_update']);
1923 if (empty($fields)) {
1927 // We are polling these contacts, so we mustn't set the update fields here.
1928 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1929 DBA::update('contact', $fields, $condition);
1933 * @brief Remove duplicated contacts
1935 * @param string $nurl Normalised contact url
1936 * @param integer $uid User id
1938 * @throws \Exception
1940 public static function removeDuplicates(string $nurl, int $uid)
1942 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1943 $count = DBA::count('contact', $condition);
1948 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1949 if (!DBA::isResult($first_contact)) {
1950 // Shouldn't happen - so we handle it
1954 $first = $first_contact['id'];
1955 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1956 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1957 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1958 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1962 // Find all duplicates
1963 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1964 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1965 while ($duplicate = DBA::fetch($duplicates)) {
1966 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1970 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1972 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1977 * @param integer $id contact id
1978 * @param string $network Optional network we are probing for
1979 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1982 * @throws \ImagickException
1984 public static function updateFromProbe($id, $network = '', $force = false)
1987 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1988 This will reliably kill your communication with old Friendica contacts.
1991 // These fields aren't updated by this routine:
1992 // 'xmpp', 'sensitive'
1994 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
1995 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1996 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
1997 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1998 if (!DBA::isResult($contact)) {
2002 $uid = $contact['uid'];
2003 unset($contact['uid']);
2005 $pubkey = $contact['pubkey'];
2006 unset($contact['pubkey']);
2008 $contact['photo'] = $contact['avatar'];
2009 unset($contact['avatar']);
2011 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2013 $updated = DateTimeFormat::utcNow();
2015 // We must not try to update relay contacts via probe. They are no real contacts.
2016 // We check after the probing to be able to correct falsely detected contact types.
2017 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2018 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2019 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2020 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2024 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
2025 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
2026 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
2027 if ($force && ($uid == 0)) {
2028 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2033 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2034 $ret['unsearchable'] = $ret['hide'];
2037 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2038 $ret['forum'] = false;
2039 $ret['prv'] = false;
2040 $ret['contact-type'] = $ret['account-type'];
2041 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2042 $apcontact = APContact::getByURL($ret['url'], false);
2043 if (isset($apcontact['manually-approve'])) {
2044 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2045 $ret['prv'] = (bool)!$ret['forum'];
2050 $new_pubkey = $ret['pubkey'];
2054 // make sure to not overwrite existing values with blank entries except some technical fields
2055 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2056 foreach ($ret as $key => $val) {
2057 if (!array_key_exists($key, $contact)) {
2059 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2060 $ret[$key] = $contact[$key];
2061 } elseif ($ret[$key] != $contact[$key]) {
2066 if ($ret['network'] != Protocol::FEED) {
2067 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2072 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2077 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2078 $ret['updated'] = $updated;
2080 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2081 if (empty($pubkey) && !empty($new_pubkey)) {
2082 $ret['pubkey'] = $new_pubkey;
2085 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2086 $ret['uri-date'] = DateTimeFormat::utcNow();
2089 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2090 $ret['name-date'] = $updated;
2093 if ($force && ($uid == 0)) {
2094 $ret['last-update'] = $updated;
2095 $ret['success_update'] = $updated;
2098 unset($ret['photo']);
2100 self::updateContact($id, $uid, $ret['url'], $ret);
2105 public static function updateFromProbeByURL($url, $force = false)
2107 $id = self::getIdForURL($url);
2113 self::updateFromProbe($id, '', $force);
2119 * Detects if a given contact array belongs to a legacy DFRN connection
2121 * @param array $contact
2124 public static function isLegacyDFRNContact($contact)
2126 // Newer Friendica contacts are connected via AP, then these fields aren't set
2127 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2131 * Detects the communication protocol for a given contact url.
2132 * This is used to detect Friendica contacts that we can communicate via AP.
2134 * @param string $url contact url
2135 * @param string $network Network of that contact
2136 * @return string with protocol
2138 public static function getProtocol($url, $network)
2140 if ($network != Protocol::DFRN) {
2144 $apcontact = APContact::getByURL($url);
2145 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2146 return Protocol::ACTIVITYPUB;
2153 * Takes a $uid and a url/handle and adds a new contact
2154 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2155 * dfrn_request page.
2157 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2160 * $return['success'] boolean true if successful
2161 * $return['message'] error text if success is false.
2163 * @brief Takes a $uid and a url/handle and adds a new contact
2165 * @param string $url
2166 * @param bool $interactive
2167 * @param string $network
2169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2170 * @throws \ImagickException
2172 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2174 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2178 // remove ajax junk, e.g. Twitter
2179 $url = str_replace('/#!/', '/', $url);
2181 if (!Network::isUrlAllowed($url)) {
2182 $result['message'] = L10n::t('Disallowed profile URL.');
2186 if (Network::isUrlBlocked($url)) {
2187 $result['message'] = L10n::t('Blocked domain');
2192 $result['message'] = L10n::t('Connect URL missing.');
2196 $arr = ['url' => $url, 'contact' => []];
2198 Hook::callAll('follow', $arr);
2201 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2205 if (!empty($arr['contact']['name'])) {
2206 $ret = $arr['contact'];
2208 $ret = Probe::uri($url, $network, $uid, false);
2211 if (($network != '') && ($ret['network'] != $network)) {
2212 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2216 // check if we already have a contact
2217 // the poll url is more reliable than the profile url, as we may have
2218 // indirect links or webfinger links
2220 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2221 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2222 if (!DBA::isResult($contact)) {
2223 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2224 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2227 $protocol = self::getProtocol($url, $ret['network']);
2229 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2231 if (strlen($a->getURLPath())) {
2232 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2234 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2237 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2241 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2242 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2243 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2247 // This extra param just confuses things, remove it
2248 if ($protocol === Protocol::DIASPORA) {
2249 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2252 // do we have enough information?
2253 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2254 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2255 if (empty($ret['poll'])) {
2256 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2258 if (empty($ret['name'])) {
2259 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2261 if (empty($ret['url'])) {
2262 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2264 if (strpos($url, '@') !== false) {
2265 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2266 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2271 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2272 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2273 $ret['notify'] = '';
2276 if (!$ret['notify']) {
2277 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2280 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2282 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2284 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2286 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2288 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2292 if (DBA::isResult($contact)) {
2294 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2296 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2297 DBA::update('contact', $fields, ['id' => $contact['id']]);
2299 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2301 // create contact record
2304 'created' => DateTimeFormat::utcNow(),
2305 'url' => $ret['url'],
2306 'nurl' => Strings::normaliseLink($ret['url']),
2307 'addr' => $ret['addr'],
2308 'alias' => $ret['alias'],
2309 'batch' => $ret['batch'],
2310 'notify' => $ret['notify'],
2311 'poll' => $ret['poll'],
2312 'poco' => $ret['poco'],
2313 'name' => $ret['name'],
2314 'nick' => $ret['nick'],
2315 'network' => $ret['network'],
2316 'baseurl' => $ret['baseurl'],
2317 'protocol' => $protocol,
2318 'pubkey' => $ret['pubkey'],
2319 'rel' => $new_relation,
2320 'priority'=> $ret['priority'],
2321 'writable'=> $writeable,
2322 'hidden' => $hidden,
2325 'pending' => $pending,
2330 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2331 if (!DBA::isResult($contact)) {
2332 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2336 $contact_id = $contact['id'];
2337 $result['cid'] = $contact_id;
2339 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2341 // Update the avatar
2342 self::updateAvatar($ret['photo'], $uid, $contact_id);
2344 // pull feed and consume it, which should subscribe to the hub.
2346 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2348 $owner = User::getOwnerDataById($uid);
2350 if (DBA::isResult($owner)) {
2351 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2352 // create a follow slap
2354 $item['verb'] = ACTIVITY_FOLLOW;
2355 $item['follow'] = $contact["url"];
2357 $item['title'] = '';
2360 $item['attach'] = '';
2362 $slap = OStatus::salmon($item, $owner);
2364 if (!empty($contact['notify'])) {
2365 Salmon::slapper($owner, $contact['notify'], $slap);
2367 } elseif ($protocol == Protocol::DIASPORA) {
2368 $ret = Diaspora::sendShare($a->user, $contact);
2369 Logger::log('share returns: ' . $ret);
2370 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2371 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2372 if (empty($activity_id)) {
2373 // This really should never happen
2377 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2378 Logger::log('Follow returns: ' . $ret);
2382 $result['success'] = true;
2387 * @brief Updated contact's SSL policy
2389 * @param array $contact Contact array
2390 * @param string $new_policy New policy, valid: self,full
2392 * @return array Contact array with updated values
2393 * @throws \Exception
2395 public static function updateSslPolicy(array $contact, $new_policy)
2397 $ssl_changed = false;
2398 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2399 $ssl_changed = true;
2400 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2401 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2402 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2403 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2404 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2405 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2408 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2409 $ssl_changed = true;
2410 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2411 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2412 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2413 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2414 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2415 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2419 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2420 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2421 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2422 DBA::update('contact', $fields, ['id' => $contact['id']]);
2429 * @param array $importer Owner (local user) data
2430 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2431 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2432 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2433 * @param string $note Introduction additional message
2434 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2435 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2436 * @throws \ImagickException
2438 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2440 // Should always be set
2441 if (empty($datarray['author-id'])) {
2445 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2446 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2447 if (!DBA::isResult($pub_contact)) {
2448 // Should never happen
2452 // Contact is blocked at node-level
2453 if (self::isBlocked($datarray['author-id'])) {
2457 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2458 $name = $pub_contact['name'];
2459 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2460 $nick = $pub_contact['nick'];
2461 $network = $pub_contact['network'];
2463 // Ensure that we don't create a new contact when there already is one
2464 $cid = self::getIdForURL($url, $importer['uid']);
2466 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2469 if (!empty($contact)) {
2470 if (!empty($contact['pending'])) {
2471 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2475 // Contact is blocked at user-level
2476 if (!empty($contact['id']) && !empty($importer['id']) &&
2477 self::isBlockedByUser($contact['id'], $importer['id'])) {
2481 // Make sure that the existing contact isn't archived
2482 self::unmarkForArchival($contact);
2484 if (($contact['rel'] == self::SHARING)
2485 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2486 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2487 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2492 // send email notification to owner?
2493 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2494 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2498 // create contact record
2499 DBA::insert('contact', [
2500 'uid' => $importer['uid'],
2501 'created' => DateTimeFormat::utcNow(),
2503 'nurl' => Strings::normaliseLink($url),
2507 'network' => $network,
2508 'rel' => self::FOLLOWER,
2516 'id' => DBA::lastInsertId(),
2517 'network' => $network,
2523 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2525 /// @TODO Encapsulate this into a function/method
2526 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2527 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2528 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2529 // create notification
2530 $hash = Strings::getRandomHex();
2532 if (is_array($contact_record)) {
2533 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2534 'blocked' => false, 'knowyou' => false, 'note' => $note,
2535 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2538 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2540 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2541 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2544 'type' => NOTIFY_INTRO,
2545 'notify_flags' => $user['notify-flags'],
2546 'language' => $user['language'],
2547 'to_name' => $user['username'],
2548 'to_email' => $user['email'],
2549 'uid' => $user['uid'],
2550 'link' => System::baseUrl() . '/notifications/intro',
2551 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2552 'source_link' => $contact_record['url'],
2553 'source_photo' => $contact_record['photo'],
2554 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2558 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2559 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2560 DBA::update('contact', ['pending' => false], $condition);
2569 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2571 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2572 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2574 Contact::remove($contact['id']);
2578 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2580 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2581 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2583 Contact::remove($contact['id']);
2588 * @brief Create a birthday event.
2590 * Update the year and the birthday.
2592 public static function updateBirthdays()
2596 AND `bd` > "0001-01-01"
2597 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2598 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2599 AND NOT `contact`.`pending`
2600 AND NOT `contact`.`hidden`
2601 AND NOT `contact`.`blocked`
2602 AND NOT `contact`.`archive`
2603 AND NOT `contact`.`deleted`',
2608 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2610 while ($contact = DBA::fetch($contacts)) {
2611 Logger::log('update_contact_birthday: ' . $contact['bd']);
2613 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2615 if (Event::createBirthday($contact, $nextbd)) {
2619 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2620 ['id' => $contact['id']]
2627 * Remove the unavailable contact ids from the provided list
2629 * @param array $contact_ids Contact id list
2630 * @throws \Exception
2632 public static function pruneUnavailable(array &$contact_ids)
2634 if (empty($contact_ids)) {
2638 $str = DBA::escape(implode(',', $contact_ids));
2640 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2643 while($contact = DBA::fetch($stmt)) {
2644 $return[] = $contact['id'];
2649 $contact_ids = $return;
2653 * @brief Returns a magic link to authenticate remote visitors
2655 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2657 * @param string $contact_url The address of the target contact profile
2658 * @param string $url An url that we will be redirected to after the authentication
2660 * @return string with "redir" link
2661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2662 * @throws \ImagickException
2664 public static function magicLink($contact_url, $url = '')
2666 if (!local_user() && !remote_user()) {
2667 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2670 $data = self::getProbeDataFromDatabase($contact_url);
2672 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2675 // Prevents endless loop in case only a non-public contact exists for the contact URL
2676 unset($data['uid']);
2678 return self::magicLinkByContact($data, $url ?: $contact_url);
2682 * @brief Returns a magic link to authenticate remote visitors
2684 * @param integer $cid The contact id of the target contact profile
2685 * @param string $url An url that we will be redirected to after the authentication
2687 * @return string with "redir" link
2688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2689 * @throws \ImagickException
2691 public static function magicLinkbyId($cid, $url = '')
2693 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2695 return self::magicLinkByContact($contact, $url);
2699 * @brief Returns a magic link to authenticate remote visitors
2701 * @param array $contact The contact array with "uid", "network" and "url"
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 magicLinkByContact($contact, $url = '')
2710 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2711 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2714 // Only redirections to the same host do make sense
2715 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2719 if (!empty($contact['uid'])) {
2720 return self::magicLink($contact['url'], $url);
2723 if (empty($contact['id'])) {
2724 return $url ?: $contact['url'];
2727 $redirect = 'redir/' . $contact['id'];
2730 $redirect .= '?url=' . $url;
2737 * Remove a contact from all groups
2739 * @param integer $contact_id
2741 * @return boolean Success
2743 public static function removeFromGroups($contact_id)
2745 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2749 * Is the contact a forum?
2751 * @param integer $contactid ID of the contact
2753 * @return boolean "true" if it is a forum
2755 public static function isForum($contactid)
2757 $fields = ['forum', 'prv'];
2758 $condition = ['id' => $contactid];
2759 $contact = DBA::selectFirst('contact', $fields, $condition);
2760 if (!DBA::isResult($contact)) {
2765 return ($contact['forum'] || $contact['prv']);
2769 * Can the remote contact receive private messages?
2771 * @param array $contact
2774 public static function canReceivePrivateMessages(array $contact)
2776 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2777 $self = $contact['self'] ?? false;
2779 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;