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 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
597 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
598 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
599 'gender' => $profile['gender'], 'avatar' => $profile['photo'],
600 'contact-type' => $user['account-type'], 'xmpp' => $profile['xmpp']];
602 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
603 if (DBA::isResult($avatar)) {
604 if ($update_avatar) {
605 $fields['avatar-date'] = DateTimeFormat::utcNow();
608 // Creating the path to the avatar, beginning with the file suffix
609 $types = Image::supportedTypes();
610 if (isset($types[$avatar['type']])) {
611 $file_suffix = $types[$avatar['type']];
613 $file_suffix = 'jpg';
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['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
633 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
635 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
636 $fields['url'] = System::baseUrl() . '/profile/' . $user['nickname'];
637 $fields['nurl'] = Strings::normaliseLink($fields['url']);
638 $fields['addr'] = $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3);
639 $fields['request'] = System::baseUrl() . '/dfrn_request/' . $user['nickname'];
640 $fields['notify'] = System::baseUrl() . '/dfrn_notify/' . $user['nickname'];
641 $fields['poll'] = System::baseUrl() . '/dfrn_poll/'. $user['nickname'];
642 $fields['confirm'] = System::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
643 $fields['poco'] = System::baseUrl() . '/poco/' . $user['nickname'];
647 foreach ($fields as $field => $content) {
648 if ($self[$field] != $content) {
654 if ($fields['name'] != $self['name']) {
655 $fields['name-date'] = DateTimeFormat::utcNow();
657 $fields['updated'] = DateTimeFormat::utcNow();
658 DBA::update('contact', $fields, ['id' => $self['id']]);
660 // Update the public contact as well
661 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
663 // Update the profile
664 $fields = ['photo' => System::baseUrl() . '/photo/profile/' .$uid . '.jpg',
665 'thumb' => System::baseUrl() . '/photo/avatar/' . $uid .'.jpg'];
666 DBA::update('profile', $fields, ['uid' => $uid, 'is-default' => true]);
671 * @brief Marks a contact for removal
673 * @param int $id contact id
675 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
677 public static function remove($id)
679 // We want just to make sure that we don't delete our "self" contact
680 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
681 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
685 // Archive the contact
686 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
688 // Delete it in the background
689 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
693 * @brief Sends an unfriend message. Does not remove the contact
695 * @param array $user User unfriending
696 * @param array $contact Contact unfriended
697 * @param boolean $dissolve Remove the contact on the remote side
699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
700 * @throws \ImagickException
702 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
704 if (empty($contact['network'])) {
708 $protocol = $contact['network'];
709 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
710 $protocol = Protocol::ACTIVITYPUB;
713 if (($protocol == Protocol::DFRN) && $dissolve) {
714 DFRN::deliver($user, $contact, 'placeholder', true);
715 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
716 // create an unfollow slap
718 $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
719 $item['follow'] = $contact["url"];
724 $item['attach'] = '';
725 $slap = OStatus::salmon($item, $user);
727 if (!empty($contact['notify'])) {
728 Salmon::slapper($user, $contact['notify'], $slap);
730 } elseif ($protocol == Protocol::DIASPORA) {
731 Diaspora::sendUnshare($user, $contact);
732 } elseif ($protocol == Protocol::ACTIVITYPUB) {
733 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
736 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
742 * @brief Marks a contact for archival after a communication issue delay
744 * Contact has refused to recognise us as a friend. We will start a countdown.
745 * If they still don't recognise us in 32 days, the relationship is over,
746 * and we won't waste any more time trying to communicate with them.
747 * This provides for the possibility that their database is temporarily messed
748 * up or some other transient event and that there's a possibility we could recover from it.
750 * @param array $contact contact to mark for archival
752 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
754 public static function markForArchival(array $contact)
756 if (!isset($contact['url']) && !empty($contact['id'])) {
757 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
758 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
759 if (!DBA::isResult($contact)) {
762 } elseif (!isset($contact['url'])) {
763 Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
766 Logger::log('Contact '.$contact['id'].' is marked for archival', Logger::DEBUG);
768 // Contact already archived or "self" contact? => nothing to do
769 if ($contact['archive'] || $contact['self']) {
773 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
774 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
775 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
778 * We really should send a notification to the owner after 2-3 weeks
779 * so they won't be surprised when the contact vanishes and can take
780 * remedial action if this was a serious mistake or glitch
783 /// @todo Check for contact vitality via probing
784 $archival_days = Config::get('system', 'archival_days', 32);
786 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
787 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
788 /* Relationship is really truly dead. archive them rather than
789 * delete, though if the owner tries to unarchive them we'll start
790 * the whole process over again.
792 DBA::update('contact', ['archive' => 1], ['id' => $contact['id']]);
793 DBA::update('contact', ['archive' => 1], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
799 * @brief Cancels the archival countdown
801 * @see Contact::markForArchival()
803 * @param array $contact contact to be unmarked for archival
807 public static function unmarkForArchival(array $contact)
809 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
810 $exists = DBA::exists('contact', $condition);
812 // We don't need to update, we never marked this contact for archival
817 Logger::log('Contact '.$contact['id'].' is marked as vital again', Logger::DEBUG);
819 if (!isset($contact['url']) && !empty($contact['id'])) {
820 $fields = ['id', 'url', 'batch'];
821 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
822 if (!DBA::isResult($contact)) {
827 // It's a miracle. Our dead contact has inexplicably come back to life.
828 $fields = ['term-date' => DBA::NULL_DATETIME, 'archive' => false];
829 DBA::update('contact', $fields, ['id' => $contact['id']]);
830 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url'])]);
832 if (!empty($contact['batch'])) {
833 $condition = ['batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
834 DBA::update('contact', $fields, $condition);
839 * @brief Get contact data for a given profile link
841 * The function looks at several places (contact table and gcontact table) for the contact
842 * It caches its result for the same script execution to prevent duplicate calls
844 * @param string $url The profile link
845 * @param int $uid User id
846 * @param array $default If not data was found take this data as default value
848 * @return array Contact data
849 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
851 public static function getDetailsByURL($url, $uid = -1, array $default = [])
863 if (isset($cache[$url][$uid])) {
864 return $cache[$url][$uid];
867 $ssl_url = str_replace('http://', 'https://', $url);
869 // Fetch contact data from the contact table for the given user
870 $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`,
871 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
872 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", Strings::normaliseLink($url), $uid);
873 $r = DBA::toArray($s);
875 // Fetch contact data from the contact table for the given user, checking with the alias
876 if (!DBA::isResult($r)) {
877 $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`,
878 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
879 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", Strings::normaliseLink($url), $url, $ssl_url, $uid);
880 $r = DBA::toArray($s);
883 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
884 if (!DBA::isResult($r)) {
885 $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`,
886 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
887 FROM `contact` WHERE `nurl` = ? AND `uid` = 0", Strings::normaliseLink($url));
888 $r = DBA::toArray($s);
891 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
892 if (!DBA::isResult($r)) {
893 $s = DBA::p("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
894 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
895 FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", Strings::normaliseLink($url), $url, $ssl_url);
896 $r = DBA::toArray($s);
899 // Fetch the data from the gcontact table
900 if (!DBA::isResult($r)) {
901 $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`,
902 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, 0 AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
903 FROM `gcontact` WHERE `nurl` = ?", Strings::normaliseLink($url));
904 $r = DBA::toArray($s);
907 if (DBA::isResult($r)) {
908 // If there is more than one entry we filter out the connector networks
910 foreach ($r as $id => $result) {
911 if (!in_array($result["network"], Protocol::NATIVE_SUPPORT)) {
917 $profile = array_shift($r);
919 // "bd" always contains the upcoming birthday of a contact.
920 // "birthday" might contain the birthday including the year of birth.
921 if ($profile["birthday"] > DBA::NULL_DATE) {
922 $bd_timestamp = strtotime($profile["birthday"]);
923 $month = date("m", $bd_timestamp);
924 $day = date("d", $bd_timestamp);
926 $current_timestamp = time();
927 $current_year = date("Y", $current_timestamp);
928 $current_month = date("m", $current_timestamp);
929 $current_day = date("d", $current_timestamp);
931 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
932 $current = $current_year . "-" . $current_month . "-" . $current_day;
934 if ($profile["bd"] < $current) {
935 $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
938 $profile["bd"] = DBA::NULL_DATE;
944 if (empty($profile["photo"]) && isset($default["photo"])) {
945 $profile["photo"] = $default["photo"];
948 if (empty($profile["name"]) && isset($default["name"])) {
949 $profile["name"] = $default["name"];
952 if (empty($profile["network"]) && isset($default["network"])) {
953 $profile["network"] = $default["network"];
956 if (empty($profile["thumb"]) && isset($profile["photo"])) {
957 $profile["thumb"] = $profile["photo"];
960 if (empty($profile["micro"]) && isset($profile["thumb"])) {
961 $profile["micro"] = $profile["thumb"];
964 if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
965 && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
967 Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
970 // Show contact details of Diaspora contacts only if connected
971 if ((defaults($profile, "cid", 0) == 0) && (defaults($profile, "network", "") == Protocol::DIASPORA)) {
972 $profile["location"] = "";
973 $profile["about"] = "";
974 $profile["gender"] = "";
975 $profile["birthday"] = DBA::NULL_DATE;
978 $cache[$url][$uid] = $profile;
984 * @brief Get contact data for a given address
986 * The function looks at several places (contact table and gcontact table) for the contact
988 * @param string $addr The profile link
989 * @param int $uid User id
991 * @return array Contact data
992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993 * @throws \ImagickException
995 public static function getDetailsByAddr($addr, $uid = -1)
1002 $uid = local_user();
1005 // Fetch contact data from the contact table for the given user
1006 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1007 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
1008 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d AND NOT `deleted`",
1012 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
1013 if (!DBA::isResult($r)) {
1014 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
1015 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
1016 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0 AND NOT `deleted`",
1021 // Fetch the data from the gcontact table
1022 if (!DBA::isResult($r)) {
1023 $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`,
1024 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
1025 FROM `gcontact` WHERE `addr` = '%s'",
1030 if (!DBA::isResult($r)) {
1031 $data = Probe::uri($addr);
1033 $profile = self::getDetailsByURL($data['url'], $uid);
1042 * @brief Returns the data array for the photo menu of a given contact
1044 * @param array $contact contact
1045 * @param int $uid optional, default 0
1047 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1048 * @throws \ImagickException
1050 public static function photoMenu(array $contact, $uid = 0)
1055 $contact_drop_link = '';
1059 $uid = local_user();
1062 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
1064 $profile_link = self::magicLink($contact['url']);
1065 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
1070 // Look for our own contact if the uid doesn't match and isn't public
1071 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1072 if (DBA::isResult($contact_own)) {
1073 return self::photoMenu($contact_own, $uid);
1078 if (($contact['network'] === Protocol::DFRN) && !$contact['self']) {
1080 $profile_link = System::baseUrl() . '/redir/' . $contact['id'] . '?url=' . $contact['url'];
1082 $profile_link = $contact['url'];
1085 if ($profile_link === 'mailbox') {
1090 $status_link = $profile_link . '?tab=status';
1091 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1092 $profile_link = $profile_link . '?tab=profile';
1095 if (self::canReceivePrivateMessages($contact)) {
1096 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
1099 if (($contact['network'] == Protocol::DFRN) && !$contact['self']) {
1100 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
1103 $contact_url = System::baseUrl() . '/contact/' . $contact['id'];
1105 $posts_link = System::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1107 if (!$contact['self']) {
1108 $contact_drop_link = System::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1113 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1115 if (empty($contact['uid'])) {
1116 $connlnk = 'follow/?url=' . $contact['url'];
1118 'profile' => [L10n::t('View Profile'), $profile_link, true],
1119 'network' => [L10n::t('Network Posts'), $posts_link, false],
1120 'edit' => [L10n::t('View Contact'), $contact_url, false],
1121 'follow' => [L10n::t('Connect/Follow'), $connlnk, true],
1125 'status' => [L10n::t('View Status'), $status_link, true],
1126 'profile' => [L10n::t('View Profile'), $profile_link, true],
1127 'photos' => [L10n::t('View Photos'), $photos_link, true],
1128 'network' => [L10n::t('Network Posts'), $posts_link, false],
1129 'edit' => [L10n::t('View Contact'), $contact_url, false],
1130 'drop' => [L10n::t('Drop Contact'), $contact_drop_link, false],
1131 'pm' => [L10n::t('Send PM'), $pm_url, false],
1132 'poke' => [L10n::t('Poke'), $poke_link, false],
1136 $args = ['contact' => $contact, 'menu' => &$menu];
1138 Hook::callAll('contact_photo_menu', $args);
1140 $menucondensed = [];
1142 foreach ($menu as $menuname => $menuitem) {
1143 if ($menuitem[1] != '') {
1144 $menucondensed[$menuname] = $menuitem;
1148 return $menucondensed;
1152 * @brief Returns ungrouped contact count or list for user
1154 * Returns either the total number of ungrouped contacts for the given user
1155 * id or a paginated list of ungrouped contacts.
1157 * @param int $uid uid
1159 * @throws \Exception
1161 public static function getUngroupedList($uid)
1171 SELECT DISTINCT(`contact-id`)
1173 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1174 WHERE `group`.`uid` = %d
1175 )", intval($uid), intval($uid));
1179 * Have a look at all contact tables for a given profile url.
1180 * This function works as a replacement for probing the contact.
1182 * @param string $url Contact URL
1183 * @param integer $cid Contact ID
1185 * @return array Contact array in the "probe" structure
1187 private static function getProbeDataFromDatabase($url, $cid = null)
1189 // The link could be provided as http although we stored it as https
1190 $ssl_url = str_replace('http://', 'https://', $url);
1192 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1193 'photo', 'keywords', 'location', 'about', 'network',
1194 'priority', 'batch', 'request', 'confirm', 'poco'];
1197 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1198 if (DBA::isResult($data)) {
1203 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1205 if (!DBA::isResult($data)) {
1206 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1207 $data = DBA::selectFirst('contact', $fields, $condition);
1210 if (DBA::isResult($data)) {
1211 // For security reasons we don't fetch key data from our users
1212 $data["pubkey"] = '';
1216 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1217 'photo', 'keywords', 'location', 'about', 'network'];
1218 $data = DBA::selectFirst('gcontact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1220 if (!DBA::isResult($data)) {
1221 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1222 $data = DBA::selectFirst('contact', $fields, $condition);
1225 if (DBA::isResult($data)) {
1226 $data["pubkey"] = '';
1228 $data["priority"] = 0;
1229 $data["batch"] = '';
1230 $data["request"] = '';
1231 $data["confirm"] = '';
1236 $data = ActivityPub::probeProfile($url, false);
1237 if (!empty($data)) {
1241 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1242 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1243 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1245 if (!DBA::isResult($data)) {
1246 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1247 $data = DBA::selectFirst('contact', $fields, $condition);
1250 if (DBA::isResult($data)) {
1251 $data["pubkey"] = '';
1252 $data["keywords"] = '';
1253 $data["location"] = '';
1254 $data["about"] = '';
1263 * @brief Fetch the contact id for a given URL and user
1265 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1266 * `addr` or `alias`.
1268 * If there's no record and we aren't looking for a public contact, we quit.
1269 * If there's one, we check that it isn't time to update the picture else we
1270 * directly return the found contact id.
1272 * Second, we probe the provided $url whether it's http://server.tld/profile or
1273 * nick@server.tld. We quit if we can't get any info back.
1275 * Third, we create the contact record if it doesn't exist
1277 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1278 * if there's any updates
1280 * @param string $url Contact URL
1281 * @param integer $uid The user id for the contact (0 = public contact)
1282 * @param boolean $no_update Don't update the contact
1283 * @param array $default Default value for creating the contact when every else fails
1284 * @param boolean $in_loop Internally used variable to prevent an endless loop
1286 * @return integer Contact ID
1287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1288 * @throws \ImagickException
1290 public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
1292 Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
1300 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
1301 // We first try the nurl (http://server.tld/nick), most common case
1302 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false]);
1304 // Then the addr (nick@server.tld)
1305 if (!DBA::isResult($contact)) {
1306 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], ['addr' => $url, 'uid' => $uid, 'deleted' => false]);
1309 // Then the alias (which could be anything)
1310 if (!DBA::isResult($contact)) {
1311 // The link could be provided as http although we stored it as https
1312 $ssl_url = str_replace('http://', 'https://', $url);
1313 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
1314 $contact = DBA::selectFirst('contact', ['id', 'avatar', 'updated', 'network'], $condition);
1317 if (DBA::isResult($contact)) {
1318 $contact_id = $contact["id"];
1320 // Update the contact every 7 days
1321 $update_contact = ($contact['updated'] < DateTimeFormat::utc('now -7 days'));
1323 // We force the update if the avatar is empty
1324 if (empty($contact['avatar'])) {
1325 $update_contact = true;
1328 // Update the contact in the background if needed but it is called by the frontend
1329 if ($update_contact && $no_update && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1330 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1333 if (!$update_contact || $no_update) {
1336 } elseif ($uid != 0) {
1337 // Non-existing user-specific contact, exiting
1341 // When we don't want to update, we look if we know this contact in any way
1342 if ($no_update && empty($default)) {
1343 $data = self::getProbeDataFromDatabase($url, $contact_id);
1344 $background_update = true;
1347 $background_update = false;
1351 $data = Probe::uri($url, "", $uid);
1353 // Ensure that there is a gserver entry
1354 if (!empty($data['baseurl']) && ($data['network'] != Protocol::PHANTOM)) {
1355 PortableContact::checkServer($data['baseurl']);
1359 // Last try in gcontact for unsupported networks
1360 if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
1365 $contact = array_merge(self::getProbeDataFromDatabase($url, $contact_id), $default);
1366 if (empty($contact)) {
1370 $data = array_merge($data, $contact);
1377 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $url) && !$in_loop) {
1378 $contact_id = self::getIdForURL($data["alias"], $uid, true, $default, true);
1384 'created' => DateTimeFormat::utcNow(),
1385 'url' => $data['url'],
1386 'nurl' => Strings::normaliseLink($data['url']),
1387 'addr' => defaults($data, 'addr', ''),
1388 'alias' => defaults($data, 'alias', ''),
1389 'notify' => defaults($data, 'notify', ''),
1390 'poll' => defaults($data, 'poll', ''),
1391 'name' => defaults($data, 'name', ''),
1392 'nick' => defaults($data, 'nick', ''),
1393 'photo' => defaults($data, 'photo', ''),
1394 'keywords' => defaults($data, 'keywords', ''),
1395 'location' => defaults($data, 'location', ''),
1396 'about' => defaults($data, 'about', ''),
1397 'network' => $data['network'],
1398 'pubkey' => defaults($data, 'pubkey', ''),
1399 'rel' => self::SHARING,
1400 'priority' => defaults($data, 'priority', 0),
1401 'batch' => defaults($data, 'batch', ''),
1402 'request' => defaults($data, 'request', ''),
1403 'confirm' => defaults($data, 'confirm', ''),
1404 'poco' => defaults($data, 'poco', ''),
1405 'name-date' => DateTimeFormat::utcNow(),
1406 'uri-date' => DateTimeFormat::utcNow(),
1407 'avatar-date' => DateTimeFormat::utcNow(),
1413 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1415 DBA::update('contact', $fields, $condition, true);
1417 $s = DBA::select('contact', ['id'], $condition, ['order' => ['id'], 'limit' => 2]);
1418 $contacts = DBA::toArray($s);
1419 if (!DBA::isResult($contacts)) {
1423 $contact_id = $contacts[0]["id"];
1425 // Update in the background when we fetched the data solely from the database
1426 if ($background_update) {
1427 Worker::add(PRIORITY_LOW, "UpdateContact", $contact_id);
1430 // Update the newly created contact from data in the gcontact table
1431 $gcontact = DBA::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => Strings::normaliseLink($data["url"])]);
1432 if (DBA::isResult($gcontact)) {
1433 // Only use the information when the probing hadn't fetched these values
1434 if (!empty($data['keywords'])) {
1435 unset($gcontact['keywords']);
1437 if (!empty($data['location'])) {
1438 unset($gcontact['location']);
1440 if (!empty($data['about'])) {
1441 unset($gcontact['about']);
1443 DBA::update('contact', $gcontact, ['id' => $contact_id]);
1446 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
1447 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self`",
1448 Strings::normaliseLink($data["url"]), 0, $contact_id];
1449 Logger::log('Deleting duplicate contact ' . json_encode($condition), Logger::DEBUG);
1450 DBA::delete('contact', $condition);
1454 if (!empty($data['photo'])) {
1455 self::updateAvatar($data['photo'], $uid, $contact_id);
1458 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
1459 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1461 // This condition should always be true
1462 if (!DBA::isResult($contact)) {
1466 $updated = ['addr' => $data['addr'],
1467 'alias' => defaults($data, 'alias', ''),
1468 'url' => $data['url'],
1469 'nurl' => Strings::normaliseLink($data['url']),
1470 'name' => $data['name'],
1471 'nick' => $data['nick']];
1473 if (!empty($data['keywords'])) {
1474 $updated['keywords'] = $data['keywords'];
1476 if (!empty($data['location'])) {
1477 $updated['location'] = $data['location'];
1480 // Update the technical stuff as well - if filled
1481 if (!empty($data['notify'])) {
1482 $updated['notify'] = $data['notify'];
1484 if (!empty($data['poll'])) {
1485 $updated['poll'] = $data['poll'];
1487 if (!empty($data['batch'])) {
1488 $updated['batch'] = $data['batch'];
1490 if (!empty($data['request'])) {
1491 $updated['request'] = $data['request'];
1493 if (!empty($data['confirm'])) {
1494 $updated['confirm'] = $data['confirm'];
1496 if (!empty($data['poco'])) {
1497 $updated['poco'] = $data['poco'];
1500 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1501 if (empty($contact['pubkey'])) {
1502 $updated['pubkey'] = $data['pubkey'];
1505 if (($data['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1506 $updated['uri-date'] = DateTimeFormat::utcNow();
1508 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
1509 $updated['name-date'] = DateTimeFormat::utcNow();
1512 $updated['updated'] = DateTimeFormat::utcNow();
1514 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1520 * @brief Checks if the contact is blocked
1522 * @param int $cid contact id
1524 * @return boolean Is the contact blocked?
1525 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1527 public static function isBlocked($cid)
1533 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1534 if (!DBA::isResult($blocked)) {
1538 if (Network::isUrlBlocked($blocked['url'])) {
1542 return (bool) $blocked['blocked'];
1546 * @brief Checks if the contact is hidden
1548 * @param int $cid contact id
1550 * @return boolean Is the contact hidden?
1551 * @throws \Exception
1553 public static function isHidden($cid)
1559 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1560 if (!DBA::isResult($hidden)) {
1563 return (bool) $hidden['hidden'];
1567 * @brief Returns posts from a given contact url
1569 * @param string $contact_url Contact URL
1571 * @param bool $thread_mode
1572 * @param int $update
1573 * @return string posts in HTML
1574 * @throws \Exception
1576 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1578 $a = self::getApp();
1580 $cid = self::getIdForURL($contact_url);
1582 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1583 if (!DBA::isResult($contact)) {
1587 if (in_array($contact["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
1588 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1590 $sql = "`item`.`uid` = ?";
1593 $contact_field = ($contact["contact-type"] == self::TYPE_COMMUNITY ? 'owner-id' : 'author-id');
1596 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1597 $cid, GRAVITY_PARENT, local_user()];
1599 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1600 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1603 $pager = new Pager($a->query_string);
1605 $params = ['order' => ['created' => true],
1606 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1609 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1611 $items = Item::inArray($r);
1613 $o = conversation($a, $items, $pager, 'contacts', $update, false, 'commented', local_user());
1615 $r = Item::selectForUser(local_user(), [], $condition, $params);
1617 $items = Item::inArray($r);
1619 $o = conversation($a, $items, $pager, 'contact-posts', false);
1623 $o .= $pager->renderMinimal(count($items));
1630 * @brief Returns the account type name
1632 * The function can be called with either the user or the contact array
1634 * @param array $contact contact or user array
1637 public static function getAccountType(array $contact)
1639 // There are several fields that indicate that the contact or user is a forum
1640 // "page-flags" is a field in the user table,
1641 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1642 // "community" is used in the gcontact table and is true if the contact is User::PAGE_FLAGS_COMMUNITY or User::PAGE_FLAGS_PRVGROUP.
1643 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1644 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1645 || (isset($contact['forum']) && intval($contact['forum']))
1646 || (isset($contact['prv']) && intval($contact['prv']))
1647 || (isset($contact['community']) && intval($contact['community']))
1649 $type = self::TYPE_COMMUNITY;
1651 $type = self::TYPE_PERSON;
1654 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1655 if (isset($contact["contact-type"])) {
1656 $type = $contact["contact-type"];
1659 if (isset($contact["account-type"])) {
1660 $type = $contact["account-type"];
1664 case self::TYPE_ORGANISATION:
1665 $account_type = L10n::t("Organisation");
1668 case self::TYPE_NEWS:
1669 $account_type = L10n::t('News');
1672 case self::TYPE_COMMUNITY:
1673 $account_type = L10n::t("Forum");
1681 return $account_type;
1685 * @brief Blocks a contact
1689 * @throws \Exception
1691 public static function block($cid, $reason = null)
1693 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1699 * @brief Unblocks a contact
1703 * @throws \Exception
1705 public static function unblock($cid)
1707 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1713 * @brief Updates the avatar links in a contact only if needed
1715 * @param string $avatar Link to avatar picture
1716 * @param int $uid User id of contact owner
1717 * @param int $cid Contact id
1718 * @param bool $force force picture update
1720 * @return array Returns array of the different avatar sizes
1721 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1722 * @throws \ImagickException
1724 public static function updateAvatar($avatar, $uid, $cid, $force = false)
1726 $contact = DBA::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1727 if (!DBA::isResult($contact)) {
1730 $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1733 if (($contact["avatar"] != $avatar) || $force) {
1734 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1739 ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()],
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 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1759 * @param integer $id contact id
1760 * @param string $network Optional network we are probing for
1761 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1763 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1764 * @throws \ImagickException
1766 public static function updateFromProbe($id, $network = '', $force = false)
1769 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1770 This will reliably kill your communication with Friendica contacts.
1773 $fields = ['avatar', 'uid', 'name', 'nick', 'url', 'addr', 'batch', 'notify',
1774 'poll', 'request', 'confirm', 'poco', 'network', 'alias'];
1775 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1776 if (!DBA::isResult($contact)) {
1780 $uid = $contact['uid'];
1781 unset($contact['uid']);
1783 $contact['photo'] = $contact['avatar'];
1784 unset($contact['avatar']);
1786 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1788 // If Probe::uri fails the network code will be different (mostly "feed" or "unkn")
1789 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1793 if (!in_array($ret['network'], Protocol::NATIVE_SUPPORT)) {
1799 // make sure to not overwrite existing values with blank entries
1800 foreach ($ret as $key => $val) {
1801 if (!isset($contact[$key])) {
1803 } elseif (($contact[$key] != '') && ($val == '')) {
1804 $ret[$key] = $contact[$key];
1805 } elseif ($ret[$key] != $contact[$key]) {
1814 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1815 $ret['updated'] = DateTimeFormat::utcNow();
1817 self::updateAvatar($ret['photo'], $uid, $id, true);
1819 unset($ret['photo']);
1820 DBA::update('contact', $ret, ['id' => $id]);
1822 // Update the corresponding gcontact entry
1823 PortableContact::lastUpdated($ret["url"]);
1829 * Detects if a given contact array belongs to a legacy DFRN connection
1831 * @param array $contact
1834 public static function isLegacyDFRNContact($contact)
1836 // Newer Friendica contacts are connected via AP, then these fields aren't set
1837 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1841 * Detects the communication protocol for a given contact url.
1842 * This is used to detect Friendica contacts that we can communicate via AP.
1844 * @param string $url contact url
1845 * @param string $network Network of that contact
1846 * @return string with protocol
1848 public static function getProtocol($url, $network)
1850 if ($network != Protocol::DFRN) {
1854 $apcontact = APContact::getByURL($url);
1855 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1856 return Protocol::ACTIVITYPUB;
1863 * Takes a $uid and a url/handle and adds a new contact
1864 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1865 * dfrn_request page.
1867 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1870 * $return['success'] boolean true if successful
1871 * $return['message'] error text if success is false.
1873 * @brief Takes a $uid and a url/handle and adds a new contact
1875 * @param string $url
1876 * @param bool $interactive
1877 * @param string $network
1879 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1880 * @throws \ImagickException
1882 public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1884 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1888 // remove ajax junk, e.g. Twitter
1889 $url = str_replace('/#!/', '/', $url);
1891 if (!Network::isUrlAllowed($url)) {
1892 $result['message'] = L10n::t('Disallowed profile URL.');
1896 if (Network::isUrlBlocked($url)) {
1897 $result['message'] = L10n::t('Blocked domain');
1902 $result['message'] = L10n::t('Connect URL missing.');
1906 $arr = ['url' => $url, 'contact' => []];
1908 Hook::callAll('follow', $arr);
1911 $result['message'] = L10n::t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1915 if (!empty($arr['contact']['name'])) {
1916 $ret = $arr['contact'];
1918 $ret = Probe::uri($url, $network, $uid, false);
1921 if (($network != '') && ($ret['network'] != $network)) {
1922 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1926 // check if we already have a contact
1927 // the poll url is more reliable than the profile url, as we may have
1928 // indirect links or webfinger links
1930 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1931 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1932 if (!DBA::isResult($contact)) {
1933 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($url), 'network' => $ret['network'], 'pending' => false];
1934 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1937 $protocol = self::getProtocol($url, $ret['network']);
1939 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
1941 if (strlen($a->getURLPath())) {
1942 $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1944 $myaddr = bin2hex($a->user['nickname'] . '@' . $a->getHostName());
1947 $a->internalRedirect($ret['request'] . "&addr=$myaddr");
1951 } elseif (Config::get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
1952 $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1953 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1957 // This extra param just confuses things, remove it
1958 if ($protocol === Protocol::DIASPORA) {
1959 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1962 // do we have enough information?
1963 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
1964 $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1965 if (empty($ret['poll'])) {
1966 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1968 if (empty($ret['name'])) {
1969 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1971 if (empty($ret['url'])) {
1972 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1974 if (strpos($url, '@') !== false) {
1975 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1976 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1981 if ($protocol === Protocol::OSTATUS && Config::get('system', 'ostatus_disabled')) {
1982 $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1983 $ret['notify'] = '';
1986 if (!$ret['notify']) {
1987 $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1990 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
1992 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
1994 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
1996 $pending = in_array($protocol, [Protocol::ACTIVITYPUB]);
1998 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2002 if (DBA::isResult($contact)) {
2004 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2006 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2007 DBA::update('contact', $fields, ['id' => $contact['id']]);
2009 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2011 // create contact record
2012 DBA::insert('contact', [
2014 'created' => DateTimeFormat::utcNow(),
2015 'url' => $ret['url'],
2016 'nurl' => Strings::normaliseLink($ret['url']),
2017 'addr' => $ret['addr'],
2018 'alias' => $ret['alias'],
2019 'batch' => $ret['batch'],
2020 'notify' => $ret['notify'],
2021 'poll' => $ret['poll'],
2022 'poco' => $ret['poco'],
2023 'name' => $ret['name'],
2024 'nick' => $ret['nick'],
2025 'network' => $ret['network'],
2026 'protocol' => $protocol,
2027 'pubkey' => $ret['pubkey'],
2028 'rel' => $new_relation,
2029 'priority'=> $ret['priority'],
2030 'writable'=> $writeable,
2031 'hidden' => $hidden,
2034 'pending' => $pending,
2039 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2040 if (!DBA::isResult($contact)) {
2041 $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
2045 $contact_id = $contact['id'];
2046 $result['cid'] = $contact_id;
2048 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2050 // Update the avatar
2051 self::updateAvatar($ret['photo'], $uid, $contact_id);
2053 // pull feed and consume it, which should subscribe to the hub.
2055 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2057 $owner = User::getOwnerDataById($uid);
2059 if (DBA::isResult($owner)) {
2060 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2061 // create a follow slap
2063 $item['verb'] = ACTIVITY_FOLLOW;
2064 $item['follow'] = $contact["url"];
2066 $item['title'] = '';
2069 $item['attach'] = '';
2071 $slap = OStatus::salmon($item, $owner);
2073 if (!empty($contact['notify'])) {
2074 Salmon::slapper($owner, $contact['notify'], $slap);
2076 } elseif ($protocol == Protocol::DIASPORA) {
2077 $ret = Diaspora::sendShare($a->user, $contact);
2078 Logger::log('share returns: ' . $ret);
2079 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2080 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2081 if (empty($activity_id)) {
2082 // This really should never happen
2086 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2087 Logger::log('Follow returns: ' . $ret);
2091 $result['success'] = true;
2096 * @brief Updated contact's SSL policy
2098 * @param array $contact Contact array
2099 * @param string $new_policy New policy, valid: self,full
2101 * @return array Contact array with updated values
2102 * @throws \Exception
2104 public static function updateSslPolicy(array $contact, $new_policy)
2106 $ssl_changed = false;
2107 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2108 $ssl_changed = true;
2109 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2110 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2111 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2112 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2113 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2114 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2117 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2118 $ssl_changed = true;
2119 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2120 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2121 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2122 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2123 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2124 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2128 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2129 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2130 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2131 DBA::update('contact', $fields, ['id' => $contact['id']]);
2138 * @param array $importer Owner (local user) data
2139 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2140 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2141 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2142 * @param string $note Introduction additional message
2143 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2145 * @throws \ImagickException
2147 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2149 // Should always be set
2150 if (empty($datarray['author-id'])) {
2154 $fields = ['url', 'name', 'nick', 'photo', 'network', 'blocked'];
2155 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2156 if (!DBA::isResult($pub_contact)) {
2157 // Should never happen
2161 // Contact is blocked at node-level
2162 if (self::isBlocked($datarray['author-id'])) {
2166 $url = defaults($datarray, 'author-link', $pub_contact['url']);
2167 $name = $pub_contact['name'];
2168 $photo = $pub_contact['photo'];
2169 $nick = $pub_contact['nick'];
2170 $network = $pub_contact['network'];
2172 if (!empty($contact)) {
2173 // Contact is blocked at user-level
2174 if (self::isBlockedByUser($contact['id'], $importer['id'])) {
2178 // Make sure that the existing contact isn't archived
2179 self::unmarkForArchival($contact);
2181 if (($contact['rel'] == self::SHARING)
2182 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2183 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2184 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2189 // send email notification to owner?
2190 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2191 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2195 // create contact record
2196 DBA::insert('contact', [
2197 'uid' => $importer['uid'],
2198 'created' => DateTimeFormat::utcNow(),
2200 'nurl' => Strings::normaliseLink($url),
2204 'network' => $network,
2205 'rel' => self::FOLLOWER,
2213 'id' => DBA::lastInsertId(),
2214 'network' => $network,
2220 Contact::updateAvatar($photo, $importer["uid"], $contact_record["id"], true);
2222 /// @TODO Encapsulate this into a function/method
2223 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2224 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2225 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2226 // create notification
2227 $hash = Strings::getRandomHex();
2229 if (is_array($contact_record)) {
2230 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2231 'blocked' => false, 'knowyou' => false, 'note' => $note,
2232 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2235 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2237 if (($user['notify-flags'] & NOTIFY_INTRO) &&
2238 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2241 'type' => NOTIFY_INTRO,
2242 'notify_flags' => $user['notify-flags'],
2243 'language' => $user['language'],
2244 'to_name' => $user['username'],
2245 'to_email' => $user['email'],
2246 'uid' => $user['uid'],
2247 'link' => System::baseUrl() . '/notifications/intro',
2248 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : L10n::t('[Name Withheld]')),
2249 'source_link' => $contact_record['url'],
2250 'source_photo' => $contact_record['photo'],
2251 'verb' => ($sharing ? ACTIVITY_FRIEND : ACTIVITY_FOLLOW),
2255 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2256 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2257 DBA::update('contact', ['pending' => false], $condition);
2266 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2268 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2269 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2271 Contact::remove($contact['id']);
2275 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2277 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2278 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2280 Contact::remove($contact['id']);
2285 * @brief Create a birthday event.
2287 * Update the year and the birthday.
2289 public static function updateBirthdays()
2293 AND `bd` > "0001-01-01"
2294 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2295 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2296 AND NOT `contact`.`pending`
2297 AND NOT `contact`.`hidden`
2298 AND NOT `contact`.`blocked`
2299 AND NOT `contact`.`archive`
2300 AND NOT `contact`.`deleted`',
2305 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2307 while ($contact = DBA::fetch($contacts)) {
2308 Logger::log('update_contact_birthday: ' . $contact['bd']);
2310 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2312 if (Event::createBirthday($contact, $nextbd)) {
2316 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2317 ['id' => $contact['id']]
2324 * Remove the unavailable contact ids from the provided list
2326 * @param array $contact_ids Contact id list
2327 * @throws \Exception
2329 public static function pruneUnavailable(array &$contact_ids)
2331 if (empty($contact_ids)) {
2335 $str = DBA::escape(implode(',', $contact_ids));
2337 $stmt = DBA::p("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0");
2340 while($contact = DBA::fetch($stmt)) {
2341 $return[] = $contact['id'];
2346 $contact_ids = $return;
2350 * @brief Returns a magic link to authenticate remote visitors
2352 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2354 * @param string $contact_url The address of the target contact profile
2355 * @param string $url An url that we will be redirected to after the authentication
2357 * @return string with "redir" link
2358 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2359 * @throws \ImagickException
2361 public static function magicLink($contact_url, $url = '')
2363 if (!local_user() && !remote_user()) {
2364 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2367 $data = self::getProbeDataFromDatabase($contact_url);
2369 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2372 // Prevents endless loop in case only a non-public contact exists for the contact URL
2373 unset($data['uid']);
2375 return self::magicLinkByContact($data, $contact_url);
2379 * @brief Returns a magic link to authenticate remote visitors
2381 * @param integer $cid The contact id of the target contact profile
2382 * @param string $url An url that we will be redirected to after the authentication
2384 * @return string with "redir" link
2385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2386 * @throws \ImagickException
2388 public static function magicLinkbyId($cid, $url = '')
2390 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2392 return self::magicLinkByContact($contact, $url);
2396 * @brief Returns a magic link to authenticate remote visitors
2398 * @param array $contact The contact array with "uid", "network" and "url"
2399 * @param string $url An url that we will be redirected to after the authentication
2401 * @return string with "redir" link
2402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2403 * @throws \ImagickException
2405 public static function magicLinkByContact($contact, $url = '')
2407 if ((!local_user() && !remote_user()) || ($contact['network'] != Protocol::DFRN)) {
2408 return $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2411 // Only redirections to the same host do make sense
2412 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2416 if (!empty($contact['uid'])) {
2417 return self::magicLink($contact['url'], $url);
2420 if (empty($contact['id'])) {
2421 return $url ?: $contact['url'];
2424 $redirect = 'redir/' . $contact['id'];
2427 $redirect .= '?url=' . $url;
2434 * Remove a contact from all groups
2436 * @param integer $contact_id
2438 * @return boolean Success
2440 public static function removeFromGroups($contact_id)
2442 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2446 * Is the contact a forum?
2448 * @param integer $contactid ID of the contact
2450 * @return boolean "true" if it is a forum
2452 public static function isForum($contactid)
2454 $fields = ['forum', 'prv'];
2455 $condition = ['id' => $contactid];
2456 $contact = DBA::selectFirst('contact', $fields, $condition);
2457 if (!DBA::isResult($contact)) {
2462 return ($contact['forum'] || $contact['prv']);
2466 * Can the remote contact receive private messages?
2468 * @param array $contact
2471 public static function canReceivePrivateMessages(array $contact)
2473 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2474 $self = $contact['self'] ?? false;
2476 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;