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 * @brief Insert a row into the contact table
142 * @param array $param parameter array
143 * @param bool $on_duplicate_update Do an update on a duplicate entry
145 * @return boolean was the insert successful?
148 public static function insert($param, $on_duplicate_update = false)
150 $ret = DBA::insert('contact', $param, $on_duplicate_update);
152 $contact = DBA::selectFirst('contact', ['nurl', 'uid', 'id'], ['id' => DBA::lastInsertId()]);
153 if (!DBA::isResult($contact)) {
158 // Search for duplicated contacts and get rid of them
159 self::handleDuplicates($contact['nurl'], $contact['uid'], $contact['id']);
165 * @param array $fields contains the fields that are updated
166 * @param array $condition condition array with the key values
167 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate)
169 * @return boolean was the update successfull?
172 public static function update($fields, $condition, $old_fields = [])
174 $ret = DBA::update('contact', $fields, $condition, $old_fields);
176 // We quit when the update affected more than one row
177 if (DBA::affectedRows() > 1) {
181 // Don't proceed when the command aboved queried more than one row
182 // This is not a duplicate of the test above since that only checked for affected rows
183 if (DBA::count('contact', $condition) != 1) {
187 $contact = DBA::selectFirst('contact', ['nurl', 'uid', 'id'], $condition);
188 if (!DBA::isResult($contact)) {
193 // Search for duplicated contacts and get rid of them
194 self::handleDuplicates($contact['nurl'], $contact['uid'], $contact['id']);
200 * @param integer $id Contact ID
201 * @param array $fields Array of selected fields, empty for all
202 * @return array|boolean Contact record if it exists, false otherwise
205 public static function getById($id, $fields = [])
207 return DBA::selectFirst('contact', $fields, ['id' => $id]);
211 * @brief Tests if the given contact is a follower
213 * @param int $cid Either public contact id or user's contact id
214 * @param int $uid User ID
216 * @return boolean is the contact id a follower?
217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218 * @throws \ImagickException
220 public static function isFollower($cid, $uid)
222 if (self::isBlockedByUser($cid, $uid)) {
226 $cdata = self::getPublicAndUserContacID($cid, $uid);
227 if (empty($cdata['user'])) {
231 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
232 return DBA::exists('contact', $condition);
236 * @brief Tests if the given contact url is a follower
238 * @param string $url Contact URL
239 * @param int $uid User ID
241 * @return boolean is the contact id a follower?
242 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
243 * @throws \ImagickException
245 public static function isFollowerByURL($url, $uid)
247 $cid = self::getIdForURL($url, $uid, true);
253 return self::isFollower($cid, $uid);
257 * @brief Tests if the given user follow the given contact
259 * @param int $cid Either public contact id or user's contact id
260 * @param int $uid User ID
262 * @return boolean is the contact url being followed?
263 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
264 * @throws \ImagickException
266 public static function isSharing($cid, $uid)
268 if (self::isBlockedByUser($cid, $uid)) {
272 $cdata = self::getPublicAndUserContacID($cid, $uid);
273 if (empty($cdata['user'])) {
277 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
278 return DBA::exists('contact', $condition);
282 * @brief Tests if the given user follow the given contact url
284 * @param string $url Contact URL
285 * @param int $uid User ID
287 * @return boolean is the contact url being followed?
288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289 * @throws \ImagickException
291 public static function isSharingByURL($url, $uid)
293 $cid = self::getIdForURL($url, $uid, true);
299 return self::isSharing($cid, $uid);
303 * @brief Get the basepath for a given contact link
305 * @param string $url The contact link
307 * @return string basepath
308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309 * @throws \ImagickException
311 public static function getBasepath($url)
313 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
314 if (!empty($contact['baseurl'])) {
315 return $contact['baseurl'];
318 self::updateFromProbeByURL($url, true);
320 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
321 if (!empty($contact['baseurl'])) {
322 return $contact['baseurl'];
329 * Returns the public contact id of the given user id
331 * @param integer $uid User ID
333 * @return integer|boolean Public contact id for given user id
336 public static function getPublicIdByUserId($uid)
338 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
339 if (!DBA::isResult($self)) {
342 return self::getIdForURL($self['url'], 0, true);
346 * @brief Returns the contact id for the user and the public contact id for a given contact id
348 * @param int $cid Either public contact id or user's contact id
349 * @param int $uid User ID
351 * @return array with public and user's contact id
352 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
353 * @throws \ImagickException
355 public static function getPublicAndUserContacID($cid, $uid)
357 if (empty($uid) || empty($cid)) {
361 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
362 if (!DBA::isResult($contact)) {
366 // We quit when the user id don't match the user id of the provided contact
367 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
371 if ($contact['uid'] != 0) {
372 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
376 $ucid = $contact['id'];
378 $pcid = $contact['id'];
379 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
382 return ['public' => $pcid, 'user' => $ucid];
386 * Returns contact details for a given contact id in combination with a user id
388 * @param int $cid A contact ID
389 * @param int $uid The User ID
390 * @param array $fields The selected fields for the contact
392 * @return array The contact details
396 public static function getContactForUser($cid, $uid, array $fields = [])
398 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
400 if (!DBA::isResult($contact)) {
408 * @brief Block contact id for user id
410 * @param int $cid Either public contact id or user's contact id
411 * @param int $uid User ID
412 * @param boolean $blocked Is the contact blocked or unblocked?
415 public static function setBlockedForUser($cid, $uid, $blocked)
417 $cdata = self::getPublicAndUserContacID($cid, $uid);
422 if ($cdata['user'] != 0) {
423 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
426 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
429 // Blocked contact can't be in any group
430 self::removeFromGroups($cid);
435 * @brief Returns "block" state for contact id and user id
437 * @param int $cid Either public contact id or user's contact id
438 * @param int $uid User ID
440 * @return boolean is the contact id blocked for the given user?
443 public static function isBlockedByUser($cid, $uid)
445 $cdata = self::getPublicAndUserContacID($cid, $uid);
450 $public_blocked = false;
452 if (!empty($cdata['public'])) {
453 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
454 if (DBA::isResult($public_contact)) {
455 $public_blocked = $public_contact['blocked'];
459 $user_blocked = $public_blocked;
461 if (!empty($cdata['user'])) {
462 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
463 if (DBA::isResult($user_contact)) {
464 $user_blocked = $user_contact['blocked'];
468 if ($user_blocked != $public_blocked) {
469 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
472 return $user_blocked;
476 * @brief Ignore contact id for user id
478 * @param int $cid Either public contact id or user's contact id
479 * @param int $uid User ID
480 * @param boolean $ignored Is the contact ignored or unignored?
483 public static function setIgnoredForUser($cid, $uid, $ignored)
485 $cdata = self::getPublicAndUserContacID($cid, $uid);
490 if ($cdata['user'] != 0) {
491 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
494 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
498 * @brief Returns "ignore" state for contact id and user id
500 * @param int $cid Either public contact id or user's contact id
501 * @param int $uid User ID
503 * @return boolean is the contact id ignored for the given user?
506 public static function isIgnoredByUser($cid, $uid)
508 $cdata = self::getPublicAndUserContacID($cid, $uid);
513 $public_ignored = false;
515 if (!empty($cdata['public'])) {
516 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
517 if (DBA::isResult($public_contact)) {
518 $public_ignored = $public_contact['ignored'];
522 $user_ignored = $public_ignored;
524 if (!empty($cdata['user'])) {
525 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
526 if (DBA::isResult($user_contact)) {
527 $user_ignored = $user_contact['readonly'];
531 if ($user_ignored != $public_ignored) {
532 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
535 return $user_ignored;
539 * @brief Set "collapsed" for contact id and user id
541 * @param int $cid Either public contact id or user's contact id
542 * @param int $uid User ID
543 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
546 public static function setCollapsedForUser($cid, $uid, $collapsed)
548 $cdata = self::getPublicAndUserContacID($cid, $uid);
553 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
557 * @brief Returns "collapsed" state for contact id and user id
559 * @param int $cid Either public contact id or user's contact id
560 * @param int $uid User ID
562 * @return boolean is the contact id blocked for the given user?
563 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
564 * @throws \ImagickException
566 public static function isCollapsedByUser($cid, $uid)
568 $cdata = self::getPublicAndUserContacID($cid, $uid);
575 if (!empty($cdata['public'])) {
576 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
577 if (DBA::isResult($public_contact)) {
578 $collapsed = $public_contact['collapsed'];
586 * @brief Returns a list of contacts belonging in a group
592 public static function getByGroupId($gid)
597 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
599 INNER JOIN `group_member`
600 ON `contact`.`id` = `group_member`.`contact-id`
602 AND `contact`.`uid` = ?
603 AND NOT `contact`.`self`
604 AND NOT `contact`.`deleted`
605 AND NOT `contact`.`blocked`
606 AND NOT `contact`.`pending`
607 ORDER BY `contact`.`name` ASC',
612 if (DBA::isResult($stmt)) {
613 $return = DBA::toArray($stmt);
621 * @brief Returns the count of OStatus contacts in a group
627 public static function getOStatusCountByGroupId($gid)
631 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
633 INNER JOIN `group_member`
634 ON `contact`.`id` = `group_member`.`contact-id`
636 AND `contact`.`uid` = ?
637 AND `contact`.`network` = ?
638 AND `contact`.`notify` != ""',
643 $return = $contacts['count'];
650 * Creates the self-contact for the provided user id
653 * @return bool Operation success
654 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
656 public static function createSelfFromUserId($uid)
658 // Only create the entry if it doesn't exist yet
659 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
663 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
664 if (!DBA::isResult($user)) {
668 $return = DBA::insert('contact', [
669 'uid' => $user['uid'],
670 'created' => DateTimeFormat::utcNow(),
672 'name' => $user['username'],
673 'nick' => $user['nickname'],
674 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
675 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
676 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
679 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
680 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
681 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
682 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
683 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
684 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
685 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
686 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
687 'name-date' => DateTimeFormat::utcNow(),
688 'uri-date' => DateTimeFormat::utcNow(),
689 'avatar-date' => DateTimeFormat::utcNow(),
697 * Updates the self-contact for the provided user id
700 * @param boolean $update_avatar Force the avatar update
701 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
703 public static function updateSelfFromUserID($uid, $update_avatar = false)
705 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
706 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
707 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
708 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
709 if (!DBA::isResult($self)) {
713 $fields = ['nickname', 'page-flags', 'account-type'];
714 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
715 if (!DBA::isResult($user)) {
719 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
720 'country-name', 'gender', 'pub_keywords', 'xmpp'];
721 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
722 if (!DBA::isResult($profile)) {
726 $file_suffix = 'jpg';
728 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
729 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
730 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
731 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
732 'xmpp' => $profile['xmpp']];
734 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
735 if (DBA::isResult($avatar)) {
736 if ($update_avatar) {
737 $fields['avatar-date'] = DateTimeFormat::utcNow();
740 // Creating the path to the avatar, beginning with the file suffix
741 $types = Image::supportedTypes();
742 if (isset($types[$avatar['type']])) {
743 $file_suffix = $types[$avatar['type']];
746 // We are adding a timestamp value so that other systems won't use cached content
747 $timestamp = strtotime($fields['avatar-date']);
749 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
750 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
752 $fields['photo'] = $prefix . '4' . $suffix;
753 $fields['thumb'] = $prefix . '5' . $suffix;
754 $fields['micro'] = $prefix . '6' . $suffix;
756 // We hadn't found a photo entry, so we use the default avatar
757 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
758 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
759 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
762 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
763 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
764 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
766 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
767 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
768 $fields['nurl'] = Strings::normaliseLink($fields['url']);
769 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
770 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
771 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
772 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
773 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
774 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
778 foreach ($fields as $field => $content) {
779 if ($self[$field] != $content) {
785 if ($fields['name'] != $self['name']) {
786 $fields['name-date'] = DateTimeFormat::utcNow();
788 $fields['updated'] = DateTimeFormat::utcNow();
789 DBA::update('contact', $fields, ['id' => $self['id']]);
791 // Update the public contact as well
792 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
794 // Update the profile
795 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
796 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
797 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
802 * @brief Marks a contact for removal
804 * @param int $id contact id
806 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
808 public static function remove($id)
810 // We want just to make sure that we don't delete our "self" contact
811 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
812 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
816 // Archive the contact
817 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
819 // Delete it in the background
820 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
824 * @brief Sends an unfriend message. Does not remove the contact
826 * @param array $user User unfriending
827 * @param array $contact Contact unfriended
828 * @param boolean $dissolve Remove the contact on the remote side
830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
831 * @throws \ImagickException
833 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
835 if (empty($contact['network'])) {
839 $protocol = $contact['network'];
840 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
841 $protocol = Protocol::ACTIVITYPUB;
844 if (($protocol == Protocol::DFRN) && $dissolve) {
845 DFRN::deliver($user, $contact, 'placeholder', true);
846 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
847 // create an unfollow slap
849 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
850 $item['follow'] = $contact["url"];
855 $item['attach'] = '';
856 $slap = OStatus::salmon($item, $user);
858 if (!empty($contact['notify'])) {
859 Salmon::slapper($user, $contact['notify'], $slap);
861 } elseif ($protocol == Protocol::DIASPORA) {
862 Diaspora::sendUnshare($user, $contact);
863 } elseif ($protocol == Protocol::ACTIVITYPUB) {
864 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
867 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
873 * @brief Marks a contact for archival after a communication issue delay
875 * Contact has refused to recognise us as a friend. We will start a countdown.
876 * If they still don't recognise us in 32 days, the relationship is over,
877 * and we won't waste any more time trying to communicate with them.
878 * This provides for the possibility that their database is temporarily messed
879 * up or some other transient event and that there's a possibility we could recover from it.
881 * @param array $contact contact to mark for archival
883 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
885 public static function markForArchival(array $contact)
887 if (!isset($contact['url']) && !empty($contact['id'])) {
888 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
889 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
890 if (!DBA::isResult($contact)) {
893 } elseif (!isset($contact['url'])) {
894 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
897 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
899 // Contact already archived or "self" contact? => nothing to do
900 if ($contact['archive'] || $contact['self']) {
904 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
905 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
906 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
909 * We really should send a notification to the owner after 2-3 weeks
910 * so they won't be surprised when the contact vanishes and can take
911 * remedial action if this was a serious mistake or glitch
914 /// @todo Check for contact vitality via probing
915 $archival_days = Config::get('system', 'archival_days', 32);
917 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
918 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
919 /* Relationship is really truly dead. archive them rather than
920 * delete, though if the owner tries to unarchive them we'll start
921 * the whole process over again.
923 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
924 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
925 GContact::updateFromPublicContactURL($contact['url']);
931 * @brief Cancels the archival countdown
933 * @see Contact::markForArchival()
935 * @param array $contact contact to be unmarked for archival
939 public static function unmarkForArchival(array $contact)
941 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
942 $exists = DBA::exists('contact', $condition);
944 // We don't need to update, we never marked this contact for archival
949 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
951 if (!isset($contact['url']) && !empty($contact['id'])) {
952 $fields = ['id', 'url', 'batch'];
953 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
954 if (!DBA::isResult($contact)) {
959 // It's a miracle. Our dead contact has inexplicably come back to life.
960 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
961 DBA::update('contact', $fields, ['id' => $contact['id']]);
962 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
963 GContact::updateFromPublicContactURL($contact['url']);
965 if (!empty($contact['batch'])) {
966 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
967 DBA::update('contact', $fields, $condition);
972 * @brief Get contact data for a given profile link
974 * The function looks at several places (contact table and gcontact table) for the contact
975 * It caches its result for the same script execution to prevent duplicate calls
977 * @param string $url The profile link
978 * @param int $uid User id
979 * @param array $default If not data was found take this data as default value
981 * @return array Contact data
982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
984 public static function getDetailsByURL($url, $uid = -1, array $default = [])
996 if (isset($cache[$url][$uid])) {
997 return $cache[$url][$uid];
1000 $ssl_url = str_replace('http://', 'https://', $url);
1002 // Fetch contact data from the contact table for the given user
1003 $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`,
1004 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1005 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
1006 $r = DBA::toArray($s);
1008 // Fetch contact data from the contact table for the given user, checking with the alias
1009 if (!DBA::isResult($r)) {
1010 $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`,
1011 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1012 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
1013 $r = DBA::toArray($s);
1016 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1017 if (!DBA::isResult($r)) {
1018 $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`,
1019 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1020 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
1021 $r = DBA::toArray($s);
1024 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
1025 if (!DBA::isResult($r)) {
1026 $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`,
1027 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1028 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
1029 $r = DBA::toArray($s);
1032 // Fetch the data from the gcontact table
1033 if (!DBA::isResult($r)) {
1034 $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`,
1035 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1036 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
1037 $r = DBA::toArray($s);
1040 if (DBA::isResult($r)) {
1041 // If there is more than one entry we filter out the connector networks
1042 if (count($r) > 1) {
1043 foreach ($r as $id => $result) {
1044 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
1050 $profile = array_shift($r);
1052 // "bd" always contains the upcoming birthday of a contact.
1053 // "birthday" might contain the birthday including the year of birth.
1054 if ($profile["birthday"] > DBA::NULL_DATE) {
1055 $bd_timestamp = strtotime($profile["birthday"]);
1056 $month = date("m", $bd_timestamp);
1057 $day = date("d", $bd_timestamp);
1059 $current_timestamp = time();
1060 $current_year = date("Y", $current_timestamp);
1061 $current_month = date("m", $current_timestamp);
1062 $current_day = date("d", $current_timestamp);
1064 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1065 $current = $current_year . "-" . $current_month . "-" . $current_day;
1067 if ($profile["bd"] < $current) {
1068 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1071 $profile["bd"] = DBA::NULL_DATE;
1074 $profile = $default;
1077 if (empty($profile["photo"]) && isset($default["photo"])) {
1078 $profile["photo"] = $default["photo"];
1081 if (empty($profile["name"]) && isset($default["name"])) {
1082 $profile["name"] = $default["name"];
1085 if (empty($profile["network"]) && isset($default["network"])) {
1086 $profile["network"] = $default["network"];
1089 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1090 $profile["thumb"] = $profile["photo"];
1093 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1094 $profile["micro"] = $profile["thumb"];
1097 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1098 && in_array($profile["network"], Protocol::FEDERATED)
1100 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1103 // Show contact details of Diaspora contacts only if connected
1104 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1105 $profile["location"] = "";
1106 $profile["about"] = "";
1107 $profile["gender"] = "";
1108 $profile["birthday"] = DBA::NULL_DATE;
1111 $cache[$url][$uid] = $profile;
1117 * @brief Get contact data for a given address
1119 * The function looks at several places (contact table and gcontact table) for the contact
1121 * @param string $addr The profile link
1122 * @param int $uid User id
1124 * @return array Contact data
1125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1126 * @throws \ImagickException
1128 public static function getDetailsByAddr($addr, $uid = -1)
1135 $uid = local_user();
1138 // Fetch contact data from the contact table for the given user
1139 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1140 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1141 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1145 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1146 if (!DBA::isResult($r)) {
1147 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1148 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1149 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1154 // Fetch the data from the gcontact table
1155 if (!DBA::isResult($r)) {
1156 $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`,
1157 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1158 FROM `gcontact` WHERE `addr` = '%s'",
1163 if (!DBA::isResult($r)) {
1164 $data = Probe::uri($addr);
1166 $profile = self::getDetailsByURL($data['url'], $uid);
1175 * @brief Returns the data array for the photo menu of a given contact
1177 * @param array $contact contact
1178 * @param int $uid optional, default 0
1180 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1181 * @throws \ImagickException
1183 public static function photoMenu(array $contact, $uid = 0)
1188 $contact_drop_link = '';
1192 $uid = local_user();
1195 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1197 $profile_link = self::magicLink($contact['url']);
1198 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1203 // Look for our own contact if the uid doesn't match and isn't public
1204 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1205 if (DBA::isResult($contact_own)) {
1206 return self::photoMenu($contact_own, $uid);
1211 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1213 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1215 $profile_link = $contact['url'];
1218 if ($profile_link === 'mailbox') {
1223 $status_link = $profile_link . '?tab=status';
1224 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1225 $profile_link = $profile_link . '?tab=profile';
1228 if (self::canReceivePrivateMessages($contact)) {
1229 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1232 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1233 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1236 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1238 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1240 if (!$contact['self']) {
1241 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1246 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1248 if (empty($contact['uid'])) {
1249 $connlnk = 'follow/?url=' . $contact['url'];
1251 'profile' => [L10n::t('View Profile'), $profile_link, true],
1252 'network' => [L10n::t('Network Posts'), $posts_link, false],
1253 'edit' => [L10n::t('View Contact'), $contact_url, false],
1254 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1258 'status' => [L10n::t('View Status'), $status_link, true],
1259 'profile' => [L10n::t('View Profile'), $profile_link, true],
1260 'photos' => [L10n::t('View Photos'), $photos_link, true],
1261 'network' => [L10n::t('Network Posts'), $posts_link, false],
1262 'edit' => [L10n::t('View Contact'), $contact_url, false],
1263 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1264 'pm' => [L10n::t('Send PM'), $pm_url, false],
1265 'poke' => [L10n::t('Poke'), $poke_link, false],
1269 $args = ['contact' => $contact, 'menu' => &$menu];
1271 Hook::callAll('contact_photo_menu', $args);
1273 $menucondensed = [];
1275 foreach ($menu as $menuname => $menuitem) {
1276 if ($menuitem[1] != '') {
1277 $menucondensed[$menuname] = $menuitem;
1281 return $menucondensed;
1285 * @brief Returns ungrouped contact count or list for user
1287 * Returns either the total number of ungrouped contacts for the given user
1288 * id or a paginated list of ungrouped contacts.
1290 * @param int $uid uid
1292 * @throws \Exception
1294 public static function getUngroupedList($uid)
1304 SELECT DISTINCT(`contact-id`)
1306 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1307 WHERE `group`.`uid` = %d
1308 )", intval($uid), intval($uid));
1312 * Have a look at all contact tables for a given profile url.
1313 * This function works as a replacement for probing the contact.
1315 * @param string $url Contact URL
1316 * @param integer $cid Contact ID
1318 * @return array Contact array in the "probe" structure
1320 private static function getProbeDataFromDatabase($url, $cid = null)
1322 // The link could be provided as http although we stored it as https
1323 $ssl_url = str_replace('http://', 'https://', $url);
1325 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1326 'photo', 'keywords', 'location', 'about', 'network',
1327 'priority', 'batch', 'request', 'confirm', 'poco'];
1330 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1331 if (DBA::isResult($data)) {
1336 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1338 if (!DBA::isResult($data)) {
1339 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1340 $data = DBA::selectFirst('contact', $fields, $condition);
1343 if (DBA::isResult($data)) {
1344 // For security reasons we don't fetch key data from our users
1345 $data["pubkey"] = '';
1349 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1350 'photo', 'keywords', 'location', 'about', 'network'];
1351 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1353 if (!DBA::isResult($data)) {
1354 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1355 $data = DBA::selectFirst('contact', $fields, $condition);
1358 if (DBA::isResult($data)) {
1359 $data["pubkey"] = '';
1361 $data["priority"] = 0;
1362 $data["batch"] = '';
1363 $data["request"] = '';
1364 $data["confirm"] = '';
1369 $data = ActivityPub::probeProfile($url, false);
1370 if (!empty($data)) {
1374 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1375 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1376 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1378 if (!DBA::isResult($data)) {
1379 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1380 $data = DBA::selectFirst('contact', $fields, $condition);
1383 if (DBA::isResult($data)) {
1384 $data["pubkey"] = '';
1385 $data["keywords"] = '';
1386 $data["location"] = '';
1387 $data["about"] = '';
1396 * @brief Fetch the contact id for a given URL and user
1398 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1399 * `addr` or `alias`.
1401 * If there's no record and we aren't looking for a public contact, we quit.
1402 * If there's one, we check that it isn't time to update the picture else we
1403 * directly return the found contact id.
1405 * Second, we probe the provided $url whether it's http://server.tld/profile or
1406 * nick@server.tld. We quit if we can't get any info back.
1408 * Third, we create the contact record if it doesn't exist
1410 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1411 * if there's any updates
1413 * @param string $url Contact URL
1414 * @param integer $uid The user id for the contact (0 = public contact)
1415 * @param boolean $no_update Don't update the contact
1416 * @param array $default Default value for creating the contact when every else fails
1417 * @param boolean $in_loop Internally used variable to prevent an endless loop
1419 * @return integer Contact ID
1420 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1421 * @throws \ImagickException
1423 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1425 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1433 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1434 // We first try the nurl (http://server.tld/nick), most common case
1435 $fields = ['id', 'avatar', 'updated', 'network'];
1436 $options = ['order' => ['id']];
1437 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1439 // Then the addr (nick@server.tld)
1440 if (!DBA::isResult($contact)) {
1441 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1444 // Then the alias (which could be anything)
1445 if (!DBA::isResult($contact)) {
1446 // The link could be provided as http although we stored it as https
1447 $ssl_url = str_replace('http://', 'https://', $url);
1448 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1449 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1452 if (DBA::isResult($contact)) {
1453 $contact_id = $contact["id"];
1455 // Update the contact every 7 days
1456 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1458 // We force the update if the avatar is empty
1459 if (empty($contact['avatar'])) {
1460 $update_contact = true;
1463 // Update the contact in the background if needed but it is called by the frontend
1464 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1465 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1468 if (!$update_contact || $no_update) {
1471 } elseif ($uid != 0) {
1472 // Non-existing user-specific contact, exiting
1476 if ($no_update && empty($default)) {
1477 // When we don't want to update, we look if we know this contact in any way
1478 $data = self::getProbeDataFromDatabase($url, $contact_id);
1479 $background_update = true;
1480 } elseif ($no_update && !empty($default['network'])) {
1481 // If there are default values, take these
1483 $background_update = false;
1486 $background_update = false;
1490 $data = Probe::uri($url, "", $uid);
1492 // Ensure that there is a gserver entry
1493 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1494 PortableContact::checkServer($data['baseurl']);
1498 // Take the default values when probing failed
1499 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1500 $data = array_merge($data, $default);
1507 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1508 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1514 'created' => DateTimeFormat::utcNow(),
1515 'url' => $data['url'],
1516 'nurl' => Strings::normaliseLink($data['url']),
1517 'addr' => defaults($data, 'addr', ''),
1518 'alias' => defaults($data, 'alias', ''),
1519 'notify' => defaults($data, 'notify', ''),
1520 'poll' => defaults($data, 'poll', ''),
1521 'name' => defaults($data, 'name', ''),
1522 'nick' => defaults($data, 'nick', ''),
1523 'photo' => defaults($data, 'photo', ''),
1524 'keywords' => defaults($data, 'keywords', ''),
1525 'location' => defaults($data, 'location', ''),
1526 'about' => defaults($data, 'about', ''),
1527 'network' => $data['network'],
1528 'pubkey' => defaults($data, 'pubkey', ''),
1529 'rel' => self::SHARING,
1530 'priority' => defaults($data, 'priority', 0),
1531 'batch' => defaults($data, 'batch', ''),
1532 'request' => defaults($data, 'request', ''),
1533 'confirm' => defaults($data, 'confirm', ''),
1534 'poco' => defaults($data, 'poco', ''),
1535 'baseurl' => defaults($data, 'baseurl', ''),
1536 'name-date' => DateTimeFormat::utcNow(),
1537 'uri-date' => DateTimeFormat::utcNow(),
1538 'avatar-date' => DateTimeFormat::utcNow(),
1544 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1546 // Before inserting we do check if the entry does exist now.
1547 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1548 if (!DBA::isResult($contact)) {
1549 Logger::info('Create new contact', $fields);
1551 DBA::insert('contact', $fields);
1553 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1554 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1555 if (!DBA::isResult($contact)) {
1556 Logger::info('Contact creation failed', $fields);
1561 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1564 $contact_id = $contact["id"];
1567 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1568 self::updateAvatar($data['photo'], $uid, $contact_id);
1571 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1572 if ($background_update) {
1573 // Update in the background when we fetched the data solely from the database
1574 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1576 // Else do a direct update
1577 self::updateFromProbe($contact_id, '', false);
1579 // Update the gcontact entry
1581 GContact::updateFromPublicContactID($contact_id);
1585 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1586 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1588 // This condition should always be true
1589 if (!DBA::isResult($contact)) {
1594 'url' => $data['url'],
1595 'nurl' => Strings::normaliseLink($data['url']),
1596 'updated' => DateTimeFormat::utcNow()
1599 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1601 foreach ($fields as $field) {
1602 $updated[$field] = defaults($data, $field, $contact[$field]);
1605 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1606 $updated['uri-date'] = DateTimeFormat::utcNow();
1609 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1610 $updated['name-date'] = DateTimeFormat::utcNow();
1613 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1620 * @brief Checks if the contact is archived
1622 * @param int $cid contact id
1624 * @return boolean Is the contact archived?
1625 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1627 public static function isArchived(int $cid)
1633 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1634 if (!DBA::isResult($contact)) {
1638 if ($contact['archive']) {
1642 // Check status of ActivityPub endpoints
1643 $apcontact = APContact::getByURL($contact['url'], false);
1644 if (!empty($apcontact)) {
1645 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1649 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1654 // Check status of Diaspora endpoints
1655 if (!empty($contact['batch'])) {
1656 return DBA::exists('contact', ['archive' => true, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY]);
1663 * @brief Checks if the contact is blocked
1665 * @param int $cid contact id
1667 * @return boolean Is the contact blocked?
1668 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1670 public static function isBlocked($cid)
1676 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1677 if (!DBA::isResult($blocked)) {
1681 if (Network::isUrlBlocked($blocked['url'])) {
1685 return (bool) $blocked['blocked'];
1689 * @brief Checks if the contact is hidden
1691 * @param int $cid contact id
1693 * @return boolean Is the contact hidden?
1694 * @throws \Exception
1696 public static function isHidden($cid)
1702 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1703 if (!DBA::isResult($hidden)) {
1706 return (bool) $hidden['hidden'];
1710 * @brief Returns posts from a given contact url
1712 * @param string $contact_url Contact URL
1714 * @param bool $thread_mode
1715 * @param int $update
1716 * @return string posts in HTML
1717 * @throws \Exception
1719 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1721 $a = self::getApp();
1723 $cid = self::getIdForURL($contact_url);
1725 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1726 if (!DBA::isResult($contact)) {
1730 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1731 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1733 $sql = "`item`.`uid` = ?";
1736 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1739 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1740 $cid, GRAVITY_PARENT, local_user()];
1742 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1743 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1746 $pager = new Pager($a->query_string);
1748 $params = ['order' => ['received' => true],
1749 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1752 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1754 $items = Item::inArray($r);
1756 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1758 $r = Item::selectForUser(local_user(), [], $condition, $params);
1760 $items = Item::inArray($r);
1762 $o = conversation($a, $items, $pager, 'contact-posts', false);
1766 $o .= $pager->renderMinimal(count($items));
1773 * @brief Returns the account type name
1775 * The function can be called with either the user or the contact array
1777 * @param array $contact contact or user array
1780 public static function getAccountType(array $contact)
1782 // There are several fields that indicate that the contact or user is a forum
1783 // "page-flags" is a field in the user table,
1784 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1785 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1786 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1787 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1788 || (isset($contact['forum']) && intval($contact['forum']))
1789 || (isset($contact['prv']) && intval($contact['prv']))
1790 || (isset($contact['community']) && intval($contact['community']))
1792 $type = self::TYPE_COMMUNITY;
1794 $type = self::TYPE_PERSON;
1797 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1798 if (isset($contact["contact-type"])) {
1799 $type = $contact["contact-type"];
1802 if (isset($contact["account-type"])) {
1803 $type = $contact["account-type"];
1807 case self::TYPE_ORGANISATION:
1808 $account_type = L10n::t("Organisation");
1811 case self::TYPE_NEWS:
1812 $account_type = L10n::t('News');
1815 case self::TYPE_COMMUNITY:
1816 $account_type = L10n::t("Forum");
1824 return $account_type;
1828 * @brief Blocks a contact
1832 * @throws \Exception
1834 public static function block($cid, $reason = null)
1836 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1842 * @brief Unblocks a contact
1846 * @throws \Exception
1848 public static function unblock($cid)
1850 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1856 * @brief Updates the avatar links in a contact only if needed
1858 * @param string $avatar Link to avatar picture
1859 * @param int $uid User id of contact owner
1860 * @param int $cid Contact id
1861 * @param bool $force force picture update
1863 * @return array Returns array of the different avatar sizes
1864 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1865 * @throws \ImagickException
1867 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1869 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1870 if (!DBA::isResult($contact)) {
1873 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1876 if (($contact["avatar"] != $avatar) || $force) {
1877 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1880 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1881 DBA::update('contact', $fields, ['id' => $cid]);
1883 // Update the public contact (contact id = 0)
1885 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1886 if (DBA::isResult($pcontact)) {
1887 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1899 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1901 * @param integer $id contact id
1902 * @param integer $uid user id
1903 * @param string $url The profile URL of the contact
1904 * @param array $fields The fields that are updated
1906 * @throws \Exception
1908 private static function updateContact($id, $uid, $url, array $fields)
1910 if (!DBA::update('contact', $fields, ['id' => $id])) {
1911 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1915 // Search for duplicated contacts and get rid of them
1916 if (self::handleDuplicates(Strings::normaliseLink($url), $uid, $id) || ($uid != 0)) {
1920 // Update the corresponding gcontact entry
1921 GContact::updateFromPublicContactID($id);
1923 // Archive or unarchive the contact. We only need to do this for the public contact.
1924 // The archive/unarchive function will update the personal contacts by themselves.
1925 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1926 if (!DBA::isResult($contact)) {
1927 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1931 if (!empty($fields['success_update'])) {
1932 self::unmarkForArchival($contact);
1933 } elseif (!empty($fields['failure_update'])) {
1934 self::markForArchival($contact);
1937 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1939 // These contacts are sharing with us, we don't poll them.
1940 // This means that we don't set the update fields in "OnePoll.php".
1941 $condition['rel'] = self::SHARING;
1942 DBA::update('contact', $fields, $condition);
1944 unset($fields['last-update']);
1945 unset($fields['success_update']);
1946 unset($fields['failure_update']);
1948 if (empty($fields)) {
1952 // We are polling these contacts, so we mustn't set the update fields here.
1953 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1954 DBA::update('contact', $fields, $condition);
1958 * @brief Helper function for "updateFromProbe". Remove duplicated contacts
1960 * @param string $nurl Normalised contact url
1961 * @param integer $uid User id
1962 * @param integer $id Contact id of a duplicate
1964 * @throws \Exception
1966 private static function handleDuplicates($nurl, $uid, $id)
1968 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1969 $count = DBA::count('contact', $condition);
1974 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1975 if (!DBA::isResult($first_contact)) {
1976 // Shouldn't happen - so we handle it
1980 $first = $first_contact['id'];
1981 Logger::info('Found duplicates', ['count' => $count, 'id' => $id, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1982 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1983 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1984 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1988 // Find all duplicates
1989 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1990 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1991 while ($duplicate = DBA::fetch($duplicates)) {
1992 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1996 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1998 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
2003 * @param integer $id contact id
2004 * @param string $network Optional network we are probing for
2005 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
2007 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2008 * @throws \ImagickException
2010 public static function updateFromProbe($id, $network = '', $force = false)
2013 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2014 This will reliably kill your communication with old Friendica contacts.
2017 // These fields aren't updated by this routine:
2018 // 'xmpp', 'sensitive'
2020 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
2021 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2022 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
2023 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2024 if (!DBA::isResult($contact)) {
2028 $uid = $contact['uid'];
2029 unset($contact['uid']);
2031 $pubkey = $contact['pubkey'];
2032 unset($contact['pubkey']);
2034 $contact['photo'] = $contact['avatar'];
2035 unset($contact['avatar']);
2037 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
2039 $updated = DateTimeFormat::utcNow();
2041 // We must not try to update relay contacts via probe. They are no real contacts.
2042 // We check after the probing to be able to correct falsely detected contact types.
2043 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2044 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2045 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
2046 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2050 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
2051 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
2052 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
2053 if ($force && ($uid == 0)) {
2054 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
2059 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2060 $ret['unsearchable'] = $ret['hide'];
2063 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2064 $ret['forum'] = false;
2065 $ret['prv'] = false;
2066 $ret['contact-type'] = $ret['account-type'];
2067 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2068 $apcontact = APContact::getByURL($ret['url'], false);
2069 if (isset($apcontact['manually-approve'])) {
2070 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2071 $ret['prv'] = (bool)!$ret['forum'];
2076 $new_pubkey = $ret['pubkey'];
2080 // make sure to not overwrite existing values with blank entries except some technical fields
2081 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2082 foreach ($ret as $key => $val) {
2083 if (!array_key_exists($key, $contact)) {
2085 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2086 $ret[$key] = $contact[$key];
2087 } elseif ($ret[$key] != $contact[$key]) {
2092 if ($ret['network'] != Protocol::FEED) {
2093 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2098 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2103 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2104 $ret['updated'] = $updated;
2106 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2107 if (empty($pubkey) && !empty($new_pubkey)) {
2108 $ret['pubkey'] = $new_pubkey;
2111 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2112 $ret['uri-date'] = DateTimeFormat::utcNow();
2115 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2116 $ret['name-date'] = $updated;
2119 if ($force && ($uid == 0)) {
2120 $ret['last-update'] = $updated;
2121 $ret['success_update'] = $updated;
2124 unset($ret['photo']);
2126 self::updateContact($id, $uid, $ret['url'], $ret);
2131 public static function updateFromProbeByURL($url, $force = false)
2133 $id = self::getIdForURL($url);
2139 self::updateFromProbe($id, '', $force);
2145 * Detects if a given contact array belongs to a legacy DFRN connection
2147 * @param array $contact
2150 public static function isLegacyDFRNContact($contact)
2152 // Newer Friendica contacts are connected via AP, then these fields aren't set
2153 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2157 * Detects the communication protocol for a given contact url.
2158 * This is used to detect Friendica contacts that we can communicate via AP.
2160 * @param string $url contact url
2161 * @param string $network Network of that contact
2162 * @return string with protocol
2164 public static function getProtocol($url, $network)
2166 if ($network != Protocol::DFRN) {
2170 $apcontact = APContact::getByURL($url);
2171 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2172 return Protocol::ACTIVITYPUB;
2179 * Takes a $uid and a url/handle and adds a new contact
2180 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2181 * dfrn_request page.
2183 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2186 * $return['success'] boolean true if successful
2187 * $return['message'] error text if success is false.
2189 * @brief Takes a $uid and a url/handle and adds a new contact
2191 * @param string $url
2192 * @param bool $interactive
2193 * @param string $network
2195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2196 * @throws \ImagickException
2198 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2200 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2204 // remove ajax junk, e.g. Twitter
2205 $url = str_replace('/#!/', '/', $url);
2207 if (!Network::isUrlAllowed($url)) {
2208 $result['message'] = L10n::t('Disallowed profile URL.');
2212 if (Network::isUrlBlocked($url)) {
2213 $result['message'] = L10n::t('Blocked domain');
2218 $result['message'] = L10n::t('Connect URL missing.');
2222 $arr = ['url' => $url, 'contact' => []];
2224 Hook::callAll('follow', $arr);
2227 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2231 if (!empty($arr['contact']['name'])) {
2232 $ret = $arr['contact'];
2234 $ret = Probe::uri($url, $network, $uid, false);
2237 if (($network != '') && ($ret['network'] != $network)) {
2238 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2242 // check if we already have a contact
2243 // the poll url is more reliable than the profile url, as we may have
2244 // indirect links or webfinger links
2246 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2247 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2248 if (!DBA::isResult($contact)) {
2249 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2250 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2253 $protocol = self::getProtocol($url, $ret['network']);
2255 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2257 if (strlen($a->getURLPath())) {
2258 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2260 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2263 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2267 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2268 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2269 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2273 // This extra param just confuses things, remove it
2274 if ($protocol === Protocol::DIASPORA) {
2275 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2278 // do we have enough information?
2279 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2280 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2281 if (empty($ret['poll'])) {
2282 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2284 if (empty($ret['name'])) {
2285 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2287 if (empty($ret['url'])) {
2288 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2290 if (strpos($url, '@') !== false) {
2291 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2292 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2297 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2298 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2299 $ret['notify'] = '';
2302 if (!$ret['notify']) {
2303 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2306 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2308 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2310 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2312 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2314 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2318 if (DBA::isResult($contact)) {
2320 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2322 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2323 DBA::update('contact', $fields, ['id' => $contact['id']]);
2325 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2327 // create contact record
2328 DBA::insert('contact', [
2330 'created' => DateTimeFormat::utcNow(),
2331 'url' => $ret['url'],
2332 'nurl' => Strings::normaliseLink($ret['url']),
2333 'addr' => $ret['addr'],
2334 'alias' => $ret['alias'],
2335 'batch' => $ret['batch'],
2336 'notify' => $ret['notify'],
2337 'poll' => $ret['poll'],
2338 'poco' => $ret['poco'],
2339 'name' => $ret['name'],
2340 'nick' => $ret['nick'],
2341 'network' => $ret['network'],
2342 'baseurl' => $ret['baseurl'],
2343 'protocol' => $protocol,
2344 'pubkey' => $ret['pubkey'],
2345 'rel' => $new_relation,
2346 'priority'=> $ret['priority'],
2347 'writable'=> $writeable,
2348 'hidden' => $hidden,
2351 'pending' => $pending,
2356 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2357 if (!DBA::isResult($contact)) {
2358 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2362 $contact_id = $contact['id'];
2363 $result['cid'] = $contact_id;
2365 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2367 // Update the avatar
2368 self::updateAvatar($ret['photo'], $uid, $contact_id);
2370 // pull feed and consume it, which should subscribe to the hub.
2372 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2374 $owner = User::getOwnerDataById($uid);
2376 if (DBA::isResult($owner)) {
2377 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2378 // create a follow slap
2380 $item['verb'] = ACTIVITY_FOLLOW;
2381 $item['follow'] = $contact["url"];
2383 $item['title'] = '';
2386 $item['attach'] = '';
2388 $slap = OStatus::salmon($item, $owner);
2390 if (!empty($contact['notify'])) {
2391 Salmon::slapper($owner, $contact['notify'], $slap);
2393 } elseif ($protocol == Protocol::DIASPORA) {
2394 $ret = Diaspora::sendShare($a->user, $contact);
2395 Logger::log('share returns: ' . $ret);
2396 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2397 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2398 if (empty($activity_id)) {
2399 // This really should never happen
2403 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2404 Logger::log('Follow returns: ' . $ret);
2408 $result['success'] = true;
2413 * @brief Updated contact's SSL policy
2415 * @param array $contact Contact array
2416 * @param string $new_policy New policy, valid: self,full
2418 * @return array Contact array with updated values
2419 * @throws \Exception
2421 public static function updateSslPolicy(array $contact, $new_policy)
2423 $ssl_changed = false;
2424 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2425 $ssl_changed = true;
2426 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2427 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2428 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2429 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2430 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2431 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2434 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2435 $ssl_changed = true;
2436 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2437 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2438 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2439 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2440 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2441 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2445 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2446 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2447 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2448 DBA::update('contact', $fields, ['id' => $contact['id']]);
2455 * @param array $importer Owner (local user) data
2456 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2457 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2458 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2459 * @param string $note Introduction additional message
2460 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2462 * @throws \ImagickException
2464 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2466 // Should always be set
2467 if (empty($datarray['author-id'])) {
2471 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2472 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2473 if (!DBA::isResult($pub_contact)) {
2474 // Should never happen
2478 // Contact is blocked at node-level
2479 if (self::isBlocked($datarray['author-id'])) {
2483 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2484 $name = $pub_contact['name'];
2485 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2486 $nick = $pub_contact['nick'];
2487 $network = $pub_contact['network'];
2489 // Ensure that we don't create a new contact when there already is one
2490 $cid = self::getIdForURL($url, $importer['uid']);
2492 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2495 if (!empty($contact)) {
2496 if (!empty($contact['pending'])) {
2497 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2501 // Contact is blocked at user-level
2502 if (!empty($contact['id']) && !empty($importer['id']) &&
2503 self::isBlockedByUser($contact['id'], $importer['id'])) {
2507 // Make sure that the existing contact isn't archived
2508 self::unmarkForArchival($contact);
2510 if (($contact['rel'] == self::SHARING)
2511 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2512 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2513 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2518 // send email notification to owner?
2519 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2520 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2524 // create contact record
2525 DBA::insert('contact', [
2526 'uid' => $importer['uid'],
2527 'created' => DateTimeFormat::utcNow(),
2529 'nurl' => Strings::normaliseLink($url),
2533 'network' => $network,
2534 'rel' => self::FOLLOWER,
2542 'id' => DBA::lastInsertId(),
2543 'network' => $network,
2549 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2551 /// @TODO Encapsulate this into a function/method
2552 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2553 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2554 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2555 // create notification
2556 $hash = Strings::getRandomHex();
2558 if (is_array($contact_record)) {
2559 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2560 'blocked' => false, 'knowyou' => false, 'note' => $note,
2561 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2564 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2566 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2567 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2570 'type' => NOTIFY_INTRO,
2571 'notify_flags' => $user['notify-flags'],
2572 'language' => $user['language'],
2573 'to_name' => $user['username'],
2574 'to_email' => $user['email'],
2575 'uid' => $user['uid'],
2576 'link' => System::baseUrl() . '/notifications/intro',
2577 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2578 'source_link' => $contact_record['url'],
2579 'source_photo' => $contact_record['photo'],
2580 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2584 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2585 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2586 DBA::update('contact', ['pending' => false], $condition);
2595 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2597 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2598 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2600 Contact::remove($contact['id']);
2604 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2606 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2607 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2609 Contact::remove($contact['id']);
2614 * @brief Create a birthday event.
2616 * Update the year and the birthday.
2618 public static function updateBirthdays()
2622 AND `bd` > "0001-01-01"
2623 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2624 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2625 AND NOT `contact`.`pending`
2626 AND NOT `contact`.`hidden`
2627 AND NOT `contact`.`blocked`
2628 AND NOT `contact`.`archive`
2629 AND NOT `contact`.`deleted`',
2634 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2636 while ($contact = DBA::fetch($contacts)) {
2637 Logger::log('update_contact_birthday: ' . $contact['bd']);
2639 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2641 if (Event::createBirthday($contact, $nextbd)) {
2645 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2646 ['id' => $contact['id']]
2653 * Remove the unavailable contact ids from the provided list
2655 * @param array $contact_ids Contact id list
2656 * @throws \Exception
2658 public static function pruneUnavailable(array &$contact_ids)
2660 if (empty($contact_ids)) {
2664 $str = DBA::escape(implode(',', $contact_ids));
2666 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2669 while($contact = DBA::fetch($stmt)) {
2670 $return[] = $contact['id'];
2675 $contact_ids = $return;
2679 * @brief Returns a magic link to authenticate remote visitors
2681 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2683 * @param string $contact_url The address of the target contact profile
2684 * @param string $url An url that we will be redirected to after the authentication
2686 * @return string with "redir" link
2687 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2688 * @throws \ImagickException
2690 public static function magicLink($contact_url, $url = '')
2692 if (!local_user() && !remote_user()) {
2693 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2696 $data = self::getProbeDataFromDatabase($contact_url);
2698 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2701 // Prevents endless loop in case only a non-public contact exists for the contact URL
2702 unset($data['uid']);
2704 return self::magicLinkByContact($data, $contact_url);
2708 * @brief Returns a magic link to authenticate remote visitors
2710 * @param integer $cid The contact id of the target contact profile
2711 * @param string $url An url that we will be redirected to after the authentication
2713 * @return string with "redir" link
2714 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2715 * @throws \ImagickException
2717 public static function magicLinkbyId($cid, $url = '')
2719 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2721 return self::magicLinkByContact($contact, $url);
2725 * @brief Returns a magic link to authenticate remote visitors
2727 * @param array $contact The contact array with "uid", "network" and "url"
2728 * @param string $url An url that we will be redirected to after the authentication
2730 * @return string with "redir" link
2731 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2732 * @throws \ImagickException
2734 public static function magicLinkByContact($contact, $url = '')
2736 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2737 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2740 // Only redirections to the same host do make sense
2741 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2745 if (!empty($contact['uid'])) {
2746 return self::magicLink($contact['url'], $url);
2749 if (empty($contact['id'])) {
2750 return $url ?: $contact['url'];
2753 $redirect = 'redir/' . $contact['id'];
2756 $redirect .= '?url=' . $url;
2763 * Remove a contact from all groups
2765 * @param integer $contact_id
2767 * @return boolean Success
2769 public static function removeFromGroups($contact_id)
2771 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2775 * Is the contact a forum?
2777 * @param integer $contactid ID of the contact
2779 * @return boolean "true" if it is a forum
2781 public static function isForum($contactid)
2783 $fields = ['forum', 'prv'];
2784 $condition = ['id' => $contactid];
2785 $contact = DBA::selectFirst('contact', $fields, $condition);
2786 if (!DBA::isResult($contact)) {
2791 return ($contact['forum'] || $contact['prv']);
2795 * Can the remote contact receive private messages?
2797 * @param array $contact
2800 public static function canReceivePrivateMessages(array $contact)
2802 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2803 $self = $contact['self'] ?? false;
2805 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;