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]);
800 * @brief Cancels the archival countdown
802 * @see Contact::markForArchival()
804 * @param array $contact contact to be unmarked for archival
808 public static function unmarkForArchival(array $contact)
810 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
811 $exists = DBA::exists('contact', $condition);
813 // We don't need to update, we never marked this contact for archival
818 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
820 if (!isset($contact['url']) && !empty($contact['id'])) {
821 $fields = ['id', 'url', 'batch'];
822 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
823 if (!DBA::isResult($contact)) {
828 // It's a miracle. Our dead contact has inexplicably come back to life.
829 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
830 DBA::update('contact', $fields, ['id' => $contact['id']]);
831 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
833 if (!empty($contact['batch'])) {
834 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
835 DBA::update('contact', $fields, $condition);
840 * @brief Get contact data for a given profile link
842 * The function looks at several places (contact table and gcontact table) for the contact
843 * It caches its result for the same script execution to prevent duplicate calls
845 * @param string $url The profile link
846 * @param int $uid User id
847 * @param array $default If not data was found take this data as default value
849 * @return array Contact data
850 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
852 public static function getDetailsByURL($url, $uid = -1, array $default = [])
864 if (isset($cache[$url][$uid])) {
865 return $cache[$url][$uid];
868 $ssl_url = str_replace('http://', 'https://', $url);
870 // Fetch contact data from the contact table for the given user
871 $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`,
872 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
873 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
874 $r = DBA::toArray($s);
876 // Fetch contact data from the contact table for the given user, checking with the alias
877 if (!DBA::isResult($r)) {
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 `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
881 $r = DBA::toArray($s);
884 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
885 if (!DBA::isResult($r)) {
886 $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`,
887 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
888 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
889 $r = DBA::toArray($s);
892 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
893 if (!DBA::isResult($r)) {
894 $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`,
895 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
896 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
897 $r = DBA::toArray($s);
900 // Fetch the data from the gcontact table
901 if (!DBA::isResult($r)) {
902 $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`,
903 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
904 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
905 $r = DBA::toArray($s);
908 if (DBA::isResult($r)) {
909 // If there is more than one entry we filter out the connector networks
911 foreach ($r as $id => $result) {
912 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
918 $profile = array_shift($r);
920 // "bd" always contains the upcoming birthday of a contact.
921 // "birthday" might contain the birthday including the year of birth.
922 if ($profile["birthday"] > DBA::NULL_DATE) {
923 $bd_timestamp = strtotime($profile["birthday"]);
924 $month = date("m", $bd_timestamp);
925 $day = date("d", $bd_timestamp);
927 $current_timestamp = time();
928 $current_year = date("Y", $current_timestamp);
929 $current_month = date("m", $current_timestamp);
930 $current_day = date("d", $current_timestamp);
932 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
933 $current = $current_year . "-" . $current_month . "-" . $current_day;
935 if ($profile["bd"] < $current) {
936 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
939 $profile["bd"] = DBA::NULL_DATE;
945 if (empty($profile["photo"]) && isset($default["photo"])) {
946 $profile["photo"] = $default["photo"];
949 if (empty($profile["name"]) && isset($default["name"])) {
950 $profile["name"] = $default["name"];
953 if (empty($profile["network"]) && isset($default["network"])) {
954 $profile["network"] = $default["network"];
957 if (empty($profile["thumb"]) && isset($profile["photo"])) {
958 $profile["thumb"] = $profile["photo"];
961 if (empty($profile["micro"]) && isset($profile["thumb"])) {
962 $profile["micro"] = $profile["thumb"];
965 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
966 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
968 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
971 // Show contact details of Diaspora contacts only if connected
972 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
973 $profile["location"] = "";
974 $profile["about"] = "";
975 $profile["gender"] = "";
976 $profile["birthday"] = DBA::NULL_DATE;
979 $cache[$url][$uid] = $profile;
985 * @brief Get contact data for a given address
987 * The function looks at several places (contact table and gcontact table) for the contact
989 * @param string $addr The profile link
990 * @param int $uid User id
992 * @return array Contact data
993 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994 * @throws \ImagickException
996 public static function getDetailsByAddr($addr, $uid = -1)
1003 $uid = local_user();
1006 // Fetch contact data from the contact table for the given user
1007 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1008 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1009 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1013 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1014 if (!DBA::isResult($r)) {
1015 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1016 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1017 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1022 // Fetch the data from the gcontact table
1023 if (!DBA::isResult($r)) {
1024 $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`,
1025 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1026 FROM `gcontact` WHERE `addr` = '%s'",
1031 if (!DBA::isResult($r)) {
1032 $data = Probe::uri($addr);
1034 $profile = self::getDetailsByURL($data['url'], $uid);
1043 * @brief Returns the data array for the photo menu of a given contact
1045 * @param array $contact contact
1046 * @param int $uid optional, default 0
1048 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1049 * @throws \ImagickException
1051 public static function photoMenu(array $contact, $uid = 0)
1056 $contact_drop_link = '';
1060 $uid = local_user();
1063 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1065 $profile_link = self::magicLink($contact['url']);
1066 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1071 // Look for our own contact if the uid doesn't match and isn't public
1072 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1073 if (DBA::isResult($contact_own)) {
1074 return self::photoMenu($contact_own, $uid);
1079 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1081 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1083 $profile_link = $contact['url'];
1086 if ($profile_link === 'mailbox') {
1091 $status_link = $profile_link . '?tab=status';
1092 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1093 $profile_link = $profile_link . '?tab=profile';
1096 if (self::canReceivePrivateMessages($contact)) {
1097 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1100 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1101 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1104 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1106 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1108 if (!$contact['self']) {
1109 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1114 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1116 if (empty($contact['uid'])) {
1117 $connlnk = 'follow/?url=' . $contact['url'];
1119 'profile' => [L10n::t('View Profile'), $profile_link, true],
1120 'network' => [L10n::t('Network Posts'), $posts_link, false],
1121 'edit' => [L10n::t('View Contact'), $contact_url, false],
1122 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1126 'status' => [L10n::t('View Status'), $status_link, true],
1127 'profile' => [L10n::t('View Profile'), $profile_link, true],
1128 'photos' => [L10n::t('View Photos'), $photos_link, true],
1129 'network' => [L10n::t('Network Posts'), $posts_link, false],
1130 'edit' => [L10n::t('View Contact'), $contact_url, false],
1131 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1132 'pm' => [L10n::t('Send PM'), $pm_url, false],
1133 'poke' => [L10n::t('Poke'), $poke_link, false],
1137 $args = ['contact' => $contact, 'menu' => &$menu];
1139 Hook::callAll('contact_photo_menu', $args);
1141 $menucondensed = [];
1143 foreach ($menu as $menuname => $menuitem) {
1144 if ($menuitem[1] != '') {
1145 $menucondensed[$menuname] = $menuitem;
1149 return $menucondensed;
1153 * @brief Returns ungrouped contact count or list for user
1155 * Returns either the total number of ungrouped contacts for the given user
1156 * id or a paginated list of ungrouped contacts.
1158 * @param int $uid uid
1160 * @throws \Exception
1162 public static function getUngroupedList($uid)
1172 SELECT DISTINCT(`contact-id`)
1174 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1175 WHERE `group`.`uid` = %d
1176 )", intval($uid), intval($uid));
1180 * Have a look at all contact tables for a given profile url.
1181 * This function works as a replacement for probing the contact.
1183 * @param string $url Contact URL
1184 * @param integer $cid Contact ID
1186 * @return array Contact array in the "probe" structure
1188 private static function getProbeDataFromDatabase($url, $cid = null)
1190 // The link could be provided as http although we stored it as https
1191 $ssl_url = str_replace('http://', 'https://', $url);
1193 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1194 'photo', 'keywords', 'location', 'about', 'network',
1195 'priority', 'batch', 'request', 'confirm', 'poco'];
1198 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1199 if (DBA::isResult($data)) {
1204 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1206 if (!DBA::isResult($data)) {
1207 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1208 $data = DBA::selectFirst('contact', $fields, $condition);
1211 if (DBA::isResult($data)) {
1212 // For security reasons we don't fetch key data from our users
1213 $data["pubkey"] = '';
1217 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1218 'photo', 'keywords', 'location', 'about', 'network'];
1219 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1221 if (!DBA::isResult($data)) {
1222 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1223 $data = DBA::selectFirst('contact', $fields, $condition);
1226 if (DBA::isResult($data)) {
1227 $data["pubkey"] = '';
1229 $data["priority"] = 0;
1230 $data["batch"] = '';
1231 $data["request"] = '';
1232 $data["confirm"] = '';
1237 $data = ActivityPub::probeProfile($url, false);
1238 if (!empty($data)) {
1242 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1243 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1244 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1246 if (!DBA::isResult($data)) {
1247 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1248 $data = DBA::selectFirst('contact', $fields, $condition);
1251 if (DBA::isResult($data)) {
1252 $data["pubkey"] = '';
1253 $data["keywords"] = '';
1254 $data["location"] = '';
1255 $data["about"] = '';
1264 * @brief Fetch the contact id for a given URL and user
1266 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1267 * `addr` or `alias`.
1269 * If there's no record and we aren't looking for a public contact, we quit.
1270 * If there's one, we check that it isn't time to update the picture else we
1271 * directly return the found contact id.
1273 * Second, we probe the provided $url whether it's http://server.tld/profile or
1274 * nick@server.tld. We quit if we can't get any info back.
1276 * Third, we create the contact record if it doesn't exist
1278 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1279 * if there's any updates
1281 * @param string $url Contact URL
1282 * @param integer $uid The user id for the contact (0 = public contact)
1283 * @param boolean $no_update Don't update the contact
1284 * @param array $default Default value for creating the contact when every else fails
1285 * @param boolean $in_loop Internally used variable to prevent an endless loop
1287 * @return integer Contact ID
1288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1289 * @throws \ImagickException
1291 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1293 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1301 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1302 // We first try the nurl (http://server.tld/nick), most common case
1303 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1305 // Then the addr (nick@server.tld)
1306 if (!DBA::isResult($contact)) {
1307 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1310 // Then the alias (which could be anything)
1311 if (!DBA::isResult($contact)) {
1312 // The link could be provided as http although we stored it as https
1313 $ssl_url = str_replace('http://', 'https://', $url);
1314 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1315 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1318 if (DBA::isResult($contact)) {
1319 $contact_id = $contact["id"];
1321 // Update the contact every 7 days
1322 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1324 // We force the update if the avatar is empty
1325 if (empty($contact['avatar'])) {
1326 $update_contact = true;
1329 // Update the contact in the background if needed but it is called by the frontend
1330 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1331 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1334 if (!$update_contact || $no_update) {
1337 } elseif ($uid != 0) {
1338 // Non-existing user-specific contact, exiting
1342 // When we don't want to update, we look if we know this contact in any way
1343 if ($no_update && empty($default)) {
1344 $data = self::getProbeDataFromDatabase($url, $contact_id);
1345 $background_update = true;
1348 $background_update = false;
1352 $data = Probe::uri($url, "", $uid);
1354 // Ensure that there is a gserver entry
1355 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1356 PortableContact::checkServer($data['baseurl']);
1360 // Last try in gcontact for unsupported networks
1361 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1366 $contact = array_merge(self::getProbeDataFromDatabase($url, $contact_id), $default);
1367 if (empty($contact)) {
1371 $data = array_merge($data, $contact);
1378 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1379 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1385 'created' => DateTimeFormat::utcNow(),
1386 'url' => $data['url'],
1387 'nurl' => Strings::normaliseLink($data['url']),
1388 'addr' => defaults($data, 'addr', ''),
1389 'alias' => defaults($data, 'alias', ''),
1390 'notify' => defaults($data, 'notify', ''),
1391 'poll' => defaults($data, 'poll', ''),
1392 'name' => defaults($data, 'name', ''),
1393 'nick' => defaults($data, 'nick', ''),
1394 'photo' => defaults($data, 'photo', ''),
1395 'keywords' => defaults($data, 'keywords', ''),
1396 'location' => defaults($data, 'location', ''),
1397 'about' => defaults($data, 'about', ''),
1398 'network' => $data['network'],
1399 'pubkey' => defaults($data, 'pubkey', ''),
1400 'rel' => self::SHARING,
1401 'priority' => defaults($data, 'priority', 0),
1402 'batch' => defaults($data, 'batch', ''),
1403 'request' => defaults($data, 'request', ''),
1404 'confirm' => defaults($data, 'confirm', ''),
1405 'poco' => defaults($data, 'poco', ''),
1406 'name-date' => DateTimeFormat::utcNow(),
1407 'uri-date' => DateTimeFormat::utcNow(),
1408 'avatar-date' => DateTimeFormat::utcNow(),
1414 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1416 DBA::update('contact', $fields, $condition, true);
1418 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1419 $contacts = DBA::toArray($s);
1420 if (!DBA::isResult($contacts)) {
1424 $contact_id = $contacts[0]["id"];
1426 // Update in the background when we fetched the data solely from the database
1427 if ($background_update) {
1428 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1431 // Update the newly created contact from data in the gcontact table
1432 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1433 if (DBA::isResult($gcontact)) {
1434 // Only use the information when the probing hadn't fetched these values
1435 if (!empty($data['keywords'])) {
1436 unset($gcontact['keywords']);
1438 if (!empty($data['location'])) {
1439 unset($gcontact['location']);
1441 if (!empty($data['about'])) {
1442 unset($gcontact['about']);
1444 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1447 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1448 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1449 Strings::normaliseLink($data["url"]), 0, $contact_id];
1450 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1451 DBA::delete('contact', $condition);
1455 if (!empty($data['photo'])) {
1456 self::updateAvatar($data['photo'], $uid, $contact_id);
1459 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1460 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1462 // This condition should always be true
1463 if (!DBA::isResult($contact)) {
1468 'addr' => $data['addr'] ?? '',
1469 'alias' => defaults($data, 'alias', ''),
1470 'url' => $data['url'],
1471 'nurl' => Strings::normaliseLink($data['url']),
1472 'name' => $data['name'],
1473 'nick' => $data['nick']
1476 if (!empty($data['keywords'])) {
1477 $updated['keywords'] = $data['keywords'];
1479 if (!empty($data['location'])) {
1480 $updated['location'] = $data['location'];
1483 // Update the technical stuff as well - if filled
1484 if (!empty($data['notify'])) {
1485 $updated['notify'] = $data['notify'];
1487 if (!empty($data['poll'])) {
1488 $updated['poll'] = $data['poll'];
1490 if (!empty($data['batch'])) {
1491 $updated['batch'] = $data['batch'];
1493 if (!empty($data['request'])) {
1494 $updated['request'] = $data['request'];
1496 if (!empty($data['confirm'])) {
1497 $updated['confirm'] = $data['confirm'];
1499 if (!empty($data['poco'])) {
1500 $updated['poco'] = $data['poco'];
1503 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1504 if (empty($contact['pubkey'])) {
1505 $updated['pubkey'] = $data['pubkey'];
1508 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1509 $updated['uri-date'] = DateTimeFormat::utcNow();
1511 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1512 $updated['name-date'] = DateTimeFormat::utcNow();
1515 $updated['updated'] = DateTimeFormat::utcNow();
1517 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1523 * @brief Checks if the contact is blocked
1525 * @param int $cid contact id
1527 * @return boolean Is the contact blocked?
1528 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1530 public static function isBlocked($cid)
1536 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1537 if (!DBA::isResult($blocked)) {
1541 if (Network::isUrlBlocked($blocked['url'])) {
1545 return (bool) $blocked['blocked'];
1549 * @brief Checks if the contact is hidden
1551 * @param int $cid contact id
1553 * @return boolean Is the contact hidden?
1554 * @throws \Exception
1556 public static function isHidden($cid)
1562 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1563 if (!DBA::isResult($hidden)) {
1566 return (bool) $hidden['hidden'];
1570 * @brief Returns posts from a given contact url
1572 * @param string $contact_url Contact URL
1574 * @param bool $thread_mode
1575 * @param int $update
1576 * @return string posts in HTML
1577 * @throws \Exception
1579 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1581 $a = self::getApp();
1583 $cid = self::getIdForURL($contact_url);
1585 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1586 if (!DBA::isResult($contact)) {
1590 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1591 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1593 $sql = "`item`.`uid` = ?";
1596 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1599 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1600 $cid, GRAVITY_PARENT, local_user()];
1602 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1603 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1606 $pager = new Pager($a->query_string);
1608 $params = ['order' => ['created' => true],
1609 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1612 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1614 $items = Item::inArray($r);
1616 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1618 $r = Item::selectForUser(local_user(), [], $condition, $params);
1620 $items = Item::inArray($r);
1622 $o = conversation($a, $items, $pager, 'contact-posts', false);
1626 $o .= $pager->renderMinimal(count($items));
1633 * @brief Returns the account type name
1635 * The function can be called with either the user or the contact array
1637 * @param array $contact contact or user array
1640 public static function getAccountType(array $contact)
1642 // There are several fields that indicate that the contact or user is a forum
1643 // "page-flags" is a field in the user table,
1644 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1645 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1646 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1647 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1648 || (isset($contact['forum']) && intval($contact['forum']))
1649 || (isset($contact['prv']) && intval($contact['prv']))
1650 || (isset($contact['community']) && intval($contact['community']))
1652 $type = self::TYPE_COMMUNITY;
1654 $type = self::TYPE_PERSON;
1657 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1658 if (isset($contact["contact-type"])) {
1659 $type = $contact["contact-type"];
1662 if (isset($contact["account-type"])) {
1663 $type = $contact["account-type"];
1667 case self::TYPE_ORGANISATION:
1668 $account_type = L10n::t("Organisation");
1671 case self::TYPE_NEWS:
1672 $account_type = L10n::t('News');
1675 case self::TYPE_COMMUNITY:
1676 $account_type = L10n::t("Forum");
1684 return $account_type;
1688 * @brief Blocks a contact
1692 * @throws \Exception
1694 public static function block($cid, $reason = null)
1696 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1702 * @brief Unblocks a contact
1706 * @throws \Exception
1708 public static function unblock($cid)
1710 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1716 * @brief Updates the avatar links in a contact only if needed
1718 * @param string $avatar Link to avatar picture
1719 * @param int $uid User id of contact owner
1720 * @param int $cid Contact id
1721 * @param bool $force force picture update
1723 * @return array Returns array of the different avatar sizes
1724 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1725 * @throws \ImagickException
1727 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1729 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1730 if (!DBA::isResult($contact)) {
1733 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1736 if (($contact["avatar"] != $avatar) || $force) {
1737 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1740 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1741 DBA::update('contact', $fields, ['id' => $cid]);
1743 // Update the public contact (contact id = 0)
1745 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1746 if (DBA::isResult($pcontact)) {
1747 DBA::update('contact', $fields, ['id' => $pcontact['id']]);
1759 * @brief Helper function for "updateFromProbe". Updates personal and public contact
1761 * @param array $contact The personal contact entry
1762 * @param array $fields The fields that are updated
1763 * @throws \Exception
1765 private static function updateContact($id, $uid, $url, array $fields)
1767 DBA::update('contact', $fields, ['id' => $id]);
1773 // Archive or unarchive the contact. We only need to do this for the public contact.
1774 // The archive/unarchive function will update the personal contacts by themselves.
1775 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1776 if (!empty($fields['success_update'])) {
1777 self::unmarkForArchival($contact);
1778 } elseif (!empty($fields['failure_update'])) {
1779 self::markForArchival($contact);
1782 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url),
1783 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1785 // These contacts are sharing with us, we don't poll them.
1786 // This means that we don't set the update fields in "OnePoll.php".
1787 $condition['rel'] = self::SHARING;
1788 DBA::update('contact', $fields, $condition);
1790 unset($fields['last-update']);
1791 unset($fields['success_update']);
1792 unset($fields['failure_update']);
1794 if (empty($fields)) {
1798 // We are polling these contacts, so we mustn't set the update fields here.
1799 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1800 DBA::update('contact', $fields, $condition);
1804 * @param integer $id contact id
1805 * @param string $network Optional network we are probing for
1806 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1809 * @throws \ImagickException
1811 public static function updateFromProbe($id, $network = '', $force = false)
1814 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1815 This will reliably kill your communication with old Friendica contacts.
1818 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1819 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1820 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1821 if (!DBA::isResult($contact)) {
1825 $uid = $contact['uid'];
1826 unset($contact['uid']);
1828 $contact['photo'] = $contact['avatar'];
1829 unset($contact['avatar']);
1831 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1833 $updated = DateTimeFormat::utcNow();
1835 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1836 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT) ||
1837 (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network']))) {
1838 if ($force && ($uid == 0)) {
1839 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'failure_update' => $updated]);
1846 // make sure to not overwrite existing values with blank entries
1847 foreach ($ret as $key => $val) {
1848 if (!isset($contact[$key])) {
1850 } elseif (($contact[$key] != '') && ($val == '')) {
1851 $ret[$key] = $contact[$key];
1852 } elseif ($ret[$key] != $contact[$key]) {
1857 self::updateAvatar($ret['photo'], $uid, $id, $update || $force);
1860 if ($force && ($uid == 0)) {
1861 self::updateContact($id, $uid, $ret['url'], ['last-update' => $updated, 'success_update' => $updated]);
1866 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1867 $ret['updated'] = $updated;
1869 if ($force && ($uid == 0)) {
1870 $ret['last-update'] = $updated;
1871 $ret['success_update'] = $updated;
1874 unset($ret['photo']);
1876 self::updateContact($id, $uid, $ret['url'], $ret);
1878 // Update the corresponding gcontact entry
1879 PortableContact::lastUpdated($ret["url"]);
1885 * Detects if a given contact array belongs to a legacy DFRN connection
1887 * @param array $contact
1890 public static function isLegacyDFRNContact($contact)
1892 // Newer Friendica contacts are connected via AP, then these fields aren't set
1893 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1897 * Detects the communication protocol for a given contact url.
1898 * This is used to detect Friendica contacts that we can communicate via AP.
1900 * @param string $url contact url
1901 * @param string $network Network of that contact
1902 * @return string with protocol
1904 public static function getProtocol($url, $network)
1906 if ($network != Protocol::DFRN) {
1910 $apcontact = APContact::getByURL($url);
1911 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1912 return Protocol::ACTIVITYPUB;
1919 * Takes a $uid and a url/handle and adds a new contact
1920 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1921 * dfrn_request page.
1923 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1926 * $return['success'] boolean true if successful
1927 * $return['message'] error text if success is false.
1929 * @brief Takes a $uid and a url/handle and adds a new contact
1931 * @param string $url
1932 * @param bool $interactive
1933 * @param string $network
1935 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1936 * @throws \ImagickException
1938 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1940 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1944 // remove ajax junk, e.g. Twitter
1945 $url = str_replace('/#!/', '/', $url);
1947 if (!Network::isUrlAllowed($url)) {
1948 $result['message'] = L10n::t('Disallowed profile URL.');
1952 if (Network::isUrlBlocked($url)) {
1953 $result['message'] = L10n::t('Blocked domain');
1958 $result['message'] = L10n::t('Connect URL missing.');
1962 $arr = ['url' => $url, 'contact' => []];
1964 Hook::callAll('follow', $arr);
1967 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1971 if (!empty($arr['contact']['name'])) {
1972 $ret = $arr['contact'];
1974 $ret = Probe::uri($url, $network, $uid, false);
1977 if (($network != '') && ($ret['network'] != $network)) {
1978 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1982 // check if we already have a contact
1983 // the poll url is more reliable than the profile url, as we may have
1984 // indirect links or webfinger links
1986 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1987 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1988 if (!DBA::isResult($contact)) {
1989 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1990 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1993 $protocol = self::getProtocol($url, $ret['network']);
1995 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
1997 if (strlen($a->getURLPath())) {
1998 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
2000 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
2003 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
2007 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2008 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
2009 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2013 // This extra param just confuses things, remove it
2014 if ($protocol === Protocol::DIASPORA) {
2015 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2018 // do we have enough information?
2019 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2020 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
2021 if (empty($ret['poll'])) {
2022 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
2024 if (empty($ret['name'])) {
2025 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
2027 if (empty($ret['url'])) {
2028 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
2030 if (strpos($url, '@') !== false) {
2031 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2032 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
2037 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
2038 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2039 $ret['notify'] = '';
2042 if (!$ret['notify']) {
2043 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2046 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2048 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2050 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2052 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
2054 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2058 if (DBA::isResult($contact)) {
2060 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2062 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2063 DBA::update('contact', $fields, ['id' => $contact['id']]);
2065 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2067 // create contact record
2068 DBA::insert('contact', [
2070 'created' => DateTimeFormat::utcNow(),
2071 'url' => $ret['url'],
2072 'nurl' => Strings::normaliseLink($ret['url']),
2073 'addr' => $ret['addr'],
2074 'alias' => $ret['alias'],
2075 'batch' => $ret['batch'],
2076 'notify' => $ret['notify'],
2077 'poll' => $ret['poll'],
2078 'poco' => $ret['poco'],
2079 'name' => $ret['name'],
2080 'nick' => $ret['nick'],
2081 'network' => $ret['network'],
2082 'protocol' => $protocol,
2083 'pubkey' => $ret['pubkey'],
2084 'rel' => $new_relation,
2085 'priority'=> $ret['priority'],
2086 'writable'=> $writeable,
2087 'hidden' => $hidden,
2090 'pending' => $pending,
2095 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2096 if (!DBA::isResult($contact)) {
2097 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2101 $contact_id = $contact['id'];
2102 $result['cid'] = $contact_id;
2104 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2106 // Update the avatar
2107 self::updateAvatar($ret['photo'], $uid, $contact_id);
2109 // pull feed and consume it, which should subscribe to the hub.
2111 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2113 $owner = User::getOwnerDataById($uid);
2115 if (DBA::isResult($owner)) {
2116 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2117 // create a follow slap
2119 $item['verb'] = ACTIVITY_FOLLOW;
2120 $item['follow'] = $contact["url"];
2122 $item['title'] = '';
2125 $item['attach'] = '';
2127 $slap = OStatus::salmon($item, $owner);
2129 if (!empty($contact['notify'])) {
2130 Salmon::slapper($owner, $contact['notify'], $slap);
2132 } elseif ($protocol == Protocol::DIASPORA) {
2133 $ret = Diaspora::sendShare($a->user, $contact);
2134 Logger::log('share returns: ' . $ret);
2135 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2136 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2137 if (empty($activity_id)) {
2138 // This really should never happen
2142 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2143 Logger::log('Follow returns: ' . $ret);
2147 $result['success'] = true;
2152 * @brief Updated contact's SSL policy
2154 * @param array $contact Contact array
2155 * @param string $new_policy New policy, valid: self,full
2157 * @return array Contact array with updated values
2158 * @throws \Exception
2160 public static function updateSslPolicy(array $contact, $new_policy)
2162 $ssl_changed = false;
2163 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2164 $ssl_changed = true;
2165 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2166 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2167 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2168 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2169 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2170 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2173 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2174 $ssl_changed = true;
2175 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2176 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2177 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2178 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2179 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2180 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2184 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2185 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2186 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2187 DBA::update('contact', $fields, ['id' => $contact['id']]);
2194 * @param array $importer Owner (local user) data
2195 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2196 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2197 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2198 * @param string $note Introduction additional message
2199 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2201 * @throws \ImagickException
2203 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2205 // Should always be set
2206 if (empty($datarray['author-id'])) {
2210 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2211 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2212 if (!DBA::isResult($pub_contact)) {
2213 // Should never happen
2217 // Contact is blocked at node-level
2218 if (self::isBlocked($datarray['author-id'])) {
2222 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2223 $name = $pub_contact['name'];
2224 $photo = defaults($pub_contact, 'avatar', $pub_contact["photo"]);
2225 $nick = $pub_contact['nick'];
2226 $network = $pub_contact['network'];
2228 if (!empty($contact)) {
2229 // Contact is blocked at user-level
2230 if (!empty($contact['id']) && !empty($importer['id']) &&
2231 self::isBlockedByUser($contact['id'], $importer['id'])) {
2235 // Make sure that the existing contact isn't archived
2236 self::unmarkForArchival($contact);
2238 if (($contact['rel'] == self::SHARING)
2239 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2240 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2241 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2246 // send email notification to owner?
2247 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2248 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2252 // create contact record
2253 DBA::insert('contact', [
2254 'uid' => $importer['uid'],
2255 'created' => DateTimeFormat::utcNow(),
2257 'nurl' => Strings::normaliseLink($url),
2261 'network' => $network,
2262 'rel' => self::FOLLOWER,
2270 'id' => DBA::lastInsertId(),
2271 'network' => $network,
2277 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2279 /// @TODO Encapsulate this into a function/method
2280 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2281 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2282 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2283 // create notification
2284 $hash = Strings::getRandomHex();
2286 if (is_array($contact_record)) {
2287 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2288 'blocked' => false, 'knowyou' => false, 'note' => $note,
2289 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2292 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2294 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2295 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2298 'type' => NOTIFY_INTRO,
2299 'notify_flags' => $user['notify-flags'],
2300 'language' => $user['language'],
2301 'to_name' => $user['username'],
2302 'to_email' => $user['email'],
2303 'uid' => $user['uid'],
2304 'link' => System::baseUrl() . '/notifications/intro',
2305 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2306 'source_link' => $contact_record['url'],
2307 'source_photo' => $contact_record['photo'],
2308 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2312 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2313 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2314 DBA::update('contact', ['pending' => false], $condition);
2323 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2325 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2326 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2328 Contact::remove($contact['id']);
2332 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2334 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2335 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2337 Contact::remove($contact['id']);
2342 * @brief Create a birthday event.
2344 * Update the year and the birthday.
2346 public static function updateBirthdays()
2350 AND `bd` > "0001-01-01"
2351 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2352 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2353 AND NOT `contact`.`pending`
2354 AND NOT `contact`.`hidden`
2355 AND NOT `contact`.`blocked`
2356 AND NOT `contact`.`archive`
2357 AND NOT `contact`.`deleted`',
2362 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2364 while ($contact = DBA::fetch($contacts)) {
2365 Logger::log('update_contact_birthday: ' . $contact['bd']);
2367 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2369 if (Event::createBirthday($contact, $nextbd)) {
2373 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2374 ['id' => $contact['id']]
2381 * Remove the unavailable contact ids from the provided list
2383 * @param array $contact_ids Contact id list
2384 * @throws \Exception
2386 public static function pruneUnavailable(array &$contact_ids)
2388 if (empty($contact_ids)) {
2392 $str = DBA::escape(implode(',', $contact_ids));
2394 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2397 while($contact = DBA::fetch($stmt)) {
2398 $return[] = $contact['id'];
2403 $contact_ids = $return;
2407 * @brief Returns a magic link to authenticate remote visitors
2409 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2411 * @param string $contact_url The address of the target contact profile
2412 * @param string $url An url that we will be redirected to after the authentication
2414 * @return string with "redir" link
2415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2416 * @throws \ImagickException
2418 public static function magicLink($contact_url, $url = '')
2420 if (!local_user() && !remote_user()) {
2421 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2424 $data = self::getProbeDataFromDatabase($contact_url);
2426 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2429 // Prevents endless loop in case only a non-public contact exists for the contact URL
2430 unset($data['uid']);
2432 return self::magicLinkByContact($data, $contact_url);
2436 * @brief Returns a magic link to authenticate remote visitors
2438 * @param integer $cid The contact id of the target contact profile
2439 * @param string $url An url that we will be redirected to after the authentication
2441 * @return string with "redir" link
2442 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2443 * @throws \ImagickException
2445 public static function magicLinkbyId($cid, $url = '')
2447 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2449 return self::magicLinkByContact($contact, $url);
2453 * @brief Returns a magic link to authenticate remote visitors
2455 * @param array $contact The contact array with "uid", "network" and "url"
2456 * @param string $url An url that we will be redirected to after the authentication
2458 * @return string with "redir" link
2459 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2460 * @throws \ImagickException
2462 public static function magicLinkByContact($contact, $url = '')
2464 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2465 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2468 // Only redirections to the same host do make sense
2469 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2473 if (!empty($contact['uid'])) {
2474 return self::magicLink($contact['url'], $url);
2477 if (empty($contact['id'])) {
2478 return $url ?: $contact['url'];
2481 $redirect = 'redir/' . $contact['id'];
2484 $redirect .= '?url=' . $url;
2491 * Remove a contact from all groups
2493 * @param integer $contact_id
2495 * @return boolean Success
2497 public static function removeFromGroups($contact_id)
2499 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2503 * Is the contact a forum?
2505 * @param integer $contactid ID of the contact
2507 * @return boolean "true" if it is a forum
2509 public static function isForum($contactid)
2511 $fields = ['forum', 'prv'];
2512 $condition = ['id' => $contactid];
2513 $contact = DBA::selectFirst('contact', $fields, $condition);
2514 if (!DBA::isResult($contact)) {
2519 return ($contact['forum'] || $contact['prv']);
2523 * Can the remote contact receive private messages?
2525 * @param array $contact
2528 public static function canReceivePrivateMessages(array $contact)
2530 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2531 $self = $contact['self'] ?? false;
2533 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;