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;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
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
56 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
57 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
58 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
61 * @deprecated since version 2019.03
62 * @see User::PAGE_FLAGS_NORMAL
64 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
66 * @deprecated since version 2019.03
67 * @see User::PAGE_FLAGS_SOAPBOX
69 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
71 * @deprecated since version 2019.03
72 * @see User::PAGE_FLAGS_COMMUNITY
74 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
76 * @deprecated since version 2019.03
77 * @see User::PAGE_FLAGS_FREELOVE
79 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
81 * @deprecated since version 2019.03
82 * @see User::PAGE_FLAGS_BLOG
84 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
86 * @deprecated since version 2019.03
87 * @see User::PAGE_FLAGS_PRVGROUP
89 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
94 const LOCK_INSERT = 'contact-insert';
99 * TYPE_UNKNOWN - unknown type
101 * TYPE_PERSON - the account belongs to a person
102 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
104 * TYPE_ORGANISATION - the account belongs to an organisation
105 * Associated page type: PAGE_SOAPBOX
107 * TYPE_NEWS - the account is a news reflector
108 * Associated page type: PAGE_SOAPBOX
110 * TYPE_COMMUNITY - the account is community forum
111 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
113 * TYPE_RELAY - the account is a relay
114 * This will only be assigned to contacts, not to user accounts
117 const TYPE_UNKNOWN = -1;
118 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
119 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
120 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
121 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
122 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
142 * @param array $fields Array of selected fields, empty for all
143 * @param array $condition Array of fields for condition
144 * @param array $params Array of several parameters
148 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
150 return DBA::selectToArray('contact', $fields, $condition, $params);
154 * @param array $fields Array of selected fields, empty for all
155 * @param array $condition Array of fields for condition
156 * @param array $params Array of several parameters
160 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
162 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
168 * Insert a row into the contact table
169 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
171 * @param array $fields field array
172 * @param bool $on_duplicate_update Do an update on a duplicate entry
174 * @return boolean was the insert successful?
177 public static function insert(array $fields, bool $on_duplicate_update = false)
179 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
180 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
183 if (empty($fields['created'])) {
184 $fields['created'] = DateTimeFormat::utcNow();
187 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
188 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
189 if (!DBA::isResult($contact)) {
194 // Search for duplicated contacts and get rid of them
195 self::removeDuplicates($contact['nurl'], $contact['uid']);
201 * @param integer $id Contact ID
202 * @param array $fields Array of selected fields, empty for all
203 * @return array|boolean Contact record if it exists, false otherwise
206 public static function getById($id, $fields = [])
208 return DBA::selectFirst('contact', $fields, ['id' => $id]);
212 * Fetches a contact by a given url
214 * @param string $url profile url
215 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
216 * @param array $fields Field list
217 * @param integer $uid User ID of the contact
218 * @return array contact array
220 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
222 if ($update || is_null($update)) {
223 $cid = self::getIdForURL($url, $uid, $update);
228 $contact = self::getById($cid, $fields);
229 if (empty($contact)) {
235 // Add internal fields
237 if (!empty($fields)) {
238 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
239 if (!in_array($internal, $fields)) {
240 $fields[] = $internal;
241 $removal[] = $internal;
246 // We first try the nurl (http://server.tld/nick), most common case
247 $options = ['order' => ['id']];
248 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
250 // Then the addr (nick@server.tld)
251 if (!DBA::isResult($contact)) {
252 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
255 // Then the alias (which could be anything)
256 if (!DBA::isResult($contact)) {
257 // The link could be provided as http although we stored it as https
258 $ssl_url = str_replace('http://', 'https://', $url);
259 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
260 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
263 if (!DBA::isResult($contact)) {
267 // Update the contact in the background if needed
268 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
269 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED)) {
270 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
273 // Remove the internal fields
274 foreach ($removal as $internal) {
275 unset($contact[$internal]);
282 * Fetches a contact for a given user by a given url.
283 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
285 * @param string $url profile url
286 * @param integer $uid User ID of the contact
287 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
288 * @param array $fields Field list
289 * @return array contact array
291 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
294 $contact = self::getByURL($url, $update, $fields, $uid);
295 if (!empty($contact)) {
296 if (!empty($contact['id'])) {
297 $contact['cid'] = $contact['id'];
304 $contact = self::getByURL($url, $update, $fields);
305 if (!empty($contact['id'])) {
307 $contact['zid'] = $contact['id'];
313 * Tests if the given contact is a follower
315 * @param int $cid Either public contact id or user's contact id
316 * @param int $uid User ID
318 * @return boolean is the contact id a follower?
319 * @throws HTTPException\InternalServerErrorException
320 * @throws \ImagickException
322 public static function isFollower($cid, $uid)
324 if (Contact\User::isBlocked($cid, $uid)) {
328 $cdata = self::getPublicAndUserContacID($cid, $uid);
329 if (empty($cdata['user'])) {
333 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
334 return DBA::exists('contact', $condition);
338 * Tests if the given contact url is a follower
340 * @param string $url Contact URL
341 * @param int $uid User ID
343 * @return boolean is the contact id a follower?
344 * @throws HTTPException\InternalServerErrorException
345 * @throws \ImagickException
347 public static function isFollowerByURL($url, $uid)
349 $cid = self::getIdForURL($url, $uid);
355 return self::isFollower($cid, $uid);
359 * Tests if the given user follow the given contact
361 * @param int $cid Either public contact id or user's contact id
362 * @param int $uid User ID
364 * @return boolean is the contact url being followed?
365 * @throws HTTPException\InternalServerErrorException
366 * @throws \ImagickException
368 public static function isSharing($cid, $uid)
370 if (Contact\User::isBlocked($cid, $uid)) {
374 $cdata = self::getPublicAndUserContacID($cid, $uid);
375 if (empty($cdata['user'])) {
379 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
380 return DBA::exists('contact', $condition);
384 * Tests if the given user follow the given contact url
386 * @param string $url Contact URL
387 * @param int $uid User ID
389 * @return boolean is the contact url being followed?
390 * @throws HTTPException\InternalServerErrorException
391 * @throws \ImagickException
393 public static function isSharingByURL($url, $uid)
395 $cid = self::getIdForURL($url, $uid);
401 return self::isSharing($cid, $uid);
405 * Get the basepath for a given contact link
407 * @param string $url The contact link
408 * @param boolean $dont_update Don't update the contact
410 * @return string basepath
411 * @throws HTTPException\InternalServerErrorException
412 * @throws \ImagickException
414 public static function getBasepath($url, $dont_update = false)
416 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
417 if (!DBA::isResult($contact)) {
421 if (!empty($contact['baseurl'])) {
422 return $contact['baseurl'];
423 } elseif ($dont_update) {
427 // Update the existing contact
428 self::updateFromProbe($contact['id']);
430 // And fetch the result
431 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
432 if (empty($contact['baseurl'])) {
433 Logger::info('No baseurl for contact', ['url' => $url]);
437 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
438 return $contact['baseurl'];
442 * Check if the given contact url is on the same server
444 * @param string $url The contact link
446 * @return boolean Is it the same server?
448 public static function isLocal($url)
450 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
454 * Check if the given contact ID is on the same server
456 * @param string $url The contact link
458 * @return boolean Is it the same server?
460 public static function isLocalById(int $cid)
462 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
463 if (!DBA::isResult($contact)) {
467 if (empty($contact['baseurl'])) {
468 $baseurl = self::getBasepath($contact['url'], true);
470 $baseurl = $contact['baseurl'];
473 return Strings::compareLink($baseurl, DI::baseUrl());
477 * Returns the public contact id of the given user id
479 * @param integer $uid User ID
481 * @return integer|boolean Public contact id for given user id
484 public static function getPublicIdByUserId($uid)
486 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
487 if (!DBA::isResult($self)) {
490 return self::getIdForURL($self['url']);
494 * Returns the contact id for the user and the public contact id for a given contact id
496 * @param int $cid Either public contact id or user's contact id
497 * @param int $uid User ID
499 * @return array with public and user's contact id
500 * @throws HTTPException\InternalServerErrorException
501 * @throws \ImagickException
503 public static function getPublicAndUserContacID($cid, $uid)
505 if (empty($uid) || empty($cid)) {
509 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
510 if (!DBA::isResult($contact)) {
514 // We quit when the user id don't match the user id of the provided contact
515 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
519 if ($contact['uid'] != 0) {
520 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
524 $ucid = $contact['id'];
526 $pcid = $contact['id'];
527 $ucid = Contact::getIdForURL($contact['url'], $uid);
530 return ['public' => $pcid, 'user' => $ucid];
534 * Returns contact details for a given contact id in combination with a user id
536 * @param int $cid A contact ID
537 * @param int $uid The User ID
538 * @param array $fields The selected fields for the contact
540 * @return array The contact details
544 public static function getContactForUser($cid, $uid, array $fields = [])
546 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
548 if (!DBA::isResult($contact)) {
556 * Creates the self-contact for the provided user id
559 * @return bool Operation success
560 * @throws HTTPException\InternalServerErrorException
562 public static function createSelfFromUserId($uid)
564 // Only create the entry if it doesn't exist yet
565 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
569 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'], ['uid' => $uid]);
570 if (!DBA::isResult($user)) {
574 $return = DBA::insert('contact', [
575 'uid' => $user['uid'],
576 'created' => DateTimeFormat::utcNow(),
578 'name' => $user['username'],
579 'nick' => $user['nickname'],
580 'pubkey' => $user['pubkey'],
581 'prvkey' => $user['prvkey'],
582 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
583 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
584 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
587 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
588 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
589 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
590 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
591 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
592 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
593 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
594 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
595 'name-date' => DateTimeFormat::utcNow(),
596 'uri-date' => DateTimeFormat::utcNow(),
597 'avatar-date' => DateTimeFormat::utcNow(),
605 * Updates the self-contact for the provided user id
608 * @param boolean $update_avatar Force the avatar update
609 * @throws HTTPException\InternalServerErrorException
611 public static function updateSelfFromUserID($uid, $update_avatar = false)
613 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
614 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
615 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
616 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
617 if (!DBA::isResult($self)) {
621 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
622 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
623 if (!DBA::isResult($user)) {
627 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
628 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
629 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
630 if (!DBA::isResult($profile)) {
634 $file_suffix = 'jpg';
636 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
637 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
638 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
639 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
640 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp']];
642 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
643 if (DBA::isResult($avatar)) {
644 if ($update_avatar) {
645 $fields['avatar-date'] = DateTimeFormat::utcNow();
648 // Creating the path to the avatar, beginning with the file suffix
649 $types = Images::supportedTypes();
650 if (isset($types[$avatar['type']])) {
651 $file_suffix = $types[$avatar['type']];
654 // We are adding a timestamp value so that other systems won't use cached content
655 $timestamp = strtotime($fields['avatar-date']);
657 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
658 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
660 $fields['photo'] = $prefix . '4' . $suffix;
661 $fields['thumb'] = $prefix . '5' . $suffix;
662 $fields['micro'] = $prefix . '6' . $suffix;
664 // We hadn't found a photo entry, so we use the default avatar
665 $fields['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
666 $fields['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
667 $fields['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
670 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
671 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
672 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
673 $fields['unsearchable'] = !$profile['net-publish'];
675 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
676 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
677 $fields['nurl'] = Strings::normaliseLink($fields['url']);
678 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
679 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
680 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
681 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
682 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
683 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
687 foreach ($fields as $field => $content) {
688 if ($self[$field] != $content) {
694 if ($fields['name'] != $self['name']) {
695 $fields['name-date'] = DateTimeFormat::utcNow();
697 $fields['updated'] = DateTimeFormat::utcNow();
698 DBA::update('contact', $fields, ['id' => $self['id']]);
700 // Update the public contact as well
701 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
703 // Update the profile
704 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
705 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
706 DBA::update('profile', $fields, ['uid' => $uid]);
711 * Marks a contact for removal
713 * @param int $id contact id
715 * @throws HTTPException\InternalServerErrorException
717 public static function remove($id)
719 // We want just to make sure that we don't delete our "self" contact
720 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
721 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
725 // Archive the contact
726 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
728 // Delete it in the background
729 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
733 * Sends an unfriend message. Does not remove the contact
735 * @param array $user User unfriending
736 * @param array $contact Contact unfriended
737 * @param boolean $dissolve Remove the contact on the remote side
739 * @throws HTTPException\InternalServerErrorException
740 * @throws \ImagickException
742 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
744 if (empty($contact['network'])) {
748 $protocol = $contact['network'];
749 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
750 $protocol = Protocol::ACTIVITYPUB;
753 if (($protocol == Protocol::DFRN) && $dissolve) {
754 DFRN::deliver($user, $contact, 'placeholder', true);
755 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
756 // create an unfollow slap
758 $item['verb'] = Activity::O_UNFOLLOW;
759 $item['gravity'] = GRAVITY_ACTIVITY;
760 $item['follow'] = $contact["url"];
765 $slap = OStatus::salmon($item, $user);
767 if (!empty($contact['notify'])) {
768 Salmon::slapper($user, $contact['notify'], $slap);
770 } elseif ($protocol == Protocol::DIASPORA) {
771 Diaspora::sendUnshare($user, $contact);
772 } elseif ($protocol == Protocol::ACTIVITYPUB) {
773 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
776 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
782 * Marks a contact for archival after a communication issue delay
784 * Contact has refused to recognise us as a friend. We will start a countdown.
785 * If they still don't recognise us in 32 days, the relationship is over,
786 * and we won't waste any more time trying to communicate with them.
787 * This provides for the possibility that their database is temporarily messed
788 * up or some other transient event and that there's a possibility we could recover from it.
790 * @param array $contact contact to mark for archival
792 * @throws HTTPException\InternalServerErrorException
794 public static function markForArchival(array $contact)
796 if (!isset($contact['url']) && !empty($contact['id'])) {
797 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
798 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
799 if (!DBA::isResult($contact)) {
802 } elseif (!isset($contact['url'])) {
803 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
806 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
808 // Contact already archived or "self" contact? => nothing to do
809 if ($contact['archive'] || $contact['self']) {
813 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
814 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
815 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
818 * We really should send a notification to the owner after 2-3 weeks
819 * so they won't be surprised when the contact vanishes and can take
820 * remedial action if this was a serious mistake or glitch
823 /// @todo Check for contact vitality via probing
824 $archival_days = DI::config()->get('system', 'archival_days', 32);
826 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
827 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
828 /* Relationship is really truly dead. archive them rather than
829 * delete, though if the owner tries to unarchive them we'll start
830 * the whole process over again.
832 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
833 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
839 * Cancels the archival countdown
841 * @see Contact::markForArchival()
843 * @param array $contact contact to be unmarked for archival
847 public static function unmarkForArchival(array $contact)
849 // Always unarchive the relay contact entry
850 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
851 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
852 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
853 DBA::update('contact', $fields, $condition);
856 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
857 $exists = DBA::exists('contact', $condition);
859 // We don't need to update, we never marked this contact for archival
864 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
866 if (!isset($contact['url']) && !empty($contact['id'])) {
867 $fields = ['id', 'url', 'batch'];
868 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
869 if (!DBA::isResult($contact)) {
874 // It's a miracle. Our dead contact has inexplicably come back to life.
875 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
876 DBA::update('contact', $fields, ['id' => $contact['id']]);
877 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
881 * Returns the data array for the photo menu of a given contact
883 * @param array $contact contact
884 * @param int $uid optional, default 0
886 * @throws HTTPException\InternalServerErrorException
887 * @throws \ImagickException
889 public static function photoMenu(array $contact, $uid = 0)
894 $contact_drop_link = '';
901 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
903 $profile_link = self::magicLink($contact['url']);
904 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
909 // Look for our own contact if the uid doesn't match and isn't public
910 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
911 if (DBA::isResult($contact_own)) {
912 return self::photoMenu($contact_own, $uid);
917 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
919 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
921 $profile_link = $contact['url'];
924 if ($profile_link === 'mailbox') {
929 $status_link = $profile_link . '/status';
930 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
931 $profile_link = $profile_link . '/profile';
934 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
935 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
938 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
939 $poke_link = 'contact/' . $contact['id'] . '/poke';
942 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
944 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
946 if (!$contact['self']) {
947 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
952 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
953 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
954 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
955 } elseif(!$contact['pending']) {
956 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
960 if (!empty($follow_link) || !empty($unfollow_link)) {
961 $contact_drop_link = '';
966 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
968 if (empty($contact['uid'])) {
970 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
971 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
972 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
973 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
974 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
978 'status' => [DI::l10n()->t('View Status') , $status_link , true],
979 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
980 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
981 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
982 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
983 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
984 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
985 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
986 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
987 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
990 if (!empty($contact['pending'])) {
991 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
992 if (DBA::isResult($intro)) {
993 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
998 $args = ['contact' => $contact, 'menu' => &$menu];
1000 Hook::callAll('contact_photo_menu', $args);
1002 $menucondensed = [];
1004 foreach ($menu as $menuname => $menuitem) {
1005 if ($menuitem[1] != '') {
1006 $menucondensed[$menuname] = $menuitem;
1010 return $menucondensed;
1014 * Fetch the contact id for a given URL and user
1016 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1017 * `addr` or `alias`.
1019 * If there's no record and we aren't looking for a public contact, we quit.
1020 * If there's one, we check that it isn't time to update the picture else we
1021 * directly return the found contact id.
1023 * Second, we probe the provided $url whether it's http://server.tld/profile or
1024 * nick@server.tld. We quit if we can't get any info back.
1026 * Third, we create the contact record if it doesn't exist
1028 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1029 * if there's any updates
1031 * @param string $url Contact URL
1032 * @param integer $uid The user id for the contact (0 = public contact)
1033 * @param boolean $update true = always update, false = never update, null = update when not found
1034 * @param array $default Default value for creating the contact when everything else fails
1036 * @return integer Contact ID
1037 * @throws HTTPException\InternalServerErrorException
1038 * @throws \ImagickException
1040 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1045 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1049 $contact = self::getByURL($url, false, ['id', 'network'], $uid);
1051 if (!empty($contact)) {
1052 $contact_id = $contact["id"];
1054 if (empty($update)) {
1055 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1058 } elseif ($uid != 0) {
1059 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1061 } elseif (empty($default) && !is_null($update) && !$update) {
1062 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1068 if (empty($default['network']) || $update) {
1069 $data = Probe::uri($url, "", $uid);
1071 // Take the default values when probing failed
1072 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1073 $data = array_merge($data, $default);
1075 } elseif (!empty($default['network'])) {
1079 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1080 // Fetch data for the public contact via the first found personal contact
1081 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1082 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'contact-type',
1083 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1084 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1086 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1087 if (!DBA::isResult($personal_contact)) {
1088 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1091 if (DBA::isResult($personal_contact)) {
1092 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1093 $data = $personal_contact;
1094 $data['photo'] = $personal_contact['avatar'];
1095 $data['account-type'] = $personal_contact['contact-type'];
1096 $data['hide'] = $personal_contact['unsearchable'];
1097 unset($data['avatar']);
1098 unset($data['contact-type']);
1099 unset($data['unsearchable']);
1103 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1104 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1109 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1110 if (!empty($data['alias'])) {
1111 $urls[] = Strings::normaliseLink($data['alias']);
1113 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1114 if (!empty($contact['id'])) {
1115 $contact_id = $contact['id'];
1116 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1121 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1124 'url' => $data['url'],
1125 'nurl' => Strings::normaliseLink($data['url']),
1126 'network' => $data['network'],
1127 'created' => DateTimeFormat::utcNow(),
1128 'rel' => self::SHARING,
1134 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1136 // Before inserting we do check if the entry does exist now.
1137 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1138 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1139 if (DBA::isResult($contact)) {
1140 $contact_id = $contact['id'];
1141 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1143 DBA::insert('contact', $fields);
1144 $contact_id = DBA::lastInsertId();
1146 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1149 DI::lock()->release(self::LOCK_INSERT);
1151 Logger::warning('Contact lock had not been acquired');
1155 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1159 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1162 self::updateFromProbeArray($contact_id, $data);
1168 * Checks if the contact is archived
1170 * @param int $cid contact id
1172 * @return boolean Is the contact archived?
1173 * @throws HTTPException\InternalServerErrorException
1175 public static function isArchived(int $cid)
1181 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1182 if (!DBA::isResult($contact)) {
1186 if ($contact['archive']) {
1190 // Check status of ActivityPub endpoints
1191 $apcontact = APContact::getByURL($contact['url'], false);
1192 if (!empty($apcontact)) {
1193 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1197 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1202 // Check status of Diaspora endpoints
1203 if (!empty($contact['batch'])) {
1204 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1205 return DBA::exists('contact', $condition);
1212 * Checks if the contact is blocked
1214 * @param int $cid contact id
1216 * @return boolean Is the contact blocked?
1217 * @throws HTTPException\InternalServerErrorException
1219 public static function isBlocked($cid)
1225 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1226 if (!DBA::isResult($blocked)) {
1230 if (Network::isUrlBlocked($blocked['url'])) {
1234 return (bool) $blocked['blocked'];
1238 * Checks if the contact is hidden
1240 * @param int $cid contact id
1242 * @return boolean Is the contact hidden?
1243 * @throws \Exception
1245 public static function isHidden($cid)
1251 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1252 if (!DBA::isResult($hidden)) {
1255 return (bool) $hidden['hidden'];
1259 * Returns posts from a given contact url
1261 * @param string $contact_url Contact URL
1262 * @param bool $thread_mode
1263 * @param int $update Update mode
1264 * @param int $parent Item parent ID for the update mode
1265 * @return string posts in HTML
1266 * @throws \Exception
1268 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1270 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1274 * Returns posts from a given contact id
1276 * @param int $cid Contact ID
1277 * @param bool $thread_mode
1278 * @param int $update Update mode
1279 * @param int $parent Item parent ID for the update mode
1280 * @return string posts in HTML
1281 * @throws \Exception
1283 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1287 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1288 if (!DBA::isResult($contact)) {
1292 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1293 $sql = "`item`.`uid` IN (0, ?)";
1295 $sql = "`item`.`uid` = ?";
1298 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1301 $condition = ["(`$contact_field` = ? OR (`causer-id` = ? AND `post-type` = ?)) AND `gravity` = ? AND " . $sql,
1302 $cid, $cid, Item::PT_ANNOUNCEMENT, GRAVITY_PARENT, local_user()];
1304 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1305 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1308 if (!empty($parent)) {
1309 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1311 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1312 if (!empty($last_received)) {
1313 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1317 if (DI::mode()->isMobile()) {
1318 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1319 DI::config()->get('system', 'itemspage_network_mobile'));
1321 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1322 DI::config()->get('system', 'itemspage_network'));
1325 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1327 $params = ['order' => ['received' => true], 'group_by' => ['uri-id'],
1328 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1330 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1331 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1332 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1338 $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1340 while ($item = DBA::fetch($r)) {
1341 if ($item['gravity'] != GRAVITY_PARENT) {
1342 $item['uri'] = $item['parent-uri'];
1344 unset($item['parent-uri']);
1345 unset($item['gravity']);
1351 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1353 $r = Item::selectForUser(local_user(), [], $condition, $params);
1355 $items = Item::inArray($r);
1357 $o .= conversation($a, $items, 'contact-posts', $update);
1361 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1362 $o .= HTML::scrollLoader();
1364 $o .= $pager->renderMinimal(count($items));
1372 * Returns the account type name
1374 * The function can be called with either the user or the contact array
1376 * @param array $contact contact or user array
1379 public static function getAccountType(array $contact)
1381 // There are several fields that indicate that the contact or user is a forum
1382 // "page-flags" is a field in the user table,
1383 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1384 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1385 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1386 || (isset($contact['forum']) && intval($contact['forum']))
1387 || (isset($contact['prv']) && intval($contact['prv']))
1388 || (isset($contact['community']) && intval($contact['community']))
1390 $type = self::TYPE_COMMUNITY;
1392 $type = self::TYPE_PERSON;
1395 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1396 if (isset($contact["contact-type"])) {
1397 $type = $contact["contact-type"];
1400 if (isset($contact["account-type"])) {
1401 $type = $contact["account-type"];
1405 case self::TYPE_ORGANISATION:
1406 $account_type = DI::l10n()->t("Organisation");
1409 case self::TYPE_NEWS:
1410 $account_type = DI::l10n()->t('News');
1413 case self::TYPE_COMMUNITY:
1414 $account_type = DI::l10n()->t("Forum");
1422 return $account_type;
1430 * @throws \Exception
1432 public static function block($cid, $reason = null)
1434 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1440 * Unblocks a contact
1444 * @throws \Exception
1446 public static function unblock($cid)
1448 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1454 * Ensure that cached avatar exist
1456 * @param integer $cid
1458 public static function checkAvatarCache(int $cid)
1460 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1461 if (!DBA::isResult($contact)) {
1465 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1469 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1471 self::updateAvatar($cid, $contact['avatar'], true);
1475 * Return the photo path for a given contact array in the given size
1477 * @param array $contact contact array
1478 * @param string $field Fieldname of the photo in the contact array
1479 * @param string $default Default path when no picture had been found
1480 * @param string $size Size of the avatar picture
1481 * @param string $avatar Avatar path that is displayed when no photo had been found
1482 * @return string photo path
1484 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1486 if (!empty($contact)) {
1487 $contact = self::checkAvatarCacheByArray($contact);
1488 if (!empty($contact[$field])) {
1489 $avatar = $contact[$field];
1493 if (empty($avatar)) {
1497 if (Proxy::isLocalImage($avatar)) {
1500 return Proxy::proxifyUrl($avatar, false, $size);
1505 * Return the photo path for a given contact array
1507 * @param array $contact Contact array
1508 * @param string $avatar Avatar path that is displayed when no photo had been found
1509 * @return string photo path
1511 public static function getPhoto(array $contact, string $avatar = '')
1513 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO, Proxy::SIZE_SMALL, $avatar);
1517 * Return the photo path (thumb size) for a given contact array
1519 * @param array $contact Contact array
1520 * @param string $avatar Avatar path that is displayed when no photo had been found
1521 * @return string photo path
1523 public static function getThumb(array $contact, string $avatar = '')
1525 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . self::DEFAULT_AVATAR_THUMB, Proxy::SIZE_THUMB, $avatar);
1529 * Return the photo path (micro size) for a given contact array
1531 * @param array $contact Contact array
1532 * @param string $avatar Avatar path that is displayed when no photo had been found
1533 * @return string photo path
1535 public static function getMicro(array $contact, string $avatar = '')
1537 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . self::DEFAULT_AVATAR_MICRO, Proxy::SIZE_MICRO, $avatar);
1541 * Check the given contact array for avatar cache fields
1543 * @param array $contact
1544 * @return array contact array with avatar cache fields
1546 private static function checkAvatarCacheByArray(array $contact)
1549 $contact_fields = [];
1550 $fields = ['photo', 'thumb', 'micro'];
1551 foreach ($fields as $field) {
1552 if (isset($contact[$field])) {
1553 $contact_fields[] = $field;
1555 if (isset($contact[$field]) && empty($contact[$field])) {
1564 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1565 self::updateAvatar($contact['id'], $contact['avatar'], true);
1567 $new_contact = self::getById($contact['id'], $contact_fields);
1568 if (DBA::isResult($new_contact)) {
1569 // We only update the cache fields
1570 $contact = array_merge($contact, $new_contact);
1574 /// add the default avatars if the fields aren't filled
1575 if (isset($contact['photo']) && empty($contact['photo'])) {
1576 $contact['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
1578 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1579 $contact['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
1581 if (isset($contact['micro']) && empty($contact['micro'])) {
1582 $contact['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
1589 * Updates the avatar links in a contact only if needed
1591 * @param int $cid Contact id
1592 * @param string $avatar Link to avatar picture
1593 * @param bool $force force picture update
1594 * @param bool $create_cache Enforces the creation of cached avatar fields
1597 * @throws HTTPException\InternalServerErrorException
1598 * @throws HTTPException\NotFoundException
1599 * @throws \ImagickException
1601 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1603 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl', 'url', 'network'], ['id' => $cid, 'self' => false]);
1604 if (!DBA::isResult($contact)) {
1608 $uid = $contact['uid'];
1610 // Only update the cached photo links of public contacts when they already are cached
1611 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1612 if ($contact['avatar'] != $avatar) {
1613 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1614 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1619 // User contacts use are updated through the public contacts
1620 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1621 $pcid = self::getIdForURL($contact['url'], false);
1622 if (!empty($pcid)) {
1623 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1624 self::updateAvatar($pcid, $avatar, $force, true);
1629 // Replace cached avatar pictures from the default avatar with the default avatars in different sizes
1630 if (strpos($avatar, self::DEFAULT_AVATAR_PHOTO)) {
1631 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1632 'photo' => DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO,
1633 'thumb' => DI::baseUrl() . self::DEFAULT_AVATAR_THUMB,
1634 'micro' => DI::baseUrl() . self::DEFAULT_AVATAR_MICRO];
1635 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1638 // Use the data from the self account
1639 if (empty($fields)) {
1640 $local_uid = User::getIdForURL($contact['url']);
1641 if (!empty($local_uid)) {
1642 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1643 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1647 if (empty($fields)) {
1648 $update = ($contact['avatar'] != $avatar) || $force;
1652 $contact['photo'] ?? '',
1653 $contact['thumb'] ?? '',
1654 $contact['micro'] ?? '',
1657 foreach ($data as $image_uri) {
1658 $image_rid = Photo::ridFromURI($image_uri);
1659 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1660 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1667 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1669 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1670 $update = !empty($fields);
1671 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1677 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1686 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1687 // Collect all user contacts of the given public contact
1688 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1689 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1690 while ($personal_contact = DBA::fetch($personal_contacts)) {
1691 $cids[] = $personal_contact['id'];
1692 $uids[] = $personal_contact['uid'];
1694 DBA::close($personal_contacts);
1696 if (!empty($cids)) {
1697 // Delete possibly existing cached user contact avatars
1698 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1704 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1705 DBA::update('contact', $fields, ['id' => $cids]);
1709 * Helper function for "updateFromProbe". Updates personal and public contact
1711 * @param integer $id contact id
1712 * @param integer $uid user id
1713 * @param string $url The profile URL of the contact
1714 * @param array $fields The fields that are updated
1716 * @throws \Exception
1718 private static function updateContact($id, $uid, $url, array $fields)
1720 if (!DBA::update('contact', $fields, ['id' => $id])) {
1721 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1725 // Search for duplicated contacts and get rid of them
1726 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1730 // Archive or unarchive the contact. We only need to do this for the public contact.
1731 // The archive/unarchive function will update the personal contacts by themselves.
1732 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1733 if (!DBA::isResult($contact)) {
1734 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1738 if (!empty($fields['success_update'])) {
1739 self::unmarkForArchival($contact);
1740 } elseif (!empty($fields['failure_update'])) {
1741 self::markForArchival($contact);
1744 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1746 // These contacts are sharing with us, we don't poll them.
1747 // This means that we don't set the update fields in "OnePoll.php".
1748 $condition['rel'] = self::SHARING;
1749 DBA::update('contact', $fields, $condition);
1751 unset($fields['last-update']);
1752 unset($fields['success_update']);
1753 unset($fields['failure_update']);
1755 if (empty($fields)) {
1759 // We are polling these contacts, so we mustn't set the update fields here.
1760 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1761 DBA::update('contact', $fields, $condition);
1765 * Remove duplicated contacts
1767 * @param string $nurl Normalised contact url
1768 * @param integer $uid User id
1770 * @throws \Exception
1772 public static function removeDuplicates(string $nurl, int $uid)
1774 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1775 $count = DBA::count('contact', $condition);
1780 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1781 if (!DBA::isResult($first_contact)) {
1782 // Shouldn't happen - so we handle it
1786 $first = $first_contact['id'];
1787 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1788 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1789 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1790 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1794 // Find all duplicates
1795 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1796 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1797 while ($duplicate = DBA::fetch($duplicates)) {
1798 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1802 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1804 DBA::close($duplicates);
1805 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1810 * @param integer $id contact id
1811 * @param string $network Optional network we are probing for
1813 * @throws HTTPException\InternalServerErrorException
1814 * @throws \ImagickException
1816 public static function updateFromProbe(int $id, string $network = '')
1818 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1819 if (!DBA::isResult($contact)) {
1823 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1824 return self::updateFromProbeArray($id, $ret);
1828 * @param integer $id contact id
1829 * @param array $ret Probed data
1831 * @throws HTTPException\InternalServerErrorException
1832 * @throws \ImagickException
1834 private static function updateFromProbeArray(int $id, array $ret)
1837 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1838 This will reliably kill your communication with old Friendica contacts.
1841 // These fields aren't updated by this routine:
1842 // 'xmpp', 'sensitive'
1844 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe', 'manually-approve',
1845 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1846 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1847 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1848 if (!DBA::isResult($contact)) {
1852 $uid = $contact['uid'];
1853 unset($contact['uid']);
1855 $pubkey = $contact['pubkey'];
1856 unset($contact['pubkey']);
1858 $contact['photo'] = $contact['avatar'];
1859 unset($contact['avatar']);
1861 $updated = DateTimeFormat::utcNow();
1863 // We must not try to update relay contacts via probe. They are no real contacts.
1864 // We check after the probing to be able to correct falsely detected contact types.
1865 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1866 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1867 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1868 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1872 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1873 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1875 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1880 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1881 $ret['unsearchable'] = $ret['hide'];
1884 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1885 $ret['forum'] = false;
1886 $ret['prv'] = false;
1887 $ret['contact-type'] = $ret['account-type'];
1888 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1889 $ret['forum'] = (bool)!$ret['manually-approve'];
1890 $ret['prv'] = (bool)!$ret['forum'];
1894 $new_pubkey = $ret['pubkey'] ?? '';
1897 $ret['last-item'] = Probe::getLastUpdate($ret);
1898 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1903 // make sure to not overwrite existing values with blank entries except some technical fields
1904 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1905 foreach ($ret as $key => $val) {
1906 if (!array_key_exists($key, $contact)) {
1908 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1909 $ret[$key] = $contact[$key];
1910 } elseif ($ret[$key] != $contact[$key]) {
1915 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1918 unset($ret['last-item']);
1921 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1922 self::updateAvatar($id, $ret['photo'], $update);
1926 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1928 if (Contact\Relation::isDiscoverable($ret['url'])) {
1929 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1932 // Update the public contact
1934 $contact = self::getByURL($ret['url'], false, ['id']);
1935 if (!empty($contact['id'])) {
1936 self::updateFromProbeArray($contact['id'], $ret);
1943 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1944 $ret['updated'] = $updated;
1946 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1947 if (empty($pubkey) && !empty($new_pubkey)) {
1948 $ret['pubkey'] = $new_pubkey;
1951 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1952 $ret['uri-date'] = DateTimeFormat::utcNow();
1955 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1956 $ret['name-date'] = $updated;
1960 $ret['last-update'] = $updated;
1961 $ret['success_update'] = $updated;
1962 $ret['failed'] = false;
1965 unset($ret['photo']);
1967 self::updateContact($id, $uid, $ret['url'], $ret);
1969 if (Contact\Relation::isDiscoverable($ret['url'])) {
1970 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1977 * @param integer $url contact url
1978 * @return integer Contact id
1979 * @throws HTTPException\InternalServerErrorException
1980 * @throws \ImagickException
1982 public static function updateFromProbeByURL($url)
1984 $id = self::getIdForURL($url);
1990 self::updateFromProbe($id);
1996 * Detects if a given contact array belongs to a legacy DFRN connection
1998 * @param array $contact
2001 public static function isLegacyDFRNContact($contact)
2003 // Newer Friendica contacts are connected via AP, then these fields aren't set
2004 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2008 * Detects the communication protocol for a given contact url.
2009 * This is used to detect Friendica contacts that we can communicate via AP.
2011 * @param string $url contact url
2012 * @param string $network Network of that contact
2013 * @return string with protocol
2015 public static function getProtocol($url, $network)
2017 if ($network != Protocol::DFRN) {
2021 $apcontact = APContact::getByURL($url);
2022 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2023 return Protocol::ACTIVITYPUB;
2030 * Takes a $uid and a url/handle and adds a new contact
2032 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2033 * dfrn_request page.
2035 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2038 * $return['success'] boolean true if successful
2039 * $return['message'] error text if success is false.
2041 * Takes a $uid and a url/handle and adds a new contact
2043 * @param array $user The user the contact should be created for
2044 * @param string $url The profile URL of the contact
2045 * @param bool $interactive
2046 * @param string $network
2048 * @throws HTTPException\InternalServerErrorException
2049 * @throws HTTPException\NotFoundException
2050 * @throws \ImagickException
2052 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2054 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2056 // remove ajax junk, e.g. Twitter
2057 $url = str_replace('/#!/', '/', $url);
2059 if (!Network::isUrlAllowed($url)) {
2060 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2064 if (Network::isUrlBlocked($url)) {
2065 $result['message'] = DI::l10n()->t('Blocked domain');
2070 $result['message'] = DI::l10n()->t('Connect URL missing.');
2074 $arr = ['url' => $url, 'contact' => []];
2076 Hook::callAll('follow', $arr);
2079 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2083 if (!empty($arr['contact']['name'])) {
2084 $ret = $arr['contact'];
2086 $ret = Probe::uri($url, $network, $user['uid']);
2089 if (($network != '') && ($ret['network'] != $network)) {
2090 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2094 // check if we already have a contact
2095 // the poll url is more reliable than the profile url, as we may have
2096 // indirect links or webfinger links
2098 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2099 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2100 if (!DBA::isResult($contact)) {
2101 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2102 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2105 $protocol = self::getProtocol($ret['url'], $ret['network']);
2107 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2109 if (strlen(DI::baseUrl()->getUrlPath())) {
2110 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2112 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2115 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2119 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2120 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2121 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2125 // This extra param just confuses things, remove it
2126 if ($protocol === Protocol::DIASPORA) {
2127 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2130 // do we have enough information?
2131 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2132 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2133 if (empty($ret['poll'])) {
2134 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2136 if (empty($ret['name'])) {
2137 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2139 if (empty($ret['url'])) {
2140 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2142 if (strpos($ret['url'], '@') !== false) {
2143 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2144 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2149 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2150 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2151 $ret['notify'] = '';
2154 if (!$ret['notify']) {
2155 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2158 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2160 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2162 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2165 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2166 $pending = (bool)$ret['manually-approve'];
2169 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2173 if (DBA::isResult($contact)) {
2175 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2177 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2178 DBA::update('contact', $fields, ['id' => $contact['id']]);
2180 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2182 // create contact record
2184 'uid' => $user['uid'],
2185 'created' => DateTimeFormat::utcNow(),
2186 'url' => $ret['url'],
2187 'nurl' => Strings::normaliseLink($ret['url']),
2188 'addr' => $ret['addr'],
2189 'alias' => $ret['alias'],
2190 'batch' => $ret['batch'],
2191 'notify' => $ret['notify'],
2192 'poll' => $ret['poll'],
2193 'poco' => $ret['poco'],
2194 'name' => $ret['name'],
2195 'nick' => $ret['nick'],
2196 'network' => $ret['network'],
2197 'baseurl' => $ret['baseurl'],
2198 'gsid' => $ret['gsid'] ?? null,
2199 'protocol' => $protocol,
2200 'pubkey' => $ret['pubkey'],
2201 'rel' => $new_relation,
2202 'priority'=> $ret['priority'],
2203 'writable'=> $writeable,
2204 'hidden' => $hidden,
2207 'pending' => $pending,
2212 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2213 if (!DBA::isResult($contact)) {
2214 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2218 $contact_id = $contact['id'];
2219 $result['cid'] = $contact_id;
2221 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2223 // Update the avatar
2224 self::updateAvatar($contact_id, $ret['photo']);
2226 // pull feed and consume it, which should subscribe to the hub.
2228 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2230 $owner = User::getOwnerDataById($user['uid']);
2232 if (DBA::isResult($owner)) {
2233 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2234 // create a follow slap
2236 $item['verb'] = Activity::FOLLOW;
2237 $item['gravity'] = GRAVITY_ACTIVITY;
2238 $item['follow'] = $contact["url"];
2240 $item['title'] = '';
2242 $item['uri-id'] = 0;
2244 $slap = OStatus::salmon($item, $owner);
2246 if (!empty($contact['notify'])) {
2247 Salmon::slapper($owner, $contact['notify'], $slap);
2249 } elseif ($protocol == Protocol::DIASPORA) {
2250 $ret = Diaspora::sendShare($owner, $contact);
2251 Logger::log('share returns: ' . $ret);
2252 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2253 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2254 if (empty($activity_id)) {
2255 // This really should never happen
2259 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2260 Logger::log('Follow returns: ' . $ret);
2264 $result['success'] = true;
2269 * Updated contact's SSL policy
2271 * @param array $contact Contact array
2272 * @param string $new_policy New policy, valid: self,full
2274 * @return array Contact array with updated values
2275 * @throws \Exception
2277 public static function updateSslPolicy(array $contact, $new_policy)
2279 $ssl_changed = false;
2280 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2281 $ssl_changed = true;
2282 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2283 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2284 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2285 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2286 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2287 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2290 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2291 $ssl_changed = true;
2292 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2293 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2294 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2295 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2296 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2297 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2301 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2302 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2303 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2304 DBA::update('contact', $fields, ['id' => $contact['id']]);
2311 * @param array $importer Owner (local user) data
2312 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2313 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2314 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2315 * @param string $note Introduction additional message
2316 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2317 * @throws HTTPException\InternalServerErrorException
2318 * @throws \ImagickException
2320 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2322 // Should always be set
2323 if (empty($datarray['author-id'])) {
2327 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2328 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2329 if (!DBA::isResult($pub_contact)) {
2330 // Should never happen
2334 // Contact is blocked at node-level
2335 if (self::isBlocked($datarray['author-id'])) {
2339 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2340 $name = $pub_contact['name'];
2341 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2342 $nick = $pub_contact['nick'];
2343 $network = $pub_contact['network'];
2345 // Ensure that we don't create a new contact when there already is one
2346 $cid = self::getIdForURL($url, $importer['uid']);
2348 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2351 if (!empty($contact)) {
2352 if (!empty($contact['pending'])) {
2353 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2357 // Contact is blocked at user-level
2358 if (!empty($contact['id']) && !empty($importer['id']) &&
2359 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2363 // Make sure that the existing contact isn't archived
2364 self::unmarkForArchival($contact);
2366 if (($contact['rel'] == self::SHARING)
2367 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2368 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2369 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2372 // Ensure to always have the correct network type, independent from the connection request method
2373 self::updateFromProbe($contact['id']);
2377 // send email notification to owner?
2378 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2379 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2383 // create contact record
2384 DBA::insert('contact', [
2385 'uid' => $importer['uid'],
2386 'created' => DateTimeFormat::utcNow(),
2388 'nurl' => Strings::normaliseLink($url),
2391 'network' => $network,
2392 'rel' => self::FOLLOWER,
2399 $contact_id = DBA::lastInsertId();
2401 // Ensure to always have the correct network type, independent from the connection request method
2402 self::updateFromProbe($contact_id);
2404 self::updateAvatar($contact_id, $photo, true);
2406 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2408 /// @TODO Encapsulate this into a function/method
2409 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2410 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2411 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2412 // create notification
2413 $hash = Strings::getRandomHex();
2415 if (is_array($contact_record)) {
2416 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2417 'blocked' => false, 'knowyou' => false, 'note' => $note,
2418 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2421 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2423 if (($user['notify-flags'] & Type::INTRO) &&
2424 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2427 'type' => Type::INTRO,
2428 'notify_flags' => $user['notify-flags'],
2429 'language' => $user['language'],
2430 'to_name' => $user['username'],
2431 'to_email' => $user['email'],
2432 'uid' => $user['uid'],
2433 'link' => DI::baseUrl() . '/notifications/intros',
2434 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2435 'source_link' => $contact_record['url'],
2436 'source_photo' => $contact_record['photo'],
2437 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2441 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2442 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2443 self::createFromProbe($importer, $url, false, $network);
2446 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2447 $fields = ['pending' => false];
2448 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2449 $fields['rel'] = Contact::FRIEND;
2452 DBA::update('contact', $fields, $condition);
2461 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2463 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2464 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2466 Contact::remove($contact['id']);
2470 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2472 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2473 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2475 Contact::remove($contact['id']);
2480 * Create a birthday event.
2482 * Update the year and the birthday.
2484 public static function updateBirthdays()
2488 AND `bd` > "0001-01-01"
2489 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2490 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2491 AND NOT `contact`.`pending`
2492 AND NOT `contact`.`hidden`
2493 AND NOT `contact`.`blocked`
2494 AND NOT `contact`.`archive`
2495 AND NOT `contact`.`deleted`',
2500 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2502 while ($contact = DBA::fetch($contacts)) {
2503 Logger::log('update_contact_birthday: ' . $contact['bd']);
2505 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2507 if (Event::createBirthday($contact, $nextbd)) {
2511 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2512 ['id' => $contact['id']]
2516 DBA::close($contacts);
2520 * Remove the unavailable contact ids from the provided list
2522 * @param array $contact_ids Contact id list
2524 * @throws \Exception
2526 public static function pruneUnavailable(array $contact_ids)
2528 if (empty($contact_ids)) {
2532 $contacts = Contact::selectToArray(['id'], [
2533 'id' => $contact_ids,
2539 return array_column($contacts, 'id');
2543 * Returns a magic link to authenticate remote visitors
2545 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2547 * @param string $contact_url The address of the target contact profile
2548 * @param string $url An url that we will be redirected to after the authentication
2550 * @return string with "redir" link
2551 * @throws HTTPException\InternalServerErrorException
2552 * @throws \ImagickException
2554 public static function magicLink($contact_url, $url = '')
2556 if (!Session::isAuthenticated()) {
2557 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2560 $contact = self::getByURL($contact_url, false);
2561 if (empty($contact)) {
2562 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2565 // Prevents endless loop in case only a non-public contact exists for the contact URL
2566 unset($contact['uid']);
2568 return self::magicLinkByContact($contact, $url ?: $contact_url);
2572 * Returns a magic link to authenticate remote visitors
2574 * @param integer $cid The contact id of the target contact profile
2575 * @param string $url An url that we will be redirected to after the authentication
2577 * @return string with "redir" link
2578 * @throws HTTPException\InternalServerErrorException
2579 * @throws \ImagickException
2581 public static function magicLinkbyId($cid, $url = '')
2583 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2585 return self::magicLinkByContact($contact, $url);
2589 * Returns a magic link to authenticate remote visitors
2591 * @param array $contact The contact array with "uid", "network" and "url"
2592 * @param string $url An url that we will be redirected to after the authentication
2594 * @return string with "redir" link
2595 * @throws HTTPException\InternalServerErrorException
2596 * @throws \ImagickException
2598 public static function magicLinkByContact($contact, $url = '')
2600 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2602 if (!Session::isAuthenticated()) {
2603 return $destination;
2606 // Only redirections to the same host do make sense
2607 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2611 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2612 return 'contact/' . $contact['id'] . '/conversations';
2615 if ($contact['network'] != Protocol::DFRN) {
2616 return $destination;
2619 if (!empty($contact['uid'])) {
2620 return self::magicLink($contact['url'], $url);
2623 if (empty($contact['id'])) {
2624 return $destination;
2627 $redirect = 'redir/' . $contact['id'];
2629 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2630 $redirect .= '?url=' . $url;
2637 * Is the contact a forum?
2639 * @param integer $contactid ID of the contact
2641 * @return boolean "true" if it is a forum
2643 public static function isForum($contactid)
2645 $fields = ['forum', 'prv'];
2646 $condition = ['id' => $contactid];
2647 $contact = DBA::selectFirst('contact', $fields, $condition);
2648 if (!DBA::isResult($contact)) {
2653 return ($contact['forum'] || $contact['prv']);
2657 * Can the remote contact receive private messages?
2659 * @param array $contact
2662 public static function canReceivePrivateMessages(array $contact)
2664 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2665 $self = $contact['self'] ?? false;
2667 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2671 * Search contact table by nick or name
2673 * @param string $search Name or nick
2674 * @param string $mode Search mode (e.g. "community")
2676 * @return array with search results
2677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2679 public static function searchByName($search, $mode = '')
2681 if (empty($search)) {
2685 // check supported networks
2686 if (DI::config()->get('system', 'diaspora_enabled')) {
2687 $diaspora = Protocol::DIASPORA;
2689 $diaspora = Protocol::DFRN;
2692 if (!DI::config()->get('system', 'ostatus_disabled')) {
2693 $ostatus = Protocol::OSTATUS;
2695 $ostatus = Protocol::DFRN;
2698 // check if we search only communities or every contact
2699 if ($mode === 'community') {
2700 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2707 $results = DBA::p("SELECT * FROM `contact`
2708 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2709 NOT `failed` AND `uid` = ? AND
2710 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2711 ORDER BY `nurl` DESC LIMIT 1000",
2712 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2715 $contacts = DBA::toArray($results);
2720 * Add public contacts from an array
2722 * @param array $urls
2723 * @return array result "count", "added" and "updated"
2725 public static function addByUrls(array $urls)
2732 foreach ($urls as $url) {
2733 $contact = Contact::getByURL($url, false, ['id', 'updated']);
2734 if (empty($contact['id'])) {
2735 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2737 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
2738 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2746 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
2750 * Returns a random, global contact of the current node
2752 * @return string The profile URL
2755 public static function getRandomUrl()
2757 $r = DBA::selectFirst('contact', ['url'], [
2758 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2759 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2760 ], ['order' => ['RAND()']]);
2762 if (DBA::isResult($r)) {