3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
26 use Friendica\App\BaseURL;
27 use Friendica\Content\Pager;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Logger;
30 use Friendica\Core\Protocol;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
36 use Friendica\Model\Notify\Type;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\DFRN;
42 use Friendica\Protocol\Diaspora;
43 use Friendica\Protocol\OStatus;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\Images;
47 use Friendica\Util\Network;
48 use Friendica\Util\Proxy;
49 use Friendica\Util\Strings;
52 * functions for interacting with a contact
57 * @deprecated since version 2019.03
58 * @see User::PAGE_FLAGS_NORMAL
60 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_SOAPBOX
65 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
67 * @deprecated since version 2019.03
68 * @see User::PAGE_FLAGS_COMMUNITY
70 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
72 * @deprecated since version 2019.03
73 * @see User::PAGE_FLAGS_FREELOVE
75 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
77 * @deprecated since version 2019.03
78 * @see User::PAGE_FLAGS_BLOG
80 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
82 * @deprecated since version 2019.03
83 * @see User::PAGE_FLAGS_PRVGROUP
85 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
93 * TYPE_UNKNOWN - unknown type
95 * TYPE_PERSON - the account belongs to a person
96 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
98 * TYPE_ORGANISATION - the account belongs to an organisation
99 * Associated page type: PAGE_SOAPBOX
101 * TYPE_NEWS - the account is a news reflector
102 * Associated page type: PAGE_SOAPBOX
104 * TYPE_COMMUNITY - the account is community forum
105 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
107 * TYPE_RELAY - the account is a relay
108 * This will only be assigned to contacts, not to user accounts
111 const TYPE_UNKNOWN = -1;
112 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
113 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
114 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
115 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
116 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
135 * @param array $fields Array of selected fields, empty for all
136 * @param array $condition Array of fields for condition
137 * @param array $params Array of several parameters
141 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
143 return DBA::selectToArray('contact', $fields, $condition, $params);
147 * @param array $fields Array of selected fields, empty for all
148 * @param array $condition Array of fields for condition
149 * @param array $params Array of several parameters
153 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
155 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
161 * Insert a row into the contact table
162 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
164 * @param array $fields field array
165 * @param bool $on_duplicate_update Do an update on a duplicate entry
167 * @return boolean was the insert successful?
170 public static function insert(array $fields, bool $on_duplicate_update = false)
172 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
173 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
174 if (!DBA::isResult($contact)) {
179 // Search for duplicated contacts and get rid of them
180 self::removeDuplicates($contact['nurl'], $contact['uid']);
186 * @param integer $id Contact ID
187 * @param array $fields Array of selected fields, empty for all
188 * @return array|boolean Contact record if it exists, false otherwise
191 public static function getById($id, $fields = [])
193 return DBA::selectFirst('contact', $fields, ['id' => $id]);
197 * Fetches a contact by a given url
199 * @param string $url profile url
200 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
201 * @param array $fields Field list
202 * @param integer $uid User ID of the contact
203 * @return array contact array
205 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
207 if ($update || is_null($update)) {
208 $cid = self::getIdForURL($url, $uid, $update);
213 $contact = self::getById($cid, $fields);
214 if (empty($contact)) {
220 // Add internal fields
222 if (!empty($fields)) {
223 foreach (['id', 'updated', 'network'] as $internal) {
224 if (!in_array($internal, $fields)) {
225 $fields[] = $internal;
226 $removal[] = $internal;
231 // We first try the nurl (http://server.tld/nick), most common case
232 $options = ['order' => ['id']];
233 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
235 // Then the addr (nick@server.tld)
236 if (!DBA::isResult($contact)) {
237 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
240 // Then the alias (which could be anything)
241 if (!DBA::isResult($contact)) {
242 // The link could be provided as http although we stored it as https
243 $ssl_url = str_replace('http://', 'https://', $url);
244 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
245 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
248 if (!DBA::isResult($contact)) {
252 // Update the contact in the background if needed
253 if ((($contact['updated'] < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
254 in_array($contact['network'], Protocol::FEDERATED)) {
255 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], ($uid == 0 ? 'force' : ''));
258 // Remove the internal fields
259 foreach ($removal as $internal) {
260 unset($contact[$internal]);
267 * Fetches a contact for a given user by a given url.
268 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
270 * @param string $url profile url
271 * @param integer $uid User ID of the contact
272 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
273 * @param array $fields Field list
274 * @return array contact array
276 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
279 $contact = self::getByURL($url, $update, $fields, $uid);
280 if (!empty($contact)) {
281 if (!empty($contact['id'])) {
282 $contact['cid'] = $contact['id'];
289 $contact = self::getByURL($url, $update, $fields);
290 if (!empty($contact['id'])) {
292 $contact['zid'] = $contact['id'];
298 * Tests if the given contact is a follower
300 * @param int $cid Either public contact id or user's contact id
301 * @param int $uid User ID
303 * @return boolean is the contact id a follower?
304 * @throws HTTPException\InternalServerErrorException
305 * @throws \ImagickException
307 public static function isFollower($cid, $uid)
309 if (Contact\User::isBlocked($cid, $uid)) {
313 $cdata = self::getPublicAndUserContacID($cid, $uid);
314 if (empty($cdata['user'])) {
318 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
319 return DBA::exists('contact', $condition);
323 * Tests if the given contact url is a follower
325 * @param string $url Contact URL
326 * @param int $uid User ID
328 * @return boolean is the contact id a follower?
329 * @throws HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 public static function isFollowerByURL($url, $uid)
334 $cid = self::getIdForURL($url, $uid, false);
340 return self::isFollower($cid, $uid);
344 * Tests if the given user follow the given contact
346 * @param int $cid Either public contact id or user's contact id
347 * @param int $uid User ID
349 * @return boolean is the contact url being followed?
350 * @throws HTTPException\InternalServerErrorException
351 * @throws \ImagickException
353 public static function isSharing($cid, $uid)
355 if (Contact\User::isBlocked($cid, $uid)) {
359 $cdata = self::getPublicAndUserContacID($cid, $uid);
360 if (empty($cdata['user'])) {
364 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
365 return DBA::exists('contact', $condition);
369 * Tests if the given user follow the given contact url
371 * @param string $url Contact URL
372 * @param int $uid User ID
374 * @return boolean is the contact url being followed?
375 * @throws HTTPException\InternalServerErrorException
376 * @throws \ImagickException
378 public static function isSharingByURL($url, $uid)
380 $cid = self::getIdForURL($url, $uid, false);
386 return self::isSharing($cid, $uid);
390 * Get the basepath for a given contact link
392 * @param string $url The contact link
393 * @param boolean $dont_update Don't update the contact
395 * @return string basepath
396 * @throws HTTPException\InternalServerErrorException
397 * @throws \ImagickException
399 public static function getBasepath($url, $dont_update = false)
401 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
402 if (!DBA::isResult($contact)) {
406 if (!empty($contact['baseurl'])) {
407 return $contact['baseurl'];
408 } elseif ($dont_update) {
412 // Update the existing contact
413 self::updateFromProbe($contact['id'], '', true);
415 // And fetch the result
416 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
417 if (empty($contact['baseurl'])) {
418 Logger::info('No baseurl for contact', ['url' => $url]);
422 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
423 return $contact['baseurl'];
427 * Check if the given contact url is on the same server
429 * @param string $url The contact link
431 * @return boolean Is it the same server?
433 public static function isLocal($url)
435 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
439 * Check if the given contact ID is on the same server
441 * @param string $url The contact link
443 * @return boolean Is it the same server?
445 public static function isLocalById(int $cid)
447 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
448 if (!DBA::isResult($contact)) {
452 if (empty($contact['baseurl'])) {
453 $baseurl = self::getBasepath($contact['url'], true);
455 $baseurl = $contact['baseurl'];
458 return Strings::compareLink($baseurl, DI::baseUrl());
462 * Returns the public contact id of the given user id
464 * @param integer $uid User ID
466 * @return integer|boolean Public contact id for given user id
469 public static function getPublicIdByUserId($uid)
471 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
472 if (!DBA::isResult($self)) {
475 return self::getIdForURL($self['url'], 0, false);
479 * Returns the contact id for the user and the public contact id for a given contact id
481 * @param int $cid Either public contact id or user's contact id
482 * @param int $uid User ID
484 * @return array with public and user's contact id
485 * @throws HTTPException\InternalServerErrorException
486 * @throws \ImagickException
488 public static function getPublicAndUserContacID($cid, $uid)
490 if (empty($uid) || empty($cid)) {
494 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
495 if (!DBA::isResult($contact)) {
499 // We quit when the user id don't match the user id of the provided contact
500 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
504 if ($contact['uid'] != 0) {
505 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
509 $ucid = $contact['id'];
511 $pcid = $contact['id'];
512 $ucid = Contact::getIdForURL($contact['url'], $uid, false);
515 return ['public' => $pcid, 'user' => $ucid];
519 * Returns contact details for a given contact id in combination with a user id
521 * @param int $cid A contact ID
522 * @param int $uid The User ID
523 * @param array $fields The selected fields for the contact
525 * @return array The contact details
529 public static function getContactForUser($cid, $uid, array $fields = [])
531 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
533 if (!DBA::isResult($contact)) {
541 * Returns a list of contacts belonging in a group
547 public static function getByGroupId($gid)
552 $stmt = DBA::p('SELECT `group_member`.`contact-id`, `contact`.*
554 INNER JOIN `group_member`
555 ON `contact`.`id` = `group_member`.`contact-id`
557 AND `contact`.`uid` = ?
558 AND NOT `contact`.`self`
559 AND NOT `contact`.`deleted`
560 AND NOT `contact`.`blocked`
561 AND NOT `contact`.`pending`
562 ORDER BY `contact`.`name` ASC',
567 if (DBA::isResult($stmt)) {
568 $return = DBA::toArray($stmt);
576 * Creates the self-contact for the provided user id
579 * @return bool Operation success
580 * @throws HTTPException\InternalServerErrorException
582 public static function createSelfFromUserId($uid)
584 // Only create the entry if it doesn't exist yet
585 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
589 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
590 if (!DBA::isResult($user)) {
594 $return = DBA::insert('contact', [
595 'uid' => $user['uid'],
596 'created' => DateTimeFormat::utcNow(),
598 'name' => $user['username'],
599 'nick' => $user['nickname'],
600 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
601 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
602 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
605 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
606 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
607 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
608 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
609 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
610 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
611 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
612 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
613 'name-date' => DateTimeFormat::utcNow(),
614 'uri-date' => DateTimeFormat::utcNow(),
615 'avatar-date' => DateTimeFormat::utcNow(),
623 * Updates the self-contact for the provided user id
626 * @param boolean $update_avatar Force the avatar update
627 * @throws HTTPException\InternalServerErrorException
629 public static function updateSelfFromUserID($uid, $update_avatar = false)
631 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
632 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
633 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
634 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
635 if (!DBA::isResult($self)) {
639 $fields = ['nickname', 'page-flags', 'account-type'];
640 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
641 if (!DBA::isResult($user)) {
645 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
646 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
647 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
648 if (!DBA::isResult($profile)) {
652 $file_suffix = 'jpg';
654 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
655 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
656 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
657 'contact-type' => $user['account-type'],
658 'xmpp' => $profile['xmpp']];
660 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
661 if (DBA::isResult($avatar)) {
662 if ($update_avatar) {
663 $fields['avatar-date'] = DateTimeFormat::utcNow();
666 // Creating the path to the avatar, beginning with the file suffix
667 $types = Images::supportedTypes();
668 if (isset($types[$avatar['type']])) {
669 $file_suffix = $types[$avatar['type']];
672 // We are adding a timestamp value so that other systems won't use cached content
673 $timestamp = strtotime($fields['avatar-date']);
675 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
676 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
678 $fields['photo'] = $prefix . '4' . $suffix;
679 $fields['thumb'] = $prefix . '5' . $suffix;
680 $fields['micro'] = $prefix . '6' . $suffix;
682 // We hadn't found a photo entry, so we use the default avatar
683 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
684 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
685 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
688 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
689 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
690 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
691 $fields['unsearchable'] = !$profile['net-publish'];
693 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
694 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
695 $fields['nurl'] = Strings::normaliseLink($fields['url']);
696 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
697 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
698 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
699 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
700 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
701 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
705 foreach ($fields as $field => $content) {
706 if ($self[$field] != $content) {
712 if ($fields['name'] != $self['name']) {
713 $fields['name-date'] = DateTimeFormat::utcNow();
715 $fields['updated'] = DateTimeFormat::utcNow();
716 DBA::update('contact', $fields, ['id' => $self['id']]);
718 // Update the public contact as well
719 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
721 // Update the profile
722 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
723 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
724 DBA::update('profile', $fields, ['uid' => $uid]);
729 * Marks a contact for removal
731 * @param int $id contact id
733 * @throws HTTPException\InternalServerErrorException
735 public static function remove($id)
737 // We want just to make sure that we don't delete our "self" contact
738 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
739 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
743 // Archive the contact
744 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
746 // Delete it in the background
747 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
751 * Sends an unfriend message. Does not remove the contact
753 * @param array $user User unfriending
754 * @param array $contact Contact unfriended
755 * @param boolean $dissolve Remove the contact on the remote side
757 * @throws HTTPException\InternalServerErrorException
758 * @throws \ImagickException
760 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
762 if (empty($contact['network'])) {
766 $protocol = $contact['network'];
767 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
768 $protocol = Protocol::ACTIVITYPUB;
771 if (($protocol == Protocol::DFRN) && $dissolve) {
772 DFRN::deliver($user, $contact, 'placeholder', true);
773 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
774 // create an unfollow slap
776 $item['verb'] = Activity::O_UNFOLLOW;
777 $item['gravity'] = GRAVITY_ACTIVITY;
778 $item['follow'] = $contact["url"];
783 $item['attach'] = '';
784 $slap = OStatus::salmon($item, $user);
786 if (!empty($contact['notify'])) {
787 Salmon::slapper($user, $contact['notify'], $slap);
789 } elseif ($protocol == Protocol::DIASPORA) {
790 Diaspora::sendUnshare($user, $contact);
791 } elseif ($protocol == Protocol::ACTIVITYPUB) {
792 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
795 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
801 * Marks a contact for archival after a communication issue delay
803 * Contact has refused to recognise us as a friend. We will start a countdown.
804 * If they still don't recognise us in 32 days, the relationship is over,
805 * and we won't waste any more time trying to communicate with them.
806 * This provides for the possibility that their database is temporarily messed
807 * up or some other transient event and that there's a possibility we could recover from it.
809 * @param array $contact contact to mark for archival
811 * @throws HTTPException\InternalServerErrorException
813 public static function markForArchival(array $contact)
815 if (!isset($contact['url']) && !empty($contact['id'])) {
816 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
817 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
818 if (!DBA::isResult($contact)) {
821 } elseif (!isset($contact['url'])) {
822 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
825 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
827 // Contact already archived or "self" contact? => nothing to do
828 if ($contact['archive'] || $contact['self']) {
832 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
833 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
834 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
837 * We really should send a notification to the owner after 2-3 weeks
838 * so they won't be surprised when the contact vanishes and can take
839 * remedial action if this was a serious mistake or glitch
842 /// @todo Check for contact vitality via probing
843 $archival_days = DI::config()->get('system', 'archival_days', 32);
845 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
846 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
847 /* Relationship is really truly dead. archive them rather than
848 * delete, though if the owner tries to unarchive them we'll start
849 * the whole process over again.
851 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
852 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
858 * Cancels the archival countdown
860 * @see Contact::markForArchival()
862 * @param array $contact contact to be unmarked for archival
866 public static function unmarkForArchival(array $contact)
868 // Always unarchive the relay contact entry
869 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
870 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
871 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
872 DBA::update('contact', $fields, $condition);
875 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
876 $exists = DBA::exists('contact', $condition);
878 // We don't need to update, we never marked this contact for archival
883 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
885 if (!isset($contact['url']) && !empty($contact['id'])) {
886 $fields = ['id', 'url', 'batch'];
887 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
888 if (!DBA::isResult($contact)) {
893 // It's a miracle. Our dead contact has inexplicably come back to life.
894 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
895 DBA::update('contact', $fields, ['id' => $contact['id']]);
896 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
900 * Returns the data array for the photo menu of a given contact
902 * @param array $contact contact
903 * @param int $uid optional, default 0
905 * @throws HTTPException\InternalServerErrorException
906 * @throws \ImagickException
908 public static function photoMenu(array $contact, $uid = 0)
913 $contact_drop_link = '';
920 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
922 $profile_link = self::magicLink($contact['url']);
923 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
928 // Look for our own contact if the uid doesn't match and isn't public
929 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
930 if (DBA::isResult($contact_own)) {
931 return self::photoMenu($contact_own, $uid);
936 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
938 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
940 $profile_link = $contact['url'];
943 if ($profile_link === 'mailbox') {
948 $status_link = $profile_link . '/status';
949 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
950 $profile_link = $profile_link . '/profile';
953 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
954 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
957 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
958 $poke_link = 'contact/' . $contact['id'] . '/poke';
961 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
963 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
965 if (!$contact['self']) {
966 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
971 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
972 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
973 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
974 } elseif(!$contact['pending']) {
975 $follow_link = 'follow?url=' . urlencode($contact['url']);
979 if (!empty($follow_link) || !empty($unfollow_link)) {
980 $contact_drop_link = '';
985 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
987 if (empty($contact['uid'])) {
989 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
990 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
991 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
992 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
993 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
997 'status' => [DI::l10n()->t('View Status') , $status_link , true],
998 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
999 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1000 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1001 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1002 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1003 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1004 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1005 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1006 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1009 if (!empty($contact['pending'])) {
1010 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1011 if (DBA::isResult($intro)) {
1012 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1017 $args = ['contact' => $contact, 'menu' => &$menu];
1019 Hook::callAll('contact_photo_menu', $args);
1021 $menucondensed = [];
1023 foreach ($menu as $menuname => $menuitem) {
1024 if ($menuitem[1] != '') {
1025 $menucondensed[$menuname] = $menuitem;
1029 return $menucondensed;
1033 * Returns ungrouped contact count or list for user
1035 * Returns either the total number of ungrouped contacts for the given user
1036 * id or a paginated list of ungrouped contacts.
1038 * @param int $uid uid
1040 * @throws \Exception
1042 public static function getUngroupedList($uid)
1052 SELECT DISTINCT(`contact-id`)
1054 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
1055 WHERE `group`.`uid` = %d
1056 )", intval($uid), intval($uid));
1060 * Have a look at all contact tables for a given profile url.
1061 * This function works as a replacement for probing the contact.
1063 * @param string $url Contact URL
1064 * @param integer $cid Contact ID
1066 * @return array Contact array in the "probe" structure
1068 private static function getProbeDataFromDatabase($url, $cid = null)
1070 // The link could be provided as http although we stored it as https
1071 $ssl_url = str_replace('http://', 'https://', $url);
1073 $fields = ['id', 'uid', 'url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1074 'photo', 'keywords', 'location', 'about', 'network',
1075 'priority', 'batch', 'request', 'confirm', 'poco'];
1078 $data = DBA::selectFirst('contact', $fields, ['id' => $cid]);
1079 if (DBA::isResult($data)) {
1084 $data = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url)]);
1086 if (!DBA::isResult($data)) {
1087 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1088 $data = DBA::selectFirst('contact', $fields, $condition);
1091 if (DBA::isResult($data)) {
1092 // For security reasons we don't fetch key data from our users
1093 $data["pubkey"] = '';
1097 $fields = ['url', 'addr', 'alias', 'notify', 'name', 'nick',
1098 'photo', 'keywords', 'location', 'about', 'network'];
1099 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1100 $data = DBA::selectFirst('contact', $fields, $condition);
1102 if (DBA::isResult($data)) {
1103 $data["pubkey"] = '';
1105 $data["priority"] = 0;
1106 $data["batch"] = '';
1107 $data["request"] = '';
1108 $data["confirm"] = '';
1113 $data = ActivityPub::probeProfile($url, false);
1114 if (!empty($data)) {
1118 $fields = ['url', 'addr', 'alias', 'notify', 'poll', 'name', 'nick',
1119 'photo', 'network', 'priority', 'batch', 'request', 'confirm'];
1120 $data = DBA::selectFirst('fcontact', $fields, ['url' => $url]);
1122 if (!DBA::isResult($data)) {
1123 $condition = ['alias' => [$url, Strings::normaliseLink($url), $ssl_url]];
1124 $data = DBA::selectFirst('contact', $fields, $condition);
1127 if (DBA::isResult($data)) {
1128 $data["pubkey"] = '';
1129 $data["keywords"] = '';
1130 $data["location"] = '';
1131 $data["about"] = '';
1140 * Fetch the contact id for a given URL and user
1142 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1143 * `addr` or `alias`.
1145 * If there's no record and we aren't looking for a public contact, we quit.
1146 * If there's one, we check that it isn't time to update the picture else we
1147 * directly return the found contact id.
1149 * Second, we probe the provided $url whether it's http://server.tld/profile or
1150 * nick@server.tld. We quit if we can't get any info back.
1152 * Third, we create the contact record if it doesn't exist
1154 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1155 * if there's any updates
1157 * @param string $url Contact URL
1158 * @param integer $uid The user id for the contact (0 = public contact)
1159 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
1160 * @param array $default Default value for creating the contact when every else fails
1162 * @return integer Contact ID
1163 * @throws HTTPException\InternalServerErrorException
1164 * @throws \ImagickException
1166 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1168 Logger::info('Get contact data', ['url' => $url, 'user' => $uid]);
1176 $contact = self::getByURL($url, false, ['id', 'avatar', 'updated', 'network'], $uid);
1178 if (!empty($contact)) {
1179 $contact_id = $contact["id"];
1181 if (empty($default) && in_array($contact['network'], [Protocol::MAIL, Protocol::PHANTOM]) && ($uid == 0)) {
1182 // Update public mail accounts via their user's accounts
1183 $fields = ['network', 'addr', 'name', 'nick', 'avatar', 'photo', 'thumb', 'micro'];
1184 $mailcontact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1185 if (!DBA::isResult($mailcontact)) {
1186 $mailcontact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `network` = ? AND `uid` != 0", $url, Protocol::MAIL]);
1189 if (DBA::isResult($mailcontact)) {
1190 DBA::update('contact', $mailcontact, ['id' => $contact_id]);
1194 if (empty($update)) {
1197 } elseif ($uid != 0) {
1198 // Non-existing user-specific contact, exiting
1202 if (!$update && empty($default)) {
1203 // When we don't want to update, we look if we know this contact in any way
1204 $data = self::getProbeDataFromDatabase($url, $contact_id);
1205 $background_update = true;
1206 } elseif (!$update && !empty($default['network'])) {
1207 // If there are default values, take these
1209 $background_update = false;
1212 $background_update = false;
1215 if ((empty($data) && is_null($update)) || $update) {
1216 $data = Probe::uri($url, "", $uid);
1219 // Take the default values when probing failed
1220 if (!empty($default) && (empty($data['network']) || !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO])))) {
1221 $data = array_merge($data, $default);
1224 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1225 Logger::info('No valid network found', ['url' => $url, 'data' => $data, 'callstack' => System::callstack(20)]);
1229 if (!empty($data['baseurl'])) {
1230 $data['baseurl'] = GServer::cleanURL($data['baseurl']);
1233 if (!empty($data['baseurl']) && empty($data['gsid'])) {
1234 $data['gsid'] = GServer::getID($data['baseurl']);
1237 if (!$contact_id && !empty($data['alias']) && ($data['alias'] != $data['url'])) {
1238 $contact = self::getByURL($data['alias'], false, ['id']);
1239 if (!empty($contact['id'])) {
1240 $contact_id = $contact['id'];
1245 $data['last-item'] = Probe::getLastUpdate($data);
1246 Logger::info('Fetched last item', ['url' => $url, 'probed_url' => $data['url'], 'last-item' => $data['last-item'], 'callstack' => System::callstack(20)]);
1252 'created' => DateTimeFormat::utcNow(),
1253 'url' => $data['url'],
1254 'nurl' => Strings::normaliseLink($data['url']),
1255 'addr' => $data['addr'] ?? '',
1256 'alias' => $data['alias'] ?? '',
1257 'notify' => $data['notify'] ?? '',
1258 'poll' => $data['poll'] ?? '',
1259 'name' => $data['name'] ?? '',
1260 'nick' => $data['nick'] ?? '',
1261 'keywords' => $data['keywords'] ?? '',
1262 'location' => $data['location'] ?? '',
1263 'about' => $data['about'] ?? '',
1264 'network' => $data['network'],
1265 'pubkey' => $data['pubkey'] ?? '',
1266 'rel' => self::SHARING,
1267 'priority' => $data['priority'] ?? 0,
1268 'batch' => $data['batch'] ?? '',
1269 'request' => $data['request'] ?? '',
1270 'confirm' => $data['confirm'] ?? '',
1271 'poco' => $data['poco'] ?? '',
1272 'baseurl' => $data['baseurl'] ?? '',
1273 'gsid' => $data['gsid'] ?? null,
1274 'name-date' => DateTimeFormat::utcNow(),
1275 'uri-date' => DateTimeFormat::utcNow(),
1276 'avatar-date' => DateTimeFormat::utcNow(),
1282 if (!empty($data['last-item'])) {
1283 $fields['last-item'] = $data['last-item'];
1286 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1288 // Before inserting we do check if the entry does exist now.
1289 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1290 if (!DBA::isResult($contact)) {
1291 Logger::info('Create new contact', $fields);
1293 self::insert($fields);
1295 // We intentionally aren't using lastInsertId here. There is a chance for duplicates.
1296 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1297 if (!DBA::isResult($contact)) {
1298 Logger::info('Contact creation failed', $fields);
1303 Logger::info('Contact had been created before', ['id' => $contact["id"], 'url' => $url, 'contact' => $fields]);
1306 $contact_id = $contact["id"];
1309 if (!empty($data['photo']) && ($data['network'] != Protocol::FEED)) {
1310 self::updateAvatar($contact_id, $data['photo']);
1313 if (in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1314 if ($background_update) {
1315 // Update in the background when we fetched the data solely from the database
1316 Worker::add(PRIORITY_MEDIUM, "UpdateContact", $contact_id, ($uid == 0 ? 'force' : ''));
1318 // Else do a direct update
1319 self::updateFromProbe($contact_id, '', false);
1322 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'baseurl', 'gsid', 'last-item'];
1323 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact_id]);
1325 // This condition should always be true
1326 if (!DBA::isResult($contact)) {
1331 'url' => $data['url'],
1332 'nurl' => Strings::normaliseLink($data['url']),
1333 'updated' => DateTimeFormat::utcNow(),
1337 $fields = ['addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'baseurl', 'gsid'];
1339 foreach ($fields as $field) {
1340 $updated[$field] = ($data[$field] ?? '') ?: $contact[$field];
1343 if (!empty($data['last-item']) && ($contact['last-item'] < $data['last-item'])) {
1344 $updated['last-item'] = $data['last-item'];
1347 if (($updated['addr'] != $contact['addr']) || (!empty($data['alias']) && ($data['alias'] != $contact['alias']))) {
1348 $updated['uri-date'] = DateTimeFormat::utcNow();
1351 if (($data['name'] != $contact['name']) || ($data['nick'] != $contact['nick'])) {
1352 $updated['name-date'] = DateTimeFormat::utcNow();
1355 DBA::update('contact', $updated, ['id' => $contact_id], $contact);
1362 * Checks if the contact is archived
1364 * @param int $cid contact id
1366 * @return boolean Is the contact archived?
1367 * @throws HTTPException\InternalServerErrorException
1369 public static function isArchived(int $cid)
1375 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1376 if (!DBA::isResult($contact)) {
1380 if ($contact['archive']) {
1384 // Check status of ActivityPub endpoints
1385 $apcontact = APContact::getByURL($contact['url'], false);
1386 if (!empty($apcontact)) {
1387 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1391 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1396 // Check status of Diaspora endpoints
1397 if (!empty($contact['batch'])) {
1398 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1399 return DBA::exists('contact', $condition);
1406 * Checks if the contact is blocked
1408 * @param int $cid contact id
1410 * @return boolean Is the contact blocked?
1411 * @throws HTTPException\InternalServerErrorException
1413 public static function isBlocked($cid)
1419 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1420 if (!DBA::isResult($blocked)) {
1424 if (Network::isUrlBlocked($blocked['url'])) {
1428 return (bool) $blocked['blocked'];
1432 * Checks if the contact is hidden
1434 * @param int $cid contact id
1436 * @return boolean Is the contact hidden?
1437 * @throws \Exception
1439 public static function isHidden($cid)
1445 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1446 if (!DBA::isResult($hidden)) {
1449 return (bool) $hidden['hidden'];
1453 * Returns posts from a given contact url
1455 * @param string $contact_url Contact URL
1456 * @param bool $thread_mode
1457 * @param int $update
1458 * @return string posts in HTML
1459 * @throws \Exception
1461 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1463 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1467 * Returns posts from a given contact id
1469 * @param integer $cid
1470 * @param bool $thread_mode
1471 * @param integer $update
1472 * @return string posts in HTML
1473 * @throws \Exception
1475 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1479 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1480 if (!DBA::isResult($contact)) {
1484 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1485 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1487 $sql = "`item`.`uid` = ?";
1490 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1493 $condition = ["`$contact_field` = ? AND `gravity` = ? AND " . $sql,
1494 $cid, GRAVITY_PARENT, local_user()];
1496 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1497 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1500 if (DI::mode()->isMobile()) {
1501 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1502 DI::config()->get('system', 'itemspage_network_mobile'));
1504 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1505 DI::config()->get('system', 'itemspage_network'));
1508 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1510 $params = ['order' => ['received' => true],
1511 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1514 $r = Item::selectThreadForUser(local_user(), ['uri'], $condition, $params);
1516 $items = Item::inArray($r);
1518 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1520 $r = Item::selectForUser(local_user(), [], $condition, $params);
1522 $items = Item::inArray($r);
1524 $o = conversation($a, $items, 'contact-posts', false);
1528 $o .= $pager->renderMinimal(count($items));
1535 * Returns the account type name
1537 * The function can be called with either the user or the contact array
1539 * @param array $contact contact or user array
1542 public static function getAccountType(array $contact)
1544 // There are several fields that indicate that the contact or user is a forum
1545 // "page-flags" is a field in the user table,
1546 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1547 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1548 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1549 || (isset($contact['forum']) && intval($contact['forum']))
1550 || (isset($contact['prv']) && intval($contact['prv']))
1551 || (isset($contact['community']) && intval($contact['community']))
1553 $type = self::TYPE_COMMUNITY;
1555 $type = self::TYPE_PERSON;
1558 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1559 if (isset($contact["contact-type"])) {
1560 $type = $contact["contact-type"];
1563 if (isset($contact["account-type"])) {
1564 $type = $contact["account-type"];
1568 case self::TYPE_ORGANISATION:
1569 $account_type = DI::l10n()->t("Organisation");
1572 case self::TYPE_NEWS:
1573 $account_type = DI::l10n()->t('News');
1576 case self::TYPE_COMMUNITY:
1577 $account_type = DI::l10n()->t("Forum");
1585 return $account_type;
1593 * @throws \Exception
1595 public static function block($cid, $reason = null)
1597 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1603 * Unblocks a contact
1607 * @throws \Exception
1609 public static function unblock($cid)
1611 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1617 * Ensure that cached avatar exist
1619 * @param integer $cid
1621 public static function checkAvatarCache(int $cid)
1623 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1624 if (!DBA::isResult($contact)) {
1628 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1632 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1634 self::updateAvatar($cid, $contact['avatar'], true);
1638 * Return the photo path for a given contact array in the given size
1640 * @param array $contact contact array
1641 * @param string $field Fieldname of the photo in the contact array
1642 * @param string $default Default path when no picture had been found
1643 * @param string $size Size of the avatar picture
1644 * @param string $avatar Avatar path that is displayed when no photo had been found
1645 * @return string photo path
1647 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1649 if (!empty($contact)) {
1650 $contact = self::checkAvatarCacheByArray($contact);
1651 if (!empty($contact[$field])) {
1652 $avatar = $contact[$field];
1656 if (empty($avatar)) {
1660 if (Proxy::isLocalImage($avatar)) {
1663 return Proxy::proxifyUrl($avatar, false, $size);
1668 * Return the photo path for a given contact array
1670 * @param array $contact Contact array
1671 * @param string $avatar Avatar path that is displayed when no photo had been found
1672 * @return string photo path
1674 public static function getPhoto(array $contact, string $avatar = '')
1676 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1680 * Return the photo path (thumb size) for a given contact array
1682 * @param array $contact Contact array
1683 * @param string $avatar Avatar path that is displayed when no photo had been found
1684 * @return string photo path
1686 public static function getThumb(array $contact, string $avatar = '')
1688 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1692 * Return the photo path (micro size) for a given contact array
1694 * @param array $contact Contact array
1695 * @param string $avatar Avatar path that is displayed when no photo had been found
1696 * @return string photo path
1698 public static function getMicro(array $contact, string $avatar = '')
1700 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1704 * Check the given contact array for avatar cache fields
1706 * @param array $contact
1707 * @return array contact array with avatar cache fields
1709 private static function checkAvatarCacheByArray(array $contact)
1712 $contact_fields = [];
1713 $fields = ['photo', 'thumb', 'micro'];
1714 foreach ($fields as $field) {
1715 if (isset($contact[$field])) {
1716 $contact_fields[] = $field;
1718 if (isset($contact[$field]) && empty($contact[$field])) {
1727 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1728 self::updateAvatar($contact['id'], $contact['avatar'], true);
1730 $new_contact = self::getById($contact['id'], $contact_fields);
1731 if (DBA::isResult($new_contact)) {
1732 // We only update the cache fields
1733 $contact = array_merge($contact, $new_contact);
1737 /// add the default avatars if the fields aren't filled
1738 if (isset($contact['photo']) && empty($contact['photo'])) {
1739 $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1741 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1742 $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1744 if (isset($contact['micro']) && empty($contact['micro'])) {
1745 $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1752 * Updates the avatar links in a contact only if needed
1754 * @param int $cid Contact id
1755 * @param string $avatar Link to avatar picture
1756 * @param bool $force force picture update
1759 * @throws HTTPException\InternalServerErrorException
1760 * @throws HTTPException\NotFoundException
1761 * @throws \ImagickException
1763 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1765 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1766 if (!DBA::isResult($contact)) {
1770 $uid = $contact['uid'];
1772 // Only update the cached photo links of public contacts when they already are cached
1773 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1774 if ($contact['avatar'] != $avatar) {
1775 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1776 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1782 $contact['photo'] ?? '',
1783 $contact['thumb'] ?? '',
1784 $contact['micro'] ?? '',
1787 $update = ($contact['avatar'] != $avatar) || $force;
1790 foreach ($data as $image_uri) {
1791 $image_rid = Photo::ridFromURI($image_uri);
1792 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1793 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1800 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1802 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1803 DBA::update('contact', $fields, ['id' => $cid]);
1804 } elseif (empty($contact['avatar'])) {
1805 // Ensure that the avatar field is set
1806 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1807 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1813 * Helper function for "updateFromProbe". Updates personal and public contact
1815 * @param integer $id contact id
1816 * @param integer $uid user id
1817 * @param string $url The profile URL of the contact
1818 * @param array $fields The fields that are updated
1820 * @throws \Exception
1822 private static function updateContact($id, $uid, $url, array $fields)
1824 if (!DBA::update('contact', $fields, ['id' => $id])) {
1825 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1829 // Search for duplicated contacts and get rid of them
1830 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1834 // Archive or unarchive the contact. We only need to do this for the public contact.
1835 // The archive/unarchive function will update the personal contacts by themselves.
1836 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1837 if (!DBA::isResult($contact)) {
1838 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1842 if (!empty($fields['success_update'])) {
1843 self::unmarkForArchival($contact);
1844 } elseif (!empty($fields['failure_update'])) {
1845 self::markForArchival($contact);
1848 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1850 // These contacts are sharing with us, we don't poll them.
1851 // This means that we don't set the update fields in "OnePoll.php".
1852 $condition['rel'] = self::SHARING;
1853 DBA::update('contact', $fields, $condition);
1855 unset($fields['last-update']);
1856 unset($fields['success_update']);
1857 unset($fields['failure_update']);
1859 if (empty($fields)) {
1863 // We are polling these contacts, so we mustn't set the update fields here.
1864 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1865 DBA::update('contact', $fields, $condition);
1869 * Remove duplicated contacts
1871 * @param string $nurl Normalised contact url
1872 * @param integer $uid User id
1874 * @throws \Exception
1876 public static function removeDuplicates(string $nurl, int $uid)
1878 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1879 $count = DBA::count('contact', $condition);
1884 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1885 if (!DBA::isResult($first_contact)) {
1886 // Shouldn't happen - so we handle it
1890 $first = $first_contact['id'];
1891 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1892 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1893 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1894 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1898 // Find all duplicates
1899 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1900 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1901 while ($duplicate = DBA::fetch($duplicates)) {
1902 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1906 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1908 DBA::close($duplicates);
1909 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1914 * @param integer $id contact id
1915 * @param string $network Optional network we are probing for
1916 * @param boolean $force Optional forcing of network probing (otherwise we use the cached data)
1918 * @throws HTTPException\InternalServerErrorException
1919 * @throws \ImagickException
1921 public static function updateFromProbe(int $id, string $network = '', bool $force = false)
1924 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1925 This will reliably kill your communication with old Friendica contacts.
1928 // These fields aren't updated by this routine:
1929 // 'xmpp', 'sensitive'
1931 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
1932 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1933 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey'];
1934 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1935 if (!DBA::isResult($contact)) {
1939 $uid = $contact['uid'];
1940 unset($contact['uid']);
1942 $pubkey = $contact['pubkey'];
1943 unset($contact['pubkey']);
1945 $contact['photo'] = $contact['avatar'];
1946 unset($contact['avatar']);
1948 $ret = Probe::uri($contact['url'], $network, $uid, !$force);
1950 $updated = DateTimeFormat::utcNow();
1952 // We must not try to update relay contacts via probe. They are no real contacts.
1953 // We check after the probing to be able to correct falsely detected contact types.
1954 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1955 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1956 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1957 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1961 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1962 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1963 if ($force && ($uid == 0)) {
1964 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1969 if (Contact\Relation::isDiscoverable($ret['url'])) {
1970 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1973 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1974 $ret['unsearchable'] = $ret['hide'];
1977 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1978 $ret['forum'] = false;
1979 $ret['prv'] = false;
1980 $ret['contact-type'] = $ret['account-type'];
1981 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1982 $apcontact = APContact::getByURL($ret['url'], false);
1983 if (isset($apcontact['manually-approve'])) {
1984 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1985 $ret['prv'] = (bool)!$ret['forum'];
1990 $new_pubkey = $ret['pubkey'];
1994 // make sure to not overwrite existing values with blank entries except some technical fields
1995 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1996 foreach ($ret as $key => $val) {
1997 if (!array_key_exists($key, $contact)) {
1999 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2000 $ret[$key] = $contact[$key];
2001 } elseif ($ret[$key] != $contact[$key]) {
2006 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2007 self::updateAvatar($id, $ret['photo'], $update || $force);
2012 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2015 // Update the public contact
2017 self::updateFromProbeByURL($ret['url']);
2023 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2024 $ret['updated'] = $updated;
2026 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2027 if (empty($pubkey) && !empty($new_pubkey)) {
2028 $ret['pubkey'] = $new_pubkey;
2031 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2032 $ret['uri-date'] = DateTimeFormat::utcNow();
2035 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
2036 $ret['name-date'] = $updated;
2039 if ($force && ($uid == 0)) {
2040 $ret['last-update'] = $updated;
2041 $ret['success_update'] = $updated;
2042 $ret['failed'] = false;
2045 unset($ret['photo']);
2047 self::updateContact($id, $uid, $ret['url'], $ret);
2052 public static function updateFromProbeByURL($url, $force = false)
2054 $id = self::getIdForURL($url);
2060 self::updateFromProbe($id, '', $force);
2066 * Detects if a given contact array belongs to a legacy DFRN connection
2068 * @param array $contact
2071 public static function isLegacyDFRNContact($contact)
2073 // Newer Friendica contacts are connected via AP, then these fields aren't set
2074 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2078 * Detects the communication protocol for a given contact url.
2079 * This is used to detect Friendica contacts that we can communicate via AP.
2081 * @param string $url contact url
2082 * @param string $network Network of that contact
2083 * @return string with protocol
2085 public static function getProtocol($url, $network)
2087 if ($network != Protocol::DFRN) {
2091 $apcontact = APContact::getByURL($url);
2092 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2093 return Protocol::ACTIVITYPUB;
2100 * Takes a $uid and a url/handle and adds a new contact
2102 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2103 * dfrn_request page.
2105 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2108 * $return['success'] boolean true if successful
2109 * $return['message'] error text if success is false.
2111 * Takes a $uid and a url/handle and adds a new contact
2113 * @param array $user The user the contact should be created for
2114 * @param string $url The profile URL of the contact
2115 * @param bool $interactive
2116 * @param string $network
2118 * @throws HTTPException\InternalServerErrorException
2119 * @throws HTTPException\NotFoundException
2120 * @throws \ImagickException
2122 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2124 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2126 // remove ajax junk, e.g. Twitter
2127 $url = str_replace('/#!/', '/', $url);
2129 if (!Network::isUrlAllowed($url)) {
2130 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2134 if (Network::isUrlBlocked($url)) {
2135 $result['message'] = DI::l10n()->t('Blocked domain');
2140 $result['message'] = DI::l10n()->t('Connect URL missing.');
2144 $arr = ['url' => $url, 'contact' => []];
2146 Hook::callAll('follow', $arr);
2149 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2153 if (!empty($arr['contact']['name'])) {
2154 $ret = $arr['contact'];
2156 $ret = Probe::uri($url, $network, $user['uid'], false);
2159 if (($network != '') && ($ret['network'] != $network)) {
2160 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2164 // check if we already have a contact
2165 // the poll url is more reliable than the profile url, as we may have
2166 // indirect links or webfinger links
2168 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2169 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2170 if (!DBA::isResult($contact)) {
2171 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2172 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2175 $protocol = self::getProtocol($ret['url'], $ret['network']);
2177 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2179 if (strlen(DI::baseUrl()->getUrlPath())) {
2180 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2182 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2185 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2189 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2190 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2191 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2195 // This extra param just confuses things, remove it
2196 if ($protocol === Protocol::DIASPORA) {
2197 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2200 // do we have enough information?
2201 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2202 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2203 if (empty($ret['poll'])) {
2204 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2206 if (empty($ret['name'])) {
2207 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2209 if (empty($ret['url'])) {
2210 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2212 if (strpos($ret['url'], '@') !== false) {
2213 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2214 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2219 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2220 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2221 $ret['notify'] = '';
2224 if (!$ret['notify']) {
2225 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2228 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2230 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2232 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2235 if ($protocol == Protocol::ACTIVITYPUB) {
2236 $apcontact = APContact::getByURL($ret['url'], false);
2237 if (isset($apcontact['manually-approve'])) {
2238 $pending = (bool)$apcontact['manually-approve'];
2242 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2246 if (DBA::isResult($contact)) {
2248 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2250 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2251 DBA::update('contact', $fields, ['id' => $contact['id']]);
2253 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2255 // create contact record
2257 'uid' => $user['uid'],
2258 'created' => DateTimeFormat::utcNow(),
2259 'url' => $ret['url'],
2260 'nurl' => Strings::normaliseLink($ret['url']),
2261 'addr' => $ret['addr'],
2262 'alias' => $ret['alias'],
2263 'batch' => $ret['batch'],
2264 'notify' => $ret['notify'],
2265 'poll' => $ret['poll'],
2266 'poco' => $ret['poco'],
2267 'name' => $ret['name'],
2268 'nick' => $ret['nick'],
2269 'network' => $ret['network'],
2270 'baseurl' => $ret['baseurl'],
2271 'gsid' => $ret['gsid'] ?? null,
2272 'protocol' => $protocol,
2273 'pubkey' => $ret['pubkey'],
2274 'rel' => $new_relation,
2275 'priority'=> $ret['priority'],
2276 'writable'=> $writeable,
2277 'hidden' => $hidden,
2280 'pending' => $pending,
2285 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2286 if (!DBA::isResult($contact)) {
2287 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2291 $contact_id = $contact['id'];
2292 $result['cid'] = $contact_id;
2294 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2296 // Update the avatar
2297 self::updateAvatar($contact_id, $ret['photo']);
2299 // pull feed and consume it, which should subscribe to the hub.
2301 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2303 $owner = User::getOwnerDataById($user['uid']);
2305 if (DBA::isResult($owner)) {
2306 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2307 // create a follow slap
2309 $item['verb'] = Activity::FOLLOW;
2310 $item['gravity'] = GRAVITY_ACTIVITY;
2311 $item['follow'] = $contact["url"];
2313 $item['title'] = '';
2315 $item['uri-id'] = 0;
2316 $item['attach'] = '';
2318 $slap = OStatus::salmon($item, $owner);
2320 if (!empty($contact['notify'])) {
2321 Salmon::slapper($owner, $contact['notify'], $slap);
2323 } elseif ($protocol == Protocol::DIASPORA) {
2324 $ret = Diaspora::sendShare($owner, $contact);
2325 Logger::log('share returns: ' . $ret);
2326 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2327 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2328 if (empty($activity_id)) {
2329 // This really should never happen
2333 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2334 Logger::log('Follow returns: ' . $ret);
2338 $result['success'] = true;
2343 * Updated contact's SSL policy
2345 * @param array $contact Contact array
2346 * @param string $new_policy New policy, valid: self,full
2348 * @return array Contact array with updated values
2349 * @throws \Exception
2351 public static function updateSslPolicy(array $contact, $new_policy)
2353 $ssl_changed = false;
2354 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2355 $ssl_changed = true;
2356 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2357 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2358 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2359 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2360 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2361 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2364 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2365 $ssl_changed = true;
2366 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2367 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2368 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2369 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2370 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2371 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2375 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2376 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2377 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2378 DBA::update('contact', $fields, ['id' => $contact['id']]);
2385 * @param array $importer Owner (local user) data
2386 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2387 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2388 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2389 * @param string $note Introduction additional message
2390 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2391 * @throws HTTPException\InternalServerErrorException
2392 * @throws \ImagickException
2394 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2396 // Should always be set
2397 if (empty($datarray['author-id'])) {
2401 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2402 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2403 if (!DBA::isResult($pub_contact)) {
2404 // Should never happen
2408 // Contact is blocked at node-level
2409 if (self::isBlocked($datarray['author-id'])) {
2413 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2414 $name = $pub_contact['name'];
2415 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2416 $nick = $pub_contact['nick'];
2417 $network = $pub_contact['network'];
2419 // Ensure that we don't create a new contact when there already is one
2420 $cid = self::getIdForURL($url, $importer['uid']);
2422 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2425 if (!empty($contact)) {
2426 if (!empty($contact['pending'])) {
2427 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2431 // Contact is blocked at user-level
2432 if (!empty($contact['id']) && !empty($importer['id']) &&
2433 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2437 // Make sure that the existing contact isn't archived
2438 self::unmarkForArchival($contact);
2440 if (($contact['rel'] == self::SHARING)
2441 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2442 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2443 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2446 // Ensure to always have the correct network type, independent from the connection request method
2447 self::updateFromProbe($contact['id'], '', true);
2451 // send email notification to owner?
2452 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2453 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2457 // create contact record
2458 DBA::insert('contact', [
2459 'uid' => $importer['uid'],
2460 'created' => DateTimeFormat::utcNow(),
2462 'nurl' => Strings::normaliseLink($url),
2465 'network' => $network,
2466 'rel' => self::FOLLOWER,
2473 $contact_id = DBA::lastInsertId();
2475 // Ensure to always have the correct network type, independent from the connection request method
2476 self::updateFromProbe($contact_id, '', true);
2478 self::updateAvatar($contact_id, $photo, true);
2480 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2482 /// @TODO Encapsulate this into a function/method
2483 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2484 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2485 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2486 // create notification
2487 $hash = Strings::getRandomHex();
2489 if (is_array($contact_record)) {
2490 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2491 'blocked' => false, 'knowyou' => false, 'note' => $note,
2492 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2495 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2497 if (($user['notify-flags'] & Type::INTRO) &&
2498 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2501 'type' => Type::INTRO,
2502 'notify_flags' => $user['notify-flags'],
2503 'language' => $user['language'],
2504 'to_name' => $user['username'],
2505 'to_email' => $user['email'],
2506 'uid' => $user['uid'],
2507 'link' => DI::baseUrl() . '/notifications/intros',
2508 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2509 'source_link' => $contact_record['url'],
2510 'source_photo' => $contact_record['photo'],
2511 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2515 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2516 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2517 self::createFromProbe($importer, $url, false, $network);
2520 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2521 $fields = ['pending' => false];
2522 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2523 $fields['rel'] = Contact::FRIEND;
2526 DBA::update('contact', $fields, $condition);
2535 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2537 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2538 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2540 Contact::remove($contact['id']);
2544 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2546 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2547 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2549 Contact::remove($contact['id']);
2554 * Create a birthday event.
2556 * Update the year and the birthday.
2558 public static function updateBirthdays()
2562 AND `bd` > "0001-01-01"
2563 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2564 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2565 AND NOT `contact`.`pending`
2566 AND NOT `contact`.`hidden`
2567 AND NOT `contact`.`blocked`
2568 AND NOT `contact`.`archive`
2569 AND NOT `contact`.`deleted`',
2574 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2576 while ($contact = DBA::fetch($contacts)) {
2577 Logger::log('update_contact_birthday: ' . $contact['bd']);
2579 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2581 if (Event::createBirthday($contact, $nextbd)) {
2585 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2586 ['id' => $contact['id']]
2590 DBA::close($contacts);
2594 * Remove the unavailable contact ids from the provided list
2596 * @param array $contact_ids Contact id list
2598 * @throws \Exception
2600 public static function pruneUnavailable(array $contact_ids)
2602 if (empty($contact_ids)) {
2606 $contacts = Contact::selectToArray(['id'], [
2607 'id' => $contact_ids,
2613 return array_column($contacts, 'id');
2617 * Returns a magic link to authenticate remote visitors
2619 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2621 * @param string $contact_url The address of the target contact profile
2622 * @param string $url An url that we will be redirected to after the authentication
2624 * @return string with "redir" link
2625 * @throws HTTPException\InternalServerErrorException
2626 * @throws \ImagickException
2628 public static function magicLink($contact_url, $url = '')
2630 if (!Session::isAuthenticated()) {
2631 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2634 $data = self::getProbeDataFromDatabase($contact_url);
2636 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2639 // Prevents endless loop in case only a non-public contact exists for the contact URL
2640 unset($data['uid']);
2642 return self::magicLinkByContact($data, $url ?: $contact_url);
2646 * Returns a magic link to authenticate remote visitors
2648 * @param integer $cid The contact id of the target contact profile
2649 * @param string $url An url that we will be redirected to after the authentication
2651 * @return string with "redir" link
2652 * @throws HTTPException\InternalServerErrorException
2653 * @throws \ImagickException
2655 public static function magicLinkbyId($cid, $url = '')
2657 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2659 return self::magicLinkByContact($contact, $url);
2663 * Returns a magic link to authenticate remote visitors
2665 * @param array $contact The contact array with "uid", "network" and "url"
2666 * @param string $url An url that we will be redirected to after the authentication
2668 * @return string with "redir" link
2669 * @throws HTTPException\InternalServerErrorException
2670 * @throws \ImagickException
2672 public static function magicLinkByContact($contact, $url = '')
2674 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2676 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2677 return $destination;
2680 // Only redirections to the same host do make sense
2681 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2685 if (!empty($contact['uid'])) {
2686 return self::magicLink($contact['url'], $url);
2689 if (empty($contact['id'])) {
2690 return $destination;
2693 $redirect = 'redir/' . $contact['id'];
2695 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2696 $redirect .= '?url=' . $url;
2703 * Remove a contact from all groups
2705 * @param integer $contact_id
2707 * @return boolean Success
2709 public static function removeFromGroups($contact_id)
2711 return DBA::delete('group_member', ['contact-id' => $contact_id]);
2715 * Is the contact a forum?
2717 * @param integer $contactid ID of the contact
2719 * @return boolean "true" if it is a forum
2721 public static function isForum($contactid)
2723 $fields = ['forum', 'prv'];
2724 $condition = ['id' => $contactid];
2725 $contact = DBA::selectFirst('contact', $fields, $condition);
2726 if (!DBA::isResult($contact)) {
2731 return ($contact['forum'] || $contact['prv']);
2735 * Can the remote contact receive private messages?
2737 * @param array $contact
2740 public static function canReceivePrivateMessages(array $contact)
2742 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2743 $self = $contact['self'] ?? false;
2745 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2749 * Search contact table by nick or name
2751 * @param string $search Name or nick
2752 * @param string $mode Search mode (e.g. "community")
2754 * @return array with search results
2755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2757 public static function searchByName($search, $mode = '')
2759 if (empty($search)) {
2763 // check supported networks
2764 if (DI::config()->get('system', 'diaspora_enabled')) {
2765 $diaspora = Protocol::DIASPORA;
2767 $diaspora = Protocol::DFRN;
2770 if (!DI::config()->get('system', 'ostatus_disabled')) {
2771 $ostatus = Protocol::OSTATUS;
2773 $ostatus = Protocol::DFRN;
2776 // check if we search only communities or every contact
2777 if ($mode === 'community') {
2778 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2785 $results = DBA::p("SELECT * FROM `contact`
2786 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2787 NOT `failed` AND `uid` = ? AND
2788 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2789 ORDER BY `nurl` DESC LIMIT 1000",
2790 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2793 $contacts = DBA::toArray($results);
2798 * Add public contacts from an array
2800 * @param array $urls
2801 * @return array result "count", "added" and "updated"
2803 public static function addByUrls(array $urls)
2809 foreach ($urls as $url) {
2810 $contact = Contact::getByURL($url, false, ['id']);
2811 if (empty($contact['id'])) {
2812 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2815 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2821 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2825 * Returns a random, global contact of the current node
2827 * @return string The profile URL
2830 public static function getRandomUrl()
2832 $r = DBA::selectFirst('contact', ['url'], [
2833 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2834 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2835 ], ['order' => ['RAND()']]);
2837 if (DBA::isResult($r)) {