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
179 * @todo Add functionality to store this value in the contact table
181 * @param string $url The contact link
183 * @return string basepath
184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 * @throws \ImagickException
187 public static function getBasepath($url)
189 $data = Probe::uri($url);
190 if (!empty($data['baseurl'])) {
191 return $data['baseurl'];
194 // When we can't probe the server, we use some ugly function that does some pattern matching
195 return PortableContact::detectServer($url);
199 * Returns the public contact id of the given user id
201 * @param integer $uid User ID
203 * @return integer|boolean Public contact id for given user id
206 public static function getPublicIdByUserId($uid)
208 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
209 if (!DBA::isResult($self)) {
212 return self::getIdForURL($self['url'], 0, true);
216 * @brief Returns the contact id for the user and the public contact id for a given contact id
218 * @param int $cid Either public contact id or user's contact id
219 * @param int $uid User ID
221 * @return array with public and user's contact id
222 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
223 * @throws \ImagickException
225 public static function getPublicAndUserContacID($cid, $uid)
227 if (empty($uid) || empty($cid)) {
231 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
232 if (!DBA::isResult($contact)) {
236 // We quit when the user id don't match the user id of the provided contact
237 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
241 if ($contact['uid'] != 0) {
242 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
246 $ucid = $contact['id'];
248 $pcid = $contact['id'];
249 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
252 return ['public' => $pcid, 'user' => $ucid];
256 * Returns contact details for a given contact id in combination with a user id
258 * @param int $cid A contact ID
259 * @param int $uid The User ID
260 * @param array $fields The selected fields for the contact
262 * @return array The contact details
266 public static function getContactForUser($cid, $uid, array $fields = [])
268 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
270 if (!DBA::isResult($contact)) {
278 * @brief Block contact id for user id
280 * @param int $cid Either public contact id or user's contact id
281 * @param int $uid User ID
282 * @param boolean $blocked Is the contact blocked or unblocked?
285 public static function setBlockedForUser($cid, $uid, $blocked)
287 $cdata = self::getPublicAndUserContacID($cid, $uid);
292 if ($cdata['user'] != 0) {
293 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
296 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
299 // Blocked contact can't be in any group
300 self::removeFromGroups($cid);
305 * @brief Returns "block" state for contact id and user id
307 * @param int $cid Either public contact id or user's contact id
308 * @param int $uid User ID
310 * @return boolean is the contact id blocked for the given user?
313 public static function isBlockedByUser($cid, $uid)
315 $cdata = self::getPublicAndUserContacID($cid, $uid);
320 $public_blocked = false;
322 if (!empty($cdata['public'])) {
323 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
324 if (DBA::isResult($public_contact)) {
325 $public_blocked = $public_contact['blocked'];
329 $user_blocked = $public_blocked;
331 if (!empty($cdata['user'])) {
332 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
333 if (DBA::isResult($user_contact)) {
334 $user_blocked = $user_contact['blocked'];
338 if ($user_blocked != $public_blocked) {
339 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
342 return $user_blocked;
346 * @brief Ignore contact id for user id
348 * @param int $cid Either public contact id or user's contact id
349 * @param int $uid User ID
350 * @param boolean $ignored Is the contact ignored or unignored?
353 public static function setIgnoredForUser($cid, $uid, $ignored)
355 $cdata = self::getPublicAndUserContacID($cid, $uid);
360 if ($cdata['user'] != 0) {
361 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
364 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
368 * @brief Returns "ignore" state for contact id and user id
370 * @param int $cid Either public contact id or user's contact id
371 * @param int $uid User ID
373 * @return boolean is the contact id ignored for the given user?
376 public static function isIgnoredByUser($cid, $uid)
378 $cdata = self::getPublicAndUserContacID($cid, $uid);
383 $public_ignored = false;
385 if (!empty($cdata['public'])) {
386 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
387 if (DBA::isResult($public_contact)) {
388 $public_ignored = $public_contact['ignored'];
392 $user_ignored = $public_ignored;
394 if (!empty($cdata['user'])) {
395 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
396 if (DBA::isResult($user_contact)) {
397 $user_ignored = $user_contact['readonly'];
401 if ($user_ignored != $public_ignored) {
402 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
405 return $user_ignored;
409 * @brief Set "collapsed" for contact id and user id
411 * @param int $cid Either public contact id or user's contact id
412 * @param int $uid User ID
413 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
416 public static function setCollapsedForUser($cid, $uid, $collapsed)
418 $cdata = self::getPublicAndUserContacID($cid, $uid);
423 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
427 * @brief Returns "collapsed" state for contact id and user id
429 * @param int $cid Either public contact id or user's contact id
430 * @param int $uid User ID
432 * @return boolean is the contact id blocked for the given user?
433 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 * @throws \ImagickException
436 public static function isCollapsedByUser($cid, $uid)
438 $cdata = self::getPublicAndUserContacID($cid, $uid);
445 if (!empty($cdata['public'])) {
446 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
447 if (DBA::isResult($public_contact)) {
448 $collapsed = $public_contact['collapsed'];
456 * @brief Returns a list of contacts belonging in a group
462 public static function getByGroupId($gid)
467 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
469 INNER JOIN `group_member`
470 ON `contact`.`id` = `group_member`.`contact-id`
472 AND `contact`.`uid` = ?
473 AND NOT `contact`.`self`
474 AND NOT `contact`.`deleted`
475 AND NOT `contact`.`blocked`
476 AND NOT `contact`.`pending`
477 ORDER BY `contact`.`name` ASC',
482 if (DBA::isResult($stmt)) {
483 $return = DBA::toArray($stmt);
491 * @brief Returns the count of OStatus contacts in a group
497 public static function getOStatusCountByGroupId($gid)
501 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
503 INNER JOIN `group_member`
504 ON `contact`.`id` = `group_member`.`contact-id`
506 AND `contact`.`uid` = ?
507 AND `contact`.`network` = ?
508 AND `contact`.`notify` != ""',
513 $return = $contacts['count'];
520 * Creates the self-contact for the provided user id
523 * @return bool Operation success
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
526 public static function createSelfFromUserId($uid)
528 // Only create the entry if it doesn't exist yet
529 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
533 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
534 if (!DBA::isResult($user)) {
538 $return = DBA::insert('contact', [
539 'uid' => $user['uid'],
540 'created' => DateTimeFormat::utcNow(),
542 'name' => $user['username'],
543 'nick' => $user['nickname'],
544 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
545 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
546 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
549 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
550 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
551 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
552 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
553 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
554 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
555 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
556 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
557 'name-date' => DateTimeFormat::utcNow(),
558 'uri-date' => DateTimeFormat::utcNow(),
559 'avatar-date' => DateTimeFormat::utcNow(),
567 * Updates the self-contact for the provided user id
570 * @param boolean $update_avatar Force the avatar update
571 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
573 public static function updateSelfFromUserID($uid, $update_avatar = false)
575 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
576 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
577 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
578 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
579 if (!DBA::isResult($self)) {
583 $fields = ['nickname', 'page-flags', 'account-type'];
584 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
585 if (!DBA::isResult($user)) {
589 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
590 'country-name', 'gender', 'pub_keywords', 'xmpp'];
591 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
592 if (!DBA::isResult($profile)) {
596 $file_suffix = 'jpg';
598 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
599 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
600 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
601 'gender' => $profile['gender'], 'contact-type' => $user['account-type'],
602 'xmpp' => $profile['xmpp']];
604 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
605 if (DBA::isResult($avatar)) {
606 if ($update_avatar) {
607 $fields['avatar-date'] = DateTimeFormat::utcNow();
610 // Creating the path to the avatar, beginning with the file suffix
611 $types = Image::supportedTypes();
612 if (isset($types[$avatar['type']])) {
613 $file_suffix = $types[$avatar['type']];
616 // We are adding a timestamp value so that other systems won't use cached content
617 $timestamp = strtotime($fields['avatar-date']);
619 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
620 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
622 $fields['photo'] = $prefix . '4' . $suffix;
623 $fields['thumb'] = $prefix . '5' . $suffix;
624 $fields['micro'] = $prefix . '6' . $suffix;
626 // We hadn't found a photo entry, so we use the default avatar
627 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
628 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
629 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
632 $fields['avatar'] = System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
633 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
634 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
636 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
637 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
638 $fields['nurl'] = Strings::normaliseLink($fields['url']);
639 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
640 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
641 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
642 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
643 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
644 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
648 foreach ($fields as $field => $content) {
649 if ($self[$field] != $content) {
655 if ($fields['name'] != $self['name']) {
656 $fields['name-date'] = DateTimeFormat::utcNow();
658 $fields['updated'] = DateTimeFormat::utcNow();
659 DBA::update('contact', $fields, ['id' => $self['id']]);
661 // Update the public contact as well
662 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
664 // Update the profile
665 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
666 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
667 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
672 * @brief Marks a contact for removal
674 * @param int $id contact id
676 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
678 public static function remove($id)
680 // We want just to make sure that we don't delete our "self" contact
681 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
682 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
686 // Archive the contact
687 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
689 // Delete it in the background
690 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
694 * @brief Sends an unfriend message. Does not remove the contact
696 * @param array $user User unfriending
697 * @param array $contact Contact unfriended
698 * @param boolean $dissolve Remove the contact on the remote side
700 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
701 * @throws \ImagickException
703 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
705 if (empty($contact['network'])) {
709 $protocol = $contact['network'];
710 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
711 $protocol = Protocol::ACTIVITYPUB;
714 if (($protocol == Protocol::DFRN) && $dissolve) {
715 DFRN::deliver($user, $contact, 'placeholder', true);
716 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
717 // create an unfollow slap
719 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
720 $item['follow'] = $contact["url"];
725 $item['attach'] = '';
726 $slap = OStatus::salmon($item, $user);
728 if (!empty($contact['notify'])) {
729 Salmon::slapper($user, $contact['notify'], $slap);
731 } elseif ($protocol == Protocol::DIASPORA) {
732 Diaspora::sendUnshare($user, $contact);
733 } elseif ($protocol == Protocol::ACTIVITYPUB) {
734 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
737 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
743 * @brief Marks a contact for archival after a communication issue delay
745 * Contact has refused to recognise us as a friend. We will start a countdown.
746 * If they still don't recognise us in 32 days, the relationship is over,
747 * and we won't waste any more time trying to communicate with them.
748 * This provides for the possibility that their database is temporarily messed
749 * up or some other transient event and that there's a possibility we could recover from it.
751 * @param array $contact contact to mark for archival
753 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
755 public static function markForArchival(array $contact)
757 if (!isset($contact['url']) && !empty($contact['id'])) {
758 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
759 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
760 if (!DBA::isResult($contact)) {
763 } elseif (!isset($contact['url'])) {
764 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
767 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
769 // Contact already archived or "self" contact? => nothing to do
770 if ($contact['archive'] || $contact['self']) {
774 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
775 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
776 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
779 * We really should send a notification to the owner after 2-3 weeks
780 * so they won't be surprised when the contact vanishes and can take
781 * remedial action if this was a serious mistake or glitch
784 /// @todo Check for contact vitality via probing
785 $archival_days = Config::get('system', 'archival_days', 32);
787 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
788 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
789 /* Relationship is really truly dead. archive them rather than
790 * delete, though if the owner tries to unarchive them we'll start
791 * the whole process over again.
793 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
794 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
795 GContact::updateFromPublicContactURL($contact['url']);
801 * @brief Cancels the archival countdown
803 * @see Contact::markForArchival()
805 * @param array $contact contact to be unmarked for archival
809 public static function unmarkForArchival(array $contact)
811 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
812 $exists = DBA::exists('contact', $condition);
814 // We don't need to update, we never marked this contact for archival
819 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
821 if (!isset($contact['url']) && !empty($contact['id'])) {
822 $fields = ['id', 'url', 'batch'];
823 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
824 if (!DBA::isResult($contact)) {
829 // It's a miracle. Our dead contact has inexplicably come back to life.
830 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
831 DBA::update('contact', $fields, ['id' => $contact['id']]);
832 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
833 GContact::updateFromPublicContactURL($contact['url']);
835 if (!empty($contact['batch'])) {
836 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
837 DBA::update('contact', $fields, $condition);
842 * @brief Get contact data for a given profile link
844 * The function looks at several places (contact table and gcontact table) for the contact
845 * It caches its result for the same script execution to prevent duplicate calls
847 * @param string $url The profile link
848 * @param int $uid User id
849 * @param array $default If not data was found take this data as default value
851 * @return array Contact data
852 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
854 public static function getDetailsByURL($url, $uid = -1, array $default = [])
866 if (isset($cache[$url][$uid])) {
867 return $cache[$url][$uid];
870 $ssl_url = str_replace('http://', 'https://', $url);
872 // Fetch contact data from the contact table for the given user
873 $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`,
874 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
875 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
876 $r = DBA::toArray($s);
878 // Fetch contact data from the contact table for the given user, checking with the alias
879 if (!DBA::isResult($r)) {
880 $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`,
881 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
882 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
883 $r = DBA::toArray($s);
886 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
887 if (!DBA::isResult($r)) {
888 $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`,
889 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
890 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
891 $r = DBA::toArray($s);
894 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
895 if (!DBA::isResult($r)) {
896 $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`,
897 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
898 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
899 $r = DBA::toArray($s);
902 // Fetch the data from the gcontact table
903 if (!DBA::isResult($r)) {
904 $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`,
905 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
906 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
907 $r = DBA::toArray($s);
910 if (DBA::isResult($r)) {
911 // If there is more than one entry we filter out the connector networks
913 foreach ($r as $id => $result) {
914 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
920 $profile = array_shift($r);
922 // "bd" always contains the upcoming birthday of a contact.
923 // "birthday" might contain the birthday including the year of birth.
924 if ($profile["birthday"] > DBA::NULL_DATE) {
925 $bd_timestamp = strtotime($profile["birthday"]);
926 $month = date("m", $bd_timestamp);
927 $day = date("d", $bd_timestamp);
929 $current_timestamp = time();
930 $current_year = date("Y", $current_timestamp);
931 $current_month = date("m", $current_timestamp);
932 $current_day = date("d", $current_timestamp);
934 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
935 $current = $current_year . "-" . $current_month . "-" . $current_day;
937 if ($profile["bd"] < $current) {
938 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
941 $profile["bd"] = DBA::NULL_DATE;
947 if (empty($profile["photo"]) && isset($default["photo"])) {
948 $profile["photo"] = $default["photo"];
951 if (empty($profile["name"]) && isset($default["name"])) {
952 $profile["name"] = $default["name"];
955 if (empty($profile["network"]) && isset($default["network"])) {
956 $profile["network"] = $default["network"];
959 if (empty($profile["thumb"]) && isset($profile["photo"])) {
960 $profile["thumb"] = $profile["photo"];
963 if (empty($profile["micro"]) && isset($profile["thumb"])) {
964 $profile["micro"] = $profile["thumb"];
967 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
968 && in_array($profile["network"], Protocol::FEDERATED)
970 Worker::add(PRIORITY_LOW, "UpdateGContact", $url);
973 // Show contact details of Diaspora contacts only if connected
974 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
975 $profile["location"] = "";
976 $profile["about"] = "";
977 $profile["gender"] = "";
978 $profile["birthday"] = DBA::NULL_DATE;
981 $cache[$url][$uid] = $profile;
987 * @brief Get contact data for a given address
989 * The function looks at several places (contact table and gcontact table) for the contact
991 * @param string $addr The profile link
992 * @param int $uid User id
994 * @return array Contact data
995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996 * @throws \ImagickException
998 public static function getDetailsByAddr($addr, $uid = -1)
1005 $uid = local_user();
1008 // Fetch contact data from the contact table for the given user
1009 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1010 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1011 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1015 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1016 if (!DBA::isResult($r)) {
1017 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1018 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1019 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1024 // Fetch the data from the gcontact table
1025 if (!DBA::isResult($r)) {
1026 $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`,
1027 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1028 FROM `gcontact` WHERE `addr` = '%s'",
1033 if (!DBA::isResult($r)) {
1034 $data = Probe::uri($addr);
1036 $profile = self::getDetailsByURL($data['url'], $uid);
1045 * @brief Returns the data array for the photo menu of a given contact
1047 * @param array $contact contact
1048 * @param int $uid optional, default 0
1050 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1051 * @throws \ImagickException
1053 public static function photoMenu(array $contact, $uid = 0)
1058 $contact_drop_link = '';
1062 $uid = local_user();
1065 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1067 $profile_link = self::magicLink($contact['url']);
1068 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1073 // Look for our own contact if the uid doesn't match and isn't public
1074 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1075 if (DBA::isResult($contact_own)) {
1076 return self::photoMenu($contact_own, $uid);
1081 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1083 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1085 $profile_link = $contact['url'];
1088 if ($profile_link === 'mailbox') {
1093 $status_link = $profile_link . '?tab=status';
1094 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1095 $profile_link = $profile_link . '?tab=profile';
1098 if (self::canReceivePrivateMessages($contact)) {
1099 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1102 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1103 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1106 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1108 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1110 if (!$contact['self']) {
1111 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1116 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1118 if (empty($contact['uid'])) {
1119 $connlnk = 'follow/?url=' . $contact['url'];
1121 'profile' => [L10n::t('View Profile'), $profile_link, true],
1122 'network' => [L10n::t('Network Posts'), $posts_link, false],
1123 'edit' => [L10n::t('View Contact'), $contact_url, false],
1124 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1128 'status' => [L10n::t('View Status'), $status_link, true],
1129 'profile' => [L10n::t('View Profile'), $profile_link, true],
1130 'photos' => [L10n::t('View Photos'), $photos_link, true],
1131 'network' => [L10n::t('Network Posts'), $posts_link, false],
1132 'edit' => [L10n::t('View Contact'), $contact_url, false],
1133 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1134 'pm' => [L10n::t('Send PM'), $pm_url, false],
1135 'poke' => [L10n::t('Poke'), $poke_link, false],
1139 $args = ['contact' => $contact, 'menu' => &$menu];
1141 Hook::callAll('contact_photo_menu', $args);
1143 $menucondensed = [];
1145 foreach ($menu as $menuname => $menuitem) {
1146 if ($menuitem[1] != '') {
1147 $menucondensed[$menuname] = $menuitem;
1151 return $menucondensed;
1155 * @brief Returns ungrouped contact count or list for user
1157 * Returns either the total number of ungrouped contacts for the given user
1158 * id or a paginated list of ungrouped contacts.
1160 * @param int $uid uid
1162 * @throws \Exception
1164 public static function getUngroupedList($uid)
1174 SELECT DISTINCT(`contact-id`)
1176 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1177 WHERE `group`.`uid` = %d
1178 )", intval($uid), intval($uid));
1182 * Have a look at all contact tables for a given profile url.
1183 * This function works as a replacement for probing the contact.
1185 * @param string $url Contact URL
1186 * @param integer $cid Contact ID
1188 * @return array Contact array in the "probe" structure
1190 private static function getProbeDataFromDatabase($url, $cid = null)
1192 // The link could be provided as http although we stored it as https
1193 $ssl_url = str_replace('http://', 'https://', $url);
1195 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1196 'photo', 'keywords', 'location', 'about', 'network',
1197 'priority', 'batch', 'request', 'confirm', 'poco'];
1200 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1201 if (DBA::isResult($data)) {
1206 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1208 if (!DBA::isResult($data)) {
1209 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1210 $data = DBA::selectFirst('contact', $fields, $condition);
1213 if (DBA::isResult($data)) {
1214 // For security reasons we don't fetch key data from our users
1215 $data["pubkey"] = '';
1219 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1220 'photo', 'keywords', 'location', 'about', 'network'];
1221 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1223 if (!DBA::isResult($data)) {
1224 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1225 $data = DBA::selectFirst('contact', $fields, $condition);
1228 if (DBA::isResult($data)) {
1229 $data["pubkey"] = '';
1231 $data["priority"] = 0;
1232 $data["batch"] = '';
1233 $data["request"] = '';
1234 $data["confirm"] = '';
1239 $data = ActivityPub::probeProfile($url, false);
1240 if (!empty($data)) {
1244 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1245 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1246 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1248 if (!DBA::isResult($data)) {
1249 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1250 $data = DBA::selectFirst('contact', $fields, $condition);
1253 if (DBA::isResult($data)) {
1254 $data["pubkey"] = '';
1255 $data["keywords"] = '';
1256 $data["location"] = '';
1257 $data["about"] = '';
1266 * @brief Fetch the contact id for a given URL and user
1268 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1269 * `addr` or `alias`.
1271 * If there's no record and we aren't looking for a public contact, we quit.
1272 * If there's one, we check that it isn't time to update the picture else we
1273 * directly return the found contact id.
1275 * Second, we probe the provided $url whether it's http://server.tld/profile or
1276 * nick@server.tld. We quit if we can't get any info back.
1278 * Third, we create the contact record if it doesn't exist
1280 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1281 * if there's any updates
1283 * @param string $url Contact URL
1284 * @param integer $uid The user id for the contact (0 = public contact)
1285 * @param boolean $no_update Don't update the contact
1286 * @param array $default Default value for creating the contact when every else fails
1287 * @param boolean $in_loop Internally used variable to prevent an endless loop
1289 * @return integer Contact ID
1290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1291 * @throws \ImagickException
1293 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1295 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1303 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1304 // We first try the nurl (http://server.tld/nick), most common case
1305 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1307 // Then the addr (nick@server.tld)
1308 if (!DBA::isResult($contact)) {
1309 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1312 // Then the alias (which could be anything)
1313 if (!DBA::isResult($contact)) {
1314 // The link could be provided as http although we stored it as https
1315 $ssl_url = str_replace('http://', 'https://', $url);
1316 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1317 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1320 if (DBA::isResult($contact)) {
1321 $contact_id = $contact["id"];
1323 // Update the contact every 7 days
1324 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1326 // We force the update if the avatar is empty
1327 if (empty($contact['avatar'])) {
1328 $update_contact = true;
1331 // Update the contact in the background if needed but it is called by the frontend
1332 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1333 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1336 if (!$update_contact || $no_update) {
1339 } elseif ($uid != 0) {
1340 // Non-existing user-specific contact, exiting
1344 if ($no_update && empty($default)) {
1345 // When we don't want to update, we look if we know this contact in any way
1346 $data = self::getProbeDataFromDatabase($url, $contact_id);
1347 $background_update = true;
1348 } elseif ($no_update && !empty($default)) {
1349 // If there are default values, take these
1351 $background_update = false;
1354 $background_update = false;
1358 $data = Probe::uri($url, "", $uid);
1360 // Ensure that there is a gserver entry
1361 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1362 PortableContact::checkServer($data['baseurl']);
1366 // Take the default values when probing failed
1367 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1368 $data = array_merge($data, $default);
1375 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1376 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1382 'created' => DateTimeFormat::utcNow(),
1383 'url' => $data['url'],
1384 'nurl' => Strings::normaliseLink($data['url']),
1385 'addr' => defaults($data, 'addr', ''),
1386 'alias' => defaults($data, 'alias', ''),
1387 'notify' => defaults($data, 'notify', ''),
1388 'poll' => defaults($data, 'poll', ''),
1389 'name' => defaults($data, 'name', ''),
1390 'nick' => defaults($data, 'nick', ''),
1391 'photo' => defaults($data, 'photo', ''),
1392 'keywords' => defaults($data, 'keywords', ''),
1393 'location' => defaults($data, 'location', ''),
1394 'about' => defaults($data, 'about', ''),
1395 'network' => $data['network'],
1396 'pubkey' => defaults($data, 'pubkey', ''),
1397 'rel' => self::SHARING,
1398 'priority' => defaults($data, 'priority', 0),
1399 'batch' => defaults($data, 'batch', ''),
1400 'request' => defaults($data, 'request', ''),
1401 'confirm' => defaults($data, 'confirm', ''),
1402 'poco' => defaults($data, 'poco', ''),
1403 'baseurl' => defaults($data, 'baseurl', ''),
1404 'name-date' => DateTimeFormat::utcNow(),
1405 'uri-date' => DateTimeFormat::utcNow(),
1406 'avatar-date' => DateTimeFormat::utcNow(),
1412 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1414 DBA::update('contact', $fields, $condition, true);
1416 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1417 $contacts = DBA::toArray($s);
1418 if (!DBA::isResult($contacts)) {
1422 $contact_id = $contacts[0]["id"];
1424 // Update in the background when we fetched the data solely from the database
1425 if ($background_update) {
1426 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1429 // Update the newly created contact from data in the gcontact table
1430 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1431 if (DBA::isResult($gcontact)) {
1432 // Only use the information when the probing hadn't fetched these values
1433 if (!empty($data['keywords'])) {
1434 unset($gcontact['keywords']);
1436 if (!empty($data['location'])) {
1437 unset($gcontact['location']);
1439 if (!empty($data['about'])) {
1440 unset($gcontact['about']);
1442 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1445 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1446 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1447 Strings::normaliseLink($data["url"]), 0, $contact_id];
1448 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1449 DBA::delete('contact', $condition);
1453 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1454 self::updateAvatar($data['photo'], $uid, $contact_id);
1457 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey', 'baseurl'];
1458 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1460 // This condition should always be true
1461 if (!DBA::isResult($contact)) {
1466 'addr' => $data['addr'] ?? '',
1467 'alias' => defaults($data, 'alias', ''),
1468 'url' => $data['url'],
1469 'nurl' => Strings::normaliseLink($data['url']),
1470 'name' => $data['name'],
1471 'nick' => $data['nick'],
1472 'baseurl' => $data['baseurl']
1475 if (!empty($data['keywords'])) {
1476 $updated['keywords'] = $data['keywords'];
1478 if (!empty($data['location'])) {
1479 $updated['location'] = $data['location'];
1482 // Update the technical stuff as well - if filled
1483 if (!empty($data['notify'])) {
1484 $updated['notify'] = $data['notify'];
1486 if (!empty($data['poll'])) {
1487 $updated['poll'] = $data['poll'];
1489 if (!empty($data['batch'])) {
1490 $updated['batch'] = $data['batch'];
1492 if (!empty($data['request'])) {
1493 $updated['request'] = $data['request'];
1495 if (!empty($data['confirm'])) {
1496 $updated['confirm'] = $data['confirm'];
1498 if (!empty($data['poco'])) {
1499 $updated['poco'] = $data['poco'];
1502 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1503 if (empty($contact['pubkey'])) {
1504 $updated['pubkey'] = $data['pubkey'];
1507 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1508 $updated['uri-date'] = DateTimeFormat::utcNow();
1510 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1511 $updated['name-date'] = DateTimeFormat::utcNow();
1514 $updated['updated'] = DateTimeFormat::utcNow();
1516 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1518 if (!$background_update && ($uid == 0)) {
1519 // Update the gcontact entry
1520 GContact::updateFromPublicContactID($contact_id);
1527 * @brief Checks if the contact is blocked
1529 * @param int $cid contact id
1531 * @return boolean Is the contact blocked?
1532 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1534 public static function isBlocked($cid)
1540 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1541 if (!DBA::isResult($blocked)) {
1545 if (Network::isUrlBlocked($blocked['url'])) {
1549 return (bool) $blocked['blocked'];
1553 * @brief Checks if the contact is hidden
1555 * @param int $cid contact id
1557 * @return boolean Is the contact hidden?
1558 * @throws \Exception
1560 public static function isHidden($cid)
1566 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1567 if (!DBA::isResult($hidden)) {
1570 return (bool) $hidden['hidden'];
1574 * @brief Returns posts from a given contact url
1576 * @param string $contact_url Contact URL
1578 * @param bool $thread_mode
1579 * @param int $update
1580 * @return string posts in HTML
1581 * @throws \Exception
1583 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1585 $a = self::getApp();
1587 $cid = self::getIdForURL($contact_url);
1589 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1590 if (!DBA::isResult($contact)) {
1594 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1595 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1597 $sql = "`item`.`uid` = ?";
1600 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1603 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1604 $cid, GRAVITY_PARENT, local_user()];
1606 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1607 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1610 $pager = new Pager($a->query_string);
1612 $params = ['order' => ['created' => true],
1613 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1616 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1618 $items = Item::inArray($r);
1620 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1622 $r = Item::selectForUser(local_user(), [], $condition, $params);
1624 $items = Item::inArray($r);
1626 $o = conversation($a, $items, $pager, 'contact-posts', false);
1630 $o .= $pager->renderMinimal(count($items));
1637 * @brief Returns the account type name
1639 * The function can be called with either the user or the contact array
1641 * @param array $contact contact or user array
1644 public static function getAccountType(array $contact)
1646 // There are several fields that indicate that the contact or user is a forum
1647 // "page-flags" is a field in the user table,
1648 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1649 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1650 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1651 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1652 || (isset($contact['forum']) && intval($contact['forum']))
1653 || (isset($contact['prv']) && intval($contact['prv']))
1654 || (isset($contact['community']) && intval($contact['community']))
1656 $type = self::TYPE_COMMUNITY;
1658 $type = self::TYPE_PERSON;
1661 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1662 if (isset($contact["contact-type"])) {
1663 $type = $contact["contact-type"];
1666 if (isset($contact["account-type"])) {
1667 $type = $contact["account-type"];
1671 case self::TYPE_ORGANISATION:
1672 $account_type = L10n::t("Organisation");
1675 case self::TYPE_NEWS:
1676 $account_type = L10n::t('News');
1679 case self::TYPE_COMMUNITY:
1680 $account_type = L10n::t("Forum");
1688 return $account_type;
1692 * @brief Blocks a contact
1696 * @throws \Exception
1698 public static function block($cid, $reason = null)
1700 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1706 * @brief Unblocks a contact
1710 * @throws \Exception
1712 public static function unblock($cid)
1714 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1720 * @brief Updates the avatar links in a contact only if needed
1722 * @param string $avatar Link to avatar picture
1723 * @param int $uid User id of contact owner
1724 * @param int $cid Contact id
1725 * @param bool $force force picture update
1727 * @return array Returns array of the different avatar sizes
1728 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1729 * @throws \ImagickException
1731 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1733 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1734 if (!DBA::isResult($contact)) {
1737 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1740 if (($contact["avatar"] != $avatar) || $force) {
1741 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1744 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1745 DBA::update('contact', $fields, ['id' => $cid]);
1747 // Update the public contact (contact id = 0)
1749 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1750 if (DBA::isResult($pcontact)) {
1751 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1763 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1765 * @param array $contact The personal contact entry
1766 * @param array $fields The fields that are updated
1767 * @throws \Exception
1769 private static function updateContact($id, $uid, $url, array $fields)
1771 DBA::update('contact', $fields, ['id' => $id]);
1777 // Update the corresponding gcontact entry
1778 GContact::updateFromPublicContactID($id);
1780 // Archive or unarchive the contact. We only need to do this for the public contact.
1781 // The archive/unarchive function will update the personal contacts by themselves.
1782 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1783 if (!empty($fields['success_update'])) {
1784 self::unmarkForArchival($contact);
1785 } elseif (!empty($fields['failure_update'])) {
1786 self::markForArchival($contact);
1789 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1791 // These contacts are sharing with us, we don't poll them.
1792 // This means that we don't set the update fields in "OnePoll.php".
1793 $condition['rel'] = self::SHARING;
1794 DBA::update('contact', $fields, $condition);
1796 unset($fields['last-update']);
1797 unset($fields['success_update']);
1798 unset($fields['failure_update']);
1800 if (empty($fields)) {
1804 // We are polling these contacts, so we mustn't set the update fields here.
1805 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1806 DBA::update('contact', $fields, $condition);
1810 * @param integer $id contact id
1811 * @param string $network Optional network we are probing for
1812 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1815 * @throws \ImagickException
1817 public static function updateFromProbe($id, $network = '', $force = false)
1820 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1821 This will reliably kill your communication with old Friendica contacts.
1824 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1825 'poll', 'request', 'confirm', 'poco', 'network', 'alias', 'baseurl'];
1826 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1827 if (!DBA::isResult($contact)) {
1831 $uid = $contact['uid'];
1832 unset($contact['uid']);
1834 $contact['photo'] = $contact['avatar'];
1835 unset($contact['avatar']);
1837 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1839 $updated = DateTimeFormat::utcNow();
1841 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1842 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
1843 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
1844 if ($force && ($uid == 0)) {
1845 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1852 // make sure to not overwrite existing values with blank entries
1853 foreach ($ret as $key => $val) {
1854 if (!array_key_exists($key, $contact)) {
1856 } elseif (($contact[$key] != '') && ($val == '')) {
1857 $ret[$key] = $contact[$key];
1858 } elseif ($ret[$key] != $contact[$key]) {
1863 if ($ret['network'] != Protocol::FEED) {
1864 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
1868 if ($force && ($uid == 0)) {
1869 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
1874 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1875 $ret['updated'] = $updated;
1877 if ($force && ($uid == 0)) {
1878 $ret['last-update'] = $updated;
1879 $ret['success_update'] = $updated;
1882 unset($ret['photo']);
1884 self::updateContact($id, $uid, $ret['url'], $ret);
1890 * Detects if a given contact array belongs to a legacy DFRN connection
1892 * @param array $contact
1895 public static function isLegacyDFRNContact($contact)
1897 // Newer Friendica contacts are connected via AP, then these fields aren't set
1898 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1902 * Detects the communication protocol for a given contact url.
1903 * This is used to detect Friendica contacts that we can communicate via AP.
1905 * @param string $url contact url
1906 * @param string $network Network of that contact
1907 * @return string with protocol
1909 public static function getProtocol($url, $network)
1911 if ($network != Protocol::DFRN) {
1915 $apcontact = APContact::getByURL($url);
1916 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1917 return Protocol::ACTIVITYPUB;
1924 * Takes a $uid and a url/handle and adds a new contact
1925 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1926 * dfrn_request page.
1928 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1931 * $return['success'] boolean true if successful
1932 * $return['message'] error text if success is false.
1934 * @brief Takes a $uid and a url/handle and adds a new contact
1936 * @param string $url
1937 * @param bool $interactive
1938 * @param string $network
1940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1941 * @throws \ImagickException
1943 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1945 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1949 // remove ajax junk, e.g. Twitter
1950 $url = str_replace('/#!/', '/', $url);
1952 if (!Network::isUrlAllowed($url)) {
1953 $result['message'] = L10n::t('Disallowed profile URL.');
1957 if (Network::isUrlBlocked($url)) {
1958 $result['message'] = L10n::t('Blocked domain');
1963 $result['message'] = L10n::t('Connect URL missing.');
1967 $arr = ['url' => $url, 'contact' => []];
1969 Hook::callAll('follow', $arr);
1972 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1976 if (!empty($arr['contact']['name'])) {
1977 $ret = $arr['contact'];
1979 $ret = Probe::uri($url, $network, $uid, false);
1982 if (($network != '') && ($ret['network'] != $network)) {
1983 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1987 // check if we already have a contact
1988 // the poll url is more reliable than the profile url, as we may have
1989 // indirect links or webfinger links
1991 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1992 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1993 if (!DBA::isResult($contact)) {
1994 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1995 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1998 $protocol = self::getProtocol($url, $ret['network']);
2000 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2002 if (strlen($a->getURLPath())) {
2003 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2005 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2008 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2012 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2013 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2014 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2018 // This extra param just confuses things, remove it
2019 if ($protocol === Protocol::DIASPORA) {
2020 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2023 // do we have enough information?
2024 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2025 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2026 if (empty($ret['poll'])) {
2027 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2029 if (empty($ret['name'])) {
2030 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2032 if (empty($ret['url'])) {
2033 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2035 if (strpos($url, '@') !== false) {
2036 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2037 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2042 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2043 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2044 $ret['notify'] = '';
2047 if (!$ret['notify']) {
2048 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2051 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2053 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2055 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2057 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2059 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2063 if (DBA::isResult($contact)) {
2065 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2067 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2068 DBA::update('contact', $fields, ['id' => $contact['id']]);
2070 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2072 // create contact record
2073 DBA::insert('contact', [
2075 'created' => DateTimeFormat::utcNow(),
2076 'url' => $ret['url'],
2077 'nurl' => Strings::normaliseLink($ret['url']),
2078 'addr' => $ret['addr'],
2079 'alias' => $ret['alias'],
2080 'batch' => $ret['batch'],
2081 'notify' => $ret['notify'],
2082 'poll' => $ret['poll'],
2083 'poco' => $ret['poco'],
2084 'name' => $ret['name'],
2085 'nick' => $ret['nick'],
2086 'network' => $ret['network'],
2087 'baseurl' => $ret['baseurl'],
2088 'protocol' => $protocol,
2089 'pubkey' => $ret['pubkey'],
2090 'rel' => $new_relation,
2091 'priority'=> $ret['priority'],
2092 'writable'=> $writeable,
2093 'hidden' => $hidden,
2096 'pending' => $pending,
2101 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2102 if (!DBA::isResult($contact)) {
2103 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2107 $contact_id = $contact['id'];
2108 $result['cid'] = $contact_id;
2110 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2112 // Update the avatar
2113 self::updateAvatar($ret['photo'], $uid, $contact_id);
2115 // pull feed and consume it, which should subscribe to the hub.
2117 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2119 $owner = User::getOwnerDataById($uid);
2121 if (DBA::isResult($owner)) {
2122 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2123 // create a follow slap
2125 $item['verb'] = ACTIVITY_FOLLOW;
2126 $item['follow'] = $contact["url"];
2128 $item['title'] = '';
2131 $item['attach'] = '';
2133 $slap = OStatus::salmon($item, $owner);
2135 if (!empty($contact['notify'])) {
2136 Salmon::slapper($owner, $contact['notify'], $slap);
2138 } elseif ($protocol == Protocol::DIASPORA) {
2139 $ret = Diaspora::sendShare($a->user, $contact);
2140 Logger::log('share returns: ' . $ret);
2141 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2142 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2143 if (empty($activity_id)) {
2144 // This really should never happen
2148 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2149 Logger::log('Follow returns: ' . $ret);
2153 $result['success'] = true;
2158 * @brief Updated contact's SSL policy
2160 * @param array $contact Contact array
2161 * @param string $new_policy New policy, valid: self,full
2163 * @return array Contact array with updated values
2164 * @throws \Exception
2166 public static function updateSslPolicy(array $contact, $new_policy)
2168 $ssl_changed = false;
2169 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2170 $ssl_changed = true;
2171 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2172 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2173 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2174 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2175 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2176 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2179 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2180 $ssl_changed = true;
2181 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2182 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2183 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2184 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2185 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2186 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2190 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2191 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2192 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2193 DBA::update('contact', $fields, ['id' => $contact['id']]);
2200 * @param array $importer Owner (local user) data
2201 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2202 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2203 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2204 * @param string $note Introduction additional message
2205 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2207 * @throws \ImagickException
2209 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2211 // Should always be set
2212 if (empty($datarray['author-id'])) {
2216 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2217 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2218 if (!DBA::isResult($pub_contact)) {
2219 // Should never happen
2223 // Contact is blocked at node-level
2224 if (self::isBlocked($datarray['author-id'])) {
2228 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2229 $name = $pub_contact['name'];
2230 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2231 $nick = $pub_contact['nick'];
2232 $network = $pub_contact['network'];
2234 if (!empty($contact)) {
2235 // Contact is blocked at user-level
2236 if (!empty($contact['id']) && !empty($importer['id']) &&
2237 self::isBlockedByUser($contact['id'], $importer['id'])) {
2241 // Make sure that the existing contact isn't archived
2242 self::unmarkForArchival($contact);
2244 if (($contact['rel'] == self::SHARING)
2245 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2246 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2247 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2252 // send email notification to owner?
2253 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2254 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2258 // create contact record
2259 DBA::insert('contact', [
2260 'uid' => $importer['uid'],
2261 'created' => DateTimeFormat::utcNow(),
2263 'nurl' => Strings::normaliseLink($url),
2267 'network' => $network,
2268 'rel' => self::FOLLOWER,
2276 'id' => DBA::lastInsertId(),
2277 'network' => $network,
2283 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2285 /// @TODO Encapsulate this into a function/method
2286 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2287 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2288 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2289 // create notification
2290 $hash = Strings::getRandomHex();
2292 if (is_array($contact_record)) {
2293 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2294 'blocked' => false, 'knowyou' => false, 'note' => $note,
2295 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2298 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2300 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2301 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2304 'type' => NOTIFY_INTRO,
2305 'notify_flags' => $user['notify-flags'],
2306 'language' => $user['language'],
2307 'to_name' => $user['username'],
2308 'to_email' => $user['email'],
2309 'uid' => $user['uid'],
2310 'link' => System::baseUrl() . '/notifications/intro',
2311 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2312 'source_link' => $contact_record['url'],
2313 'source_photo' => $contact_record['photo'],
2314 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2318 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2319 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2320 DBA::update('contact', ['pending' => false], $condition);
2329 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2331 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2332 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2334 Contact::remove($contact['id']);
2338 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2340 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2341 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2343 Contact::remove($contact['id']);
2348 * @brief Create a birthday event.
2350 * Update the year and the birthday.
2352 public static function updateBirthdays()
2356 AND `bd` > "0001-01-01"
2357 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2358 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2359 AND NOT `contact`.`pending`
2360 AND NOT `contact`.`hidden`
2361 AND NOT `contact`.`blocked`
2362 AND NOT `contact`.`archive`
2363 AND NOT `contact`.`deleted`',
2368 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2370 while ($contact = DBA::fetch($contacts)) {
2371 Logger::log('update_contact_birthday: ' . $contact['bd']);
2373 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2375 if (Event::createBirthday($contact, $nextbd)) {
2379 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2380 ['id' => $contact['id']]
2387 * Remove the unavailable contact ids from the provided list
2389 * @param array $contact_ids Contact id list
2390 * @throws \Exception
2392 public static function pruneUnavailable(array &$contact_ids)
2394 if (empty($contact_ids)) {
2398 $str = DBA::escape(implode(',', $contact_ids));
2400 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2403 while($contact = DBA::fetch($stmt)) {
2404 $return[] = $contact['id'];
2409 $contact_ids = $return;
2413 * @brief Returns a magic link to authenticate remote visitors
2415 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2417 * @param string $contact_url The address of the target contact profile
2418 * @param string $url An url that we will be redirected to after the authentication
2420 * @return string with "redir" link
2421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2422 * @throws \ImagickException
2424 public static function magicLink($contact_url, $url = '')
2426 if (!local_user() && !remote_user()) {
2427 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2430 $data = self::getProbeDataFromDatabase($contact_url);
2432 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2435 // Prevents endless loop in case only a non-public contact exists for the contact URL
2436 unset($data['uid']);
2438 return self::magicLinkByContact($data, $contact_url);
2442 * @brief Returns a magic link to authenticate remote visitors
2444 * @param integer $cid The contact id of the target contact profile
2445 * @param string $url An url that we will be redirected to after the authentication
2447 * @return string with "redir" link
2448 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2449 * @throws \ImagickException
2451 public static function magicLinkbyId($cid, $url = '')
2453 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2455 return self::magicLinkByContact($contact, $url);
2459 * @brief Returns a magic link to authenticate remote visitors
2461 * @param array $contact The contact array with "uid", "network" and "url"
2462 * @param string $url An url that we will be redirected to after the authentication
2464 * @return string with "redir" link
2465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2466 * @throws \ImagickException
2468 public static function magicLinkByContact($contact, $url = '')
2470 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2471 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2474 // Only redirections to the same host do make sense
2475 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2479 if (!empty($contact['uid'])) {
2480 return self::magicLink($contact['url'], $url);
2483 if (empty($contact['id'])) {
2484 return $url ?: $contact['url'];
2487 $redirect = 'redir/' . $contact['id'];
2490 $redirect .= '?url=' . $url;
2497 * Remove a contact from all groups
2499 * @param integer $contact_id
2501 * @return boolean Success
2503 public static function removeFromGroups($contact_id)
2505 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2509 * Is the contact a forum?
2511 * @param integer $contactid ID of the contact
2513 * @return boolean "true" if it is a forum
2515 public static function isForum($contactid)
2517 $fields = ['forum', 'prv'];
2518 $condition = ['id' => $contactid];
2519 $contact = DBA::selectFirst('contact', $fields, $condition);
2520 if (!DBA::isResult($contact)) {
2525 return ($contact['forum'] || $contact['prv']);
2529 * Can the remote contact receive private messages?
2531 * @param array $contact
2534 public static function canReceivePrivateMessages(array $contact)
2536 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2537 $self = $contact['self'] ?? false;
2539 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;