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 Get the basepath for a given contact link
180 * @param string $url The contact link
182 * @return string basepath
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 public static function getBasepath($url)
188 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
189 if (!empty($contact['baseurl'])) {
190 return $contact['baseurl'];
193 self::updateFromProbeByURL($url, true);
195 $contact = DBA::selectFirst('contact', ['baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
196 if (!empty($contact['baseurl'])) {
197 return $contact['baseurl'];
204 * Returns the public contact id of the given user id
206 * @param integer $uid User ID
208 * @return integer|boolean Public contact id for given user id
211 public static function getPublicIdByUserId($uid)
213 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
214 if (!DBA::isResult($self)) {
217 return self::getIdForURL($self['url'], 0, true);
221 * @brief Returns the contact id for the user and the public contact id for a given contact id
223 * @param int $cid Either public contact id or user's contact id
224 * @param int $uid User ID
226 * @return array with public and user's contact id
227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
228 * @throws \ImagickException
230 public static function getPublicAndUserContacID($cid, $uid)
232 if (empty($uid) || empty($cid)) {
236 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
237 if (!DBA::isResult($contact)) {
241 // We quit when the user id don't match the user id of the provided contact
242 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
246 if ($contact['uid'] != 0) {
247 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
251 $ucid = $contact['id'];
253 $pcid = $contact['id'];
254 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
257 return ['public' => $pcid, 'user' => $ucid];
261 * Returns contact details for a given contact id in combination with a user id
263 * @param int $cid A contact ID
264 * @param int $uid The User ID
265 * @param array $fields The selected fields for the contact
267 * @return array The contact details
271 public static function getContactForUser($cid, $uid, array $fields = [])
273 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
275 if (!DBA::isResult($contact)) {
283 * @brief Block contact id for user id
285 * @param int $cid Either public contact id or user's contact id
286 * @param int $uid User ID
287 * @param boolean $blocked Is the contact blocked or unblocked?
290 public static function setBlockedForUser($cid, $uid, $blocked)
292 $cdata = self::getPublicAndUserContacID($cid, $uid);
297 if ($cdata['user'] != 0) {
298 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
301 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
304 // Blocked contact can't be in any group
305 self::removeFromGroups($cid);
310 * @brief Returns "block" state for contact id and user id
312 * @param int $cid Either public contact id or user's contact id
313 * @param int $uid User ID
315 * @return boolean is the contact id blocked for the given user?
318 public static function isBlockedByUser($cid, $uid)
320 $cdata = self::getPublicAndUserContacID($cid, $uid);
325 $public_blocked = false;
327 if (!empty($cdata['public'])) {
328 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
329 if (DBA::isResult($public_contact)) {
330 $public_blocked = $public_contact['blocked'];
334 $user_blocked = $public_blocked;
336 if (!empty($cdata['user'])) {
337 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
338 if (DBA::isResult($user_contact)) {
339 $user_blocked = $user_contact['blocked'];
343 if ($user_blocked != $public_blocked) {
344 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
347 return $user_blocked;
351 * @brief Ignore contact id for user id
353 * @param int $cid Either public contact id or user's contact id
354 * @param int $uid User ID
355 * @param boolean $ignored Is the contact ignored or unignored?
358 public static function setIgnoredForUser($cid, $uid, $ignored)
360 $cdata = self::getPublicAndUserContacID($cid, $uid);
365 if ($cdata['user'] != 0) {
366 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
369 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
373 * @brief Returns "ignore" state for contact id and user id
375 * @param int $cid Either public contact id or user's contact id
376 * @param int $uid User ID
378 * @return boolean is the contact id ignored for the given user?
381 public static function isIgnoredByUser($cid, $uid)
383 $cdata = self::getPublicAndUserContacID($cid, $uid);
388 $public_ignored = false;
390 if (!empty($cdata['public'])) {
391 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
392 if (DBA::isResult($public_contact)) {
393 $public_ignored = $public_contact['ignored'];
397 $user_ignored = $public_ignored;
399 if (!empty($cdata['user'])) {
400 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
401 if (DBA::isResult($user_contact)) {
402 $user_ignored = $user_contact['readonly'];
406 if ($user_ignored != $public_ignored) {
407 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
410 return $user_ignored;
414 * @brief Set "collapsed" for contact id and user id
416 * @param int $cid Either public contact id or user's contact id
417 * @param int $uid User ID
418 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
421 public static function setCollapsedForUser($cid, $uid, $collapsed)
423 $cdata = self::getPublicAndUserContacID($cid, $uid);
428 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
432 * @brief Returns "collapsed" state for contact id and user id
434 * @param int $cid Either public contact id or user's contact id
435 * @param int $uid User ID
437 * @return boolean is the contact id blocked for the given user?
438 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
439 * @throws \ImagickException
441 public static function isCollapsedByUser($cid, $uid)
443 $cdata = self::getPublicAndUserContacID($cid, $uid);
450 if (!empty($cdata['public'])) {
451 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
452 if (DBA::isResult($public_contact)) {
453 $collapsed = $public_contact['collapsed'];
461 * @brief Returns a list of contacts belonging in a group
467 public static function getByGroupId($gid)
472 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
474 INNER JOIN `group_member`
475 ON `contact`.`id` = `group_member`.`contact-id`
477 AND `contact`.`uid` = ?
478 AND NOT `contact`.`self`
479 AND NOT `contact`.`deleted`
480 AND NOT `contact`.`blocked`
481 AND NOT `contact`.`pending`
482 ORDER BY `contact`.`name` ASC',
487 if (DBA::isResult($stmt)) {
488 $return = DBA::toArray($stmt);
496 * @brief Returns the count of OStatus contacts in a group
502 public static function getOStatusCountByGroupId($gid)
506 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
508 INNER JOIN `group_member`
509 ON `contact`.`id` = `group_member`.`contact-id`
511 AND `contact`.`uid` = ?
512 AND `contact`.`network` = ?
513 AND `contact`.`notify` != ""',
518 $return = $contacts['count'];
525 * Creates the self-contact for the provided user id
528 * @return bool Operation success
529 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
531 public static function createSelfFromUserId($uid)
533 // Only create the entry if it doesn't exist yet
534 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
538 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
539 if (!DBA::isResult($user)) {
543 $return = DBA::insert('contact', [
544 'uid' => $user['uid'],
545 'created' => DateTimeFormat::utcNow(),
547 'name' => $user['username'],
548 'nick' => $user['nickname'],
549 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
550 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
551 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
554 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
555 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
556 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
557 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
558 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
559 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
560 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
561 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
562 'name-date' => DateTimeFormat::utcNow(),
563 'uri-date' => DateTimeFormat::utcNow(),
564 'avatar-date' => DateTimeFormat::utcNow(),
572 * Updates the self-contact for the provided user id
575 * @param boolean $update_avatar Force the avatar update
576 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
578 public static function updateSelfFromUserID($uid, $update_avatar = false)
580 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
581 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
582 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
583 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
584 if (!DBA::isResult($self)) {
588 $fields = ['nickname', 'page-flags', 'account-type'];
589 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
590 if (!DBA::isResult($user)) {
594 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
595 'country-name', 'gender', 'pub_keywords', 'xmpp'];
596 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
597 if (!DBA::isResult($profile)) {
601 $file_suffix = 'jpg';
603 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
604 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
605 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
606 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
607 'xmpp' => $profile['xmpp']];
609 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
610 if (DBA::isResult($avatar)) {
611 if ($update_avatar) {
612 $fields['avatar-date'] = DateTimeFormat::utcNow();
615 // Creating the path to the avatar, beginning with the file suffix
616 $types = Image::supportedTypes();
617 if (isset($types[$avatar['type']])) {
618 $file_suffix = $types[$avatar['type']];
621 // We are adding a timestamp value so that other systems won't use cached content
622 $timestamp = strtotime($fields['avatar-date']);
624 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
625 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
627 $fields['photo'] = $prefix . '4' . $suffix;
628 $fields['thumb'] = $prefix . '5' . $suffix;
629 $fields['micro'] = $prefix . '6' . $suffix;
631 // We hadn't found a photo entry, so we use the default avatar
632 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
633 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
634 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
637 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
638 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
639 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
641 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
642 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
643 $fields['nurl'] = Strings::normaliseLink($fields['url']);
644 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
645 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
646 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
647 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
648 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
649 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
653 foreach ($fields as $field => $content) {
654 if ($self[$field] != $content) {
660 if ($fields['name'] != $self['name']) {
661 $fields['name-date'] = DateTimeFormat::utcNow();
663 $fields['updated'] = DateTimeFormat::utcNow();
664 DBA::update('contact', $fields, ['id' => $self['id']]);
666 // Update the public contact as well
667 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
669 // Update the profile
670 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
671 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
672 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
677 * @brief Marks a contact for removal
679 * @param int $id contact id
681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
683 public static function remove($id)
685 // We want just to make sure that we don't delete our "self" contact
686 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
687 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
691 // Archive the contact
692 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
694 // Delete it in the background
695 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
699 * @brief Sends an unfriend message. Does not remove the contact
701 * @param array $user User unfriending
702 * @param array $contact Contact unfriended
703 * @param boolean $dissolve Remove the contact on the remote side
705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706 * @throws \ImagickException
708 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
710 if (empty($contact['network'])) {
714 $protocol = $contact['network'];
715 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
716 $protocol = Protocol::ACTIVITYPUB;
719 if (($protocol == Protocol::DFRN) && $dissolve) {
720 DFRN::deliver($user, $contact, 'placeholder', true);
721 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
722 // create an unfollow slap
724 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
725 $item['follow'] = $contact["url"];
730 $item['attach'] = '';
731 $slap = OStatus::salmon($item, $user);
733 if (!empty($contact['notify'])) {
734 Salmon::slapper($user, $contact['notify'], $slap);
736 } elseif ($protocol == Protocol::DIASPORA) {
737 Diaspora::sendUnshare($user, $contact);
738 } elseif ($protocol == Protocol::ACTIVITYPUB) {
739 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
742 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
748 * @brief Marks a contact for archival after a communication issue delay
750 * Contact has refused to recognise us as a friend. We will start a countdown.
751 * If they still don't recognise us in 32 days, the relationship is over,
752 * and we won't waste any more time trying to communicate with them.
753 * This provides for the possibility that their database is temporarily messed
754 * up or some other transient event and that there's a possibility we could recover from it.
756 * @param array $contact contact to mark for archival
758 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
760 public static function markForArchival(array $contact)
762 if (!isset($contact['url']) && !empty($contact['id'])) {
763 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
764 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
765 if (!DBA::isResult($contact)) {
768 } elseif (!isset($contact['url'])) {
769 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
772 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
774 // Contact already archived or "self" contact? => nothing to do
775 if ($contact['archive'] || $contact['self']) {
779 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
780 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
781 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
784 * We really should send a notification to the owner after 2-3 weeks
785 * so they won't be surprised when the contact vanishes and can take
786 * remedial action if this was a serious mistake or glitch
789 /// @todo Check for contact vitality via probing
790 $archival_days = Config::get('system', 'archival_days', 32);
792 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
793 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
794 /* Relationship is really truly dead. archive them rather than
795 * delete, though if the owner tries to unarchive them we'll start
796 * the whole process over again.
798 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
799 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
800 GContact::updateFromPublicContactURL($contact['url']);
806 * @brief Cancels the archival countdown
808 * @see Contact::markForArchival()
810 * @param array $contact contact to be unmarked for archival
814 public static function unmarkForArchival(array $contact)
816 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
817 $exists = DBA::exists('contact', $condition);
819 // We don't need to update, we never marked this contact for archival
824 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
826 if (!isset($contact['url']) && !empty($contact['id'])) {
827 $fields = ['id', 'url', 'batch'];
828 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
829 if (!DBA::isResult($contact)) {
834 // It's a miracle. Our dead contact has inexplicably come back to life.
835 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
836 DBA::update('contact', $fields, ['id' => $contact['id']]);
837 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
838 GContact::updateFromPublicContactURL($contact['url']);
840 if (!empty($contact['batch'])) {
841 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
842 DBA::update('contact', $fields, $condition);
847 * @brief Get contact data for a given profile link
849 * The function looks at several places (contact table and gcontact table) for the contact
850 * It caches its result for the same script execution to prevent duplicate calls
852 * @param string $url The profile link
853 * @param int $uid User id
854 * @param array $default If not data was found take this data as default value
856 * @return array Contact data
857 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
859 public static function getDetailsByURL($url, $uid = -1, array $default = [])
871 if (isset($cache[$url][$uid])) {
872 return $cache[$url][$uid];
875 $ssl_url = str_replace('http://', 'https://', $url);
877 // Fetch contact data from the contact table for the given user
878 $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`,
879 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
880 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
881 $r = DBA::toArray($s);
883 // Fetch contact data from the contact table for the given user, checking with the alias
884 if (!DBA::isResult($r)) {
885 $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`,
886 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
887 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
888 $r = DBA::toArray($s);
891 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
892 if (!DBA::isResult($r)) {
893 $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`,
894 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
895 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
896 $r = DBA::toArray($s);
899 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
900 if (!DBA::isResult($r)) {
901 $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`,
902 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
903 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
904 $r = DBA::toArray($s);
907 // Fetch the data from the gcontact table
908 if (!DBA::isResult($r)) {
909 $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`,
910 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
911 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
912 $r = DBA::toArray($s);
915 if (DBA::isResult($r)) {
916 // If there is more than one entry we filter out the connector networks
918 foreach ($r as $id => $result) {
919 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
925 $profile = array_shift($r);
927 // "bd" always contains the upcoming birthday of a contact.
928 // "birthday" might contain the birthday including the year of birth.
929 if ($profile["birthday"] > DBA::NULL_DATE) {
930 $bd_timestamp = strtotime($profile["birthday"]);
931 $month = date("m", $bd_timestamp);
932 $day = date("d", $bd_timestamp);
934 $current_timestamp = time();
935 $current_year = date("Y", $current_timestamp);
936 $current_month = date("m", $current_timestamp);
937 $current_day = date("d", $current_timestamp);
939 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
940 $current = $current_year . "-" . $current_month . "-" . $current_day;
942 if ($profile["bd"] < $current) {
943 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
946 $profile["bd"] = DBA::NULL_DATE;
952 if (empty($profile["photo"]) && isset($default["photo"])) {
953 $profile["photo"] = $default["photo"];
956 if (empty($profile["name"]) && isset($default["name"])) {
957 $profile["name"] = $default["name"];
960 if (empty($profile["network"]) && isset($default["network"])) {
961 $profile["network"] = $default["network"];
964 if (empty($profile["thumb"]) && isset($profile["photo"])) {
965 $profile["thumb"] = $profile["photo"];
968 if (empty($profile["micro"]) && isset($profile["thumb"])) {
969 $profile["micro"] = $profile["thumb"];
972 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
973 && in_array($profile["network"], Protocol::FEDERATED)
975 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
978 // Show contact details of Diaspora contacts only if connected
979 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
980 $profile["location"] = "";
981 $profile["about"] = "";
982 $profile["gender"] = "";
983 $profile["birthday"] = DBA::NULL_DATE;
986 $cache[$url][$uid] = $profile;
992 * @brief Get contact data for a given address
994 * The function looks at several places (contact table and gcontact table) for the contact
996 * @param string $addr The profile link
997 * @param int $uid User id
999 * @return array Contact data
1000 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1001 * @throws \ImagickException
1003 public static function getDetailsByAddr($addr, $uid = -1)
1010 $uid = local_user();
1013 // Fetch contact data from the contact table for the given user
1014 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1015 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1016 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1020 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1021 if (!DBA::isResult($r)) {
1022 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1023 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1024 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1029 // Fetch the data from the gcontact table
1030 if (!DBA::isResult($r)) {
1031 $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`,
1032 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1033 FROM `gcontact` WHERE `addr` = '%s'",
1038 if (!DBA::isResult($r)) {
1039 $data = Probe::uri($addr);
1041 $profile = self::getDetailsByURL($data['url'], $uid);
1050 * @brief Returns the data array for the photo menu of a given contact
1052 * @param array $contact contact
1053 * @param int $uid optional, default 0
1055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1056 * @throws \ImagickException
1058 public static function photoMenu(array $contact, $uid = 0)
1063 $contact_drop_link = '';
1067 $uid = local_user();
1070 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1072 $profile_link = self::magicLink($contact['url']);
1073 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1078 // Look for our own contact if the uid doesn't match and isn't public
1079 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1080 if (DBA::isResult($contact_own)) {
1081 return self::photoMenu($contact_own, $uid);
1086 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1088 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1090 $profile_link = $contact['url'];
1093 if ($profile_link === 'mailbox') {
1098 $status_link = $profile_link . '?tab=status';
1099 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1100 $profile_link = $profile_link . '?tab=profile';
1103 if (self::canReceivePrivateMessages($contact)) {
1104 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1107 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1108 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1111 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1113 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1115 if (!$contact['self']) {
1116 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1121 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1123 if (empty($contact['uid'])) {
1124 $connlnk = 'follow/?url=' . $contact['url'];
1126 'profile' => [L10n::t('View Profile'), $profile_link, true],
1127 'network' => [L10n::t('Network Posts'), $posts_link, false],
1128 'edit' => [L10n::t('View Contact'), $contact_url, false],
1129 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1133 'status' => [L10n::t('View Status'), $status_link, true],
1134 'profile' => [L10n::t('View Profile'), $profile_link, true],
1135 'photos' => [L10n::t('View Photos'), $photos_link, true],
1136 'network' => [L10n::t('Network Posts'), $posts_link, false],
1137 'edit' => [L10n::t('View Contact'), $contact_url, false],
1138 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1139 'pm' => [L10n::t('Send PM'), $pm_url, false],
1140 'poke' => [L10n::t('Poke'), $poke_link, false],
1144 $args = ['contact' => $contact, 'menu' => &$menu];
1146 Hook::callAll('contact_photo_menu', $args);
1148 $menucondensed = [];
1150 foreach ($menu as $menuname => $menuitem) {
1151 if ($menuitem[1] != '') {
1152 $menucondensed[$menuname] = $menuitem;
1156 return $menucondensed;
1160 * @brief Returns ungrouped contact count or list for user
1162 * Returns either the total number of ungrouped contacts for the given user
1163 * id or a paginated list of ungrouped contacts.
1165 * @param int $uid uid
1167 * @throws \Exception
1169 public static function getUngroupedList($uid)
1179 SELECT DISTINCT(`contact-id`)
1181 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1182 WHERE `group`.`uid` = %d
1183 )", intval($uid), intval($uid));
1187 * Have a look at all contact tables for a given profile url.
1188 * This function works as a replacement for probing the contact.
1190 * @param string $url Contact URL
1191 * @param integer $cid Contact ID
1193 * @return array Contact array in the "probe" structure
1195 private static function getProbeDataFromDatabase($url, $cid = null)
1197 // The link could be provided as http although we stored it as https
1198 $ssl_url = str_replace('http://', 'https://', $url);
1200 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1201 'photo', 'keywords', 'location', 'about', 'network',
1202 'priority', 'batch', 'request', 'confirm', 'poco'];
1205 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1206 if (DBA::isResult($data)) {
1211 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1213 if (!DBA::isResult($data)) {
1214 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1215 $data = DBA::selectFirst('contact', $fields, $condition);
1218 if (DBA::isResult($data)) {
1219 // For security reasons we don't fetch key data from our users
1220 $data["pubkey"] = '';
1224 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1225 'photo', 'keywords', 'location', 'about', 'network'];
1226 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1228 if (!DBA::isResult($data)) {
1229 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1230 $data = DBA::selectFirst('contact', $fields, $condition);
1233 if (DBA::isResult($data)) {
1234 $data["pubkey"] = '';
1236 $data["priority"] = 0;
1237 $data["batch"] = '';
1238 $data["request"] = '';
1239 $data["confirm"] = '';
1244 $data = ActivityPub::probeProfile($url, false);
1245 if (!empty($data)) {
1249 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1250 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1251 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1253 if (!DBA::isResult($data)) {
1254 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1255 $data = DBA::selectFirst('contact', $fields, $condition);
1258 if (DBA::isResult($data)) {
1259 $data["pubkey"] = '';
1260 $data["keywords"] = '';
1261 $data["location"] = '';
1262 $data["about"] = '';
1271 * @brief Fetch the contact id for a given URL and user
1273 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1274 * `addr` or `alias`.
1276 * If there's no record and we aren't looking for a public contact, we quit.
1277 * If there's one, we check that it isn't time to update the picture else we
1278 * directly return the found contact id.
1280 * Second, we probe the provided $url whether it's http://server.tld/profile or
1281 * nick@server.tld. We quit if we can't get any info back.
1283 * Third, we create the contact record if it doesn't exist
1285 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1286 * if there's any updates
1288 * @param string $url Contact URL
1289 * @param integer $uid The user id for the contact (0 = public contact)
1290 * @param boolean $no_update Don't update the contact
1291 * @param array $default Default value for creating the contact when every else fails
1292 * @param boolean $in_loop Internally used variable to prevent an endless loop
1294 * @return integer Contact ID
1295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1296 * @throws \ImagickException
1298 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1300 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1308 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1309 // We first try the nurl (http://server.tld/nick), most common case
1310 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1312 // Then the addr (nick@server.tld)
1313 if (!DBA::isResult($contact)) {
1314 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1317 // Then the alias (which could be anything)
1318 if (!DBA::isResult($contact)) {
1319 // The link could be provided as http although we stored it as https
1320 $ssl_url = str_replace('http://', 'https://', $url);
1321 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1322 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1325 if (DBA::isResult($contact)) {
1326 $contact_id = $contact["id"];
1328 // Update the contact every 7 days
1329 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1331 // We force the update if the avatar is empty
1332 if (empty($contact['avatar'])) {
1333 $update_contact = true;
1336 // Update the contact in the background if needed but it is called by the frontend
1337 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1338 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1341 if (!$update_contact || $no_update) {
1344 } elseif ($uid != 0) {
1345 // Non-existing user-specific contact, exiting
1349 if ($no_update && empty($default)) {
1350 // When we don't want to update, we look if we know this contact in any way
1351 $data = self::getProbeDataFromDatabase($url, $contact_id);
1352 $background_update = true;
1353 } elseif ($no_update && !empty($default)) {
1354 // If there are default values, take these
1356 $background_update = false;
1359 $background_update = false;
1363 $data = Probe::uri($url, "", $uid);
1365 // Ensure that there is a gserver entry
1366 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1367 PortableContact::checkServer($data['baseurl']);
1371 // Take the default values when probing failed
1372 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1373 $data = array_merge($data, $default);
1380 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1381 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1387 'created' => DateTimeFormat::utcNow(),
1388 'url' => $data['url'],
1389 'nurl' => Strings::normaliseLink($data['url']),
1390 'addr' => defaults($data, 'addr', ''),
1391 'alias' => defaults($data, 'alias', ''),
1392 'notify' => defaults($data, 'notify', ''),
1393 'poll' => defaults($data, 'poll', ''),
1394 'name' => defaults($data, 'name', ''),
1395 'nick' => defaults($data, 'nick', ''),
1396 'photo' => defaults($data, 'photo', ''),
1397 'keywords' => defaults($data, 'keywords', ''),
1398 'location' => defaults($data, 'location', ''),
1399 'about' => defaults($data, 'about', ''),
1400 'network' => $data['network'],
1401 'pubkey' => defaults($data, 'pubkey', ''),
1402 'rel' => self::SHARING,
1403 'priority' => defaults($data, 'priority', 0),
1404 'batch' => defaults($data, 'batch', ''),
1405 'request' => defaults($data, 'request', ''),
1406 'confirm' => defaults($data, 'confirm', ''),
1407 'poco' => defaults($data, 'poco', ''),
1408 'baseurl' => defaults($data, 'baseurl', ''),
1409 'name-date' => DateTimeFormat::utcNow(),
1410 'uri-date' => DateTimeFormat::utcNow(),
1411 'avatar-date' => DateTimeFormat::utcNow(),
1417 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1419 DBA::update('contact', $fields, $condition, true);
1421 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1422 $contacts = DBA::toArray($s);
1423 if (!DBA::isResult($contacts)) {
1427 $contact_id = $contacts[0]["id"];
1429 // Update in the background when we fetched the data solely from the database
1430 if ($background_update) {
1431 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1434 // Update the newly created contact from data in the gcontact table
1435 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1436 if (DBA::isResult($gcontact)) {
1437 // Only use the information when the probing hadn't fetched these values
1438 if (!empty($data['keywords'])) {
1439 unset($gcontact['keywords']);
1441 if (!empty($data['location'])) {
1442 unset($gcontact['location']);
1444 if (!empty($data['about'])) {
1445 unset($gcontact['about']);
1447 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1450 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1451 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1452 Strings::normaliseLink($data["url"]), 0, $contact_id];
1453 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1454 DBA::delete('contact', $condition);
1458 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1459 self::updateAvatar($data['photo'], $uid, $contact_id);
1462 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey', 'baseurl'];
1463 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1465 // This condition should always be true
1466 if (!DBA::isResult($contact)) {
1471 'addr' => $data['addr'] ?? '',
1472 'alias' => defaults($data, 'alias', ''),
1473 'url' => $data['url'],
1474 'nurl' => Strings::normaliseLink($data['url']),
1475 'name' => $data['name'],
1476 'nick' => $data['nick']
1479 if (!empty($data['baseurl'])) {
1480 $updated['baseurl'] = $data['baseurl'];
1482 if (!empty($data['keywords'])) {
1483 $updated['keywords'] = $data['keywords'];
1485 if (!empty($data['location'])) {
1486 $updated['location'] = $data['location'];
1489 // Update the technical stuff as well - if filled
1490 if (!empty($data['notify'])) {
1491 $updated['notify'] = $data['notify'];
1493 if (!empty($data['poll'])) {
1494 $updated['poll'] = $data['poll'];
1496 if (!empty($data['batch'])) {
1497 $updated['batch'] = $data['batch'];
1499 if (!empty($data['request'])) {
1500 $updated['request'] = $data['request'];
1502 if (!empty($data['confirm'])) {
1503 $updated['confirm'] = $data['confirm'];
1505 if (!empty($data['poco'])) {
1506 $updated['poco'] = $data['poco'];
1509 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1510 if (empty($contact['pubkey']) && !empty($data['pubkey'])) {
1511 $updated['pubkey'] = $data['pubkey'];
1514 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1515 $updated['uri-date'] = DateTimeFormat::utcNow();
1517 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1518 $updated['name-date'] = DateTimeFormat::utcNow();
1521 $updated['updated'] = DateTimeFormat::utcNow();
1523 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1525 if (!$background_update && ($uid == 0)) {
1526 // Update the gcontact entry
1527 GContact::updateFromPublicContactID($contact_id);
1534 * @brief Checks if the contact is blocked
1536 * @param int $cid contact id
1538 * @return boolean Is the contact blocked?
1539 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1541 public static function isBlocked($cid)
1547 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1548 if (!DBA::isResult($blocked)) {
1552 if (Network::isUrlBlocked($blocked['url'])) {
1556 return (bool) $blocked['blocked'];
1560 * @brief Checks if the contact is hidden
1562 * @param int $cid contact id
1564 * @return boolean Is the contact hidden?
1565 * @throws \Exception
1567 public static function isHidden($cid)
1573 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1574 if (!DBA::isResult($hidden)) {
1577 return (bool) $hidden['hidden'];
1581 * @brief Returns posts from a given contact url
1583 * @param string $contact_url Contact URL
1585 * @param bool $thread_mode
1586 * @param int $update
1587 * @return string posts in HTML
1588 * @throws \Exception
1590 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1592 $a = self::getApp();
1594 $cid = self::getIdForURL($contact_url);
1596 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1597 if (!DBA::isResult($contact)) {
1601 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1602 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1604 $sql = "`item`.`uid` = ?";
1607 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1610 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1611 $cid, GRAVITY_PARENT, local_user()];
1613 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1614 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1617 $pager = new Pager($a->query_string);
1619 $params = ['order' => ['received' => true],
1620 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1623 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1625 $items = Item::inArray($r);
1627 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1629 $r = Item::selectForUser(local_user(), [], $condition, $params);
1631 $items = Item::inArray($r);
1633 $o = conversation($a, $items, $pager, 'contact-posts', false);
1637 $o .= $pager->renderMinimal(count($items));
1644 * @brief Returns the account type name
1646 * The function can be called with either the user or the contact array
1648 * @param array $contact contact or user array
1651 public static function getAccountType(array $contact)
1653 // There are several fields that indicate that the contact or user is a forum
1654 // "page-flags" is a field in the user table,
1655 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1656 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1657 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1658 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1659 || (isset($contact['forum']) && intval($contact['forum']))
1660 || (isset($contact['prv']) && intval($contact['prv']))
1661 || (isset($contact['community']) && intval($contact['community']))
1663 $type = self::TYPE_COMMUNITY;
1665 $type = self::TYPE_PERSON;
1668 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1669 if (isset($contact["contact-type"])) {
1670 $type = $contact["contact-type"];
1673 if (isset($contact["account-type"])) {
1674 $type = $contact["account-type"];
1678 case self::TYPE_ORGANISATION:
1679 $account_type = L10n::t("Organisation");
1682 case self::TYPE_NEWS:
1683 $account_type = L10n::t('News');
1686 case self::TYPE_COMMUNITY:
1687 $account_type = L10n::t("Forum");
1695 return $account_type;
1699 * @brief Blocks a contact
1703 * @throws \Exception
1705 public static function block($cid, $reason = null)
1707 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1713 * @brief Unblocks a contact
1717 * @throws \Exception
1719 public static function unblock($cid)
1721 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1727 * @brief Updates the avatar links in a contact only if needed
1729 * @param string $avatar Link to avatar picture
1730 * @param int $uid User id of contact owner
1731 * @param int $cid Contact id
1732 * @param bool $force force picture update
1734 * @return array Returns array of the different avatar sizes
1735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1736 * @throws \ImagickException
1738 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1740 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1741 if (!DBA::isResult($contact)) {
1744 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1747 if (($contact["avatar"] != $avatar) || $force) {
1748 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1751 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1752 DBA::update('contact', $fields, ['id' => $cid]);
1754 // Update the public contact (contact id = 0)
1756 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1757 if (DBA::isResult($pcontact)) {
1758 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1770 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1772 * @param array $contact The personal contact entry
1773 * @param array $fields The fields that are updated
1774 * @throws \Exception
1776 private static function updateContact($id, $uid, $url, array $fields)
1778 DBA::update('contact', $fields, ['id' => $id]);
1784 // Update the corresponding gcontact entry
1785 GContact::updateFromPublicContactID($id);
1787 // Archive or unarchive the contact. We only need to do this for the public contact.
1788 // The archive/unarchive function will update the personal contacts by themselves.
1789 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1790 if (!empty($fields['success_update'])) {
1791 self::unmarkForArchival($contact);
1792 } elseif (!empty($fields['failure_update'])) {
1793 self::markForArchival($contact);
1796 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1798 // These contacts are sharing with us, we don't poll them.
1799 // This means that we don't set the update fields in "OnePoll.php".
1800 $condition['rel'] = self::SHARING;
1801 DBA::update('contact', $fields, $condition);
1803 unset($fields['last-update']);
1804 unset($fields['success_update']);
1805 unset($fields['failure_update']);
1807 if (empty($fields)) {
1811 // We are polling these contacts, so we mustn't set the update fields here.
1812 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1813 DBA::update('contact', $fields, $condition);
1817 * @param integer $id contact id
1818 * @param string $network Optional network we are probing for
1819 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1821 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1822 * @throws \ImagickException
1824 public static function updateFromProbe($id, $network = '', $force = false)
1827 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1828 This will reliably kill your communication with old Friendica contacts.
1831 // These fields aren't updated by this routine:
1832 // 'location', 'about', 'keywords', 'gender', 'xmpp', 'unsearchable', 'sensitive'];
1834 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1835 'poll', 'request', 'confirm', 'poco', 'network', 'alias', 'baseurl',
1836 'forum', 'prv', 'contact-type'];
1837 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1838 if (!DBA::isResult($contact)) {
1842 $uid = $contact['uid'];
1843 unset($contact['uid']);
1845 $contact['photo'] = $contact['avatar'];
1846 unset($contact['avatar']);
1848 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1850 $updated = DateTimeFormat::utcNow();
1852 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1853 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
1854 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
1855 if ($force && ($uid == 0)) {
1856 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1861 if (isset($ret['account-type'])) {
1862 $ret['forum'] = false;
1863 $ret['prv'] = false;
1864 $ret['contact-type'] = $ret['account-type'];
1865 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1866 $apcontact = APContact::getByURL($ret['url'], false);
1867 if (isset($apcontact['manually-approve'])) {
1868 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1869 $ret['prv'] = (bool)!$ret['forum'];
1876 // make sure to not overwrite existing values with blank entries
1877 foreach ($ret as $key => $val) {
1878 if (!array_key_exists($key, $contact)) {
1880 } elseif (($contact[$key] != '') && ($val == '') && !is_bool($ret[$key])) {
1881 $ret[$key] = $contact[$key];
1882 } elseif ($ret[$key] != $contact[$key]) {
1887 if ($ret['network'] != Protocol::FEED) {
1888 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
1892 if ($force && ($uid == 0)) {
1893 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
1898 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1899 $ret['updated'] = $updated;
1901 if ($force && ($uid == 0)) {
1902 $ret['last-update'] = $updated;
1903 $ret['success_update'] = $updated;
1906 unset($ret['photo']);
1908 self::updateContact($id, $uid, $ret['url'], $ret);
1913 public static function updateFromProbeByURL($url, $force = false)
1915 $id = self::getIdForURL($url);
1921 self::updateFromProbe($id, '', $force);
1925 * Detects if a given contact array belongs to a legacy DFRN connection
1927 * @param array $contact
1930 public static function isLegacyDFRNContact($contact)
1932 // Newer Friendica contacts are connected via AP, then these fields aren't set
1933 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1937 * Detects the communication protocol for a given contact url.
1938 * This is used to detect Friendica contacts that we can communicate via AP.
1940 * @param string $url contact url
1941 * @param string $network Network of that contact
1942 * @return string with protocol
1944 public static function getProtocol($url, $network)
1946 if ($network != Protocol::DFRN) {
1950 $apcontact = APContact::getByURL($url);
1951 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1952 return Protocol::ACTIVITYPUB;
1959 * Takes a $uid and a url/handle and adds a new contact
1960 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1961 * dfrn_request page.
1963 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1966 * $return['success'] boolean true if successful
1967 * $return['message'] error text if success is false.
1969 * @brief Takes a $uid and a url/handle and adds a new contact
1971 * @param string $url
1972 * @param bool $interactive
1973 * @param string $network
1975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1976 * @throws \ImagickException
1978 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1980 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1984 // remove ajax junk, e.g. Twitter
1985 $url = str_replace('/#!/', '/', $url);
1987 if (!Network::isUrlAllowed($url)) {
1988 $result['message'] = L10n::t('Disallowed profile URL.');
1992 if (Network::isUrlBlocked($url)) {
1993 $result['message'] = L10n::t('Blocked domain');
1998 $result['message'] = L10n::t('Connect URL missing.');
2002 $arr = ['url' => $url, 'contact' => []];
2004 Hook::callAll('follow', $arr);
2007 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2011 if (!empty($arr['contact']['name'])) {
2012 $ret = $arr['contact'];
2014 $ret = Probe::uri($url, $network, $uid, false);
2017 if (($network != '') && ($ret['network'] != $network)) {
2018 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2022 // check if we already have a contact
2023 // the poll url is more reliable than the profile url, as we may have
2024 // indirect links or webfinger links
2026 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2027 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2028 if (!DBA::isResult($contact)) {
2029 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
2030 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2033 $protocol = self::getProtocol($url, $ret['network']);
2035 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2037 if (strlen($a->getURLPath())) {
2038 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2040 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2043 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2047 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2048 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2049 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2053 // This extra param just confuses things, remove it
2054 if ($protocol === Protocol::DIASPORA) {
2055 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2058 // do we have enough information?
2059 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2060 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2061 if (empty($ret['poll'])) {
2062 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2064 if (empty($ret['name'])) {
2065 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2067 if (empty($ret['url'])) {
2068 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2070 if (strpos($url, '@') !== false) {
2071 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2072 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2077 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2078 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2079 $ret['notify'] = '';
2082 if (!$ret['notify']) {
2083 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2086 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2088 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2090 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2092 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2094 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2098 if (DBA::isResult($contact)) {
2100 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2102 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2103 DBA::update('contact', $fields, ['id' => $contact['id']]);
2105 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2107 // create contact record
2108 DBA::insert('contact', [
2110 'created' => DateTimeFormat::utcNow(),
2111 'url' => $ret['url'],
2112 'nurl' => Strings::normaliseLink($ret['url']),
2113 'addr' => $ret['addr'],
2114 'alias' => $ret['alias'],
2115 'batch' => $ret['batch'],
2116 'notify' => $ret['notify'],
2117 'poll' => $ret['poll'],
2118 'poco' => $ret['poco'],
2119 'name' => $ret['name'],
2120 'nick' => $ret['nick'],
2121 'network' => $ret['network'],
2122 'baseurl' => $ret['baseurl'],
2123 'protocol' => $protocol,
2124 'pubkey' => $ret['pubkey'],
2125 'rel' => $new_relation,
2126 'priority'=> $ret['priority'],
2127 'writable'=> $writeable,
2128 'hidden' => $hidden,
2131 'pending' => $pending,
2136 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2137 if (!DBA::isResult($contact)) {
2138 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2142 $contact_id = $contact['id'];
2143 $result['cid'] = $contact_id;
2145 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2147 // Update the avatar
2148 self::updateAvatar($ret['photo'], $uid, $contact_id);
2150 // pull feed and consume it, which should subscribe to the hub.
2152 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2154 $owner = User::getOwnerDataById($uid);
2156 if (DBA::isResult($owner)) {
2157 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2158 // create a follow slap
2160 $item['verb'] = ACTIVITY_FOLLOW;
2161 $item['follow'] = $contact["url"];
2163 $item['title'] = '';
2166 $item['attach'] = '';
2168 $slap = OStatus::salmon($item, $owner);
2170 if (!empty($contact['notify'])) {
2171 Salmon::slapper($owner, $contact['notify'], $slap);
2173 } elseif ($protocol == Protocol::DIASPORA) {
2174 $ret = Diaspora::sendShare($a->user, $contact);
2175 Logger::log('share returns: ' . $ret);
2176 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2177 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2178 if (empty($activity_id)) {
2179 // This really should never happen
2183 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2184 Logger::log('Follow returns: ' . $ret);
2188 $result['success'] = true;
2193 * @brief Updated contact's SSL policy
2195 * @param array $contact Contact array
2196 * @param string $new_policy New policy, valid: self,full
2198 * @return array Contact array with updated values
2199 * @throws \Exception
2201 public static function updateSslPolicy(array $contact, $new_policy)
2203 $ssl_changed = false;
2204 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2205 $ssl_changed = true;
2206 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2207 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2208 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2209 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2210 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2211 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2214 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2215 $ssl_changed = true;
2216 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2217 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2218 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2219 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2220 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2221 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2225 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2226 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2227 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2228 DBA::update('contact', $fields, ['id' => $contact['id']]);
2235 * @param array $importer Owner (local user) data
2236 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2237 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2238 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2239 * @param string $note Introduction additional message
2240 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2241 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2242 * @throws \ImagickException
2244 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2246 // Should always be set
2247 if (empty($datarray['author-id'])) {
2251 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2252 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2253 if (!DBA::isResult($pub_contact)) {
2254 // Should never happen
2258 // Contact is blocked at node-level
2259 if (self::isBlocked($datarray['author-id'])) {
2263 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2264 $name = $pub_contact['name'];
2265 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2266 $nick = $pub_contact['nick'];
2267 $network = $pub_contact['network'];
2269 if (!empty($contact)) {
2270 // Contact is blocked at user-level
2271 if (!empty($contact['id']) && !empty($importer['id']) &&
2272 self::isBlockedByUser($contact['id'], $importer['id'])) {
2276 // Make sure that the existing contact isn't archived
2277 self::unmarkForArchival($contact);
2279 if (($contact['rel'] == self::SHARING)
2280 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2281 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2282 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2287 // send email notification to owner?
2288 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2289 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2293 // create contact record
2294 DBA::insert('contact', [
2295 'uid' => $importer['uid'],
2296 'created' => DateTimeFormat::utcNow(),
2298 'nurl' => Strings::normaliseLink($url),
2302 'network' => $network,
2303 'rel' => self::FOLLOWER,
2311 'id' => DBA::lastInsertId(),
2312 'network' => $network,
2318 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2320 /// @TODO Encapsulate this into a function/method
2321 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2322 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2323 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2324 // create notification
2325 $hash = Strings::getRandomHex();
2327 if (is_array($contact_record)) {
2328 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2329 'blocked' => false, 'knowyou' => false, 'note' => $note,
2330 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2333 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2335 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2336 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2339 'type' => NOTIFY_INTRO,
2340 'notify_flags' => $user['notify-flags'],
2341 'language' => $user['language'],
2342 'to_name' => $user['username'],
2343 'to_email' => $user['email'],
2344 'uid' => $user['uid'],
2345 'link' => System::baseUrl() . '/notifications/intro',
2346 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2347 'source_link' => $contact_record['url'],
2348 'source_photo' => $contact_record['photo'],
2349 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2353 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2354 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2355 DBA::update('contact', ['pending' => false], $condition);
2364 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2366 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2367 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2369 Contact::remove($contact['id']);
2373 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2375 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2376 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2378 Contact::remove($contact['id']);
2383 * @brief Create a birthday event.
2385 * Update the year and the birthday.
2387 public static function updateBirthdays()
2391 AND `bd` > "0001-01-01"
2392 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2393 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2394 AND NOT `contact`.`pending`
2395 AND NOT `contact`.`hidden`
2396 AND NOT `contact`.`blocked`
2397 AND NOT `contact`.`archive`
2398 AND NOT `contact`.`deleted`',
2403 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2405 while ($contact = DBA::fetch($contacts)) {
2406 Logger::log('update_contact_birthday: ' . $contact['bd']);
2408 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2410 if (Event::createBirthday($contact, $nextbd)) {
2414 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2415 ['id' => $contact['id']]
2422 * Remove the unavailable contact ids from the provided list
2424 * @param array $contact_ids Contact id list
2425 * @throws \Exception
2427 public static function pruneUnavailable(array &$contact_ids)
2429 if (empty($contact_ids)) {
2433 $str = DBA::escape(implode(',', $contact_ids));
2435 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2438 while($contact = DBA::fetch($stmt)) {
2439 $return[] = $contact['id'];
2444 $contact_ids = $return;
2448 * @brief Returns a magic link to authenticate remote visitors
2450 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2452 * @param string $contact_url The address of the target contact profile
2453 * @param string $url An url that we will be redirected to after the authentication
2455 * @return string with "redir" link
2456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2457 * @throws \ImagickException
2459 public static function magicLink($contact_url, $url = '')
2461 if (!local_user() && !remote_user()) {
2462 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2465 $data = self::getProbeDataFromDatabase($contact_url);
2467 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2470 // Prevents endless loop in case only a non-public contact exists for the contact URL
2471 unset($data['uid']);
2473 return self::magicLinkByContact($data, $contact_url);
2477 * @brief Returns a magic link to authenticate remote visitors
2479 * @param integer $cid The contact id of the target contact profile
2480 * @param string $url An url that we will be redirected to after the authentication
2482 * @return string with "redir" link
2483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2484 * @throws \ImagickException
2486 public static function magicLinkbyId($cid, $url = '')
2488 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2490 return self::magicLinkByContact($contact, $url);
2494 * @brief Returns a magic link to authenticate remote visitors
2496 * @param array $contact The contact array with "uid", "network" and "url"
2497 * @param string $url An url that we will be redirected to after the authentication
2499 * @return string with "redir" link
2500 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2501 * @throws \ImagickException
2503 public static function magicLinkByContact($contact, $url = '')
2505 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2506 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2509 // Only redirections to the same host do make sense
2510 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2514 if (!empty($contact['uid'])) {
2515 return self::magicLink($contact['url'], $url);
2518 if (empty($contact['id'])) {
2519 return $url ?: $contact['url'];
2522 $redirect = 'redir/' . $contact['id'];
2525 $redirect .= '?url=' . $url;
2532 * Remove a contact from all groups
2534 * @param integer $contact_id
2536 * @return boolean Success
2538 public static function removeFromGroups($contact_id)
2540 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2544 * Is the contact a forum?
2546 * @param integer $contactid ID of the contact
2548 * @return boolean "true" if it is a forum
2550 public static function isForum($contactid)
2552 $fields = ['forum', 'prv'];
2553 $condition = ['id' => $contactid];
2554 $contact = DBA::selectFirst('contact', $fields, $condition);
2555 if (!DBA::isResult($contact)) {
2560 return ($contact['forum'] || $contact['prv']);
2564 * Can the remote contact receive private messages?
2566 * @param array $contact
2569 public static function canReceivePrivateMessages(array $contact)
2571 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2572 $self = $contact['self'] ?? false;
2574 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;