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 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' => 1], ['id' => $contact['id']]);
864 DBA::update('contact', ['archive' => 1], ['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'])]);
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 blocked
1562 * @param int $cid contact id
1564 * @return boolean Is the contact blocked?
1565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1567 public static function isBlocked($cid)
1573 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1574 if (!DBA::isResult($blocked)) {
1578 if (Network::isUrlBlocked($blocked['url'])) {
1582 return (bool) $blocked['blocked'];
1586 * @brief Checks if the contact is hidden
1588 * @param int $cid contact id
1590 * @return boolean Is the contact hidden?
1591 * @throws \Exception
1593 public static function isHidden($cid)
1599 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1600 if (!DBA::isResult($hidden)) {
1603 return (bool) $hidden['hidden'];
1607 * @brief Returns posts from a given contact url
1609 * @param string $contact_url Contact URL
1611 * @param bool $thread_mode
1612 * @param int $update
1613 * @return string posts in HTML
1614 * @throws \Exception
1616 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1618 $a = self::getApp();
1620 $cid = self::getIdForURL($contact_url);
1622 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1623 if (!DBA::isResult($contact)) {
1627 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1628 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1630 $sql = "`item`.`uid` = ?";
1633 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1636 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1637 $cid, GRAVITY_PARENT, local_user()];
1639 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1640 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1643 $pager = new Pager($a->query_string);
1645 $params = ['order' => ['received' => true],
1646 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1649 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1651 $items = Item::inArray($r);
1653 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1655 $r = Item::selectForUser(local_user(), [], $condition, $params);
1657 $items = Item::inArray($r);
1659 $o = conversation($a, $items, $pager, 'contact-posts', false);
1663 $o .= $pager->renderMinimal(count($items));
1670 * @brief Returns the account type name
1672 * The function can be called with either the user or the contact array
1674 * @param array $contact contact or user array
1677 public static function getAccountType(array $contact)
1679 // There are several fields that indicate that the contact or user is a forum
1680 // "page-flags" is a field in the user table,
1681 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1682 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1683 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1684 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1685 || (isset($contact['forum']) && intval($contact['forum']))
1686 || (isset($contact['prv']) && intval($contact['prv']))
1687 || (isset($contact['community']) && intval($contact['community']))
1689 $type = self::TYPE_COMMUNITY;
1691 $type = self::TYPE_PERSON;
1694 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1695 if (isset($contact["contact-type"])) {
1696 $type = $contact["contact-type"];
1699 if (isset($contact["account-type"])) {
1700 $type = $contact["account-type"];
1704 case self::TYPE_ORGANISATION:
1705 $account_type = L10n::t("Organisation");
1708 case self::TYPE_NEWS:
1709 $account_type = L10n::t('News');
1712 case self::TYPE_COMMUNITY:
1713 $account_type = L10n::t("Forum");
1721 return $account_type;
1725 * @brief Blocks a contact
1729 * @throws \Exception
1731 public static function block($cid, $reason = null)
1733 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1739 * @brief Unblocks a contact
1743 * @throws \Exception
1745 public static function unblock($cid)
1747 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1753 * @brief Updates the avatar links in a contact only if needed
1755 * @param string $avatar Link to avatar picture
1756 * @param int $uid User id of contact owner
1757 * @param int $cid Contact id
1758 * @param bool $force force picture update
1760 * @return array Returns array of the different avatar sizes
1761 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1762 * @throws \ImagickException
1764 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1766 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1767 if (!DBA::isResult($contact)) {
1770 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1773 if (($contact["avatar"] != $avatar) || $force) {
1774 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1777 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1778 DBA::update('contact', $fields, ['id' => $cid]);
1780 // Update the public contact (contact id = 0)
1782 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1783 if (DBA::isResult($pcontact)) {
1784 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1796 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1798 * @param array $contact The personal contact entry
1799 * @param array $fields The fields that are updated
1800 * @throws \Exception
1802 private static function updateContact($id, $uid, $url, array $fields)
1804 DBA::update('contact', $fields, ['id' => $id]);
1806 // Search for duplicated contacts and get rid of them
1807 if (self::handleDuplicates(Strings::normaliseLink($url), $uid, $id) || ($uid != 0)) {
1811 // Update the corresponding gcontact entry
1812 GContact::updateFromPublicContactID($id);
1814 // Archive or unarchive the contact. We only need to do this for the public contact.
1815 // The archive/unarchive function will update the personal contacts by themselves.
1816 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1817 if (!empty($fields['success_update'])) {
1818 self::unmarkForArchival($contact);
1819 } elseif (!empty($fields['failure_update'])) {
1820 self::markForArchival($contact);
1823 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1825 // These contacts are sharing with us, we don't poll them.
1826 // This means that we don't set the update fields in "OnePoll.php".
1827 $condition['rel'] = self::SHARING;
1828 DBA::update('contact', $fields, $condition);
1830 unset($fields['last-update']);
1831 unset($fields['success_update']);
1832 unset($fields['failure_update']);
1834 if (empty($fields)) {
1838 // We are polling these contacts, so we mustn't set the update fields here.
1839 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1840 DBA::update('contact', $fields, $condition);
1844 * @brief Helper function for "updateFromProbe". Remove duplicated contacts
1846 * @param string $nurl Normalised contact url
1847 * @param integer $uid User id
1848 * @param integer $id Contact id of a duplicate
1850 * @throws \Exception
1852 private static function handleDuplicates($nurl, $uid, $id)
1854 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false];
1855 $count = DBA::count('contact', $condition);
1860 $first_contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1861 if (!DBA::isResult($first_contact)) {
1862 // Shouldn't happen - so we handle it
1866 $first = $first_contact['id'];
1867 Logger::info('Found duplicates', ['count' => $count, 'id' => $id, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1869 // Don't handle non public duplicates by now
1870 Logger::info('Not handling non public duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1874 // Find all duplicates
1875 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1876 $duplicates = DBA::select('contact', ['id'], $condition);
1877 while ($duplicate = DBA::fetch($duplicates)) {
1878 $dup_id = $duplicate['id'];
1879 Logger::info('Handling duplicate', ['search' => $dup_id, 'replace' => $first]);
1881 // Search and replace
1882 DBA::update('item', ['author-id' => $first], ['author-id' => $dup_id]);
1883 DBA::update('item', ['owner-id' => $first], ['owner-id' => $dup_id]);
1884 DBA::update('item', ['contact-id' => $first], ['contact-id' => $dup_id]);
1886 // Remove the duplicate
1887 DBA::delete('contact', ['id' => $dup_id]);
1889 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1894 * @param integer $id contact id
1895 * @param string $network Optional network we are probing for
1896 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1898 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1899 * @throws \ImagickException
1901 public static function updateFromProbe($id, $network = '', $force = false)
1904 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1905 This will reliably kill your communication with old Friendica contacts.
1908 // These fields aren't updated by this routine:
1909 // 'xmpp', 'sensitive'
1911 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'gender',
1912 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1913 'network', 'alias', 'baseurl', 'forum', 'prv', 'contact-type', 'pubkey'];
1914 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1915 if (!DBA::isResult($contact)) {
1919 $uid = $contact['uid'];
1920 unset($contact['uid']);
1922 $pubkey = $contact['pubkey'];
1923 unset($contact['pubkey']);
1925 $contact['photo'] = $contact['avatar'];
1926 unset($contact['avatar']);
1928 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1930 $updated = DateTimeFormat::utcNow();
1932 // We must not try to update relay contacts via probe. They are no real contacts.
1933 // We check after the probing to be able to correct falsely detected contact types.
1934 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1935 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1936 self::updateContact($id, $uid, $contact['url'], ['last-update' => $updated, 'success_update' => $updated]);
1937 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1941 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1942 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
1943 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
1944 if ($force && ($uid == 0)) {
1945 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1950 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1951 $ret['unsearchable'] = $ret['hide'];
1954 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1955 $ret['forum'] = false;
1956 $ret['prv'] = false;
1957 $ret['contact-type'] = $ret['account-type'];
1958 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1959 $apcontact = APContact::getByURL($ret['url'], false);
1960 if (isset($apcontact['manually-approve'])) {
1961 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1962 $ret['prv'] = (bool)!$ret['forum'];
1967 $new_pubkey = $ret['pubkey'];
1971 // make sure to not overwrite existing values with blank entries except some technical fields
1972 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1973 foreach ($ret as $key => $val) {
1974 if (!array_key_exists($key, $contact)) {
1976 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1977 $ret[$key] = $contact[$key];
1978 } elseif ($ret[$key] != $contact[$key]) {
1983 if ($ret['network'] != Protocol::FEED) {
1984 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
1988 if ($force && ($uid == 0)) {
1989 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
1994 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1995 $ret['updated'] = $updated;
1997 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1998 if (empty($pubkey) && !empty($new_pubkey)) {
1999 $ret['pubkey'] = $new_pubkey;
2002 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2003 $ret['uri-date'] = DateTimeFormat::utcNow();
2006 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2007 $ret['name-date'] = $updated;
2010 if ($force && ($uid == 0)) {
2011 $ret['last-update'] = $updated;
2012 $ret['success_update'] = $updated;
2015 unset($ret['photo']);
2017 self::updateContact($id, $uid, $ret['url'], $ret);
2022 public static function updateFromProbeByURL($url, $force = false)
2024 $id = self::getIdForURL($url);
2030 self::updateFromProbe($id, '', $force);
2036 * Detects if a given contact array belongs to a legacy DFRN connection
2038 * @param array $contact
2041 public static function isLegacyDFRNContact($contact)
2043 // Newer Friendica contacts are connected via AP, then these fields aren't set
2044 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2048 * Detects the communication protocol for a given contact url.
2049 * This is used to detect Friendica contacts that we can communicate via AP.
2051 * @param string $url contact url
2052 * @param string $network Network of that contact
2053 * @return string with protocol
2055 public static function getProtocol($url, $network)
2057 if ($network != Protocol::DFRN) {
2061 $apcontact = APContact::getByURL($url);
2062 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2063 return Protocol::ACTIVITYPUB;
2070 * Takes a $uid and a url/handle and adds a new contact
2071 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2072 * dfrn_request page.
2074 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2077 * $return['success'] boolean true if successful
2078 * $return['message'] error text if success is false.
2080 * @brief Takes a $uid and a url/handle and adds a new contact
2082 * @param string $url
2083 * @param bool $interactive
2084 * @param string $network
2086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2087 * @throws \ImagickException
2089 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
2091 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2095 // remove ajax junk, e.g. Twitter
2096 $url = str_replace('/#!/', '/', $url);
2098 if (!Network::isUrlAllowed($url)) {
2099 $result['message'] = L10n::t('Disallowed profile URL.');
2103 if (Network::isUrlBlocked($url)) {
2104 $result['message'] = L10n::t('Blocked domain');
2109 $result['message'] = L10n::t('Connect URL missing.');
2113 $arr = ['url' => $url, 'contact' => []];
2115 Hook::callAll('follow', $arr);
2118 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2122 if (!empty($arr['contact']['name'])) {
2123 $ret = $arr['contact'];
2125 $ret = Probe::uri($url, $network, $uid, false);
2128 if (($network != '') && ($ret['network'] != $network)) {
2129 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2133 // check if we already have a contact
2134 // the poll url is more reliable than the profile url, as we may have
2135 // indirect links or webfinger links
2137 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2138 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2139 if (!DBA::isResult($contact)) {
2140 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2141 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2144 $protocol = self::getProtocol($url, $ret['network']);
2146 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2148 if (strlen($a->getURLPath())) {
2149 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2151 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2154 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2158 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2159 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2160 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2164 // This extra param just confuses things, remove it
2165 if ($protocol === Protocol::DIASPORA) {
2166 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2169 // do we have enough information?
2170 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2171 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2172 if (empty($ret['poll'])) {
2173 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2175 if (empty($ret['name'])) {
2176 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2178 if (empty($ret['url'])) {
2179 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2181 if (strpos($url, '@') !== false) {
2182 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2183 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2188 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2189 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2190 $ret['notify'] = '';
2193 if (!$ret['notify']) {
2194 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2197 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2199 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2201 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2203 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2205 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2209 if (DBA::isResult($contact)) {
2211 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2213 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2214 DBA::update('contact', $fields, ['id' => $contact['id']]);
2216 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2218 // create contact record
2219 DBA::insert('contact', [
2221 'created' => DateTimeFormat::utcNow(),
2222 'url' => $ret['url'],
2223 'nurl' => Strings::normaliseLink($ret['url']),
2224 'addr' => $ret['addr'],
2225 'alias' => $ret['alias'],
2226 'batch' => $ret['batch'],
2227 'notify' => $ret['notify'],
2228 'poll' => $ret['poll'],
2229 'poco' => $ret['poco'],
2230 'name' => $ret['name'],
2231 'nick' => $ret['nick'],
2232 'network' => $ret['network'],
2233 'baseurl' => $ret['baseurl'],
2234 'protocol' => $protocol,
2235 'pubkey' => $ret['pubkey'],
2236 'rel' => $new_relation,
2237 'priority'=> $ret['priority'],
2238 'writable'=> $writeable,
2239 'hidden' => $hidden,
2242 'pending' => $pending,
2247 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2248 if (!DBA::isResult($contact)) {
2249 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2253 $contact_id = $contact['id'];
2254 $result['cid'] = $contact_id;
2256 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2258 // Update the avatar
2259 self::updateAvatar($ret['photo'], $uid, $contact_id);
2261 // pull feed and consume it, which should subscribe to the hub.
2263 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2265 $owner = User::getOwnerDataById($uid);
2267 if (DBA::isResult($owner)) {
2268 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2269 // create a follow slap
2271 $item['verb'] = ACTIVITY_FOLLOW;
2272 $item['follow'] = $contact["url"];
2274 $item['title'] = '';
2277 $item['attach'] = '';
2279 $slap = OStatus::salmon($item, $owner);
2281 if (!empty($contact['notify'])) {
2282 Salmon::slapper($owner, $contact['notify'], $slap);
2284 } elseif ($protocol == Protocol::DIASPORA) {
2285 $ret = Diaspora::sendShare($a->user, $contact);
2286 Logger::log('share returns: ' . $ret);
2287 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2288 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2289 if (empty($activity_id)) {
2290 // This really should never happen
2294 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2295 Logger::log('Follow returns: ' . $ret);
2299 $result['success'] = true;
2304 * @brief Updated contact's SSL policy
2306 * @param array $contact Contact array
2307 * @param string $new_policy New policy, valid: self,full
2309 * @return array Contact array with updated values
2310 * @throws \Exception
2312 public static function updateSslPolicy(array $contact, $new_policy)
2314 $ssl_changed = false;
2315 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2316 $ssl_changed = true;
2317 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2318 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2319 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2320 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2321 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2322 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2325 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2326 $ssl_changed = true;
2327 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2328 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2329 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2330 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2331 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2332 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2336 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2337 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2338 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2339 DBA::update('contact', $fields, ['id' => $contact['id']]);
2346 * @param array $importer Owner (local user) data
2347 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2348 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2349 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2350 * @param string $note Introduction additional message
2351 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2352 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2353 * @throws \ImagickException
2355 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2357 // Should always be set
2358 if (empty($datarray['author-id'])) {
2362 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2363 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2364 if (!DBA::isResult($pub_contact)) {
2365 // Should never happen
2369 // Contact is blocked at node-level
2370 if (self::isBlocked($datarray['author-id'])) {
2374 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2375 $name = $pub_contact['name'];
2376 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2377 $nick = $pub_contact['nick'];
2378 $network = $pub_contact['network'];
2380 if (!empty($contact)) {
2381 // Contact is blocked at user-level
2382 if (!empty($contact['id']) && !empty($importer['id']) &&
2383 self::isBlockedByUser($contact['id'], $importer['id'])) {
2387 // Make sure that the existing contact isn't archived
2388 self::unmarkForArchival($contact);
2390 if (($contact['rel'] == self::SHARING)
2391 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2392 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2393 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2398 // send email notification to owner?
2399 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2400 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2404 // create contact record
2405 DBA::insert('contact', [
2406 'uid' => $importer['uid'],
2407 'created' => DateTimeFormat::utcNow(),
2409 'nurl' => Strings::normaliseLink($url),
2413 'network' => $network,
2414 'rel' => self::FOLLOWER,
2422 'id' => DBA::lastInsertId(),
2423 'network' => $network,
2429 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2431 /// @TODO Encapsulate this into a function/method
2432 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2433 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2434 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2435 // create notification
2436 $hash = Strings::getRandomHex();
2438 if (is_array($contact_record)) {
2439 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2440 'blocked' => false, 'knowyou' => false, 'note' => $note,
2441 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2444 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2446 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2447 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2450 'type' => NOTIFY_INTRO,
2451 'notify_flags' => $user['notify-flags'],
2452 'language' => $user['language'],
2453 'to_name' => $user['username'],
2454 'to_email' => $user['email'],
2455 'uid' => $user['uid'],
2456 'link' => System::baseUrl() . '/notifications/intro',
2457 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2458 'source_link' => $contact_record['url'],
2459 'source_photo' => $contact_record['photo'],
2460 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2464 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2465 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2466 DBA::update('contact', ['pending' => false], $condition);
2475 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2477 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2478 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2480 Contact::remove($contact['id']);
2484 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2486 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2487 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2489 Contact::remove($contact['id']);
2494 * @brief Create a birthday event.
2496 * Update the year and the birthday.
2498 public static function updateBirthdays()
2502 AND `bd` > "0001-01-01"
2503 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2504 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2505 AND NOT `contact`.`pending`
2506 AND NOT `contact`.`hidden`
2507 AND NOT `contact`.`blocked`
2508 AND NOT `contact`.`archive`
2509 AND NOT `contact`.`deleted`',
2514 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2516 while ($contact = DBA::fetch($contacts)) {
2517 Logger::log('update_contact_birthday: ' . $contact['bd']);
2519 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2521 if (Event::createBirthday($contact, $nextbd)) {
2525 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2526 ['id' => $contact['id']]
2533 * Remove the unavailable contact ids from the provided list
2535 * @param array $contact_ids Contact id list
2536 * @throws \Exception
2538 public static function pruneUnavailable(array &$contact_ids)
2540 if (empty($contact_ids)) {
2544 $str = DBA::escape(implode(',', $contact_ids));
2546 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2549 while($contact = DBA::fetch($stmt)) {
2550 $return[] = $contact['id'];
2555 $contact_ids = $return;
2559 * @brief Returns a magic link to authenticate remote visitors
2561 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2563 * @param string $contact_url The address of the target contact profile
2564 * @param string $url An url that we will be redirected to after the authentication
2566 * @return string with "redir" link
2567 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2568 * @throws \ImagickException
2570 public static function magicLink($contact_url, $url = '')
2572 if (!local_user() && !remote_user()) {
2573 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2576 $data = self::getProbeDataFromDatabase($contact_url);
2578 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2581 // Prevents endless loop in case only a non-public contact exists for the contact URL
2582 unset($data['uid']);
2584 return self::magicLinkByContact($data, $contact_url);
2588 * @brief Returns a magic link to authenticate remote visitors
2590 * @param integer $cid The contact id of the target contact profile
2591 * @param string $url An url that we will be redirected to after the authentication
2593 * @return string with "redir" link
2594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2595 * @throws \ImagickException
2597 public static function magicLinkbyId($cid, $url = '')
2599 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2601 return self::magicLinkByContact($contact, $url);
2605 * @brief Returns a magic link to authenticate remote visitors
2607 * @param array $contact The contact array with "uid", "network" and "url"
2608 * @param string $url An url that we will be redirected to after the authentication
2610 * @return string with "redir" link
2611 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2612 * @throws \ImagickException
2614 public static function magicLinkByContact($contact, $url = '')
2616 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2617 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2620 // Only redirections to the same host do make sense
2621 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2625 if (!empty($contact['uid'])) {
2626 return self::magicLink($contact['url'], $url);
2629 if (empty($contact['id'])) {
2630 return $url ?: $contact['url'];
2633 $redirect = 'redir/' . $contact['id'];
2636 $redirect .= '?url=' . $url;
2643 * Remove a contact from all groups
2645 * @param integer $contact_id
2647 * @return boolean Success
2649 public static function removeFromGroups($contact_id)
2651 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2655 * Is the contact a forum?
2657 * @param integer $contactid ID of the contact
2659 * @return boolean "true" if it is a forum
2661 public static function isForum($contactid)
2663 $fields = ['forum', 'prv'];
2664 $condition = ['id' => $contactid];
2665 $contact = DBA::selectFirst('contact', $fields, $condition);
2666 if (!DBA::isResult($contact)) {
2671 return ($contact['forum'] || $contact['prv']);
2675 * Can the remote contact receive private messages?
2677 * @param array $contact
2680 public static function canReceivePrivateMessages(array $contact)
2682 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2683 $self = $contact['self'] ?? false;
2685 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;