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 integer $id Contact ID
129 * @param array $fields Array of selected fields, empty for all
130 * @return array|boolean Contact record if it exists, false otherwise
133 public static function getById($id, $fields = [])
135 return DBA::selectFirst('contact', $fields, ['id' => $id]);
139 * @brief Tests if the given contact is a follower
141 * @param int $cid Either public contact id or user's contact id
142 * @param int $uid User ID
144 * @return boolean is the contact id a follower?
145 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
146 * @throws \ImagickException
148 public static function isFollower($cid, $uid)
150 if (self::isBlockedByUser($cid, $uid)) {
154 $cdata = self::getPublicAndUserContacID($cid, $uid);
155 if (empty($cdata['user'])) {
159 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
160 return DBA::exists('contact', $condition);
164 * @brief Get the basepath for a given contact link
165 * @todo Add functionality to store this value in the contact table
167 * @param string $url The contact link
169 * @return string basepath
170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
171 * @throws \ImagickException
173 public static function getBasepath($url)
175 $data = Probe::uri($url);
176 if (!empty($data['baseurl'])) {
177 return $data['baseurl'];
180 // When we can't probe the server, we use some ugly function that does some pattern matching
181 return PortableContact::detectServer($url);
185 * Returns the public contact id of the given user id
187 * @param integer $uid User ID
189 * @return integer|boolean Public contact id for given user id
192 public static function getPublicIdByUserId($uid)
194 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
195 if (!DBA::isResult($self)) {
198 return self::getIdForURL($self['url'], 0, true);
202 * @brief Returns the contact id for the user and the public contact id for a given contact id
204 * @param int $cid Either public contact id or user's contact id
205 * @param int $uid User ID
207 * @return array with public and user's contact id
208 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
209 * @throws \ImagickException
211 public static function getPublicAndUserContacID($cid, $uid)
213 if (empty($uid) || empty($cid)) {
217 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
218 if (!DBA::isResult($contact)) {
222 // We quit when the user id don't match the user id of the provided contact
223 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
227 if ($contact['uid'] != 0) {
228 $pcid = Contact::getIdForURL($contact['url'], 0, true, ['url' => $contact['url']]);
232 $ucid = $contact['id'];
234 $pcid = $contact['id'];
235 $ucid = Contact::getIdForURL($contact['url'], $uid, true);
238 return ['public' => $pcid, 'user' => $ucid];
242 * Returns contact details for a given contact id in combination with a user id
244 * @param int $cid A contact ID
245 * @param int $uid The User ID
246 * @param array $fields The selected fields for the contact
248 * @return array The contact details
252 public static function getContactForUser($cid, $uid, array $fields = [])
254 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
256 if (!DBA::isResult($contact)) {
264 * @brief Block contact id for user id
266 * @param int $cid Either public contact id or user's contact id
267 * @param int $uid User ID
268 * @param boolean $blocked Is the contact blocked or unblocked?
271 public static function setBlockedForUser($cid, $uid, $blocked)
273 $cdata = self::getPublicAndUserContacID($cid, $uid);
278 if ($cdata['user'] != 0) {
279 DBA::update('contact', ['blocked' => $blocked], ['id' => $cdata['user'], 'pending' => false]);
282 DBA::update('user-contact', ['blocked' => $blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
285 // Blocked contact can't be in any group
286 self::removeFromGroups($cid);
291 * @brief Returns "block" state for contact id and user id
293 * @param int $cid Either public contact id or user's contact id
294 * @param int $uid User ID
296 * @return boolean is the contact id blocked for the given user?
299 public static function isBlockedByUser($cid, $uid)
301 $cdata = self::getPublicAndUserContacID($cid, $uid);
306 $public_blocked = false;
308 if (!empty($cdata['public'])) {
309 $public_contact = DBA::selectFirst('user-contact', ['blocked'], ['cid' => $cdata['public'], 'uid' => $uid]);
310 if (DBA::isResult($public_contact)) {
311 $public_blocked = $public_contact['blocked'];
315 $user_blocked = $public_blocked;
317 if (!empty($cdata['user'])) {
318 $user_contact = DBA::selectFirst('contact', ['blocked'], ['id' => $cdata['user'], 'pending' => false]);
319 if (DBA::isResult($user_contact)) {
320 $user_blocked = $user_contact['blocked'];
324 if ($user_blocked != $public_blocked) {
325 DBA::update('user-contact', ['blocked' => $user_blocked], ['cid' => $cdata['public'], 'uid' => $uid], true);
328 return $user_blocked;
332 * @brief Ignore contact id for user id
334 * @param int $cid Either public contact id or user's contact id
335 * @param int $uid User ID
336 * @param boolean $ignored Is the contact ignored or unignored?
339 public static function setIgnoredForUser($cid, $uid, $ignored)
341 $cdata = self::getPublicAndUserContacID($cid, $uid);
346 if ($cdata['user'] != 0) {
347 DBA::update('contact', ['readonly' => $ignored], ['id' => $cdata['user'], 'pending' => false]);
350 DBA::update('user-contact', ['ignored' => $ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
354 * @brief Returns "ignore" state for contact id and user id
356 * @param int $cid Either public contact id or user's contact id
357 * @param int $uid User ID
359 * @return boolean is the contact id ignored for the given user?
362 public static function isIgnoredByUser($cid, $uid)
364 $cdata = self::getPublicAndUserContacID($cid, $uid);
369 $public_ignored = false;
371 if (!empty($cdata['public'])) {
372 $public_contact = DBA::selectFirst('user-contact', ['ignored'], ['cid' => $cdata['public'], 'uid' => $uid]);
373 if (DBA::isResult($public_contact)) {
374 $public_ignored = $public_contact['ignored'];
378 $user_ignored = $public_ignored;
380 if (!empty($cdata['user'])) {
381 $user_contact = DBA::selectFirst('contact', ['readonly'], ['id' => $cdata['user'], 'pending' => false]);
382 if (DBA::isResult($user_contact)) {
383 $user_ignored = $user_contact['readonly'];
387 if ($user_ignored != $public_ignored) {
388 DBA::update('user-contact', ['ignored' => $user_ignored], ['cid' => $cdata['public'], 'uid' => $uid], true);
391 return $user_ignored;
395 * @brief Set "collapsed" for contact id and user id
397 * @param int $cid Either public contact id or user's contact id
398 * @param int $uid User ID
399 * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
402 public static function setCollapsedForUser($cid, $uid, $collapsed)
404 $cdata = self::getPublicAndUserContacID($cid, $uid);
409 DBA::update('user-contact', ['collapsed' => $collapsed], ['cid' => $cdata['public'], 'uid' => $uid], true);
413 * @brief Returns "collapsed" state for contact id and user id
415 * @param int $cid Either public contact id or user's contact id
416 * @param int $uid User ID
418 * @return boolean is the contact id blocked for the given user?
419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 * @throws \ImagickException
422 public static function isCollapsedByUser($cid, $uid)
424 $cdata = self::getPublicAndUserContacID($cid, $uid);
431 if (!empty($cdata['public'])) {
432 $public_contact = DBA::selectFirst('user-contact', ['collapsed'], ['cid' => $cdata['public'], 'uid' => $uid]);
433 if (DBA::isResult($public_contact)) {
434 $collapsed = $public_contact['collapsed'];
442 * @brief Returns a list of contacts belonging in a group
448 public static function getByGroupId($gid)
453 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
455 INNER JOIN `group_member`
456 ON `contact`.`id` = `group_member`.`contact-id`
458 AND `contact`.`uid` = ?
459 AND NOT `contact`.`self`
460 AND NOT `contact`.`deleted`
461 AND NOT `contact`.`blocked`
462 AND NOT `contact`.`pending`
463 ORDER BY `contact`.`name` ASC',
468 if (DBA::isResult($stmt)) {
469 $return = DBA::toArray($stmt);
477 * @brief Returns the count of OStatus contacts in a group
483 public static function getOStatusCountByGroupId($gid)
487 $contacts = DBA::fetchFirst('SELECT COUNT(*) AS `count`
489 INNER JOIN `group_member`
490 ON `contact`.`id` = `group_member`.`contact-id`
492 AND `contact`.`uid` = ?
493 AND `contact`.`network` = ?
494 AND `contact`.`notify` != ""',
499 $return = $contacts['count'];
506 * Creates the self-contact for the provided user id
509 * @return bool Operation success
510 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
512 public static function createSelfFromUserId($uid)
514 // Only create the entry if it doesn't exist yet
515 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
519 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
520 if (!DBA::isResult($user)) {
524 $return = DBA::insert('contact', [
525 'uid' => $user['uid'],
526 'created' => DateTimeFormat::utcNow(),
528 'name' => $user['username'],
529 'nick' => $user['nickname'],
530 'photo' => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
531 'thumb' => System::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
532 'micro' => System::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
535 'url' => System::baseUrl() . '/profile/' . $user['nickname'],
536 'nurl' => Strings::normaliseLink(System::baseUrl() . '/profile/' . $user['nickname']),
537 'addr' => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
538 'request' => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
539 'notify' => System::baseUrl() . '/dfrn_notify/' . $user['nickname'],
540 'poll' => System::baseUrl() . '/dfrn_poll/' . $user['nickname'],
541 'confirm' => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
542 'poco' => System::baseUrl() . '/poco/' . $user['nickname'],
543 'name-date' => DateTimeFormat::utcNow(),
544 'uri-date' => DateTimeFormat::utcNow(),
545 'avatar-date' => DateTimeFormat::utcNow(),
553 * Updates the self-contact for the provided user id
556 * @param boolean $update_avatar Force the avatar update
557 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
559 public static function updateSelfFromUserID($uid, $update_avatar = false)
561 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'gender', 'avatar',
562 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl',
563 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
564 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
565 if (!DBA::isResult($self)) {
569 $fields = ['nickname', 'page-flags', 'account-type'];
570 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
571 if (!DBA::isResult($user)) {
575 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
576 'country-name', 'gender', 'pub_keywords', 'xmpp'];
577 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
578 if (!DBA::isResult($profile)) {
582 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
583 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
584 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
585 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
586 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
588 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
589 if (DBA::isResult($avatar)) {
590 if ($update_avatar) {
591 $fields['avatar-date'] = DateTimeFormat::utcNow();
594 // Creating the path to the avatar, beginning with the file suffix
595 $types = Image::supportedTypes();
596 if (isset($types[$avatar['type']])) {
597 $file_suffix = $types[$avatar['type']];
599 $file_suffix = 'jpg';
602 // We are adding a timestamp value so that other systems won't use cached content
603 $timestamp = strtotime($fields['avatar-date']);
605 $prefix = System::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
606 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
608 $fields['photo'] = $prefix . '4' . $suffix;
609 $fields['thumb'] = $prefix . '5' . $suffix;
610 $fields['micro'] = $prefix . '6' . $suffix;
612 // We hadn't found a photo entry, so we use the default avatar
613 $fields['photo'] = System::baseUrl() . '/images/person-300.jpg';
614 $fields['thumb'] = System::baseUrl() . '/images/person-80.jpg';
615 $fields['micro'] = System::baseUrl() . '/images/person-48.jpg';
618 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
619 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
621 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
622 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
623 $fields['nurl'] = Strings::normaliseLink($fields['url']);
624 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
625 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
626 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
627 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
628 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
629 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
633 foreach ($fields as $field => $content) {
634 if ($self[$field] != $content) {
640 if ($fields['name'] != $self['name']) {
641 $fields['name-date'] = DateTimeFormat::utcNow();
643 $fields['updated'] = DateTimeFormat::utcNow();
644 DBA::update('contact', $fields, ['id' => $self['id']]);
646 // Update the public contact as well
647 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
649 // Update the profile
650 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
651 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
652 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
657 * @brief Marks a contact for removal
659 * @param int $id contact id
661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
663 public static function remove($id)
665 // We want just to make sure that we don't delete our "self" contact
666 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
667 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
671 // Archive the contact
672 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
674 // Delete it in the background
675 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
679 * @brief Sends an unfriend message. Does not remove the contact
681 * @param array $user User unfriending
682 * @param array $contact Contact unfriended
683 * @param boolean $dissolve Remove the contact on the remote side
685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
686 * @throws \ImagickException
688 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
690 if (empty($contact['network'])) {
694 $protocol = $contact['network'];
695 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
696 $protocol = Protocol::ACTIVITYPUB;
699 if (($protocol == Protocol::DFRN) && $dissolve) {
700 DFRN::deliver($user, $contact, 'placeholder', true);
701 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
702 // create an unfollow slap
704 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
705 $item['follow'] = $contact["url"];
710 $item['attach'] = '';
711 $slap = OStatus::salmon($item, $user);
713 if (!empty($contact['notify'])) {
714 Salmon::slapper($user, $contact['notify'], $slap);
716 } elseif ($protocol == Protocol::DIASPORA) {
717 Diaspora::sendUnshare($user, $contact);
718 } elseif ($protocol == Protocol::ACTIVITYPUB) {
719 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
722 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
728 * @brief Marks a contact for archival after a communication issue delay
730 * Contact has refused to recognise us as a friend. We will start a countdown.
731 * If they still don't recognise us in 32 days, the relationship is over,
732 * and we won't waste any more time trying to communicate with them.
733 * This provides for the possibility that their database is temporarily messed
734 * up or some other transient event and that there's a possibility we could recover from it.
736 * @param array $contact contact to mark for archival
738 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
740 public static function markForArchival(array $contact)
742 if (!isset($contact['url']) && !empty($contact['id'])) {
743 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
744 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
745 if (!DBA::isResult($contact)) {
748 } elseif (!isset($contact['url'])) {
749 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
752 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
754 // Contact already archived or "self" contact? => nothing to do
755 if ($contact['archive'] || $contact['self']) {
759 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
760 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
761 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
764 * We really should send a notification to the owner after 2-3 weeks
765 * so they won't be surprised when the contact vanishes and can take
766 * remedial action if this was a serious mistake or glitch
769 /// @todo Check for contact vitality via probing
770 $archival_days = Config::get('system', 'archival_days', 32);
772 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
773 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
774 /* Relationship is really truly dead. archive them rather than
775 * delete, though if the owner tries to unarchive them we'll start
776 * the whole process over again.
778 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
779 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
785 * @brief Cancels the archival countdown
787 * @see Contact::markForArchival()
789 * @param array $contact contact to be unmarked for archival
793 public static function unmarkForArchival(array $contact)
795 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
796 $exists = DBA::exists('contact', $condition);
798 // We don't need to update, we never marked this contact for archival
803 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
805 if (!isset($contact['url']) && !empty($contact['id'])) {
806 $fields = ['id', 'url', 'batch'];
807 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
808 if (!DBA::isResult($contact)) {
813 // It's a miracle. Our dead contact has inexplicably come back to life.
814 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
815 DBA::update('contact', $fields, ['id' => $contact['id']]);
816 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
818 if (!empty($contact['batch'])) {
819 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
820 DBA::update('contact', $fields, $condition);
825 * @brief Get contact data for a given profile link
827 * The function looks at several places (contact table and gcontact table) for the contact
828 * It caches its result for the same script execution to prevent duplicate calls
830 * @param string $url The profile link
831 * @param int $uid User id
832 * @param array $default If not data was found take this data as default value
834 * @return array Contact data
835 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
837 public static function getDetailsByURL($url, $uid = -1, array $default = [])
849 if (isset($cache[$url][$uid])) {
850 return $cache[$url][$uid];
853 $ssl_url = str_replace('http://', 'https://', $url);
855 // Fetch contact data from the contact table for the given user
856 $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`,
857 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
858 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
859 $r = DBA::toArray($s);
861 // Fetch contact data from the contact table for the given user, checking with the alias
862 if (!DBA::isResult($r)) {
863 $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`,
864 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
865 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
866 $r = DBA::toArray($s);
869 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
870 if (!DBA::isResult($r)) {
871 $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`,
872 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
873 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
874 $r = DBA::toArray($s);
877 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
878 if (!DBA::isResult($r)) {
879 $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`,
880 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
881 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
882 $r = DBA::toArray($s);
885 // Fetch the data from the gcontact table
886 if (!DBA::isResult($r)) {
887 $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`,
888 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
889 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
890 $r = DBA::toArray($s);
893 if (DBA::isResult($r)) {
894 // If there is more than one entry we filter out the connector networks
896 foreach ($r as $id => $result) {
897 if ($result["network"] == Protocol::STATUSNET) {
903 $profile = array_shift($r);
905 // "bd" always contains the upcoming birthday of a contact.
906 // "birthday" might contain the birthday including the year of birth.
907 if ($profile["birthday"] > DBA::NULL_DATE) {
908 $bd_timestamp = strtotime($profile["birthday"]);
909 $month = date("m", $bd_timestamp);
910 $day = date("d", $bd_timestamp);
912 $current_timestamp = time();
913 $current_year = date("Y", $current_timestamp);
914 $current_month = date("m", $current_timestamp);
915 $current_day = date("d", $current_timestamp);
917 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
918 $current = $current_year . "-" . $current_month . "-" . $current_day;
920 if ($profile["bd"] < $current) {
921 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
924 $profile["bd"] = DBA::NULL_DATE;
930 if (empty($profile["photo"]) && isset($default["photo"])) {
931 $profile["photo"] = $default["photo"];
934 if (empty($profile["name"]) && isset($default["name"])) {
935 $profile["name"] = $default["name"];
938 if (empty($profile["network"]) && isset($default["network"])) {
939 $profile["network"] = $default["network"];
942 if (empty($profile["thumb"]) && isset($profile["photo"])) {
943 $profile["thumb"] = $profile["photo"];
946 if (empty($profile["micro"]) && isset($profile["thumb"])) {
947 $profile["micro"] = $profile["thumb"];
950 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
951 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
953 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
956 // Show contact details of Diaspora contacts only if connected
957 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
958 $profile["location"] = "";
959 $profile["about"] = "";
960 $profile["gender"] = "";
961 $profile["birthday"] = DBA::NULL_DATE;
964 $cache[$url][$uid] = $profile;
970 * @brief Get contact data for a given address
972 * The function looks at several places (contact table and gcontact table) for the contact
974 * @param string $addr The profile link
975 * @param int $uid User id
977 * @return array Contact data
978 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
979 * @throws \ImagickException
981 public static function getDetailsByAddr($addr, $uid = -1)
991 // Fetch contact data from the contact table for the given user
992 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
993 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
994 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
998 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
999 if (!DBA::isResult($r)) {
1000 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1001 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1002 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1007 // Fetch the data from the gcontact table
1008 if (!DBA::isResult($r)) {
1009 $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`,
1010 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1011 FROM `gcontact` WHERE `addr` = '%s'",
1016 if (!DBA::isResult($r)) {
1017 $data = Probe::uri($addr);
1019 $profile = self::getDetailsByURL($data['url'], $uid);
1028 * @brief Returns the data array for the photo menu of a given contact
1030 * @param array $contact contact
1031 * @param int $uid optional, default 0
1033 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1034 * @throws \ImagickException
1036 public static function photoMenu(array $contact, $uid = 0)
1041 $contact_drop_link = '';
1045 $uid = local_user();
1048 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1050 $profile_link = self::magicLink($contact['url']);
1051 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1056 // Look for our own contact if the uid doesn't match and isn't public
1057 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1058 if (DBA::isResult($contact_own)) {
1059 return self::photoMenu($contact_own, $uid);
1064 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1066 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1068 $profile_link = $contact['url'];
1071 if ($profile_link === 'mailbox') {
1076 $status_link = $profile_link . '?tab=status';
1077 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1078 $profile_link = $profile_link . '?tab=profile';
1081 if (in_array($contact['network'], [Protocol::DFRN, Protocol::DIASPORA]) && !$contact['self']) {
1082 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1085 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1086 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1089 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1091 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1093 if (!$contact['self']) {
1094 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1099 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1101 if (empty($contact['uid'])) {
1102 $connlnk = 'follow/?url=' . $contact['url'];
1104 'profile' => [L10n::t('View Profile'), $profile_link, true],
1105 'network' => [L10n::t('Network Posts'), $posts_link, false],
1106 'edit' => [L10n::t('View Contact'), $contact_url, false],
1107 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1111 'status' => [L10n::t('View Status'), $status_link, true],
1112 'profile' => [L10n::t('View Profile'), $profile_link, true],
1113 'photos' => [L10n::t('View Photos'), $photos_link, true],
1114 'network' => [L10n::t('Network Posts'), $posts_link, false],
1115 'edit' => [L10n::t('View Contact'), $contact_url, false],
1116 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1117 'pm' => [L10n::t('Send PM'), $pm_url, false],
1118 'poke' => [L10n::t('Poke'), $poke_link, false],
1122 $args = ['contact' => $contact, 'menu' => &$menu];
1124 Hook::callAll('contact_photo_menu', $args);
1126 $menucondensed = [];
1128 foreach ($menu as $menuname => $menuitem) {
1129 if ($menuitem[1] != '') {
1130 $menucondensed[$menuname] = $menuitem;
1134 return $menucondensed;
1138 * @brief Returns ungrouped contact count or list for user
1140 * Returns either the total number of ungrouped contacts for the given user
1141 * id or a paginated list of ungrouped contacts.
1143 * @param int $uid uid
1145 * @throws \Exception
1147 public static function getUngroupedList($uid)
1157 SELECT DISTINCT(`contact-id`)
1159 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1160 WHERE `group`.`uid` = %d
1161 )", intval($uid), intval($uid));
1165 * Have a look at all contact tables for a given profile url.
1166 * This function works as a replacement for probing the contact.
1168 * @param string $url Contact URL
1169 * @param integer $cid Contact ID
1171 * @return array Contact array in the "probe" structure
1173 private static function getProbeDataFromDatabase($url, $cid = null)
1175 // The link could be provided as http although we stored it as https
1176 $ssl_url = str_replace('http://', 'https://', $url);
1178 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1179 'photo', 'keywords', 'location', 'about', 'network',
1180 'priority', 'batch', 'request', 'confirm', 'poco'];
1183 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1184 if (DBA::isResult($data)) {
1189 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1191 if (!DBA::isResult($data)) {
1192 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1193 $data = DBA::selectFirst('contact', $fields, $condition);
1196 if (DBA::isResult($data)) {
1197 // For security reasons we don't fetch key data from our users
1198 $data["pubkey"] = '';
1202 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1203 'photo', 'keywords', 'location', 'about', 'network'];
1204 $data = DBA::selectFirst('gcontact', $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 $data["pubkey"] = '';
1214 $data["priority"] = 0;
1215 $data["batch"] = '';
1216 $data["request"] = '';
1217 $data["confirm"] = '';
1222 $data = ActivityPub::probeProfile($url, false);
1223 if (!empty($data)) {
1227 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1228 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1229 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1231 if (!DBA::isResult($data)) {
1232 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1233 $data = DBA::selectFirst('contact', $fields, $condition);
1236 if (DBA::isResult($data)) {
1237 $data["pubkey"] = '';
1238 $data["keywords"] = '';
1239 $data["location"] = '';
1240 $data["about"] = '';
1249 * @brief Fetch the contact id for a given URL and user
1251 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1252 * `addr` or `alias`.
1254 * If there's no record and we aren't looking for a public contact, we quit.
1255 * If there's one, we check that it isn't time to update the picture else we
1256 * directly return the found contact id.
1258 * Second, we probe the provided $url whether it's http://server.tld/profile or
1259 * nick@server.tld. We quit if we can't get any info back.
1261 * Third, we create the contact record if it doesn't exist
1263 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1264 * if there's any updates
1266 * @param string $url Contact URL
1267 * @param integer $uid The user id for the contact (0 = public contact)
1268 * @param boolean $no_update Don't update the contact
1269 * @param array $default Default value for creating the contact when every else fails
1270 * @param boolean $in_loop Internally used variable to prevent an endless loop
1272 * @return integer Contact ID
1273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1274 * @throws \ImagickException
1276 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1278 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1286 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1287 // We first try the nurl (http://server.tld/nick), most common case
1288 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1290 // Then the addr (nick@server.tld)
1291 if (!DBA::isResult($contact)) {
1292 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1295 // Then the alias (which could be anything)
1296 if (!DBA::isResult($contact)) {
1297 // The link could be provided as http although we stored it as https
1298 $ssl_url = str_replace('http://', 'https://', $url);
1299 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1300 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1303 if (DBA::isResult($contact)) {
1304 $contact_id = $contact["id"];
1306 // Update the contact every 7 days
1307 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1309 // We force the update if the avatar is empty
1310 if (empty($contact['avatar'])) {
1311 $update_contact = true;
1314 // Update the contact in the background if needed but it is called by the frontend
1315 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1316 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1319 if (!$update_contact || $no_update) {
1322 } elseif ($uid != 0) {
1323 // Non-existing user-specific contact, exiting
1327 // When we don't want to update, we look if we know this contact in any way
1328 if ($no_update && empty($default)) {
1329 $data = self::getProbeDataFromDatabase($url, $contact_id);
1330 $background_update = true;
1333 $background_update = false;
1337 $data = Probe::uri($url, "", $uid);
1339 // Ensure that there is a gserver entry
1340 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1341 PortableContact::checkServer($data['baseurl']);
1345 // Last try in gcontact for unsupported networks
1346 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1351 $contact = array_merge(self::getProbeDataFromDatabase($url, $contact_id), $default);
1352 if (empty($contact)) {
1356 $data = array_merge($data, $contact);
1363 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1364 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1370 'created' => DateTimeFormat::utcNow(),
1371 'url' => $data['url'],
1372 'nurl' => Strings::normaliseLink($data['url']),
1373 'addr' => defaults($data, 'addr', ''),
1374 'alias' => defaults($data, 'alias', ''),
1375 'notify' => defaults($data, 'notify', ''),
1376 'poll' => defaults($data, 'poll', ''),
1377 'name' => defaults($data, 'name', ''),
1378 'nick' => defaults($data, 'nick', ''),
1379 'photo' => defaults($data, 'photo', ''),
1380 'keywords' => defaults($data, 'keywords', ''),
1381 'location' => defaults($data, 'location', ''),
1382 'about' => defaults($data, 'about', ''),
1383 'network' => $data['network'],
1384 'pubkey' => defaults($data, 'pubkey', ''),
1385 'rel' => self::SHARING,
1386 'priority' => defaults($data, 'priority', 0),
1387 'batch' => defaults($data, 'batch', ''),
1388 'request' => defaults($data, 'request', ''),
1389 'confirm' => defaults($data, 'confirm', ''),
1390 'poco' => defaults($data, 'poco', ''),
1391 'name-date' => DateTimeFormat::utcNow(),
1392 'uri-date' => DateTimeFormat::utcNow(),
1393 'avatar-date' => DateTimeFormat::utcNow(),
1399 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1401 DBA::update('contact', $fields, $condition, true);
1403 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1404 $contacts = DBA::toArray($s);
1405 if (!DBA::isResult($contacts)) {
1409 $contact_id = $contacts[0]["id"];
1411 // Update in the background when we fetched the data solely from the database
1412 if ($background_update) {
1413 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1416 // Update the newly created contact from data in the gcontact table
1417 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1418 if (DBA::isResult($gcontact)) {
1419 // Only use the information when the probing hadn't fetched these values
1420 if (!empty($data['keywords'])) {
1421 unset($gcontact['keywords']);
1423 if (!empty($data['location'])) {
1424 unset($gcontact['location']);
1426 if (!empty($data['about'])) {
1427 unset($gcontact['about']);
1429 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1432 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1433 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1434 Strings::normaliseLink($data["url"]), 0, $contact_id];
1435 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1436 DBA::delete('contact', $condition);
1440 if (!empty($data['photo'])) {
1441 self::updateAvatar($data['photo'], $uid, $contact_id);
1444 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1445 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1447 // This condition should always be true
1448 if (!DBA::isResult($contact)) {
1452 $updated = ['addr' => $data['addr'],
1453 'alias' => defaults($data, 'alias', ''),
1454 'url' => $data['url'],
1455 'nurl' => Strings::normaliseLink($data['url']),
1456 'name' => $data['name'],
1457 'nick' => $data['nick']];
1459 if (!empty($data['keywords'])) {
1460 $updated['keywords'] = $data['keywords'];
1462 if (!empty($data['location'])) {
1463 $updated['location'] = $data['location'];
1466 // Update the technical stuff as well - if filled
1467 if (!empty($data['notify'])) {
1468 $updated['notify'] = $data['notify'];
1470 if (!empty($data['poll'])) {
1471 $updated['poll'] = $data['poll'];
1473 if (!empty($data['batch'])) {
1474 $updated['batch'] = $data['batch'];
1476 if (!empty($data['request'])) {
1477 $updated['request'] = $data['request'];
1479 if (!empty($data['confirm'])) {
1480 $updated['confirm'] = $data['confirm'];
1482 if (!empty($data['poco'])) {
1483 $updated['poco'] = $data['poco'];
1486 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1487 if (empty($contact['pubkey'])) {
1488 $updated['pubkey'] = $data['pubkey'];
1491 if (($data['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1492 $updated['uri-date'] = DateTimeFormat::utcNow();
1494 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1495 $updated['name-date'] = DateTimeFormat::utcNow();
1498 $updated['updated'] = DateTimeFormat::utcNow();
1500 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1506 * @brief Checks if the contact is blocked
1508 * @param int $cid contact id
1510 * @return boolean Is the contact blocked?
1511 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1513 public static function isBlocked($cid)
1519 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1520 if (!DBA::isResult($blocked)) {
1524 if (Network::isUrlBlocked($blocked['url'])) {
1528 return (bool) $blocked['blocked'];
1532 * @brief Checks if the contact is hidden
1534 * @param int $cid contact id
1536 * @return boolean Is the contact hidden?
1537 * @throws \Exception
1539 public static function isHidden($cid)
1545 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1546 if (!DBA::isResult($hidden)) {
1549 return (bool) $hidden['hidden'];
1553 * @brief Returns posts from a given contact url
1555 * @param string $contact_url Contact URL
1557 * @param bool $thread_mode
1558 * @param int $update
1559 * @return string posts in HTML
1560 * @throws \Exception
1562 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1564 $a = self::getApp();
1566 $cid = self::getIdForURL($contact_url);
1568 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1569 if (!DBA::isResult($contact)) {
1573 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1574 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1576 $sql = "`item`.`uid` = ?";
1579 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1582 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1583 $cid, GRAVITY_PARENT, local_user()];
1585 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1586 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1589 $pager = new Pager($a->query_string);
1591 $params = ['order' => ['created' => true],
1592 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1595 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1597 $items = Item::inArray($r);
1599 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1601 $r = Item::selectForUser(local_user(), [], $condition, $params);
1603 $items = Item::inArray($r);
1605 $o = conversation($a, $items, $pager, 'contact-posts', false);
1609 $o .= $pager->renderMinimal(count($items));
1616 * @brief Returns the account type name
1618 * The function can be called with either the user or the contact array
1620 * @param array $contact contact or user array
1623 public static function getAccountType(array $contact)
1625 // There are several fields that indicate that the contact or user is a forum
1626 // "page-flags" is a field in the user table,
1627 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1628 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1629 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1630 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1631 || (isset($contact['forum']) && intval($contact['forum']))
1632 || (isset($contact['prv']) && intval($contact['prv']))
1633 || (isset($contact['community']) && intval($contact['community']))
1635 $type = self::TYPE_COMMUNITY;
1637 $type = self::TYPE_PERSON;
1640 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1641 if (isset($contact["contact-type"])) {
1642 $type = $contact["contact-type"];
1645 if (isset($contact["account-type"])) {
1646 $type = $contact["account-type"];
1650 case self::TYPE_ORGANISATION:
1651 $account_type = L10n::t("Organisation");
1654 case self::TYPE_NEWS:
1655 $account_type = L10n::t('News');
1658 case self::TYPE_COMMUNITY:
1659 $account_type = L10n::t("Forum");
1667 return $account_type;
1671 * @brief Blocks a contact
1675 * @throws \Exception
1677 public static function block($cid, $reason = null)
1679 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1685 * @brief Unblocks a contact
1689 * @throws \Exception
1691 public static function unblock($cid)
1693 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1699 * @brief Updates the avatar links in a contact only if needed
1701 * @param string $avatar Link to avatar picture
1702 * @param int $uid User id of contact owner
1703 * @param int $cid Contact id
1704 * @param bool $force force picture update
1706 * @return array Returns array of the different avatar sizes
1707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1708 * @throws \ImagickException
1710 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1712 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1713 if (!DBA::isResult($contact)) {
1716 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1719 if (($contact["avatar"] != $avatar) || $force) {
1720 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1725 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
1729 // Update the public contact (contact id = 0)
1731 $pcontact = DBA::selectFirst('contact', ['id'], ['nurl' => $contact['nurl'], 'uid' => 0]);
1732 if (DBA::isResult($pcontact)) {
1733 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1745 * @param integer $id contact id
1746 * @param string $network Optional network we are probing for
1747 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1749 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1750 * @throws \ImagickException
1752 public static function updateFromProbe($id, $network = '', $force = false)
1755 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1756 This will reliably kill your communication with Friendica contacts.
1759 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1760 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1761 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1762 if (!DBA::isResult($contact)) {
1766 $uid = $contact['uid'];
1767 unset($contact['uid']);
1769 $contact['photo'] = $contact['avatar'];
1770 unset($contact['avatar']);
1772 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1774 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1775 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1779 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT)) {
1785 // make sure to not overwrite existing values with blank entries
1786 foreach ($ret as $key => $val) {
1787 if (!isset($contact[$key])) {
1789 } elseif (($contact[$key] != '') && ($val == '')) {
1790 $ret[$key] = $contact[$key];
1791 } elseif ($ret[$key] != $contact[$key]) {
1800 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1801 $ret['updated'] = DateTimeFormat::utcNow();
1803 self::updateAvatar($ret['photo'], $uid, $id, true);
1805 unset($ret['photo']);
1806 DBA::update('contact', $ret, ['id' => $id]);
1808 // Update the corresponding gcontact entry
1809 PortableContact::lastUpdated($ret["url"]);
1815 * Detects if a given contact array belongs to a legacy DFRN connection
1817 * @param array $contact
1820 public static function isLegacyDFRNContact($contact)
1822 // Newer Friendica contacts are connected via AP, then these fields aren't set
1823 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1827 * Detects the communication protocol for a given contact url.
1828 * This is used to detect Friendica contacts that we can communicate via AP.
1830 * @param string $url contact url
1831 * @param string $network Network of that contact
1832 * @return string with protocol
1834 public static function getProtocol($url, $network)
1836 if ($network != Protocol::DFRN) {
1840 $apcontact = APContact::getByURL($url);
1841 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1842 return Protocol::ACTIVITYPUB;
1849 * Takes a $uid and a url/handle and adds a new contact
1850 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1851 * dfrn_request page.
1853 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1856 * $return['success'] boolean true if successful
1857 * $return['message'] error text if success is false.
1859 * @brief Takes a $uid and a url/handle and adds a new contact
1861 * @param string $url
1862 * @param bool $interactive
1863 * @param string $network
1865 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1866 * @throws \ImagickException
1868 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1870 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1874 // remove ajax junk, e.g. Twitter
1875 $url = str_replace('/#!/', '/', $url);
1877 if (!Network::isUrlAllowed($url)) {
1878 $result['message'] = L10n::t('Disallowed profile URL.');
1882 if (Network::isUrlBlocked($url)) {
1883 $result['message'] = L10n::t('Blocked domain');
1888 $result['message'] = L10n::t('Connect URL missing.');
1892 $arr = ['url' => $url, 'contact' => []];
1894 Hook::callAll('follow', $arr);
1897 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1901 if (!empty($arr['contact']['name'])) {
1902 $ret = $arr['contact'];
1904 $ret = Probe::uri($url, $network, $uid, false);
1907 if (($network != '') && ($ret['network'] != $network)) {
1908 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1912 // check if we already have a contact
1913 // the poll url is more reliable than the profile url, as we may have
1914 // indirect links or webfinger links
1916 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1917 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1918 if (!DBA::isResult($contact)) {
1919 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1920 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1923 $protocol = self::getProtocol($url, $ret['network']);
1925 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
1927 if (strlen($a->getURLPath())) {
1928 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1930 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1933 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1937 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1938 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1939 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1943 // This extra param just confuses things, remove it
1944 if ($protocol === Protocol::DIASPORA) {
1945 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1948 // do we have enough information?
1949 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1950 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1951 if (empty($ret['poll'])) {
1952 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1954 if (empty($ret['name'])) {
1955 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1957 if (empty($ret['url'])) {
1958 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1960 if (strpos($url, '@') !== false) {
1961 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1962 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1967 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1968 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1969 $ret['notify'] = '';
1972 if (!$ret['notify']) {
1973 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1976 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1978 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
1980 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
1982 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
1984 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
1988 if (DBA::isResult($contact)) {
1990 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
1992 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1993 DBA::update('contact', $fields, ['id' => $contact['id']]);
1995 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
1997 // create contact record
1998 DBA::insert('contact', [
2000 'created' => DateTimeFormat::utcNow(),
2001 'url' => $ret['url'],
2002 'nurl' => Strings::normaliseLink($ret['url']),
2003 'addr' => $ret['addr'],
2004 'alias' => $ret['alias'],
2005 'batch' => $ret['batch'],
2006 'notify' => $ret['notify'],
2007 'poll' => $ret['poll'],
2008 'poco' => $ret['poco'],
2009 'name' => $ret['name'],
2010 'nick' => $ret['nick'],
2011 'network' => $ret['network'],
2012 'protocol' => $protocol,
2013 'pubkey' => $ret['pubkey'],
2014 'rel' => $new_relation,
2015 'priority'=> $ret['priority'],
2016 'writable'=> $writeable,
2017 'hidden' => $hidden,
2020 'pending' => $pending,
2025 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2026 if (!DBA::isResult($contact)) {
2027 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2031 $contact_id = $contact['id'];
2032 $result['cid'] = $contact_id;
2034 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2036 // Update the avatar
2037 self::updateAvatar($ret['photo'], $uid, $contact_id);
2039 // pull feed and consume it, which should subscribe to the hub.
2041 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2043 $owner = User::getOwnerDataById($uid);
2045 if (DBA::isResult($owner)) {
2046 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2047 // create a follow slap
2049 $item['verb'] = ACTIVITY_FOLLOW;
2050 $item['follow'] = $contact["url"];
2052 $item['title'] = '';
2055 $item['attach'] = '';
2057 $slap = OStatus::salmon($item, $owner);
2059 if (!empty($contact['notify'])) {
2060 Salmon::slapper($owner, $contact['notify'], $slap);
2062 } elseif ($protocol == Protocol::DIASPORA) {
2063 $ret = Diaspora::sendShare($a->user, $contact);
2064 Logger::log('share returns: ' . $ret);
2065 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2066 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2067 if (empty($activity_id)) {
2068 // This really should never happen
2072 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2073 Logger::log('Follow returns: ' . $ret);
2077 $result['success'] = true;
2082 * @brief Updated contact's SSL policy
2084 * @param array $contact Contact array
2085 * @param string $new_policy New policy, valid: self,full
2087 * @return array Contact array with updated values
2088 * @throws \Exception
2090 public static function updateSslPolicy(array $contact, $new_policy)
2092 $ssl_changed = false;
2093 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2094 $ssl_changed = true;
2095 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2096 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2097 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2098 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2099 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2100 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2103 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2104 $ssl_changed = true;
2105 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2106 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2107 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2108 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2109 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2110 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2114 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2115 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2116 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2117 DBA::update('contact', $fields, ['id' => $contact['id']]);
2123 public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false, $note = '') {
2124 // Should always be set
2125 if (empty($datarray['author-id'])) {
2129 $fields = ['url', 'name', 'nick', 'photo', 'network'];
2130 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2131 if (!DBA::isResult($pub_contact)) {
2132 // Should never happen
2136 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2137 $name = $pub_contact['name'];
2138 $photo = $pub_contact['photo'];
2139 $nick = $pub_contact['nick'];
2140 $network = $pub_contact['network'];
2142 if (is_array($contact)) {
2143 // Make sure that the existing contact isn't archived
2144 self::unmarkForArchival($contact);
2146 $protocol = self::getProtocol($url, $contact['network']);
2148 if (($contact['rel'] == self::SHARING)
2149 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2150 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2151 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2154 if ($protocol == Protocol::ACTIVITYPUB) {
2155 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2158 // send email notification to owner?
2160 $protocol = self::getProtocol($url, $network);
2162 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2163 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2166 // create contact record
2167 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
2168 `blocked`, `readonly`, `pending`, `writable`)
2169 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, 1)",
2170 intval($importer['uid']),
2171 DBA::escape(DateTimeFormat::utcNow()),
2173 DBA::escape(Strings::normaliseLink($url)),
2176 DBA::escape($photo),
2177 DBA::escape($network),
2178 intval(self::FOLLOWER)
2182 'id' => DBA::lastInsertId(),
2183 'network' => $network,
2189 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2191 /// @TODO Encapsulate this into a function/method
2192 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2193 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2194 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2195 // create notification
2196 $hash = Strings::getRandomHex();
2198 if (is_array($contact_record)) {
2199 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2200 'blocked' => false, 'knowyou' => false, 'note' => $note,
2201 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2204 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2206 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2207 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2210 'type' => NOTIFY_INTRO,
2211 'notify_flags' => $user['notify-flags'],
2212 'language' => $user['language'],
2213 'to_name' => $user['username'],
2214 'to_email' => $user['email'],
2215 'uid' => $user['uid'],
2216 'link' => System::baseUrl() . '/notifications/intro',
2217 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2218 'source_link' => $contact_record['url'],
2219 'source_photo' => $contact_record['photo'],
2220 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2225 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2226 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2227 DBA::update('contact', ['pending' => false], $condition);
2229 $contact = DBA::selectFirst('contact', ['url', 'network', 'hub-verify'], ['id' => $contact_record['id']]);
2230 $protocol = self::getProtocol($contact['url'], $contact['network']);
2232 if ($protocol == Protocol::ACTIVITYPUB) {
2233 ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
2239 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2241 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2242 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2244 Contact::remove($contact['id']);
2248 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2250 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2251 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2253 Contact::remove($contact['id']);
2258 * @brief Create a birthday event.
2260 * Update the year and the birthday.
2262 public static function updateBirthdays()
2266 AND `bd` > "0001-01-01"
2267 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2268 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2269 AND NOT `contact`.`pending`
2270 AND NOT `contact`.`hidden`
2271 AND NOT `contact`.`blocked`
2272 AND NOT `contact`.`archive`
2273 AND NOT `contact`.`deleted`',
2278 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2280 while ($contact = DBA::fetch($contacts)) {
2281 Logger::log('update_contact_birthday: ' . $contact['bd']);
2283 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2285 if (Event::createBirthday($contact, $nextbd)) {
2289 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2290 ['id' => $contact['id']]
2297 * Remove the unavailable contact ids from the provided list
2299 * @param array $contact_ids Contact id list
2300 * @throws \Exception
2302 public static function pruneUnavailable(array &$contact_ids)
2304 if (empty($contact_ids)) {
2308 $str = DBA::escape(implode(',', $contact_ids));
2310 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2313 while($contact = DBA::fetch($stmt)) {
2314 $return[] = $contact['id'];
2319 $contact_ids = $return;
2323 * @brief Returns a magic link to authenticate remote visitors
2325 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2327 * @param string $contact_url The address of the target contact profile
2328 * @param string $url An url that we will be redirected to after the authentication
2330 * @return string with "redir" link
2331 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2332 * @throws \ImagickException
2334 public static function magicLink($contact_url, $url = '')
2336 if (!local_user() && !remote_user()) {
2337 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2340 $data = self::getProbeDataFromDatabase($contact_url);
2342 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2345 return self::magicLinkByContact($data, $contact_url);
2349 * @brief Returns a magic link to authenticate remote visitors
2351 * @param integer $cid The contact id of the target contact profile
2352 * @param string $url An url that we will be redirected to after the authentication
2354 * @return string with "redir" link
2355 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2356 * @throws \ImagickException
2358 public static function magicLinkbyId($cid, $url = '')
2360 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2362 return self::magicLinkByContact($contact, $url);
2366 * @brief Returns a magic link to authenticate remote visitors
2368 * @param array $contact The contact array with "uid", "network" and "url"
2369 * @param string $url An url that we will be redirected to after the authentication
2371 * @return string with "redir" link
2372 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2373 * @throws \ImagickException
2375 public static function magicLinkByContact($contact, $url = '')
2377 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2378 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2381 // Only redirections to the same host do make sense
2382 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2386 if (!empty($contact['uid'])) {
2387 return self::magicLink($contact['url'], $url);
2390 if (empty($contact['id'])) {
2391 return $url ?: $contact['url'];
2394 $redirect = 'redir/' . $contact['id'];
2397 $redirect .= '?url=' . $url;
2404 * Remove a contact from all groups
2406 * @param integer $contact_id
2408 * @return boolean Success
2410 public static function removeFromGroups($contact_id)
2412 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2416 * Is the contact a forum?
2418 * @param integer $contactid ID of the contact
2420 * @return boolean "true" if it is a forum
2422 public static function isForum($contactid)
2424 $fields = ['forum', 'prv'];
2425 $condition = ['id' => $contactid];
2426 $contact = DBA::selectFirst('contact', $fields, $condition);
2427 if (!DBA::isResult($contact)) {
2432 return ($contact['forum'] || $contact['prv']);