3 * @file src/Model/Contact.php
5 namespace Friendica\Model;
7 use Friendica\BaseObject;
8 use Friendica\Content\Pager;
9 use Friendica\Core\Config;
10 use Friendica\Core\Hook;
11 use Friendica\Core\L10n;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Core\Worker;
16 use Friendica\Database\DBA;
17 use Friendica\Network\Probe;
18 use Friendica\Object\Image;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\DFRN;
21 use Friendica\Protocol\Diaspora;
22 use Friendica\Protocol\OStatus;
23 use Friendica\Protocol\PortableContact;
24 use Friendica\Protocol\Salmon;
25 use Friendica\Util\BaseURL;
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 select(array $fields = [], array $condition = [], array $params = [])
122 $statement = DBA::select('contact', $fields, $condition, $params);
124 return DBA::toArray($statement);
128 * @param array $fields Array of selected fields, empty for all
129 * @param array $condition Array of fields for condition
130 * @param array $params Array of several parameters
134 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
136 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
142 * @param integer $id Contact ID
143 * @param array $fields Array of selected fields, empty for all
144 * @return array|boolean Contact record if it exists, false otherwise
147 public static function getById($id, $fields = [])
149 return DBA::selectFirst('contact', $fields, ['id' => $id]);
153 * @brief Tests if the given contact is a follower
155 * @param int $cid Either public contact id or user's contact id
156 * @param int $uid User ID
158 * @return boolean is the contact id a follower?
159 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
160 * @throws \ImagickException
162 public static function isFollower($cid, $uid)
164 if (self::isBlockedByUser($cid, $uid)) {
168 $cdata = self::getPublicAndUserContacID($cid, $uid);
169 if (empty($cdata['user'])) {
173 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
174 return DBA::exists('contact', $condition);
178 * @brief Tests if the given contact url is a follower
180 * @param string $url Contact URL
181 * @param int $uid User ID
183 * @return boolean is the contact id a follower?
184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 * @throws \ImagickException
187 public static function isFollowerByURL($url, $uid)
189 $cid = self::getIdForURL($url, $uid, true);
195 return self::isFollower($cid, $uid);
199 * @brief Tests if the given user follow the given contact
201 * @param int $cid Either public contact id or user's contact id
202 * @param int $uid User ID
204 * @return boolean is the contact url being followed?
205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
206 * @throws \ImagickException
208 public static function isSharing($cid, $uid)
210 if (self::isBlockedByUser($cid, $uid)) {
214 $cdata = self::getPublicAndUserContacID($cid, $uid);
215 if (empty($cdata['user'])) {
219 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
220 return DBA::exists('contact', $condition);
224 * @brief Tests if the given user follow the given contact url
226 * @param string $url Contact URL
227 * @param int $uid User ID
229 * @return boolean is the contact url being followed?
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
231 * @throws \ImagickException
233 public static function isSharingByURL($url, $uid)
235 $cid = self::getIdForURL($url, $uid, true);
241 return self::isSharing($cid, $uid);
245 * @brief Get the basepath for a given contact link
247 * @param string $url The contact link
249 * @return string basepath
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 * @throws \ImagickException
253 public static function getBasepath($url)
255 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
256 if (!empty($contact['baseurl'])) {
257 return $contact['baseurl'];
260 self::updateFromProbeByURL($url, true);
262 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
263 if (!empty($contact['baseurl'])) {
264 return $contact['baseurl'];
271 * Returns the public contact id of the given user id
273 * @param integer $uid User ID
275 * @return integer|boolean Public contact id for given user id
278 public static function getPublicIdByUserId($uid)
280 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
281 if (!DBA::isResult($self)) {
284 return self::getIdForURL($self['url'], 0, true);
288 * @brief Returns the contact id for the user and the public contact id for a given contact id
290 * @param int $cid Either public contact id or user's contact id
291 * @param int $uid User ID
293 * @return array with public and user's contact id
294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
295 * @throws \ImagickException
297 public static function getPublicAndUserContacID($cid, $uid)
299 if (empty($uid) || empty($cid)) {
303 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
304 if (!DBA::isResult($contact)) {
308 // We quit when the user id don't match the user id of the provided contact
309 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
313 if ($contact['uid'] != 0) {
314 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
318 $ucid = $contact['id'];
320 $pcid = $contact['id'];
321 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
324 return ['public' => $pcid, 'user' => $ucid];
328 * Returns contact details for a given contact id in combination with a user id
330 * @param int $cid A contact ID
331 * @param int $uid The User ID
332 * @param array $fields The selected fields for the contact
334 * @return array The contact details
338 public static function getContactForUser($cid, $uid, array $fields = [])
340 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
342 if (!DBA::isResult($contact)) {
350 * @brief Block contact id for user id
352 * @param int $cid Either public contact id or user's contact id
353 * @param int $uid User ID
354 * @param boolean $blocked Is the contact blocked or unblocked?
357 public static function setBlockedForUser($cid, $uid, $blocked)
359 $cdata = self::getPublicAndUserContacID($cid, $uid);
364 if ($cdata['user'] != 0) {
365 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
368 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
371 // Blocked contact can't be in any group
372 self::removeFromGroups($cid);
377 * @brief Returns "block" state for contact id and user id
379 * @param int $cid Either public contact id or user's contact id
380 * @param int $uid User ID
382 * @return boolean is the contact id blocked for the given user?
385 public static function isBlockedByUser($cid, $uid)
387 $cdata = self::getPublicAndUserContacID($cid, $uid);
392 $public_blocked = false;
394 if (!empty($cdata['public'])) {
395 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
396 if (DBA::isResult($public_contact)) {
397 $public_blocked = $public_contact['blocked'];
401 $user_blocked = $public_blocked;
403 if (!empty($cdata['user'])) {
404 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
405 if (DBA::isResult($user_contact)) {
406 $user_blocked = $user_contact['blocked'];
410 if ($user_blocked != $public_blocked) {
411 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
414 return $user_blocked;
418 * @brief Ignore contact id for user id
420 * @param int $cid Either public contact id or user's contact id
421 * @param int $uid User ID
422 * @param boolean $ignored Is the contact ignored or unignored?
425 public static function setIgnoredForUser($cid, $uid, $ignored)
427 $cdata = self::getPublicAndUserContacID($cid, $uid);
432 if ($cdata['user'] != 0) {
433 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
436 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
440 * @brief Returns "ignore" state for contact id and user id
442 * @param int $cid Either public contact id or user's contact id
443 * @param int $uid User ID
445 * @return boolean is the contact id ignored for the given user?
448 public static function isIgnoredByUser($cid, $uid)
450 $cdata = self::getPublicAndUserContacID($cid, $uid);
455 $public_ignored = false;
457 if (!empty($cdata['public'])) {
458 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
459 if (DBA::isResult($public_contact)) {
460 $public_ignored = $public_contact['ignored'];
464 $user_ignored = $public_ignored;
466 if (!empty($cdata['user'])) {
467 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
468 if (DBA::isResult($user_contact)) {
469 $user_ignored = $user_contact['readonly'];
473 if ($user_ignored != $public_ignored) {
474 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
477 return $user_ignored;
481 * @brief Set "collapsed" for contact id and user id
483 * @param int $cid Either public contact id or user's contact id
484 * @param int $uid User ID
485 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
488 public static function setCollapsedForUser($cid, $uid, $collapsed)
490 $cdata = self::getPublicAndUserContacID($cid, $uid);
495 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
499 * @brief Returns "collapsed" state for contact id and user id
501 * @param int $cid Either public contact id or user's contact id
502 * @param int $uid User ID
504 * @return boolean is the contact id blocked for the given user?
505 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 * @throws \ImagickException
508 public static function isCollapsedByUser($cid, $uid)
510 $cdata = self::getPublicAndUserContacID($cid, $uid);
517 if (!empty($cdata['public'])) {
518 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
519 if (DBA::isResult($public_contact)) {
520 $collapsed = $public_contact['collapsed'];
528 * @brief Returns a list of contacts belonging in a group
534 public static function getByGroupId($gid)
539 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
541 INNER JOIN `group_member`
542 ON `contact`.`id` = `group_member`.`contact-id`
544 AND `contact`.`uid` = ?
545 AND NOT `contact`.`self`
546 AND NOT `contact`.`deleted`
547 AND NOT `contact`.`blocked`
548 AND NOT `contact`.`pending`
549 ORDER BY `contact`.`name` ASC',
554 if (DBA::isResult($stmt)) {
555 $return = DBA::toArray($stmt);
563 * @brief Returns the count of OStatus contacts in a group
569 public static function getOStatusCountByGroupId($gid)
573 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
575 INNER JOIN `group_member`
576 ON `contact`.`id` = `group_member`.`contact-id`
578 AND `contact`.`uid` = ?
579 AND `contact`.`network` = ?
580 AND `contact`.`notify` != ""',
585 $return = $contacts['count'];
592 * Creates the self-contact for the provided user id
595 * @return bool Operation success
596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
598 public static function createSelfFromUserId($uid)
600 // Only create the entry if it doesn't exist yet
601 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
605 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
606 if (!DBA::isResult($user)) {
610 $return = DBA::insert('contact', [
611 'uid' => $user['uid'],
612 'created' => DateTimeFormat::utcNow(),
614 'name' => $user['username'],
615 'nick' => $user['nickname'],
616 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
617 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
618 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
621 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
622 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
623 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
624 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
625 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
626 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
627 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
628 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
629 'name-date' => DateTimeFormat::utcNow(),
630 'uri-date' => DateTimeFormat::utcNow(),
631 'avatar-date' => DateTimeFormat::utcNow(),
639 * Updates the self-contact for the provided user id
642 * @param boolean $update_avatar Force the avatar update
643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
645 public static function updateSelfFromUserID($uid, $update_avatar = false)
647 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
648 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
649 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
650 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
651 if (!DBA::isResult($self)) {
655 $fields = ['nickname', 'page-flags', 'account-type'];
656 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
657 if (!DBA::isResult($user)) {
661 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
662 'country-name', 'gender', 'pub_keywords', 'xmpp'];
663 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
664 if (!DBA::isResult($profile)) {
668 $file_suffix = 'jpg';
670 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
671 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
672 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
673 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
674 'xmpp' => $profile['xmpp']];
676 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
677 if (DBA::isResult($avatar)) {
678 if ($update_avatar) {
679 $fields['avatar-date'] = DateTimeFormat::utcNow();
682 // Creating the path to the avatar, beginning with the file suffix
683 $types = Image::supportedTypes();
684 if (isset($types[$avatar['type']])) {
685 $file_suffix = $types[$avatar['type']];
688 // We are adding a timestamp value so that other systems won't use cached content
689 $timestamp = strtotime($fields['avatar-date']);
691 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
692 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
694 $fields['photo'] = $prefix . '4' . $suffix;
695 $fields['thumb'] = $prefix . '5' . $suffix;
696 $fields['micro'] = $prefix . '6' . $suffix;
698 // We hadn't found a photo entry, so we use the default avatar
699 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
700 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
701 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
704 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
705 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
706 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
708 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
709 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
710 $fields['nurl'] = Strings::normaliseLink($fields['url']);
711 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
712 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
713 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
714 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
715 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
716 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
720 foreach ($fields as $field => $content) {
721 if ($self[$field] != $content) {
727 if ($fields['name'] != $self['name']) {
728 $fields['name-date'] = DateTimeFormat::utcNow();
730 $fields['updated'] = DateTimeFormat::utcNow();
731 DBA::update('contact', $fields, ['id' => $self['id']]);
733 // Update the public contact as well
734 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
736 // Update the profile
737 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
738 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
739 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
744 * @brief Marks a contact for removal
746 * @param int $id contact id
748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
750 public static function remove($id)
752 // We want just to make sure that we don't delete our "self" contact
753 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
754 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
758 // Archive the contact
759 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
761 // Delete it in the background
762 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
766 * @brief Sends an unfriend message. Does not remove the contact
768 * @param array $user User unfriending
769 * @param array $contact Contact unfriended
770 * @param boolean $dissolve Remove the contact on the remote side
772 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
773 * @throws \ImagickException
775 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
777 if (empty($contact['network'])) {
781 $protocol = $contact['network'];
782 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
783 $protocol = Protocol::ACTIVITYPUB;
786 if (($protocol == Protocol::DFRN) && $dissolve) {
787 DFRN::deliver($user, $contact, 'placeholder', true);
788 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
789 // create an unfollow slap
791 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
792 $item['follow'] = $contact["url"];
797 $item['attach'] = '';
798 $slap = OStatus::salmon($item, $user);
800 if (!empty($contact['notify'])) {
801 Salmon::slapper($user, $contact['notify'], $slap);
803 } elseif ($protocol == Protocol::DIASPORA) {
804 Diaspora::sendUnshare($user, $contact);
805 } elseif ($protocol == Protocol::ACTIVITYPUB) {
806 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
809 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
815 * @brief Marks a contact for archival after a communication issue delay
817 * Contact has refused to recognise us as a friend. We will start a countdown.
818 * If they still don't recognise us in 32 days, the relationship is over,
819 * and we won't waste any more time trying to communicate with them.
820 * This provides for the possibility that their database is temporarily messed
821 * up or some other transient event and that there's a possibility we could recover from it.
823 * @param array $contact contact to mark for archival
825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
827 public static function markForArchival(array $contact)
829 if (!isset($contact['url']) && !empty($contact['id'])) {
830 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
831 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
832 if (!DBA::isResult($contact)) {
835 } elseif (!isset($contact['url'])) {
836 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
839 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
841 // Contact already archived or "self" contact? => nothing to do
842 if ($contact['archive'] || $contact['self']) {
846 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
847 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
848 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
851 * We really should send a notification to the owner after 2-3 weeks
852 * so they won't be surprised when the contact vanishes and can take
853 * remedial action if this was a serious mistake or glitch
856 /// @todo Check for contact vitality via probing
857 $archival_days = Config::get('system', 'archival_days', 32);
859 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
860 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
861 /* Relationship is really truly dead. archive them rather than
862 * delete, though if the owner tries to unarchive them we'll start
863 * the whole process over again.
865 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
866 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
867 GContact::updateFromPublicContactURL($contact['url']);
873 * @brief Cancels the archival countdown
875 * @see Contact::markForArchival()
877 * @param array $contact contact to be unmarked for archival
881 public static function unmarkForArchival(array $contact)
883 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
884 $exists = DBA::exists('contact', $condition);
886 // We don't need to update, we never marked this contact for archival
891 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
893 if (!isset($contact['url']) && !empty($contact['id'])) {
894 $fields = ['id', 'url', 'batch'];
895 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
896 if (!DBA::isResult($contact)) {
901 // It's a miracle. Our dead contact has inexplicably come back to life.
902 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
903 DBA::update('contact', $fields, ['id' => $contact['id']]);
904 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
905 GContact::updateFromPublicContactURL($contact['url']);
907 if (!empty($contact['batch'])) {
908 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
909 DBA::update('contact', $fields, $condition);
914 * @brief Get contact data for a given profile link
916 * The function looks at several places (contact table and gcontact table) for the contact
917 * It caches its result for the same script execution to prevent duplicate calls
919 * @param string $url The profile link
920 * @param int $uid User id
921 * @param array $default If not data was found take this data as default value
923 * @return array Contact data
924 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
926 public static function getDetailsByURL($url, $uid = -1, array $default = [])
938 if (isset($cache[$url][$uid])) {
939 return $cache[$url][$uid];
942 $ssl_url = str_replace('http://', 'https://', $url);
944 // Fetch contact data from the contact table for the given user
945 $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`,
946 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
947 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
948 $r = DBA::toArray($s);
950 // Fetch contact data from the contact table for the given user, checking with the alias
951 if (!DBA::isResult($r)) {
952 $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`,
953 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
954 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
955 $r = DBA::toArray($s);
958 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
959 if (!DBA::isResult($r)) {
960 $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`,
961 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
962 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
963 $r = DBA::toArray($s);
966 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
967 if (!DBA::isResult($r)) {
968 $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`,
969 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
970 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
971 $r = DBA::toArray($s);
974 // Fetch the data from the gcontact table
975 if (!DBA::isResult($r)) {
976 $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`,
977 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
978 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
979 $r = DBA::toArray($s);
982 if (DBA::isResult($r)) {
983 // If there is more than one entry we filter out the connector networks
985 foreach ($r as $id => $result) {
986 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
992 $profile = array_shift($r);
994 // "bd" always contains the upcoming birthday of a contact.
995 // "birthday" might contain the birthday including the year of birth.
996 if ($profile["birthday"] > DBA::NULL_DATE) {
997 $bd_timestamp = strtotime($profile["birthday"]);
998 $month = date("m", $bd_timestamp);
999 $day = date("d", $bd_timestamp);
1001 $current_timestamp = time();
1002 $current_year = date("Y", $current_timestamp);
1003 $current_month = date("m", $current_timestamp);
1004 $current_day = date("d", $current_timestamp);
1006 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
1007 $current = $current_year . "-" . $current_month . "-" . $current_day;
1009 if ($profile["bd"] < $current) {
1010 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
1013 $profile["bd"] = DBA::NULL_DATE;
1016 $profile = $default;
1019 if (empty($profile["photo"]) && isset($default["photo"])) {
1020 $profile["photo"] = $default["photo"];
1023 if (empty($profile["name"]) && isset($default["name"])) {
1024 $profile["name"] = $default["name"];
1027 if (empty($profile["network"]) && isset($default["network"])) {
1028 $profile["network"] = $default["network"];
1031 if (empty($profile["thumb"]) && isset($profile["photo"])) {
1032 $profile["thumb"] = $profile["photo"];
1035 if (empty($profile["micro"]) && isset($profile["thumb"])) {
1036 $profile["micro"] = $profile["thumb"];
1039 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
1040 && in_array($profile["network"], Protocol::FEDERATED)
1042 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
1045 // Show contact details of Diaspora contacts only if connected
1046 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
1047 $profile["location"] = "";
1048 $profile["about"] = "";
1049 $profile["gender"] = "";
1050 $profile["birthday"] = DBA::NULL_DATE;
1053 $cache[$url][$uid] = $profile;
1059 * @brief Get contact data for a given address
1061 * The function looks at several places (contact table and gcontact table) for the contact
1063 * @param string $addr The profile link
1064 * @param int $uid User id
1066 * @return array Contact data
1067 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1068 * @throws \ImagickException
1070 public static function getDetailsByAddr($addr, $uid = -1)
1077 $uid = local_user();
1080 // Fetch contact data from the contact table for the given user
1081 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1082 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1083 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1087 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1088 if (!DBA::isResult($r)) {
1089 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1090 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1091 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1096 // Fetch the data from the gcontact table
1097 if (!DBA::isResult($r)) {
1098 $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`,
1099 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1100 FROM `gcontact` WHERE `addr` = '%s'",
1105 if (!DBA::isResult($r)) {
1106 $data = Probe::uri($addr);
1108 $profile = self::getDetailsByURL($data['url'], $uid);
1117 * @brief Returns the data array for the photo menu of a given contact
1119 * @param array $contact contact
1120 * @param int $uid optional, default 0
1122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1123 * @throws \ImagickException
1125 public static function photoMenu(array $contact, $uid = 0)
1130 $contact_drop_link = '';
1134 $uid = local_user();
1137 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1139 $profile_link = self::magicLink($contact['url']);
1140 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1145 // Look for our own contact if the uid doesn't match and isn't public
1146 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1147 if (DBA::isResult($contact_own)) {
1148 return self::photoMenu($contact_own, $uid);
1153 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1155 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1157 $profile_link = $contact['url'];
1160 if ($profile_link === 'mailbox') {
1165 $status_link = $profile_link . '?tab=status';
1166 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1167 $profile_link = $profile_link . '?tab=profile';
1170 if (self::canReceivePrivateMessages($contact)) {
1171 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1174 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1175 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1178 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1180 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1182 if (!$contact['self']) {
1183 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1188 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1190 if (empty($contact['uid'])) {
1191 $connlnk = 'follow/?url=' . $contact['url'];
1193 'profile' => [L10n::t('View Profile'), $profile_link, true],
1194 'network' => [L10n::t('Network Posts'), $posts_link, false],
1195 'edit' => [L10n::t('View Contact'), $contact_url, false],
1196 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1200 'status' => [L10n::t('View Status'), $status_link, true],
1201 'profile' => [L10n::t('View Profile'), $profile_link, true],
1202 'photos' => [L10n::t('View Photos'), $photos_link, true],
1203 'network' => [L10n::t('Network Posts'), $posts_link, false],
1204 'edit' => [L10n::t('View Contact'), $contact_url, false],
1205 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1206 'pm' => [L10n::t('Send PM'), $pm_url, false],
1207 'poke' => [L10n::t('Poke'), $poke_link, false],
1211 $args = ['contact' => $contact, 'menu' => &$menu];
1213 Hook::callAll('contact_photo_menu', $args);
1215 $menucondensed = [];
1217 foreach ($menu as $menuname => $menuitem) {
1218 if ($menuitem[1] != '') {
1219 $menucondensed[$menuname] = $menuitem;
1223 return $menucondensed;
1227 * @brief Returns ungrouped contact count or list for user
1229 * Returns either the total number of ungrouped contacts for the given user
1230 * id or a paginated list of ungrouped contacts.
1232 * @param int $uid uid
1234 * @throws \Exception
1236 public static function getUngroupedList($uid)
1246 SELECT DISTINCT(`contact-id`)
1248 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1249 WHERE `group`.`uid` = %d
1250 )", intval($uid), intval($uid));
1254 * Have a look at all contact tables for a given profile url.
1255 * This function works as a replacement for probing the contact.
1257 * @param string $url Contact URL
1258 * @param integer $cid Contact ID
1260 * @return array Contact array in the "probe" structure
1262 private static function getProbeDataFromDatabase($url, $cid = null)
1264 // The link could be provided as http although we stored it as https
1265 $ssl_url = str_replace('http://', 'https://', $url);
1267 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1268 'photo', 'keywords', 'location', 'about', 'network',
1269 'priority', 'batch', 'request', 'confirm', 'poco'];
1272 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1273 if (DBA::isResult($data)) {
1278 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1280 if (!DBA::isResult($data)) {
1281 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1282 $data = DBA::selectFirst('contact', $fields, $condition);
1285 if (DBA::isResult($data)) {
1286 // For security reasons we don't fetch key data from our users
1287 $data["pubkey"] = '';
1291 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1292 'photo', 'keywords', 'location', 'about', 'network'];
1293 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1295 if (!DBA::isResult($data)) {
1296 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1297 $data = DBA::selectFirst('contact', $fields, $condition);
1300 if (DBA::isResult($data)) {
1301 $data["pubkey"] = '';
1303 $data["priority"] = 0;
1304 $data["batch"] = '';
1305 $data["request"] = '';
1306 $data["confirm"] = '';
1311 $data = ActivityPub::probeProfile($url, false);
1312 if (!empty($data)) {
1316 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1317 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1318 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1320 if (!DBA::isResult($data)) {
1321 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1322 $data = DBA::selectFirst('contact', $fields, $condition);
1325 if (DBA::isResult($data)) {
1326 $data["pubkey"] = '';
1327 $data["keywords"] = '';
1328 $data["location"] = '';
1329 $data["about"] = '';
1338 * @brief Fetch the contact id for a given URL and user
1340 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1341 * `addr` or `alias`.
1343 * If there's no record and we aren't looking for a public contact, we quit.
1344 * If there's one, we check that it isn't time to update the picture else we
1345 * directly return the found contact id.
1347 * Second, we probe the provided $url whether it's http://server.tld/profile or
1348 * nick@server.tld. We quit if we can't get any info back.
1350 * Third, we create the contact record if it doesn't exist
1352 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1353 * if there's any updates
1355 * @param string $url Contact URL
1356 * @param integer $uid The user id for the contact (0 = public contact)
1357 * @param boolean $no_update Don't update the contact
1358 * @param array $default Default value for creating the contact when every else fails
1359 * @param boolean $in_loop Internally used variable to prevent an endless loop
1361 * @return integer Contact ID
1362 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363 * @throws \ImagickException
1365 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1367 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1375 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1376 // We first try the nurl (http://server.tld/nick), most common case
1377 $fields = ['id', 'avatar', 'updated', 'network'];
1378 $options = ['order' => ['id']];
1379 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
1381 // Then the addr (nick@server.tld)
1382 if (!DBA::isResult($contact)) {
1383 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
1386 // Then the alias (which could be anything)
1387 if (!DBA::isResult($contact)) {
1388 // The link could be provided as http although we stored it as https
1389 $ssl_url = str_replace('http://', 'https://', $url);
1390 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1391 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
1394 if (DBA::isResult($contact)) {
1395 $contact_id = $contact["id"];
1397 // Update the contact every 7 days
1398 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1400 // We force the update if the avatar is empty
1401 if (empty($contact['avatar'])) {
1402 $update_contact = true;
1405 // Update the contact in the background if needed but it is called by the frontend
1406 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1407 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1410 if (!$update_contact || $no_update) {
1413 } elseif ($uid != 0) {
1414 // Non-existing user-specific contact, exiting
1418 if ($no_update && empty($default)) {
1419 // When we don't want to update, we look if we know this contact in any way
1420 $data = self::getProbeDataFromDatabase($url, $contact_id);
1421 $background_update = true;
1422 } elseif ($no_update && !empty($default)) {
1423 // If there are default values, take these
1425 $background_update = false;
1428 $background_update = false;
1432 $data = Probe::uri($url, "", $uid);
1434 // Ensure that there is a gserver entry
1435 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1436 PortableContact::checkServer($data['baseurl']);
1440 // Take the default values when probing failed
1441 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1442 $data = array_merge($data, $default);
1449 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1450 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1456 'created' => DateTimeFormat::utcNow(),
1457 'url' => $data['url'],
1458 'nurl' => Strings::normaliseLink($data['url']),
1459 'addr' => defaults($data, 'addr', ''),
1460 'alias' => defaults($data, 'alias', ''),
1461 'notify' => defaults($data, 'notify', ''),
1462 'poll' => defaults($data, 'poll', ''),
1463 'name' => defaults($data, 'name', ''),
1464 'nick' => defaults($data, 'nick', ''),
1465 'photo' => defaults($data, 'photo', ''),
1466 'keywords' => defaults($data, 'keywords', ''),
1467 'location' => defaults($data, 'location', ''),
1468 'about' => defaults($data, 'about', ''),
1469 'network' => $data['network'],
1470 'pubkey' => defaults($data, 'pubkey', ''),
1471 'rel' => self::SHARING,
1472 'priority' => defaults($data, 'priority', 0),
1473 'batch' => defaults($data, 'batch', ''),
1474 'request' => defaults($data, 'request', ''),
1475 'confirm' => defaults($data, 'confirm', ''),
1476 'poco' => defaults($data, 'poco', ''),
1477 'baseurl' => defaults($data, 'baseurl', ''),
1478 'name-date' => DateTimeFormat::utcNow(),
1479 'uri-date' => DateTimeFormat::utcNow(),
1480 'avatar-date' => DateTimeFormat::utcNow(),
1486 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1488 // Before inserting we do check if the entry does exist now.
1489 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1490 if (!DBA::isResult($contact)) {
1491 Logger::info('Create new contact', $fields);
1493 DBA::insert('contact', $fields);
1495 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1496 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1497 if (!DBA::isResult($contact)) {
1498 Logger::info('Contact creation failed', $fields);
1503 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1506 $contact_id = $contact["id"];
1509 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1510 self::updateAvatar($data['photo'], $uid, $contact_id);
1513 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1514 if ($background_update) {
1515 // Update in the background when we fetched the data solely from the database
1516 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1518 // Else do a direct update
1519 self::updateFromProbe($contact_id, '', false);
1521 // Update the gcontact entry
1523 GContact::updateFromPublicContactID($contact_id);
1527 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl'];
1528 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1530 // This condition should always be true
1531 if (!DBA::isResult($contact)) {
1536 'url' => $data['url'],
1537 'nurl' => Strings::normaliseLink($data['url']),
1538 'updated' => DateTimeFormat::utcNow()
1541 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl'];
1543 foreach ($fields as $field) {
1544 $updated[$field] = defaults($data, $field, $contact[$field]);
1547 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1548 $updated['uri-date'] = DateTimeFormat::utcNow();
1551 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1552 $updated['name-date'] = DateTimeFormat::utcNow();
1555 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1562 * @brief Checks if the contact is blocked
1564 * @param int $cid contact id
1566 * @return boolean Is the contact blocked?
1567 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1569 public static function isBlocked($cid)
1575 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1576 if (!DBA::isResult($blocked)) {
1580 if (Network::isUrlBlocked($blocked['url'])) {
1584 return (bool) $blocked['blocked'];
1588 * @brief Checks if the contact is hidden
1590 * @param int $cid contact id
1592 * @return boolean Is the contact hidden?
1593 * @throws \Exception
1595 public static function isHidden($cid)
1601 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1602 if (!DBA::isResult($hidden)) {
1605 return (bool) $hidden['hidden'];
1609 * @brief Returns posts from a given contact url
1611 * @param string $contact_url Contact URL
1613 * @param bool $thread_mode
1614 * @param int $update
1615 * @return string posts in HTML
1616 * @throws \Exception
1618 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1620 $a = self::getApp();
1622 $cid = self::getIdForURL($contact_url);
1624 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1625 if (!DBA::isResult($contact)) {
1629 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1630 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1632 $sql = "`item`.`uid` = ?";
1635 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1638 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1639 $cid, GRAVITY_PARENT, local_user()];
1641 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1642 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1645 $pager = new Pager($a->query_string);
1647 $params = ['order' => ['received' => true],
1648 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1651 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1653 $items = Item::inArray($r);
1655 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1657 $r = Item::selectForUser(local_user(), [], $condition, $params);
1659 $items = Item::inArray($r);
1661 $o = conversation($a, $items, $pager, 'contact-posts', false);
1665 $o .= $pager->renderMinimal(count($items));
1672 * @brief Returns the account type name
1674 * The function can be called with either the user or the contact array
1676 * @param array $contact contact or user array
1679 public static function getAccountType(array $contact)
1681 // There are several fields that indicate that the contact or user is a forum
1682 // "page-flags" is a field in the user table,
1683 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1684 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1685 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1686 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1687 || (isset($contact['forum']) && intval($contact['forum']))
1688 || (isset($contact['prv']) && intval($contact['prv']))
1689 || (isset($contact['community']) && intval($contact['community']))
1691 $type = self::TYPE_COMMUNITY;
1693 $type = self::TYPE_PERSON;
1696 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1697 if (isset($contact["contact-type"])) {
1698 $type = $contact["contact-type"];
1701 if (isset($contact["account-type"])) {
1702 $type = $contact["account-type"];
1706 case self::TYPE_ORGANISATION:
1707 $account_type = L10n::t("Organisation");
1710 case self::TYPE_NEWS:
1711 $account_type = L10n::t('News');
1714 case self::TYPE_COMMUNITY:
1715 $account_type = L10n::t("Forum");
1723 return $account_type;
1727 * @brief Blocks a contact
1731 * @throws \Exception
1733 public static function block($cid, $reason = null)
1735 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1741 * @brief Unblocks a contact
1745 * @throws \Exception
1747 public static function unblock($cid)
1749 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1755 * @brief Updates the avatar links in a contact only if needed
1757 * @param string $avatar Link to avatar picture
1758 * @param int $uid User id of contact owner
1759 * @param int $cid Contact id
1760 * @param bool $force force picture update
1762 * @return array Returns array of the different avatar sizes
1763 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1764 * @throws \ImagickException
1766 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1768 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1769 if (!DBA::isResult($contact)) {
1772 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1775 if (($contact["avatar"] != $avatar) || $force) {
1776 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1779 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1780 DBA::update('contact', $fields, ['id' => $cid]);
1782 // Update the public contact (contact id = 0)
1784 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1785 if (DBA::isResult($pcontact)) {
1786 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1798 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1800 * @param array $contact The personal contact entry
1801 * @param array $fields The fields that are updated
1802 * @throws \Exception
1804 private static function updateContact($id, $uid, $url, array $fields)
1806 DBA::update('contact', $fields, ['id' => $id]);
1808 // Search for duplicated contacts and get rid of them
1809 if (self::handleDuplicates(Strings::normaliseLink($url), $uid, $id) || ($uid != 0)) {
1813 // Update the corresponding gcontact entry
1814 GContact::updateFromPublicContactID($id);
1816 // Archive or unarchive the contact. We only need to do this for the public contact.
1817 // The archive/unarchive function will update the personal contacts by themselves.
1818 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1819 if (!empty($fields['success_update'])) {
1820 self::unmarkForArchival($contact);
1821 } elseif (!empty($fields['failure_update'])) {
1822 self::markForArchival($contact);
1825 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1827 // These contacts are sharing with us, we don't poll them.
1828 // This means that we don't set the update fields in "OnePoll.php".
1829 $condition['rel'] = self::SHARING;
1830 DBA::update('contact', $fields, $condition);
1832 unset($fields['last-update']);
1833 unset($fields['success_update']);
1834 unset($fields['failure_update']);
1836 if (empty($fields)) {
1840 // We are polling these contacts, so we mustn't set the update fields here.
1841 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1842 DBA::update('contact', $fields, $condition);
1846 * @brief Helper function for "updateFromProbe". Remove duplicated contacts
1848 * @param string $nurl Normalised contact url
1849 * @param integer $uid User id
1850 * @param integer $id Contact id of a duplicate
1852 * @throws \Exception
1854 private static function handleDuplicates($nurl, $uid, $id)
1856 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false];
1857 $count = DBA::count('contact', $condition);
1862 $first_contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1863 if (!DBA::isResult($first_contact)) {
1864 // Shouldn't happen - so we handle it
1868 $first = $first_contact['id'];
1869 Logger::info('Found duplicates', ['count' => $count, 'id' => $id, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1871 // Don't handle non public duplicates by now
1872 Logger::info('Not handling non public duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1876 // Find all duplicates
1877 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1878 $duplicates = DBA::select('contact', ['id'], $condition);
1879 while ($duplicate = DBA::fetch($duplicates)) {
1880 $dup_id = $duplicate['id'];
1881 Logger::info('Handling duplicate', ['search' => $dup_id, 'replace' => $first]);
1883 // Search and replace
1884 DBA::update('item', ['author-id' => $first], ['author-id' => $dup_id]);
1885 DBA::update('item', ['owner-id' => $first], ['owner-id' => $dup_id]);
1886 DBA::update('item', ['contact-id' => $first], ['contact-id' => $dup_id]);
1888 // Remove the duplicate
1889 DBA::delete('contact', ['id' => $dup_id]);
1891 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1896 * @param integer $id contact id
1897 * @param string $network Optional network we are probing for
1898 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1900 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1901 * @throws \ImagickException
1903 public static function updateFromProbe($id, $network = '', $force = false)
1906 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1907 This will reliably kill your communication with old Friendica contacts.
1910 // These fields aren't updated by this routine:
1911 // 'xmpp', 'sensitive'
1913 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
1914 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1915 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
1916 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1917 if (!DBA::isResult($contact)) {
1921 $uid = $contact['uid'];
1922 unset($contact['uid']);
1924 $pubkey = $contact['pubkey'];
1925 unset($contact['pubkey']);
1927 $contact['photo'] = $contact['avatar'];
1928 unset($contact['avatar']);
1930 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1932 $updated = DateTimeFormat::utcNow();
1934 // We must not try to update relay contacts via probe. They are no real contacts.
1935 // We check after the probing to be able to correct falsely detected contact types.
1936 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1937 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1938 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
1939 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1943 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1944 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
1945 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
1946 if ($force && ($uid == 0)) {
1947 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1952 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1953 $ret['unsearchable'] = $ret['hide'];
1956 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1957 $ret['forum'] = false;
1958 $ret['prv'] = false;
1959 $ret['contact-type'] = $ret['account-type'];
1960 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1961 $apcontact = APContact::getByURL($ret['url'], false);
1962 if (isset($apcontact['manually-approve'])) {
1963 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1964 $ret['prv'] = (bool)!$ret['forum'];
1969 $new_pubkey = $ret['pubkey'];
1973 // make sure to not overwrite existing values with blank entries except some technical fields
1974 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1975 foreach ($ret as $key => $val) {
1976 if (!array_key_exists($key, $contact)) {
1978 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1979 $ret[$key] = $contact[$key];
1980 } elseif ($ret[$key] != $contact[$key]) {
1985 if ($ret['network'] != Protocol::FEED) {
1986 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
1990 if ($force && ($uid == 0)) {
1991 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
1996 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1997 $ret['updated'] = $updated;
1999 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2000 if (empty($pubkey) && !empty($new_pubkey)) {
2001 $ret['pubkey'] = $new_pubkey;
2004 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2005 $ret['uri-date'] = DateTimeFormat::utcNow();
2008 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2009 $ret['name-date'] = $updated;
2012 if ($force && ($uid == 0)) {
2013 $ret['last-update'] = $updated;
2014 $ret['success_update'] = $updated;
2017 unset($ret['photo']);
2019 self::updateContact($id, $uid, $ret['url'], $ret);
2024 public static function updateFromProbeByURL($url, $force = false)
2026 $id = self::getIdForURL($url);
2032 self::updateFromProbe($id, '', $force);
2038 * Detects if a given contact array belongs to a legacy DFRN connection
2040 * @param array $contact
2043 public static function isLegacyDFRNContact($contact)
2045 // Newer Friendica contacts are connected via AP, then these fields aren't set
2046 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2050 * Detects the communication protocol for a given contact url.
2051 * This is used to detect Friendica contacts that we can communicate via AP.
2053 * @param string $url contact url
2054 * @param string $network Network of that contact
2055 * @return string with protocol
2057 public static function getProtocol($url, $network)
2059 if ($network != Protocol::DFRN) {
2063 $apcontact = APContact::getByURL($url);
2064 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2065 return Protocol::ACTIVITYPUB;
2072 * Takes a $uid and a url/handle and adds a new contact
2073 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2074 * dfrn_request page.
2076 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2079 * $return['success'] boolean true if successful
2080 * $return['message'] error text if success is false.
2082 * @brief Takes a $uid and a url/handle and adds a new contact
2084 * @param string $url
2085 * @param bool $interactive
2086 * @param string $network
2088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2089 * @throws \ImagickException
2091 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2093 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2097 // remove ajax junk, e.g. Twitter
2098 $url = str_replace('/#!/', '/', $url);
2100 if (!Network::isUrlAllowed($url)) {
2101 $result['message'] = L10n::t('Disallowed profile URL.');
2105 if (Network::isUrlBlocked($url)) {
2106 $result['message'] = L10n::t('Blocked domain');
2111 $result['message'] = L10n::t('Connect URL missing.');
2115 $arr = ['url' => $url, 'contact' => []];
2117 Hook::callAll('follow', $arr);
2120 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2124 if (!empty($arr['contact']['name'])) {
2125 $ret = $arr['contact'];
2127 $ret = Probe::uri($url, $network, $uid, false);
2130 if (($network != '') && ($ret['network'] != $network)) {
2131 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2135 // check if we already have a contact
2136 // the poll url is more reliable than the profile url, as we may have
2137 // indirect links or webfinger links
2139 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2140 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2141 if (!DBA::isResult($contact)) {
2142 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2143 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2146 $protocol = self::getProtocol($url, $ret['network']);
2148 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2150 if (strlen($a->getURLPath())) {
2151 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2153 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2156 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2160 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2161 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2162 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2166 // This extra param just confuses things, remove it
2167 if ($protocol === Protocol::DIASPORA) {
2168 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2171 // do we have enough information?
2172 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2173 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2174 if (empty($ret['poll'])) {
2175 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2177 if (empty($ret['name'])) {
2178 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2180 if (empty($ret['url'])) {
2181 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2183 if (strpos($url, '@') !== false) {
2184 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2185 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2190 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2191 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2192 $ret['notify'] = '';
2195 if (!$ret['notify']) {
2196 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2199 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2201 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2203 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2205 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2207 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2211 if (DBA::isResult($contact)) {
2213 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2215 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2216 DBA::update('contact', $fields, ['id' => $contact['id']]);
2218 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2220 // create contact record
2221 DBA::insert('contact', [
2223 'created' => DateTimeFormat::utcNow(),
2224 'url' => $ret['url'],
2225 'nurl' => Strings::normaliseLink($ret['url']),
2226 'addr' => $ret['addr'],
2227 'alias' => $ret['alias'],
2228 'batch' => $ret['batch'],
2229 'notify' => $ret['notify'],
2230 'poll' => $ret['poll'],
2231 'poco' => $ret['poco'],
2232 'name' => $ret['name'],
2233 'nick' => $ret['nick'],
2234 'network' => $ret['network'],
2235 'baseurl' => $ret['baseurl'],
2236 'protocol' => $protocol,
2237 'pubkey' => $ret['pubkey'],
2238 'rel' => $new_relation,
2239 'priority'=> $ret['priority'],
2240 'writable'=> $writeable,
2241 'hidden' => $hidden,
2244 'pending' => $pending,
2249 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2250 if (!DBA::isResult($contact)) {
2251 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2255 $contact_id = $contact['id'];
2256 $result['cid'] = $contact_id;
2258 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2260 // Update the avatar
2261 self::updateAvatar($ret['photo'], $uid, $contact_id);
2263 // pull feed and consume it, which should subscribe to the hub.
2265 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2267 $owner = User::getOwnerDataById($uid);
2269 if (DBA::isResult($owner)) {
2270 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2271 // create a follow slap
2273 $item['verb'] = ACTIVITY_FOLLOW;
2274 $item['follow'] = $contact["url"];
2276 $item['title'] = '';
2279 $item['attach'] = '';
2281 $slap = OStatus::salmon($item, $owner);
2283 if (!empty($contact['notify'])) {
2284 Salmon::slapper($owner, $contact['notify'], $slap);
2286 } elseif ($protocol == Protocol::DIASPORA) {
2287 $ret = Diaspora::sendShare($a->user, $contact);
2288 Logger::log('share returns: ' . $ret);
2289 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2290 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2291 if (empty($activity_id)) {
2292 // This really should never happen
2296 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2297 Logger::log('Follow returns: ' . $ret);
2301 $result['success'] = true;
2306 * @brief Updated contact's SSL policy
2308 * @param array $contact Contact array
2309 * @param string $new_policy New policy, valid: self,full
2311 * @return array Contact array with updated values
2312 * @throws \Exception
2314 public static function updateSslPolicy(array $contact, $new_policy)
2316 $ssl_changed = false;
2317 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2318 $ssl_changed = true;
2319 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2320 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2321 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2322 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2323 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2324 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2327 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2328 $ssl_changed = true;
2329 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2330 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2331 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2332 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2333 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2334 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2338 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2339 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2340 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2341 DBA::update('contact', $fields, ['id' => $contact['id']]);
2348 * @param array $importer Owner (local user) data
2349 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2350 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2351 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2352 * @param string $note Introduction additional message
2353 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2355 * @throws \ImagickException
2357 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2359 // Should always be set
2360 if (empty($datarray['author-id'])) {
2364 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2365 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2366 if (!DBA::isResult($pub_contact)) {
2367 // Should never happen
2371 // Contact is blocked at node-level
2372 if (self::isBlocked($datarray['author-id'])) {
2376 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2377 $name = $pub_contact['name'];
2378 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2379 $nick = $pub_contact['nick'];
2380 $network = $pub_contact['network'];
2382 if (!empty($contact)) {
2383 // Contact is blocked at user-level
2384 if (!empty($contact['id']) && !empty($importer['id']) &&
2385 self::isBlockedByUser($contact['id'], $importer['id'])) {
2389 // Make sure that the existing contact isn't archived
2390 self::unmarkForArchival($contact);
2392 if (($contact['rel'] == self::SHARING)
2393 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2394 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2395 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2400 // send email notification to owner?
2401 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2402 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2406 // create contact record
2407 DBA::insert('contact', [
2408 'uid' => $importer['uid'],
2409 'created' => DateTimeFormat::utcNow(),
2411 'nurl' => Strings::normaliseLink($url),
2415 'network' => $network,
2416 'rel' => self::FOLLOWER,
2424 'id' => DBA::lastInsertId(),
2425 'network' => $network,
2431 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2433 /// @TODO Encapsulate this into a function/method
2434 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2435 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2436 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2437 // create notification
2438 $hash = Strings::getRandomHex();
2440 if (is_array($contact_record)) {
2441 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2442 'blocked' => false, 'knowyou' => false, 'note' => $note,
2443 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2446 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2448 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2449 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2452 'type' => NOTIFY_INTRO,
2453 'notify_flags' => $user['notify-flags'],
2454 'language' => $user['language'],
2455 'to_name' => $user['username'],
2456 'to_email' => $user['email'],
2457 'uid' => $user['uid'],
2458 'link' => System::baseUrl() . '/notifications/intro',
2459 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2460 'source_link' => $contact_record['url'],
2461 'source_photo' => $contact_record['photo'],
2462 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2466 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2467 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2468 DBA::update('contact', ['pending' => false], $condition);
2477 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2479 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2480 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2482 Contact::remove($contact['id']);
2486 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2488 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2489 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2491 Contact::remove($contact['id']);
2496 * @brief Create a birthday event.
2498 * Update the year and the birthday.
2500 public static function updateBirthdays()
2504 AND `bd` > "0001-01-01"
2505 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2506 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2507 AND NOT `contact`.`pending`
2508 AND NOT `contact`.`hidden`
2509 AND NOT `contact`.`blocked`
2510 AND NOT `contact`.`archive`
2511 AND NOT `contact`.`deleted`',
2516 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2518 while ($contact = DBA::fetch($contacts)) {
2519 Logger::log('update_contact_birthday: ' . $contact['bd']);
2521 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2523 if (Event::createBirthday($contact, $nextbd)) {
2527 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2528 ['id' => $contact['id']]
2535 * Remove the unavailable contact ids from the provided list
2537 * @param array $contact_ids Contact id list
2538 * @throws \Exception
2540 public static function pruneUnavailable(array &$contact_ids)
2542 if (empty($contact_ids)) {
2546 $str = DBA::escape(implode(',', $contact_ids));
2548 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2551 while($contact = DBA::fetch($stmt)) {
2552 $return[] = $contact['id'];
2557 $contact_ids = $return;
2561 * @brief Returns a magic link to authenticate remote visitors
2563 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2565 * @param string $contact_url The address of the target contact profile
2566 * @param string $url An url that we will be redirected to after the authentication
2568 * @return string with "redir" link
2569 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2570 * @throws \ImagickException
2572 public static function magicLink($contact_url, $url = '')
2574 if (!local_user() && !remote_user()) {
2575 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2578 $data = self::getProbeDataFromDatabase($contact_url);
2580 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2583 // Prevents endless loop in case only a non-public contact exists for the contact URL
2584 unset($data['uid']);
2586 return self::magicLinkByContact($data, $contact_url);
2590 * @brief Returns a magic link to authenticate remote visitors
2592 * @param integer $cid The contact id of the target contact profile
2593 * @param string $url An url that we will be redirected to after the authentication
2595 * @return string with "redir" link
2596 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2597 * @throws \ImagickException
2599 public static function magicLinkbyId($cid, $url = '')
2601 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2603 return self::magicLinkByContact($contact, $url);
2607 * @brief Returns a magic link to authenticate remote visitors
2609 * @param array $contact The contact array with "uid", "network" and "url"
2610 * @param string $url An url that we will be redirected to after the authentication
2612 * @return string with "redir" link
2613 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2614 * @throws \ImagickException
2616 public static function magicLinkByContact($contact, $url = '')
2618 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2619 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2622 // Only redirections to the same host do make sense
2623 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2627 if (!empty($contact['uid'])) {
2628 return self::magicLink($contact['url'], $url);
2631 if (empty($contact['id'])) {
2632 return $url ?: $contact['url'];
2635 $redirect = 'redir/' . $contact['id'];
2638 $redirect .= '?url=' . $url;
2645 * Remove a contact from all groups
2647 * @param integer $contact_id
2649 * @return boolean Success
2651 public static function removeFromGroups($contact_id)
2653 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2657 * Is the contact a forum?
2659 * @param integer $contactid ID of the contact
2661 * @return boolean "true" if it is a forum
2663 public static function isForum($contactid)
2665 $fields = ['forum', 'prv'];
2666 $condition = ['id' => $contactid];
2667 $contact = DBA::selectFirst('contact', $fields, $condition);
2668 if (!DBA::isResult($contact)) {
2673 return ($contact['forum'] || $contact['prv']);
2677 * Can the remote contact receive private messages?
2679 * @param array $contact
2682 public static function canReceivePrivateMessages(array $contact)
2684 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2685 $self = $contact['self'] ?? false;
2687 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;