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 * @param integer $id Contact ID
141 * @param array $fields Array of selected fields, empty for all
142 * @return array|boolean Contact record if it exists, false otherwise
145 public static function getById($id, $fields = [])
147 return DBA::selectFirst('contact', $fields, ['id' => $id]);
151 * @brief Tests if the given contact is a follower
153 * @param int $cid Either public contact id or user's contact id
154 * @param int $uid User ID
156 * @return boolean is the contact id a follower?
157 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
158 * @throws \ImagickException
160 public static function isFollower($cid, $uid)
162 if (self::isBlockedByUser($cid, $uid)) {
166 $cdata = self::getPublicAndUserContacID($cid, $uid);
167 if (empty($cdata['user'])) {
171 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
172 return DBA::exists('contact', $condition);
176 * @brief Tests if the given contact url is a follower
178 * @param string $url Contact URL
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 isFollowerByURL($url, $uid)
187 $cid = self::getIdForURL($url, $uid, true);
193 return self::isFollower($cid, $uid);
197 * @brief Tests if the given user follow the given contact
199 * @param int $cid Either public contact id or user's contact id
200 * @param int $uid User ID
202 * @return boolean is the contact url being followed?
203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
204 * @throws \ImagickException
206 public static function isSharing($cid, $uid)
208 if (self::isBlockedByUser($cid, $uid)) {
212 $cdata = self::getPublicAndUserContacID($cid, $uid);
213 if (empty($cdata['user'])) {
217 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
218 return DBA::exists('contact', $condition);
222 * @brief Tests if the given user follow the given contact url
224 * @param string $url Contact URL
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 isSharingByURL($url, $uid)
233 $cid = self::getIdForURL($url, $uid, true);
239 return self::isSharing($cid, $uid);
243 * @brief Get the basepath for a given contact link
245 * @param string $url The contact link
247 * @return string basepath
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249 * @throws \ImagickException
251 public static function getBasepath($url)
253 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
254 if (!empty($contact['baseurl'])) {
255 return $contact['baseurl'];
258 self::updateFromProbeByURL($url, true);
260 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
261 if (!empty($contact['baseurl'])) {
262 return $contact['baseurl'];
269 * Returns the public contact id of the given user id
271 * @param integer $uid User ID
273 * @return integer|boolean Public contact id for given user id
276 public static function getPublicIdByUserId($uid)
278 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
279 if (!DBA::isResult($self)) {
282 return self::getIdForURL($self['url'], 0, true);
286 * @brief Returns the contact id for the user and the public contact id for a given contact id
288 * @param int $cid Either public contact id or user's contact id
289 * @param int $uid User ID
291 * @return array with public and user's contact id
292 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
293 * @throws \ImagickException
295 public static function getPublicAndUserContacID($cid, $uid)
297 if (empty($uid) || empty($cid)) {
301 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
302 if (!DBA::isResult($contact)) {
306 // We quit when the user id don't match the user id of the provided contact
307 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
311 if ($contact['uid'] != 0) {
312 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
316 $ucid = $contact['id'];
318 $pcid = $contact['id'];
319 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
322 return ['public' => $pcid, 'user' => $ucid];
326 * Returns contact details for a given contact id in combination with a user id
328 * @param int $cid A contact ID
329 * @param int $uid The User ID
330 * @param array $fields The selected fields for the contact
332 * @return array The contact details
336 public static function getContactForUser($cid, $uid, array $fields = [])
338 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
340 if (!DBA::isResult($contact)) {
348 * @brief Block contact id for user id
350 * @param int $cid Either public contact id or user's contact id
351 * @param int $uid User ID
352 * @param boolean $blocked Is the contact blocked or unblocked?
355 public static function setBlockedForUser($cid, $uid, $blocked)
357 $cdata = self::getPublicAndUserContacID($cid, $uid);
362 if ($cdata['user'] != 0) {
363 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
366 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
369 // Blocked contact can't be in any group
370 self::removeFromGroups($cid);
375 * @brief Returns "block" state for contact id and user id
377 * @param int $cid Either public contact id or user's contact id
378 * @param int $uid User ID
380 * @return boolean is the contact id blocked for the given user?
383 public static function isBlockedByUser($cid, $uid)
385 $cdata = self::getPublicAndUserContacID($cid, $uid);
390 $public_blocked = false;
392 if (!empty($cdata['public'])) {
393 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
394 if (DBA::isResult($public_contact)) {
395 $public_blocked = $public_contact['blocked'];
399 $user_blocked = $public_blocked;
401 if (!empty($cdata['user'])) {
402 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
403 if (DBA::isResult($user_contact)) {
404 $user_blocked = $user_contact['blocked'];
408 if ($user_blocked != $public_blocked) {
409 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
412 return $user_blocked;
416 * @brief Ignore contact id for user id
418 * @param int $cid Either public contact id or user's contact id
419 * @param int $uid User ID
420 * @param boolean $ignored Is the contact ignored or unignored?
423 public static function setIgnoredForUser($cid, $uid, $ignored)
425 $cdata = self::getPublicAndUserContacID($cid, $uid);
430 if ($cdata['user'] != 0) {
431 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
434 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
438 * @brief Returns "ignore" state for contact id and user id
440 * @param int $cid Either public contact id or user's contact id
441 * @param int $uid User ID
443 * @return boolean is the contact id ignored for the given user?
446 public static function isIgnoredByUser($cid, $uid)
448 $cdata = self::getPublicAndUserContacID($cid, $uid);
453 $public_ignored = false;
455 if (!empty($cdata['public'])) {
456 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
457 if (DBA::isResult($public_contact)) {
458 $public_ignored = $public_contact['ignored'];
462 $user_ignored = $public_ignored;
464 if (!empty($cdata['user'])) {
465 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
466 if (DBA::isResult($user_contact)) {
467 $user_ignored = $user_contact['readonly'];
471 if ($user_ignored != $public_ignored) {
472 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
475 return $user_ignored;
479 * @brief Set "collapsed" for contact id and user id
481 * @param int $cid Either public contact id or user's contact id
482 * @param int $uid User ID
483 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
486 public static function setCollapsedForUser($cid, $uid, $collapsed)
488 $cdata = self::getPublicAndUserContacID($cid, $uid);
493 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
497 * @brief Returns "collapsed" state for contact id and user id
499 * @param int $cid Either public contact id or user's contact id
500 * @param int $uid User ID
502 * @return boolean is the contact id blocked for the given user?
503 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504 * @throws \ImagickException
506 public static function isCollapsedByUser($cid, $uid)
508 $cdata = self::getPublicAndUserContacID($cid, $uid);
515 if (!empty($cdata['public'])) {
516 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
517 if (DBA::isResult($public_contact)) {
518 $collapsed = $public_contact['collapsed'];
526 * @brief Returns a list of contacts belonging in a group
532 public static function getByGroupId($gid)
537 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
539 INNER JOIN `group_member`
540 ON `contact`.`id` = `group_member`.`contact-id`
542 AND `contact`.`uid` = ?
543 AND NOT `contact`.`self`
544 AND NOT `contact`.`deleted`
545 AND NOT `contact`.`blocked`
546 AND NOT `contact`.`pending`
547 ORDER BY `contact`.`name` ASC',
552 if (DBA::isResult($stmt)) {
553 $return = DBA::toArray($stmt);
561 * @brief Returns the count of OStatus contacts in a group
567 public static function getOStatusCountByGroupId($gid)
571 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
573 INNER JOIN `group_member`
574 ON `contact`.`id` = `group_member`.`contact-id`
576 AND `contact`.`uid` = ?
577 AND `contact`.`network` = ?
578 AND `contact`.`notify` != ""',
583 $return = $contacts['count'];
590 * Creates the self-contact for the provided user id
593 * @return bool Operation success
594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
596 public static function createSelfFromUserId($uid)
598 // Only create the entry if it doesn't exist yet
599 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
603 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
604 if (!DBA::isResult($user)) {
608 $return = DBA::insert('contact', [
609 'uid' => $user['uid'],
610 'created' => DateTimeFormat::utcNow(),
612 'name' => $user['username'],
613 'nick' => $user['nickname'],
614 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
615 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
616 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
619 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
620 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
621 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
622 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
623 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
624 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
625 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
626 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
627 'name-date' => DateTimeFormat::utcNow(),
628 'uri-date' => DateTimeFormat::utcNow(),
629 'avatar-date' => DateTimeFormat::utcNow(),
637 * Updates the self-contact for the provided user id
640 * @param boolean $update_avatar Force the avatar update
641 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
643 public static function updateSelfFromUserID($uid, $update_avatar = false)
645 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
646 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
647 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
648 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
649 if (!DBA::isResult($self)) {
653 $fields = ['nickname', 'page-flags', 'account-type'];
654 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
655 if (!DBA::isResult($user)) {
659 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
660 'country-name', 'gender', 'pub_keywords', 'xmpp'];
661 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
662 if (!DBA::isResult($profile)) {
666 $file_suffix = 'jpg';
668 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
669 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
670 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
671 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
672 'xmpp' => $profile['xmpp']];
674 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
675 if (DBA::isResult($avatar)) {
676 if ($update_avatar) {
677 $fields['avatar-date'] = DateTimeFormat::utcNow();
680 // Creating the path to the avatar, beginning with the file suffix
681 $types = Image::supportedTypes();
682 if (isset($types[$avatar['type']])) {
683 $file_suffix = $types[$avatar['type']];
686 // We are adding a timestamp value so that other systems won't use cached content
687 $timestamp = strtotime($fields['avatar-date']);
689 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
690 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
692 $fields['photo'] = $prefix . '4' . $suffix;
693 $fields['thumb'] = $prefix . '5' . $suffix;
694 $fields['micro'] = $prefix . '6' . $suffix;
696 // We hadn't found a photo entry, so we use the default avatar
697 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
698 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
699 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
702 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
703 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
704 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
706 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
707 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
708 $fields['nurl'] = Strings::normaliseLink($fields['url']);
709 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
710 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
711 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
712 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
713 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
714 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
718 foreach ($fields as $field => $content) {
719 if ($self[$field] != $content) {
725 if ($fields['name'] != $self['name']) {
726 $fields['name-date'] = DateTimeFormat::utcNow();
728 $fields['updated'] = DateTimeFormat::utcNow();
729 DBA::update('contact', $fields, ['id' => $self['id']]);
731 // Update the public contact as well
732 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
734 // Update the profile
735 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
736 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
737 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
742 * @brief Marks a contact for removal
744 * @param int $id contact id
746 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
748 public static function remove($id)
750 // We want just to make sure that we don't delete our "self" contact
751 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
752 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
756 // Archive the contact
757 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
759 // Delete it in the background
760 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
764 * @brief Sends an unfriend message. Does not remove the contact
766 * @param array $user User unfriending
767 * @param array $contact Contact unfriended
768 * @param boolean $dissolve Remove the contact on the remote side
770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
771 * @throws \ImagickException
773 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
775 if (empty($contact['network'])) {
779 $protocol = $contact['network'];
780 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
781 $protocol = Protocol::ACTIVITYPUB;
784 if (($protocol == Protocol::DFRN) && $dissolve) {
785 DFRN::deliver($user, $contact, 'placeholder', true);
786 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
787 // create an unfollow slap
789 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
790 $item['follow'] = $contact["url"];
795 $item['attach'] = '';
796 $slap = OStatus::salmon($item, $user);
798 if (!empty($contact['notify'])) {
799 Salmon::slapper($user, $contact['notify'], $slap);
801 } elseif ($protocol == Protocol::DIASPORA) {
802 Diaspora::sendUnshare($user, $contact);
803 } elseif ($protocol == Protocol::ACTIVITYPUB) {
804 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
807 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
813 * @brief Marks a contact for archival after a communication issue delay
815 * Contact has refused to recognise us as a friend. We will start a countdown.
816 * If they still don't recognise us in 32 days, the relationship is over,
817 * and we won't waste any more time trying to communicate with them.
818 * This provides for the possibility that their database is temporarily messed
819 * up or some other transient event and that there's a possibility we could recover from it.
821 * @param array $contact contact to mark for archival
823 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
825 public static function markForArchival(array $contact)
827 if (!isset($contact['url']) && !empty($contact['id'])) {
828 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
829 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
830 if (!DBA::isResult($contact)) {
833 } elseif (!isset($contact['url'])) {
834 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
837 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
839 // Contact already archived or "self" contact? => nothing to do
840 if ($contact['archive'] || $contact['self']) {
844 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
845 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
846 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
849 * We really should send a notification to the owner after 2-3 weeks
850 * so they won't be surprised when the contact vanishes and can take
851 * remedial action if this was a serious mistake or glitch
854 /// @todo Check for contact vitality via probing
855 $archival_days = Config::get('system', 'archival_days', 32);
857 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
858 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
859 /* Relationship is really truly dead. archive them rather than
860 * delete, though if the owner tries to unarchive them we'll start
861 * the whole process over again.
863 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
864 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
865 GContact::updateFromPublicContactURL($contact['url']);
871 * @brief Cancels the archival countdown
873 * @see Contact::markForArchival()
875 * @param array $contact contact to be unmarked for archival
879 public static function unmarkForArchival(array $contact)
881 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
882 $exists = DBA::exists('contact', $condition);
884 // We don't need to update, we never marked this contact for archival
889 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
891 if (!isset($contact['url']) && !empty($contact['id'])) {
892 $fields = ['id', 'url', 'batch'];
893 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
894 if (!DBA::isResult($contact)) {
899 // It's a miracle. Our dead contact has inexplicably come back to life.
900 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
901 DBA::update('contact', $fields, ['id' => $contact['id']]);
902 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
903 GContact::updateFromPublicContactURL($contact['url']);
905 if (!empty($contact['batch'])) {
906 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
907 DBA::update('contact', $fields, $condition);
912 * @brief Get contact data for a given profile link
914 * The function looks at several places (contact table and gcontact table) for the contact
915 * It caches its result for the same script execution to prevent duplicate calls
917 * @param string $url The profile link
918 * @param int $uid User id
919 * @param array $default If not data was found take this data as default value
921 * @return array Contact data
922 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
924 public static function getDetailsByURL($url, $uid = -1, array $default = [])
936 if (isset($cache[$url][$uid])) {
937 return $cache[$url][$uid];
940 $ssl_url = str_replace('http://', 'https://', $url);
942 // Fetch contact data from the contact table for the given user
943 $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`,
944 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
945 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
946 $r = DBA::toArray($s);
948 // Fetch contact data from the contact table for the given user, checking with the alias
949 if (!DBA::isResult($r)) {
950 $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`,
951 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
952 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
953 $r = DBA::toArray($s);
956 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
957 if (!DBA::isResult($r)) {
958 $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`,
959 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
960 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
961 $r = DBA::toArray($s);
964 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
965 if (!DBA::isResult($r)) {
966 $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`,
967 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
968 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
969 $r = DBA::toArray($s);
972 // Fetch the data from the gcontact table
973 if (!DBA::isResult($r)) {
974 $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`,
975 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
976 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
977 $r = DBA::toArray($s);
980 if (DBA::isResult($r)) {
981 // If there is more than one entry we filter out the connector networks
983 foreach ($r as $id => $result) {
984 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
990 $profile = array_shift($r);
992 // "bd" always contains the upcoming birthday of a contact.
993 // "birthday" might contain the birthday including the year of birth.
994 if ($profile["birthday"] > DBA::NULL_DATE) {
995 $bd_timestamp = strtotime($profile["birthday"]);
996 $month = date("m", $bd_timestamp);
997 $day = date("d", $bd_timestamp);
999 $current_timestamp = time();
1000 $current_year = date("Y", $current_timestamp);
1001 $current_month = date("m", $current_timestamp);
1002 $current_day = date("d", $current_timestamp);
1004 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1005 $current = $current_year . "-" . $current_month . "-" . $current_day;
1007 if ($profile["bd"] < $current) {
1008 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1011 $profile["bd"] = DBA::NULL_DATE;
1014 $profile = $default;
1017 if (empty($profile["photo"]) && isset($default["photo"])) {
1018 $profile["photo"] = $default["photo"];
1021 if (empty($profile["name"]) && isset($default["name"])) {
1022 $profile["name"] = $default["name"];
1025 if (empty($profile["network"]) && isset($default["network"])) {
1026 $profile["network"] = $default["network"];
1029 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1030 $profile["thumb"] = $profile["photo"];
1033 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1034 $profile["micro"] = $profile["thumb"];
1037 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1038 && in_array($profile["network"], Protocol::FEDERATED)
1040 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1043 // Show contact details of Diaspora contacts only if connected
1044 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1045 $profile["location"] = "";
1046 $profile["about"] = "";
1047 $profile["gender"] = "";
1048 $profile["birthday"] = DBA::NULL_DATE;
1051 $cache[$url][$uid] = $profile;
1057 * @brief Get contact data for a given address
1059 * The function looks at several places (contact table and gcontact table) for the contact
1061 * @param string $addr The profile link
1062 * @param int $uid User id
1064 * @return array Contact data
1065 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1066 * @throws \ImagickException
1068 public static function getDetailsByAddr($addr, $uid = -1)
1075 $uid = local_user();
1078 // Fetch contact data from the contact table for the given user
1079 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1080 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1081 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1085 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1086 if (!DBA::isResult($r)) {
1087 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1088 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1089 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1094 // Fetch the data from the gcontact table
1095 if (!DBA::isResult($r)) {
1096 $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`,
1097 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1098 FROM `gcontact` WHERE `addr` = '%s'",
1103 if (!DBA::isResult($r)) {
1104 $data = Probe::uri($addr);
1106 $profile = self::getDetailsByURL($data['url'], $uid);
1115 * @brief Returns the data array for the photo menu of a given contact
1117 * @param array $contact contact
1118 * @param int $uid optional, default 0
1120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1121 * @throws \ImagickException
1123 public static function photoMenu(array $contact, $uid = 0)
1128 $contact_drop_link = '';
1132 $uid = local_user();
1135 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1137 $profile_link = self::magicLink($contact['url']);
1138 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1143 // Look for our own contact if the uid doesn't match and isn't public
1144 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1145 if (DBA::isResult($contact_own)) {
1146 return self::photoMenu($contact_own, $uid);
1151 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1153 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1155 $profile_link = $contact['url'];
1158 if ($profile_link === 'mailbox') {
1163 $status_link = $profile_link . '?tab=status';
1164 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1165 $profile_link = $profile_link . '?tab=profile';
1168 if (self::canReceivePrivateMessages($contact)) {
1169 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1172 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1173 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1176 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1178 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1180 if (!$contact['self']) {
1181 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1186 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1188 if (empty($contact['uid'])) {
1189 $connlnk = 'follow/?url=' . $contact['url'];
1191 'profile' => [L10n::t('View Profile'), $profile_link, true],
1192 'network' => [L10n::t('Network Posts'), $posts_link, false],
1193 'edit' => [L10n::t('View Contact'), $contact_url, false],
1194 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1198 'status' => [L10n::t('View Status'), $status_link, true],
1199 'profile' => [L10n::t('View Profile'), $profile_link, true],
1200 'photos' => [L10n::t('View Photos'), $photos_link, true],
1201 'network' => [L10n::t('Network Posts'), $posts_link, false],
1202 'edit' => [L10n::t('View Contact'), $contact_url, false],
1203 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1204 'pm' => [L10n::t('Send PM'), $pm_url, false],
1205 'poke' => [L10n::t('Poke'), $poke_link, false],
1209 $args = ['contact' => $contact, 'menu' => &$menu];
1211 Hook::callAll('contact_photo_menu', $args);
1213 $menucondensed = [];
1215 foreach ($menu as $menuname => $menuitem) {
1216 if ($menuitem[1] != '') {
1217 $menucondensed[$menuname] = $menuitem;
1221 return $menucondensed;
1225 * @brief Returns ungrouped contact count or list for user
1227 * Returns either the total number of ungrouped contacts for the given user
1228 * id or a paginated list of ungrouped contacts.
1230 * @param int $uid uid
1232 * @throws \Exception
1234 public static function getUngroupedList($uid)
1244 SELECT DISTINCT(`contact-id`)
1246 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1247 WHERE `group`.`uid` = %d
1248 )", intval($uid), intval($uid));
1252 * Have a look at all contact tables for a given profile url.
1253 * This function works as a replacement for probing the contact.
1255 * @param string $url Contact URL
1256 * @param integer $cid Contact ID
1258 * @return array Contact array in the "probe" structure
1260 private static function getProbeDataFromDatabase($url, $cid = null)
1262 // The link could be provided as http although we stored it as https
1263 $ssl_url = str_replace('http://', 'https://', $url);
1265 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1266 'photo', 'keywords', 'location', 'about', 'network',
1267 'priority', 'batch', 'request', 'confirm', 'poco'];
1270 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1271 if (DBA::isResult($data)) {
1276 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1278 if (!DBA::isResult($data)) {
1279 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1280 $data = DBA::selectFirst('contact', $fields, $condition);
1283 if (DBA::isResult($data)) {
1284 // For security reasons we don't fetch key data from our users
1285 $data["pubkey"] = '';
1289 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1290 'photo', 'keywords', 'location', 'about', 'network'];
1291 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1293 if (!DBA::isResult($data)) {
1294 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1295 $data = DBA::selectFirst('contact', $fields, $condition);
1298 if (DBA::isResult($data)) {
1299 $data["pubkey"] = '';
1301 $data["priority"] = 0;
1302 $data["batch"] = '';
1303 $data["request"] = '';
1304 $data["confirm"] = '';
1309 $data = ActivityPub::probeProfile($url, false);
1310 if (!empty($data)) {
1314 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1315 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1316 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1318 if (!DBA::isResult($data)) {
1319 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1320 $data = DBA::selectFirst('contact', $fields, $condition);
1323 if (DBA::isResult($data)) {
1324 $data["pubkey"] = '';
1325 $data["keywords"] = '';
1326 $data["location"] = '';
1327 $data["about"] = '';
1336 * @brief Fetch the contact id for a given URL and user
1338 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1339 * `addr` or `alias`.
1341 * If there's no record and we aren't looking for a public contact, we quit.
1342 * If there's one, we check that it isn't time to update the picture else we
1343 * directly return the found contact id.
1345 * Second, we probe the provided $url whether it's http://server.tld/profile or
1346 * nick@server.tld. We quit if we can't get any info back.
1348 * Third, we create the contact record if it doesn't exist
1350 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1351 * if there's any updates
1353 * @param string $url Contact URL
1354 * @param integer $uid The user id for the contact (0 = public contact)
1355 * @param boolean $no_update Don't update the contact
1356 * @param array $default Default value for creating the contact when every else fails
1357 * @param boolean $in_loop Internally used variable to prevent an endless loop
1359 * @return integer Contact ID
1360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1361 * @throws \ImagickException
1363 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1365 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1373 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1374 // We first try the nurl (http://server.tld/nick), most common case
1375 $fields = ['id', 'avatar', 'updated', 'network'];
1376 $options = ['order' => ['id']];
1377 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1379 // Then the addr (nick@server.tld)
1380 if (!DBA::isResult($contact)) {
1381 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1384 // Then the alias (which could be anything)
1385 if (!DBA::isResult($contact)) {
1386 // The link could be provided as http although we stored it as https
1387 $ssl_url = str_replace('http://', 'https://', $url);
1388 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1389 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1392 if (DBA::isResult($contact)) {
1393 $contact_id = $contact["id"];
1395 // Update the contact every 7 days
1396 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1398 // We force the update if the avatar is empty
1399 if (empty($contact['avatar'])) {
1400 $update_contact = true;
1403 // Update the contact in the background if needed but it is called by the frontend
1404 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1405 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1408 if (!$update_contact || $no_update) {
1411 } elseif ($uid != 0) {
1412 // Non-existing user-specific contact, exiting
1416 if ($no_update && empty($default)) {
1417 // When we don't want to update, we look if we know this contact in any way
1418 $data = self::getProbeDataFromDatabase($url, $contact_id);
1419 $background_update = true;
1420 } elseif ($no_update && !empty($default['network'])) {
1421 // If there are default values, take these
1423 $background_update = false;
1426 $background_update = false;
1430 $data = Probe::uri($url, "", $uid);
1432 // Ensure that there is a gserver entry
1433 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1434 PortableContact::checkServer($data['baseurl']);
1438 // Take the default values when probing failed
1439 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1440 $data = array_merge($data, $default);
1447 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1448 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1454 'created' => DateTimeFormat::utcNow(),
1455 'url' => $data['url'],
1456 'nurl' => Strings::normaliseLink($data['url']),
1457 'addr' => defaults($data, 'addr', ''),
1458 'alias' => defaults($data, 'alias', ''),
1459 'notify' => defaults($data, 'notify', ''),
1460 'poll' => defaults($data, 'poll', ''),
1461 'name' => defaults($data, 'name', ''),
1462 'nick' => defaults($data, 'nick', ''),
1463 'photo' => defaults($data, 'photo', ''),
1464 'keywords' => defaults($data, 'keywords', ''),
1465 'location' => defaults($data, 'location', ''),
1466 'about' => defaults($data, 'about', ''),
1467 'network' => $data['network'],
1468 'pubkey' => defaults($data, 'pubkey', ''),
1469 'rel' => self::SHARING,
1470 'priority' => defaults($data, 'priority', 0),
1471 'batch' => defaults($data, 'batch', ''),
1472 'request' => defaults($data, 'request', ''),
1473 'confirm' => defaults($data, 'confirm', ''),
1474 'poco' => defaults($data, 'poco', ''),
1475 'baseurl' => defaults($data, 'baseurl', ''),
1476 'name-date' => DateTimeFormat::utcNow(),
1477 'uri-date' => DateTimeFormat::utcNow(),
1478 'avatar-date' => DateTimeFormat::utcNow(),
1484 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1486 // Before inserting we do check if the entry does exist now.
1487 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1488 if (!DBA::isResult($contact)) {
1489 Logger::info('Create new contact', $fields);
1491 DBA::insert('contact', $fields);
1493 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1494 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1495 if (!DBA::isResult($contact)) {
1496 Logger::info('Contact creation failed', $fields);
1501 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1504 $contact_id = $contact["id"];
1507 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1508 self::updateAvatar($data['photo'], $uid, $contact_id);
1511 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1512 if ($background_update) {
1513 // Update in the background when we fetched the data solely from the database
1514 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1516 // Else do a direct update
1517 self::updateFromProbe($contact_id, '', false);
1519 // Update the gcontact entry
1521 GContact::updateFromPublicContactID($contact_id);
1525 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1526 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1528 // This condition should always be true
1529 if (!DBA::isResult($contact)) {
1534 'url' => $data['url'],
1535 'nurl' => Strings::normaliseLink($data['url']),
1536 'updated' => DateTimeFormat::utcNow()
1539 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1541 foreach ($fields as $field) {
1542 $updated[$field] = defaults($data, $field, $contact[$field]);
1545 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1546 $updated['uri-date'] = DateTimeFormat::utcNow();
1549 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1550 $updated['name-date'] = DateTimeFormat::utcNow();
1553 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1560 * @brief Checks if the contact is archived
1562 * @param int $cid contact id
1564 * @return boolean Is the contact archived?
1565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1567 public static function isArchived(int $cid)
1573 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1574 if (!DBA::isResult($contact)) {
1578 if ($contact['archive']) {
1582 // Check status of ActivityPub endpoints
1583 $apcontact = APContact::getByURL($contact['url'], false);
1584 if (!empty($apcontact)) {
1585 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1589 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1594 // Check status of Diaspora endpoints
1595 if (!empty($contact['batch'])) {
1596 return DBA::exists('contact', ['archive' => true, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY]);
1603 * @brief Checks if the contact is blocked
1605 * @param int $cid contact id
1607 * @return boolean Is the contact blocked?
1608 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1610 public static function isBlocked($cid)
1616 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1617 if (!DBA::isResult($blocked)) {
1621 if (Network::isUrlBlocked($blocked['url'])) {
1625 return (bool) $blocked['blocked'];
1629 * @brief Checks if the contact is hidden
1631 * @param int $cid contact id
1633 * @return boolean Is the contact hidden?
1634 * @throws \Exception
1636 public static function isHidden($cid)
1642 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1643 if (!DBA::isResult($hidden)) {
1646 return (bool) $hidden['hidden'];
1650 * @brief Returns posts from a given contact url
1652 * @param string $contact_url Contact URL
1654 * @param bool $thread_mode
1655 * @param int $update
1656 * @return string posts in HTML
1657 * @throws \Exception
1659 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1661 $a = self::getApp();
1663 $cid = self::getIdForURL($contact_url);
1665 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1666 if (!DBA::isResult($contact)) {
1670 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1671 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1673 $sql = "`item`.`uid` = ?";
1676 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1679 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1680 $cid, GRAVITY_PARENT, local_user()];
1682 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1683 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1686 $pager = new Pager($a->query_string);
1688 $params = ['order' => ['received' => true],
1689 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1692 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1694 $items = Item::inArray($r);
1696 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1698 $r = Item::selectForUser(local_user(), [], $condition, $params);
1700 $items = Item::inArray($r);
1702 $o = conversation($a, $items, $pager, 'contact-posts', false);
1706 $o .= $pager->renderMinimal(count($items));
1713 * @brief Returns the account type name
1715 * The function can be called with either the user or the contact array
1717 * @param array $contact contact or user array
1720 public static function getAccountType(array $contact)
1722 // There are several fields that indicate that the contact or user is a forum
1723 // "page-flags" is a field in the user table,
1724 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1725 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1726 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1727 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1728 || (isset($contact['forum']) && intval($contact['forum']))
1729 || (isset($contact['prv']) && intval($contact['prv']))
1730 || (isset($contact['community']) && intval($contact['community']))
1732 $type = self::TYPE_COMMUNITY;
1734 $type = self::TYPE_PERSON;
1737 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1738 if (isset($contact["contact-type"])) {
1739 $type = $contact["contact-type"];
1742 if (isset($contact["account-type"])) {
1743 $type = $contact["account-type"];
1747 case self::TYPE_ORGANISATION:
1748 $account_type = L10n::t("Organisation");
1751 case self::TYPE_NEWS:
1752 $account_type = L10n::t('News');
1755 case self::TYPE_COMMUNITY:
1756 $account_type = L10n::t("Forum");
1764 return $account_type;
1768 * @brief Blocks a contact
1772 * @throws \Exception
1774 public static function block($cid, $reason = null)
1776 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1782 * @brief Unblocks a contact
1786 * @throws \Exception
1788 public static function unblock($cid)
1790 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1796 * @brief Updates the avatar links in a contact only if needed
1798 * @param string $avatar Link to avatar picture
1799 * @param int $uid User id of contact owner
1800 * @param int $cid Contact id
1801 * @param bool $force force picture update
1803 * @return array Returns array of the different avatar sizes
1804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1805 * @throws \ImagickException
1807 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1809 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1810 if (!DBA::isResult($contact)) {
1813 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1816 if (($contact["avatar"] != $avatar) || $force) {
1817 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1820 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1821 DBA::update('contact', $fields, ['id' => $cid]);
1823 // Update the public contact (contact id = 0)
1825 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1826 if (DBA::isResult($pcontact)) {
1827 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1839 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1841 * @param integer $id contact id
1842 * @param integer $uid user id
1843 * @param string $url The profile URL of the contact
1844 * @param array $fields The fields that are updated
1846 * @throws \Exception
1848 private static function updateContact($id, $uid, $url, array $fields)
1850 if (!DBA::update('contact', $fields, ['id' => $id])) {
1851 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1855 // Search for duplicated contacts and get rid of them
1856 if (self::handleDuplicates(Strings::normaliseLink($url), $uid, $id) || ($uid != 0)) {
1860 // Update the corresponding gcontact entry
1861 GContact::updateFromPublicContactID($id);
1863 // Archive or unarchive the contact. We only need to do this for the public contact.
1864 // The archive/unarchive function will update the personal contacts by themselves.
1865 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1866 if (!DBA::isResult($contact)) {
1867 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1871 if (!empty($fields['success_update'])) {
1872 self::unmarkForArchival($contact);
1873 } elseif (!empty($fields['failure_update'])) {
1874 self::markForArchival($contact);
1877 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1879 // These contacts are sharing with us, we don't poll them.
1880 // This means that we don't set the update fields in "OnePoll.php".
1881 $condition['rel'] = self::SHARING;
1882 DBA::update('contact', $fields, $condition);
1884 unset($fields['last-update']);
1885 unset($fields['success_update']);
1886 unset($fields['failure_update']);
1888 if (empty($fields)) {
1892 // We are polling these contacts, so we mustn't set the update fields here.
1893 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1894 DBA::update('contact', $fields, $condition);
1898 * @brief Helper function for "updateFromProbe". Remove duplicated contacts
1900 * @param string $nurl Normalised contact url
1901 * @param integer $uid User id
1902 * @param integer $id Contact id of a duplicate
1904 * @throws \Exception
1906 private static function handleDuplicates($nurl, $uid, $id)
1908 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1909 $count = DBA::count('contact', $condition);
1914 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1915 if (!DBA::isResult($first_contact)) {
1916 // Shouldn't happen - so we handle it
1920 $first = $first_contact['id'];
1921 Logger::info('Found duplicates', ['count' => $count, 'id' => $id, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1922 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1923 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1924 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1928 // Find all duplicates
1929 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1930 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1931 while ($duplicate = DBA::fetch($duplicates)) {
1932 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1936 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1938 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1943 * @param integer $id contact id
1944 * @param string $network Optional network we are probing for
1945 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1947 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1948 * @throws \ImagickException
1950 public static function updateFromProbe($id, $network = '', $force = false)
1953 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1954 This will reliably kill your communication with old Friendica contacts.
1957 // These fields aren't updated by this routine:
1958 // 'xmpp', 'sensitive'
1960 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
1961 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1962 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
1963 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1964 if (!DBA::isResult($contact)) {
1968 $uid = $contact['uid'];
1969 unset($contact['uid']);
1971 $pubkey = $contact['pubkey'];
1972 unset($contact['pubkey']);
1974 $contact['photo'] = $contact['avatar'];
1975 unset($contact['avatar']);
1977 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1979 $updated = DateTimeFormat::utcNow();
1981 // We must not try to update relay contacts via probe. They are no real contacts.
1982 // We check after the probing to be able to correct falsely detected contact types.
1983 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1984 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1985 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
1986 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1990 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1991 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
1992 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
1993 if ($force && ($uid == 0)) {
1994 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1999 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2000 $ret['unsearchable'] = $ret['hide'];
2003 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2004 $ret['forum'] = false;
2005 $ret['prv'] = false;
2006 $ret['contact-type'] = $ret['account-type'];
2007 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2008 $apcontact = APContact::getByURL($ret['url'], false);
2009 if (isset($apcontact['manually-approve'])) {
2010 $ret['forum'] = (bool)!$apcontact['manually-approve'];
2011 $ret['prv'] = (bool)!$ret['forum'];
2016 $new_pubkey = $ret['pubkey'];
2020 // make sure to not overwrite existing values with blank entries except some technical fields
2021 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2022 foreach ($ret as $key => $val) {
2023 if (!array_key_exists($key, $contact)) {
2025 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2026 $ret[$key] = $contact[$key];
2027 } elseif ($ret[$key] != $contact[$key]) {
2032 if ($ret['network'] != Protocol::FEED) {
2033 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
2038 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
2043 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2044 $ret['updated'] = $updated;
2046 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2047 if (empty($pubkey) && !empty($new_pubkey)) {
2048 $ret['pubkey'] = $new_pubkey;
2051 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2052 $ret['uri-date'] = DateTimeFormat::utcNow();
2055 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2056 $ret['name-date'] = $updated;
2059 if ($force && ($uid == 0)) {
2060 $ret['last-update'] = $updated;
2061 $ret['success_update'] = $updated;
2064 unset($ret['photo']);
2066 self::updateContact($id, $uid, $ret['url'], $ret);
2071 public static function updateFromProbeByURL($url, $force = false)
2073 $id = self::getIdForURL($url);
2079 self::updateFromProbe($id, '', $force);
2085 * Detects if a given contact array belongs to a legacy DFRN connection
2087 * @param array $contact
2090 public static function isLegacyDFRNContact($contact)
2092 // Newer Friendica contacts are connected via AP, then these fields aren't set
2093 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2097 * Detects the communication protocol for a given contact url.
2098 * This is used to detect Friendica contacts that we can communicate via AP.
2100 * @param string $url contact url
2101 * @param string $network Network of that contact
2102 * @return string with protocol
2104 public static function getProtocol($url, $network)
2106 if ($network != Protocol::DFRN) {
2110 $apcontact = APContact::getByURL($url);
2111 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2112 return Protocol::ACTIVITYPUB;
2119 * Takes a $uid and a url/handle and adds a new contact
2120 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2121 * dfrn_request page.
2123 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2126 * $return['success'] boolean true if successful
2127 * $return['message'] error text if success is false.
2129 * @brief Takes a $uid and a url/handle and adds a new contact
2131 * @param string $url
2132 * @param bool $interactive
2133 * @param string $network
2135 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2136 * @throws \ImagickException
2138 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2140 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2144 // remove ajax junk, e.g. Twitter
2145 $url = str_replace('/#!/', '/', $url);
2147 if (!Network::isUrlAllowed($url)) {
2148 $result['message'] = L10n::t('Disallowed profile URL.');
2152 if (Network::isUrlBlocked($url)) {
2153 $result['message'] = L10n::t('Blocked domain');
2158 $result['message'] = L10n::t('Connect URL missing.');
2162 $arr = ['url' => $url, 'contact' => []];
2164 Hook::callAll('follow', $arr);
2167 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2171 if (!empty($arr['contact']['name'])) {
2172 $ret = $arr['contact'];
2174 $ret = Probe::uri($url, $network, $uid, false);
2177 if (($network != '') && ($ret['network'] != $network)) {
2178 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2182 // check if we already have a contact
2183 // the poll url is more reliable than the profile url, as we may have
2184 // indirect links or webfinger links
2186 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2187 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2188 if (!DBA::isResult($contact)) {
2189 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2190 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2193 $protocol = self::getProtocol($url, $ret['network']);
2195 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2197 if (strlen($a->getURLPath())) {
2198 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2200 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2203 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2207 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2208 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2209 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2213 // This extra param just confuses things, remove it
2214 if ($protocol === Protocol::DIASPORA) {
2215 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2218 // do we have enough information?
2219 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2220 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2221 if (empty($ret['poll'])) {
2222 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2224 if (empty($ret['name'])) {
2225 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2227 if (empty($ret['url'])) {
2228 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2230 if (strpos($url, '@') !== false) {
2231 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2232 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2237 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2238 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2239 $ret['notify'] = '';
2242 if (!$ret['notify']) {
2243 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2246 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2248 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2250 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2252 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2254 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2258 if (DBA::isResult($contact)) {
2260 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2262 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2263 DBA::update('contact', $fields, ['id' => $contact['id']]);
2265 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2267 // create contact record
2268 DBA::insert('contact', [
2270 'created' => DateTimeFormat::utcNow(),
2271 'url' => $ret['url'],
2272 'nurl' => Strings::normaliseLink($ret['url']),
2273 'addr' => $ret['addr'],
2274 'alias' => $ret['alias'],
2275 'batch' => $ret['batch'],
2276 'notify' => $ret['notify'],
2277 'poll' => $ret['poll'],
2278 'poco' => $ret['poco'],
2279 'name' => $ret['name'],
2280 'nick' => $ret['nick'],
2281 'network' => $ret['network'],
2282 'baseurl' => $ret['baseurl'],
2283 'protocol' => $protocol,
2284 'pubkey' => $ret['pubkey'],
2285 'rel' => $new_relation,
2286 'priority'=> $ret['priority'],
2287 'writable'=> $writeable,
2288 'hidden' => $hidden,
2291 'pending' => $pending,
2296 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2297 if (!DBA::isResult($contact)) {
2298 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2302 $contact_id = $contact['id'];
2303 $result['cid'] = $contact_id;
2305 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2307 // Update the avatar
2308 self::updateAvatar($ret['photo'], $uid, $contact_id);
2310 // pull feed and consume it, which should subscribe to the hub.
2312 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2314 $owner = User::getOwnerDataById($uid);
2316 if (DBA::isResult($owner)) {
2317 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2318 // create a follow slap
2320 $item['verb'] = ACTIVITY_FOLLOW;
2321 $item['follow'] = $contact["url"];
2323 $item['title'] = '';
2326 $item['attach'] = '';
2328 $slap = OStatus::salmon($item, $owner);
2330 if (!empty($contact['notify'])) {
2331 Salmon::slapper($owner, $contact['notify'], $slap);
2333 } elseif ($protocol == Protocol::DIASPORA) {
2334 $ret = Diaspora::sendShare($a->user, $contact);
2335 Logger::log('share returns: ' . $ret);
2336 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2337 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2338 if (empty($activity_id)) {
2339 // This really should never happen
2343 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2344 Logger::log('Follow returns: ' . $ret);
2348 $result['success'] = true;
2353 * @brief Updated contact's SSL policy
2355 * @param array $contact Contact array
2356 * @param string $new_policy New policy, valid: self,full
2358 * @return array Contact array with updated values
2359 * @throws \Exception
2361 public static function updateSslPolicy(array $contact, $new_policy)
2363 $ssl_changed = false;
2364 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2365 $ssl_changed = true;
2366 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2367 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2368 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2369 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2370 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2371 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2374 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2375 $ssl_changed = true;
2376 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2377 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2378 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2379 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2380 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2381 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2385 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2386 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2387 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2388 DBA::update('contact', $fields, ['id' => $contact['id']]);
2395 * @param array $importer Owner (local user) data
2396 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2397 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2398 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2399 * @param string $note Introduction additional message
2400 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2401 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2402 * @throws \ImagickException
2404 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2406 // Should always be set
2407 if (empty($datarray['author-id'])) {
2411 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2412 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2413 if (!DBA::isResult($pub_contact)) {
2414 // Should never happen
2418 // Contact is blocked at node-level
2419 if (self::isBlocked($datarray['author-id'])) {
2423 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2424 $name = $pub_contact['name'];
2425 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2426 $nick = $pub_contact['nick'];
2427 $network = $pub_contact['network'];
2429 // Ensure that we don't create a new contact when there already is one
2430 $cid = self::getIdForURL($url, $importer['uid']);
2432 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2435 if (!empty($contact)) {
2436 if (!empty($contact['pending'])) {
2437 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2441 // Contact is blocked at user-level
2442 if (!empty($contact['id']) && !empty($importer['id']) &&
2443 self::isBlockedByUser($contact['id'], $importer['id'])) {
2447 // Make sure that the existing contact isn't archived
2448 self::unmarkForArchival($contact);
2450 if (($contact['rel'] == self::SHARING)
2451 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2452 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2453 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2458 // send email notification to owner?
2459 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2460 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2464 // create contact record
2465 DBA::insert('contact', [
2466 'uid' => $importer['uid'],
2467 'created' => DateTimeFormat::utcNow(),
2469 'nurl' => Strings::normaliseLink($url),
2473 'network' => $network,
2474 'rel' => self::FOLLOWER,
2482 'id' => DBA::lastInsertId(),
2483 'network' => $network,
2489 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2491 /// @TODO Encapsulate this into a function/method
2492 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2493 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2494 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2495 // create notification
2496 $hash = Strings::getRandomHex();
2498 if (is_array($contact_record)) {
2499 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2500 'blocked' => false, 'knowyou' => false, 'note' => $note,
2501 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2504 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2506 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2507 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2510 'type' => NOTIFY_INTRO,
2511 'notify_flags' => $user['notify-flags'],
2512 'language' => $user['language'],
2513 'to_name' => $user['username'],
2514 'to_email' => $user['email'],
2515 'uid' => $user['uid'],
2516 'link' => System::baseUrl() . '/notifications/intro',
2517 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2518 'source_link' => $contact_record['url'],
2519 'source_photo' => $contact_record['photo'],
2520 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2524 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2525 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2526 DBA::update('contact', ['pending' => false], $condition);
2535 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2537 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2538 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2540 Contact::remove($contact['id']);
2544 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2546 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2547 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2549 Contact::remove($contact['id']);
2554 * @brief Create a birthday event.
2556 * Update the year and the birthday.
2558 public static function updateBirthdays()
2562 AND `bd` > "0001-01-01"
2563 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2564 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2565 AND NOT `contact`.`pending`
2566 AND NOT `contact`.`hidden`
2567 AND NOT `contact`.`blocked`
2568 AND NOT `contact`.`archive`
2569 AND NOT `contact`.`deleted`',
2574 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2576 while ($contact = DBA::fetch($contacts)) {
2577 Logger::log('update_contact_birthday: ' . $contact['bd']);
2579 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2581 if (Event::createBirthday($contact, $nextbd)) {
2585 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2586 ['id' => $contact['id']]
2593 * Remove the unavailable contact ids from the provided list
2595 * @param array $contact_ids Contact id list
2596 * @throws \Exception
2598 public static function pruneUnavailable(array &$contact_ids)
2600 if (empty($contact_ids)) {
2604 $str = DBA::escape(implode(',', $contact_ids));
2606 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2609 while($contact = DBA::fetch($stmt)) {
2610 $return[] = $contact['id'];
2615 $contact_ids = $return;
2619 * @brief Returns a magic link to authenticate remote visitors
2621 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2623 * @param string $contact_url The address of the target contact profile
2624 * @param string $url An url that we will be redirected to after the authentication
2626 * @return string with "redir" link
2627 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2628 * @throws \ImagickException
2630 public static function magicLink($contact_url, $url = '')
2632 if (!local_user() && !remote_user()) {
2633 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2636 $data = self::getProbeDataFromDatabase($contact_url);
2638 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2641 // Prevents endless loop in case only a non-public contact exists for the contact URL
2642 unset($data['uid']);
2644 return self::magicLinkByContact($data, $contact_url);
2648 * @brief Returns a magic link to authenticate remote visitors
2650 * @param integer $cid The contact id of the target contact profile
2651 * @param string $url An url that we will be redirected to after the authentication
2653 * @return string with "redir" link
2654 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2655 * @throws \ImagickException
2657 public static function magicLinkbyId($cid, $url = '')
2659 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2661 return self::magicLinkByContact($contact, $url);
2665 * @brief Returns a magic link to authenticate remote visitors
2667 * @param array $contact The contact array with "uid", "network" and "url"
2668 * @param string $url An url that we will be redirected to after the authentication
2670 * @return string with "redir" link
2671 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2672 * @throws \ImagickException
2674 public static function magicLinkByContact($contact, $url = '')
2676 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2677 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2680 // Only redirections to the same host do make sense
2681 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2685 if (!empty($contact['uid'])) {
2686 return self::magicLink($contact['url'], $url);
2689 if (empty($contact['id'])) {
2690 return $url ?: $contact['url'];
2693 $redirect = 'redir/' . $contact['id'];
2696 $redirect .= '?url=' . $url;
2703 * Remove a contact from all groups
2705 * @param integer $contact_id
2707 * @return boolean Success
2709 public static function removeFromGroups($contact_id)
2711 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2715 * Is the contact a forum?
2717 * @param integer $contactid ID of the contact
2719 * @return boolean "true" if it is a forum
2721 public static function isForum($contactid)
2723 $fields = ['forum', 'prv'];
2724 $condition = ['id' => $contactid];
2725 $contact = DBA::selectFirst('contact', $fields, $condition);
2726 if (!DBA::isResult($contact)) {
2731 return ($contact['forum'] || $contact['prv']);
2735 * Can the remote contact receive private messages?
2737 * @param array $contact
2740 public static function canReceivePrivateMessages(array $contact)
2742 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2743 $self = $contact['self'] ?? false;
2745 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;