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\Database;
35 use Friendica\Database\DBA;
37 use Friendica\Model\Notify\Type;
38 use Friendica\Network\HTTPException;
39 use Friendica\Network\Probe;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Protocol\DFRN;
43 use Friendica\Protocol\Diaspora;
44 use Friendica\Protocol\OStatus;
45 use Friendica\Protocol\Salmon;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\Images;
48 use Friendica\Util\Network;
49 use Friendica\Util\Proxy;
50 use Friendica\Util\Strings;
53 * functions for interacting with a contact
57 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
58 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
59 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
62 * @deprecated since version 2019.03
63 * @see User::PAGE_FLAGS_NORMAL
65 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
67 * @deprecated since version 2019.03
68 * @see User::PAGE_FLAGS_SOAPBOX
70 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
72 * @deprecated since version 2019.03
73 * @see User::PAGE_FLAGS_COMMUNITY
75 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
77 * @deprecated since version 2019.03
78 * @see User::PAGE_FLAGS_FREELOVE
80 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
82 * @deprecated since version 2019.03
83 * @see User::PAGE_FLAGS_BLOG
85 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
87 * @deprecated since version 2019.03
88 * @see User::PAGE_FLAGS_PRVGROUP
90 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
95 const LOCK_INSERT = 'contact-insert';
100 * TYPE_UNKNOWN - unknown type
102 * TYPE_PERSON - the account belongs to a person
103 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
105 * TYPE_ORGANISATION - the account belongs to an organisation
106 * Associated page type: PAGE_SOAPBOX
108 * TYPE_NEWS - the account is a news reflector
109 * Associated page type: PAGE_SOAPBOX
111 * TYPE_COMMUNITY - the account is community forum
112 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
114 * TYPE_RELAY - the account is a relay
115 * This will only be assigned to contacts, not to user accounts
118 const TYPE_UNKNOWN = -1;
119 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
120 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
121 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
122 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
123 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
143 * @param array $fields Array of selected fields, empty for all
144 * @param array $condition Array of fields for condition
145 * @param array $params Array of several parameters
149 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
151 return DBA::selectToArray('contact', $fields, $condition, $params);
155 * @param array $fields Array of selected fields, empty for all
156 * @param array $condition Array of fields for condition
157 * @param array $params Array of several parameters
161 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
163 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
169 * Insert a row into the contact table
170 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
172 * @param array $fields field array
173 * @param int $duplicate_mode Do an update on a duplicate entry
175 * @return boolean was the insert successful?
178 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT)
180 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
181 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
184 if (empty($fields['created'])) {
185 $fields['created'] = DateTimeFormat::utcNow();
188 $ret = DBA::insert('contact', $fields, $duplicate_mode);
189 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
190 if (!DBA::isResult($contact)) {
195 // Search for duplicated contacts and get rid of them
196 self::removeDuplicates($contact['nurl'], $contact['uid']);
202 * @param integer $id Contact ID
203 * @param array $fields Array of selected fields, empty for all
204 * @return array|boolean Contact record if it exists, false otherwise
207 public static function getById($id, $fields = [])
209 return DBA::selectFirst('contact', $fields, ['id' => $id]);
213 * Fetches a contact by a given url
215 * @param string $url profile url
216 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
217 * @param array $fields Field list
218 * @param integer $uid User ID of the contact
219 * @return array contact array
221 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
223 if ($update || is_null($update)) {
224 $cid = self::getIdForURL($url, $uid, $update);
229 $contact = self::getById($cid, $fields);
230 if (empty($contact)) {
236 // Add internal fields
238 if (!empty($fields)) {
239 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
240 if (!in_array($internal, $fields)) {
241 $fields[] = $internal;
242 $removal[] = $internal;
247 // We first try the nurl (http://server.tld/nick), most common case
248 $options = ['order' => ['id']];
249 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
251 // Then the addr (nick@server.tld)
252 if (!DBA::isResult($contact)) {
253 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
256 // Then the alias (which could be anything)
257 if (!DBA::isResult($contact)) {
258 // The link could be provided as http although we stored it as https
259 $ssl_url = str_replace('http://', 'https://', $url);
260 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
261 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
264 if (!DBA::isResult($contact)) {
268 // Update the contact in the background if needed
269 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
270 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED)) {
271 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
274 // Remove the internal fields
275 foreach ($removal as $internal) {
276 unset($contact[$internal]);
283 * Fetches a contact for a given user by a given url.
284 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
286 * @param string $url profile url
287 * @param integer $uid User ID of the contact
288 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
289 * @param array $fields Field list
290 * @return array contact array
292 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
295 $contact = self::getByURL($url, $update, $fields, $uid);
296 if (!empty($contact)) {
297 if (!empty($contact['id'])) {
298 $contact['cid'] = $contact['id'];
305 $contact = self::getByURL($url, $update, $fields);
306 if (!empty($contact['id'])) {
308 $contact['zid'] = $contact['id'];
314 * Tests if the given contact is a follower
316 * @param int $cid Either public contact id or user's contact id
317 * @param int $uid User ID
319 * @return boolean is the contact id a follower?
320 * @throws HTTPException\InternalServerErrorException
321 * @throws \ImagickException
323 public static function isFollower($cid, $uid)
325 if (Contact\User::isBlocked($cid, $uid)) {
329 $cdata = self::getPublicAndUserContacID($cid, $uid);
330 if (empty($cdata['user'])) {
334 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
335 return DBA::exists('contact', $condition);
339 * Tests if the given contact url is a follower
341 * @param string $url Contact URL
342 * @param int $uid User ID
344 * @return boolean is the contact id a follower?
345 * @throws HTTPException\InternalServerErrorException
346 * @throws \ImagickException
348 public static function isFollowerByURL($url, $uid)
350 $cid = self::getIdForURL($url, $uid);
356 return self::isFollower($cid, $uid);
360 * Tests if the given user follow the given contact
362 * @param int $cid Either public contact id or user's contact id
363 * @param int $uid User ID
365 * @return boolean is the contact url being followed?
366 * @throws HTTPException\InternalServerErrorException
367 * @throws \ImagickException
369 public static function isSharing($cid, $uid)
371 if (Contact\User::isBlocked($cid, $uid)) {
375 $cdata = self::getPublicAndUserContacID($cid, $uid);
376 if (empty($cdata['user'])) {
380 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
381 return DBA::exists('contact', $condition);
385 * Tests if the given user follow the given contact url
387 * @param string $url Contact URL
388 * @param int $uid User ID
390 * @return boolean is the contact url being followed?
391 * @throws HTTPException\InternalServerErrorException
392 * @throws \ImagickException
394 public static function isSharingByURL($url, $uid)
396 $cid = self::getIdForURL($url, $uid);
402 return self::isSharing($cid, $uid);
406 * Get the basepath for a given contact link
408 * @param string $url The contact link
409 * @param boolean $dont_update Don't update the contact
411 * @return string basepath
412 * @throws HTTPException\InternalServerErrorException
413 * @throws \ImagickException
415 public static function getBasepath($url, $dont_update = false)
417 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
418 if (!DBA::isResult($contact)) {
422 if (!empty($contact['baseurl'])) {
423 return $contact['baseurl'];
424 } elseif ($dont_update) {
428 // Update the existing contact
429 self::updateFromProbe($contact['id']);
431 // And fetch the result
432 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
433 if (empty($contact['baseurl'])) {
434 Logger::info('No baseurl for contact', ['url' => $url]);
438 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
439 return $contact['baseurl'];
443 * Check if the given contact url is on the same server
445 * @param string $url The contact link
447 * @return boolean Is it the same server?
449 public static function isLocal($url)
451 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
455 * Check if the given contact ID is on the same server
457 * @param string $url The contact link
459 * @return boolean Is it the same server?
461 public static function isLocalById(int $cid)
463 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
464 if (!DBA::isResult($contact)) {
468 if (empty($contact['baseurl'])) {
469 $baseurl = self::getBasepath($contact['url'], true);
471 $baseurl = $contact['baseurl'];
474 return Strings::compareLink($baseurl, DI::baseUrl());
478 * Returns the public contact id of the given user id
480 * @param integer $uid User ID
482 * @return integer|boolean Public contact id for given user id
485 public static function getPublicIdByUserId($uid)
487 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
488 if (!DBA::isResult($self)) {
491 return self::getIdForURL($self['url']);
495 * Returns the contact id for the user and the public contact id for a given contact id
497 * @param int $cid Either public contact id or user's contact id
498 * @param int $uid User ID
500 * @return array with public and user's contact id
501 * @throws HTTPException\InternalServerErrorException
502 * @throws \ImagickException
504 public static function getPublicAndUserContacID($cid, $uid)
506 if (empty($uid) || empty($cid)) {
510 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
511 if (!DBA::isResult($contact)) {
515 // We quit when the user id don't match the user id of the provided contact
516 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
520 if ($contact['uid'] != 0) {
521 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
525 $ucid = $contact['id'];
527 $pcid = $contact['id'];
528 $ucid = Contact::getIdForURL($contact['url'], $uid);
531 return ['public' => $pcid, 'user' => $ucid];
535 * Returns contact details for a given contact id in combination with a user id
537 * @param int $cid A contact ID
538 * @param int $uid The User ID
539 * @param array $fields The selected fields for the contact
541 * @return array The contact details
545 public static function getContactForUser($cid, $uid, array $fields = [])
547 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
549 if (!DBA::isResult($contact)) {
557 * Creates the self-contact for the provided user id
560 * @return bool Operation success
561 * @throws HTTPException\InternalServerErrorException
563 public static function createSelfFromUserId($uid)
565 // Only create the entry if it doesn't exist yet
566 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
570 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'], ['uid' => $uid]);
571 if (!DBA::isResult($user)) {
575 $return = DBA::insert('contact', [
576 'uid' => $user['uid'],
577 'created' => DateTimeFormat::utcNow(),
579 'name' => $user['username'],
580 'nick' => $user['nickname'],
581 'pubkey' => $user['pubkey'],
582 'prvkey' => $user['prvkey'],
583 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
584 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
585 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
588 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
589 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
590 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
591 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
592 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
593 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
594 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
595 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
596 'name-date' => DateTimeFormat::utcNow(),
597 'uri-date' => DateTimeFormat::utcNow(),
598 'avatar-date' => DateTimeFormat::utcNow(),
606 * Updates the self-contact for the provided user id
609 * @param boolean $update_avatar Force the avatar update
610 * @throws HTTPException\InternalServerErrorException
612 public static function updateSelfFromUserID($uid, $update_avatar = false)
614 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
615 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
616 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
617 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
618 if (!DBA::isResult($self)) {
622 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
623 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
624 if (!DBA::isResult($user)) {
628 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
629 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
630 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
631 if (!DBA::isResult($profile)) {
635 $file_suffix = 'jpg';
637 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
638 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
639 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
640 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
641 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp']];
643 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
644 if (DBA::isResult($avatar)) {
645 if ($update_avatar) {
646 $fields['avatar-date'] = DateTimeFormat::utcNow();
649 // Creating the path to the avatar, beginning with the file suffix
650 $types = Images::supportedTypes();
651 if (isset($types[$avatar['type']])) {
652 $file_suffix = $types[$avatar['type']];
655 // We are adding a timestamp value so that other systems won't use cached content
656 $timestamp = strtotime($fields['avatar-date']);
658 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
659 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
661 $fields['photo'] = $prefix . '4' . $suffix;
662 $fields['thumb'] = $prefix . '5' . $suffix;
663 $fields['micro'] = $prefix . '6' . $suffix;
665 // We hadn't found a photo entry, so we use the default avatar
666 $fields['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
667 $fields['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
668 $fields['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
671 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
672 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
673 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
674 $fields['unsearchable'] = !$profile['net-publish'];
676 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
677 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
678 $fields['nurl'] = Strings::normaliseLink($fields['url']);
679 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
680 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
681 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
682 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
683 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
684 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
688 foreach ($fields as $field => $content) {
689 if ($self[$field] != $content) {
695 if ($fields['name'] != $self['name']) {
696 $fields['name-date'] = DateTimeFormat::utcNow();
698 $fields['updated'] = DateTimeFormat::utcNow();
699 DBA::update('contact', $fields, ['id' => $self['id']]);
701 // Update the public contact as well
702 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
704 // Update the profile
705 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
706 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
707 DBA::update('profile', $fields, ['uid' => $uid]);
712 * Marks a contact for removal
714 * @param int $id contact id
716 * @throws HTTPException\InternalServerErrorException
718 public static function remove($id)
720 // We want just to make sure that we don't delete our "self" contact
721 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
722 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
726 // Archive the contact
727 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
729 // Delete it in the background
730 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
734 * Sends an unfriend message. Does not remove the contact
736 * @param array $user User unfriending
737 * @param array $contact Contact unfriended
738 * @param boolean $dissolve Remove the contact on the remote side
740 * @throws HTTPException\InternalServerErrorException
741 * @throws \ImagickException
743 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
745 if (empty($contact['network'])) {
749 $protocol = $contact['network'];
750 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
751 $protocol = Protocol::ACTIVITYPUB;
754 if (($protocol == Protocol::DFRN) && $dissolve) {
755 DFRN::deliver($user, $contact, 'placeholder', true);
756 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
757 // create an unfollow slap
759 $item['verb'] = Activity::O_UNFOLLOW;
760 $item['gravity'] = GRAVITY_ACTIVITY;
761 $item['follow'] = $contact["url"];
766 $slap = OStatus::salmon($item, $user);
768 if (!empty($contact['notify'])) {
769 Salmon::slapper($user, $contact['notify'], $slap);
771 } elseif ($protocol == Protocol::DIASPORA) {
772 Diaspora::sendUnshare($user, $contact);
773 } elseif ($protocol == Protocol::ACTIVITYPUB) {
774 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
777 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
783 * Marks a contact for archival after a communication issue delay
785 * Contact has refused to recognise us as a friend. We will start a countdown.
786 * If they still don't recognise us in 32 days, the relationship is over,
787 * and we won't waste any more time trying to communicate with them.
788 * This provides for the possibility that their database is temporarily messed
789 * up or some other transient event and that there's a possibility we could recover from it.
791 * @param array $contact contact to mark for archival
793 * @throws HTTPException\InternalServerErrorException
795 public static function markForArchival(array $contact)
797 if (!isset($contact['url']) && !empty($contact['id'])) {
798 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
799 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
800 if (!DBA::isResult($contact)) {
803 } elseif (!isset($contact['url'])) {
804 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
807 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
809 // Contact already archived or "self" contact? => nothing to do
810 if ($contact['archive'] || $contact['self']) {
814 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
815 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
816 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
819 * We really should send a notification to the owner after 2-3 weeks
820 * so they won't be surprised when the contact vanishes and can take
821 * remedial action if this was a serious mistake or glitch
824 /// @todo Check for contact vitality via probing
825 $archival_days = DI::config()->get('system', 'archival_days', 32);
827 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
828 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
829 /* Relationship is really truly dead. archive them rather than
830 * delete, though if the owner tries to unarchive them we'll start
831 * the whole process over again.
833 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
834 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
840 * Cancels the archival countdown
842 * @see Contact::markForArchival()
844 * @param array $contact contact to be unmarked for archival
848 public static function unmarkForArchival(array $contact)
850 // Always unarchive the relay contact entry
851 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
852 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
853 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
854 DBA::update('contact', $fields, $condition);
857 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
858 $exists = DBA::exists('contact', $condition);
860 // We don't need to update, we never marked this contact for archival
865 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
867 if (!isset($contact['url']) && !empty($contact['id'])) {
868 $fields = ['id', 'url', 'batch'];
869 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
870 if (!DBA::isResult($contact)) {
875 // It's a miracle. Our dead contact has inexplicably come back to life.
876 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
877 DBA::update('contact', $fields, ['id' => $contact['id']]);
878 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
882 * Returns the data array for the photo menu of a given contact
884 * @param array $contact contact
885 * @param int $uid optional, default 0
887 * @throws HTTPException\InternalServerErrorException
888 * @throws \ImagickException
890 public static function photoMenu(array $contact, $uid = 0)
895 $contact_drop_link = '';
902 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
904 $profile_link = self::magicLink($contact['url']);
905 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
910 // Look for our own contact if the uid doesn't match and isn't public
911 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
912 if (DBA::isResult($contact_own)) {
913 return self::photoMenu($contact_own, $uid);
918 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
920 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
922 $profile_link = $contact['url'];
925 if ($profile_link === 'mailbox') {
930 $status_link = $profile_link . '/status';
931 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
932 $profile_link = $profile_link . '/profile';
935 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
936 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
939 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
940 $poke_link = 'contact/' . $contact['id'] . '/poke';
943 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
945 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
947 if (!$contact['self']) {
948 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
953 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
954 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
955 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
956 } elseif(!$contact['pending']) {
957 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
961 if (!empty($follow_link) || !empty($unfollow_link)) {
962 $contact_drop_link = '';
967 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
969 if (empty($contact['uid'])) {
971 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
972 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
973 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
974 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
975 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
979 'status' => [DI::l10n()->t('View Status') , $status_link , true],
980 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
981 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
982 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
983 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
984 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
985 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
986 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
987 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
988 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
991 if (!empty($contact['pending'])) {
992 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
993 if (DBA::isResult($intro)) {
994 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
999 $args = ['contact' => $contact, 'menu' => &$menu];
1001 Hook::callAll('contact_photo_menu', $args);
1003 $menucondensed = [];
1005 foreach ($menu as $menuname => $menuitem) {
1006 if ($menuitem[1] != '') {
1007 $menucondensed[$menuname] = $menuitem;
1011 return $menucondensed;
1015 * Fetch the contact id for a given URL and user
1017 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1018 * `addr` or `alias`.
1020 * If there's no record and we aren't looking for a public contact, we quit.
1021 * If there's one, we check that it isn't time to update the picture else we
1022 * directly return the found contact id.
1024 * Second, we probe the provided $url whether it's http://server.tld/profile or
1025 * nick@server.tld. We quit if we can't get any info back.
1027 * Third, we create the contact record if it doesn't exist
1029 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1030 * if there's any updates
1032 * @param string $url Contact URL
1033 * @param integer $uid The user id for the contact (0 = public contact)
1034 * @param boolean $update true = always update, false = never update, null = update when not found
1035 * @param array $default Default value for creating the contact when everything else fails
1037 * @return integer Contact ID
1038 * @throws HTTPException\InternalServerErrorException
1039 * @throws \ImagickException
1041 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1046 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1050 $contact = self::getByURL($url, false, ['id', 'network'], $uid);
1052 if (!empty($contact)) {
1053 $contact_id = $contact["id"];
1055 if (empty($update)) {
1056 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1059 } elseif ($uid != 0) {
1060 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1062 } elseif (empty($default) && !is_null($update) && !$update) {
1063 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1069 if (empty($default['network']) || $update) {
1070 $data = Probe::uri($url, "", $uid);
1072 // Take the default values when probing failed
1073 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1074 $data = array_merge($data, $default);
1076 } elseif (!empty($default['network'])) {
1080 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1081 // Fetch data for the public contact via the first found personal contact
1082 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1083 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'contact-type',
1084 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1085 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1087 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1088 if (!DBA::isResult($personal_contact)) {
1089 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1092 if (DBA::isResult($personal_contact)) {
1093 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1094 $data = $personal_contact;
1095 $data['photo'] = $personal_contact['avatar'];
1096 $data['account-type'] = $personal_contact['contact-type'];
1097 $data['hide'] = $personal_contact['unsearchable'];
1098 unset($data['avatar']);
1099 unset($data['contact-type']);
1100 unset($data['unsearchable']);
1104 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1105 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1110 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1111 if (!empty($data['alias'])) {
1112 $urls[] = Strings::normaliseLink($data['alias']);
1114 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1115 if (!empty($contact['id'])) {
1116 $contact_id = $contact['id'];
1117 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1122 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1125 'url' => $data['url'],
1126 'nurl' => Strings::normaliseLink($data['url']),
1127 'network' => $data['network'],
1128 'created' => DateTimeFormat::utcNow(),
1129 'rel' => self::SHARING,
1135 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1137 // Before inserting we do check if the entry does exist now.
1138 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1139 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1140 if (DBA::isResult($contact)) {
1141 $contact_id = $contact['id'];
1142 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1144 DBA::insert('contact', $fields);
1145 $contact_id = DBA::lastInsertId();
1147 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1150 DI::lock()->release(self::LOCK_INSERT);
1152 Logger::warning('Contact lock had not been acquired');
1156 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1160 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1163 self::updateFromProbeArray($contact_id, $data);
1169 * Checks if the contact is archived
1171 * @param int $cid contact id
1173 * @return boolean Is the contact archived?
1174 * @throws HTTPException\InternalServerErrorException
1176 public static function isArchived(int $cid)
1182 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1183 if (!DBA::isResult($contact)) {
1187 if ($contact['archive']) {
1191 // Check status of ActivityPub endpoints
1192 $apcontact = APContact::getByURL($contact['url'], false);
1193 if (!empty($apcontact)) {
1194 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1198 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1203 // Check status of Diaspora endpoints
1204 if (!empty($contact['batch'])) {
1205 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1206 return DBA::exists('contact', $condition);
1213 * Checks if the contact is blocked
1215 * @param int $cid contact id
1217 * @return boolean Is the contact blocked?
1218 * @throws HTTPException\InternalServerErrorException
1220 public static function isBlocked($cid)
1226 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1227 if (!DBA::isResult($blocked)) {
1231 if (Network::isUrlBlocked($blocked['url'])) {
1235 return (bool) $blocked['blocked'];
1239 * Checks if the contact is hidden
1241 * @param int $cid contact id
1243 * @return boolean Is the contact hidden?
1244 * @throws \Exception
1246 public static function isHidden($cid)
1252 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1253 if (!DBA::isResult($hidden)) {
1256 return (bool) $hidden['hidden'];
1260 * Returns posts from a given contact url
1262 * @param string $contact_url Contact URL
1263 * @param bool $thread_mode
1264 * @param int $update Update mode
1265 * @param int $parent Item parent ID for the update mode
1266 * @return string posts in HTML
1267 * @throws \Exception
1269 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1271 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1275 * Returns posts from a given contact id
1277 * @param int $cid Contact ID
1278 * @param bool $thread_mode
1279 * @param int $update Update mode
1280 * @param int $parent Item parent ID for the update mode
1281 * @return string posts in HTML
1282 * @throws \Exception
1284 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1288 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1289 if (!DBA::isResult($contact)) {
1293 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1294 $sql = "`item`.`uid` IN (0, ?)";
1296 $sql = "`item`.`uid` = ?";
1299 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1302 $condition = ["(`$contact_field` = ? OR (`causer-id` = ? AND `post-type` = ?)) AND `gravity` = ? AND " . $sql,
1303 $cid, $cid, Item::PT_ANNOUNCEMENT, GRAVITY_PARENT, local_user()];
1305 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1306 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1309 if (!empty($parent)) {
1310 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1312 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1313 if (!empty($last_received)) {
1314 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1318 if (DI::mode()->isMobile()) {
1319 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1320 DI::config()->get('system', 'itemspage_network_mobile'));
1322 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1323 DI::config()->get('system', 'itemspage_network'));
1326 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1328 $params = ['order' => ['received' => true], 'group_by' => ['uri-id'],
1329 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1331 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1332 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1333 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1339 $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1341 while ($item = DBA::fetch($r)) {
1342 if ($item['gravity'] != GRAVITY_PARENT) {
1343 $item['uri'] = $item['parent-uri'];
1345 unset($item['parent-uri']);
1346 unset($item['gravity']);
1352 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1354 $r = Item::selectForUser(local_user(), [], $condition, $params);
1356 $items = Item::inArray($r);
1358 $o .= conversation($a, $items, 'contact-posts', $update);
1362 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1363 $o .= HTML::scrollLoader();
1365 $o .= $pager->renderMinimal(count($items));
1373 * Returns the account type name
1375 * The function can be called with either the user or the contact array
1377 * @param array $contact contact or user array
1380 public static function getAccountType(array $contact)
1382 // There are several fields that indicate that the contact or user is a forum
1383 // "page-flags" is a field in the user table,
1384 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1385 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1386 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1387 || (isset($contact['forum']) && intval($contact['forum']))
1388 || (isset($contact['prv']) && intval($contact['prv']))
1389 || (isset($contact['community']) && intval($contact['community']))
1391 $type = self::TYPE_COMMUNITY;
1393 $type = self::TYPE_PERSON;
1396 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1397 if (isset($contact["contact-type"])) {
1398 $type = $contact["contact-type"];
1401 if (isset($contact["account-type"])) {
1402 $type = $contact["account-type"];
1406 case self::TYPE_ORGANISATION:
1407 $account_type = DI::l10n()->t("Organisation");
1410 case self::TYPE_NEWS:
1411 $account_type = DI::l10n()->t('News');
1414 case self::TYPE_COMMUNITY:
1415 $account_type = DI::l10n()->t("Forum");
1423 return $account_type;
1431 * @throws \Exception
1433 public static function block($cid, $reason = null)
1435 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1441 * Unblocks a contact
1445 * @throws \Exception
1447 public static function unblock($cid)
1449 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1455 * Ensure that cached avatar exist
1457 * @param integer $cid
1459 public static function checkAvatarCache(int $cid)
1461 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1462 if (!DBA::isResult($contact)) {
1466 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1470 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1472 self::updateAvatar($cid, $contact['avatar'], true);
1476 * Return the photo path for a given contact array in the given size
1478 * @param array $contact contact array
1479 * @param string $field Fieldname of the photo in the contact array
1480 * @param string $default Default path when no picture had been found
1481 * @param string $size Size of the avatar picture
1482 * @param string $avatar Avatar path that is displayed when no photo had been found
1483 * @return string photo path
1485 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1487 if (!empty($contact)) {
1488 $contact = self::checkAvatarCacheByArray($contact);
1489 if (!empty($contact[$field])) {
1490 $avatar = $contact[$field];
1494 if (empty($avatar)) {
1498 if (Proxy::isLocalImage($avatar)) {
1501 return Proxy::proxifyUrl($avatar, false, $size);
1506 * Return the photo path for a given contact array
1508 * @param array $contact Contact array
1509 * @param string $avatar Avatar path that is displayed when no photo had been found
1510 * @return string photo path
1512 public static function getPhoto(array $contact, string $avatar = '')
1514 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO, Proxy::SIZE_SMALL, $avatar);
1518 * Return the photo path (thumb size) for a given contact array
1520 * @param array $contact Contact array
1521 * @param string $avatar Avatar path that is displayed when no photo had been found
1522 * @return string photo path
1524 public static function getThumb(array $contact, string $avatar = '')
1526 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . self::DEFAULT_AVATAR_THUMB, Proxy::SIZE_THUMB, $avatar);
1530 * Return the photo path (micro size) for a given contact array
1532 * @param array $contact Contact array
1533 * @param string $avatar Avatar path that is displayed when no photo had been found
1534 * @return string photo path
1536 public static function getMicro(array $contact, string $avatar = '')
1538 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . self::DEFAULT_AVATAR_MICRO, Proxy::SIZE_MICRO, $avatar);
1542 * Check the given contact array for avatar cache fields
1544 * @param array $contact
1545 * @return array contact array with avatar cache fields
1547 private static function checkAvatarCacheByArray(array $contact)
1550 $contact_fields = [];
1551 $fields = ['photo', 'thumb', 'micro'];
1552 foreach ($fields as $field) {
1553 if (isset($contact[$field])) {
1554 $contact_fields[] = $field;
1556 if (isset($contact[$field]) && empty($contact[$field])) {
1565 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1566 self::updateAvatar($contact['id'], $contact['avatar'], true);
1568 $new_contact = self::getById($contact['id'], $contact_fields);
1569 if (DBA::isResult($new_contact)) {
1570 // We only update the cache fields
1571 $contact = array_merge($contact, $new_contact);
1575 /// add the default avatars if the fields aren't filled
1576 if (isset($contact['photo']) && empty($contact['photo'])) {
1577 $contact['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
1579 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1580 $contact['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
1582 if (isset($contact['micro']) && empty($contact['micro'])) {
1583 $contact['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
1590 * Updates the avatar links in a contact only if needed
1592 * @param int $cid Contact id
1593 * @param string $avatar Link to avatar picture
1594 * @param bool $force force picture update
1595 * @param bool $create_cache Enforces the creation of cached avatar fields
1598 * @throws HTTPException\InternalServerErrorException
1599 * @throws HTTPException\NotFoundException
1600 * @throws \ImagickException
1602 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1604 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl', 'url', 'network'], ['id' => $cid, 'self' => false]);
1605 if (!DBA::isResult($contact)) {
1609 $uid = $contact['uid'];
1611 // Only update the cached photo links of public contacts when they already are cached
1612 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1613 if ($contact['avatar'] != $avatar) {
1614 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1615 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1620 // User contacts use are updated through the public contacts
1621 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1622 $pcid = self::getIdForURL($contact['url'], false);
1623 if (!empty($pcid)) {
1624 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1625 self::updateAvatar($pcid, $avatar, $force, true);
1630 // Replace cached avatar pictures from the default avatar with the default avatars in different sizes
1631 if (strpos($avatar, self::DEFAULT_AVATAR_PHOTO)) {
1632 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1633 'photo' => DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO,
1634 'thumb' => DI::baseUrl() . self::DEFAULT_AVATAR_THUMB,
1635 'micro' => DI::baseUrl() . self::DEFAULT_AVATAR_MICRO];
1636 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1639 // Use the data from the self account
1640 if (empty($fields)) {
1641 $local_uid = User::getIdForURL($contact['url']);
1642 if (!empty($local_uid)) {
1643 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1644 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1648 if (empty($fields)) {
1649 $update = ($contact['avatar'] != $avatar) || $force;
1653 $contact['photo'] ?? '',
1654 $contact['thumb'] ?? '',
1655 $contact['micro'] ?? '',
1658 foreach ($data as $image_uri) {
1659 $image_rid = Photo::ridFromURI($image_uri);
1660 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1661 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1668 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1670 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1671 $update = !empty($fields);
1672 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1678 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1687 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1688 // Collect all user contacts of the given public contact
1689 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1690 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1691 while ($personal_contact = DBA::fetch($personal_contacts)) {
1692 $cids[] = $personal_contact['id'];
1693 $uids[] = $personal_contact['uid'];
1695 DBA::close($personal_contacts);
1697 if (!empty($cids)) {
1698 // Delete possibly existing cached user contact avatars
1699 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1705 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1706 DBA::update('contact', $fields, ['id' => $cids]);
1710 * Helper function for "updateFromProbe". Updates personal and public contact
1712 * @param integer $id contact id
1713 * @param integer $uid user id
1714 * @param string $url The profile URL of the contact
1715 * @param array $fields The fields that are updated
1717 * @throws \Exception
1719 private static function updateContact($id, $uid, $url, array $fields)
1721 if (!DBA::update('contact', $fields, ['id' => $id])) {
1722 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1726 // Search for duplicated contacts and get rid of them
1727 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1731 // Archive or unarchive the contact. We only need to do this for the public contact.
1732 // The archive/unarchive function will update the personal contacts by themselves.
1733 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1734 if (!DBA::isResult($contact)) {
1735 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1739 if (!empty($fields['success_update'])) {
1740 self::unmarkForArchival($contact);
1741 } elseif (!empty($fields['failure_update'])) {
1742 self::markForArchival($contact);
1745 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1747 // These contacts are sharing with us, we don't poll them.
1748 // This means that we don't set the update fields in "OnePoll.php".
1749 $condition['rel'] = self::SHARING;
1750 DBA::update('contact', $fields, $condition);
1752 // If the contact failed, propagate the update fields to all contacts
1753 if (empty($fields['failed'])) {
1754 unset($fields['last-update']);
1755 unset($fields['success_update']);
1756 unset($fields['failure_update']);
1759 if (empty($fields)) {
1763 // We are polling these contacts, so we mustn't set the update fields here.
1764 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1765 DBA::update('contact', $fields, $condition);
1769 * Remove duplicated contacts
1771 * @param string $nurl Normalised contact url
1772 * @param integer $uid User id
1774 * @throws \Exception
1776 public static function removeDuplicates(string $nurl, int $uid)
1778 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1779 $count = DBA::count('contact', $condition);
1784 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1785 if (!DBA::isResult($first_contact)) {
1786 // Shouldn't happen - so we handle it
1790 $first = $first_contact['id'];
1791 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1792 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1793 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1794 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1798 // Find all duplicates
1799 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1800 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1801 while ($duplicate = DBA::fetch($duplicates)) {
1802 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1806 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1808 DBA::close($duplicates);
1809 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1814 * @param integer $id contact id
1815 * @param string $network Optional network we are probing for
1817 * @throws HTTPException\InternalServerErrorException
1818 * @throws \ImagickException
1820 public static function updateFromProbe(int $id, string $network = '')
1822 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1823 if (!DBA::isResult($contact)) {
1827 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1828 return self::updateFromProbeArray($id, $ret);
1832 * @param integer $id contact id
1833 * @param array $ret Probed data
1835 * @throws HTTPException\InternalServerErrorException
1836 * @throws \ImagickException
1838 private static function updateFromProbeArray(int $id, array $ret)
1841 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1842 This will reliably kill your communication with old Friendica contacts.
1845 // These fields aren't updated by this routine:
1846 // 'xmpp', 'sensitive'
1848 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe', 'manually-approve',
1849 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1850 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1851 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1852 if (!DBA::isResult($contact)) {
1856 $uid = $contact['uid'];
1857 unset($contact['uid']);
1859 $pubkey = $contact['pubkey'];
1860 unset($contact['pubkey']);
1862 $contact['photo'] = $contact['avatar'];
1863 unset($contact['avatar']);
1865 $updated = DateTimeFormat::utcNow();
1867 // We must not try to update relay contacts via probe. They are no real contacts.
1868 // We check after the probing to be able to correct falsely detected contact types.
1869 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1870 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1871 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1872 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1876 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1877 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1878 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1882 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1883 $ret['unsearchable'] = $ret['hide'];
1886 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1887 $ret['forum'] = false;
1888 $ret['prv'] = false;
1889 $ret['contact-type'] = $ret['account-type'];
1890 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1891 $ret['forum'] = (bool)!$ret['manually-approve'];
1892 $ret['prv'] = (bool)!$ret['forum'];
1896 $new_pubkey = $ret['pubkey'] ?? '';
1899 $ret['last-item'] = Probe::getLastUpdate($ret);
1900 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1905 // make sure to not overwrite existing values with blank entries except some technical fields
1906 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1907 foreach ($ret as $key => $val) {
1908 if (!array_key_exists($key, $contact)) {
1910 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1911 $ret[$key] = $contact[$key];
1912 } elseif ($ret[$key] != $contact[$key]) {
1917 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1920 unset($ret['last-item']);
1923 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1924 self::updateAvatar($id, $ret['photo'], $update);
1928 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1930 if (Contact\Relation::isDiscoverable($ret['url'])) {
1931 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1934 // Update the public contact
1936 $contact = self::getByURL($ret['url'], false, ['id']);
1937 if (!empty($contact['id'])) {
1938 self::updateFromProbeArray($contact['id'], $ret);
1945 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1946 $ret['updated'] = $updated;
1947 $ret['failed'] = false;
1949 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1950 if (empty($pubkey) && !empty($new_pubkey)) {
1951 $ret['pubkey'] = $new_pubkey;
1954 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1955 $ret['uri-date'] = DateTimeFormat::utcNow();
1958 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1959 $ret['name-date'] = $updated;
1963 $ret['last-update'] = $updated;
1964 $ret['success_update'] = $updated;
1967 unset($ret['photo']);
1969 self::updateContact($id, $uid, $ret['url'], $ret);
1971 if (Contact\Relation::isDiscoverable($ret['url'])) {
1972 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1979 * @param integer $url contact url
1980 * @return integer Contact id
1981 * @throws HTTPException\InternalServerErrorException
1982 * @throws \ImagickException
1984 public static function updateFromProbeByURL($url)
1986 $id = self::getIdForURL($url);
1992 self::updateFromProbe($id);
1998 * Detects if a given contact array belongs to a legacy DFRN connection
2000 * @param array $contact
2003 public static function isLegacyDFRNContact($contact)
2005 // Newer Friendica contacts are connected via AP, then these fields aren't set
2006 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
2010 * Detects the communication protocol for a given contact url.
2011 * This is used to detect Friendica contacts that we can communicate via AP.
2013 * @param string $url contact url
2014 * @param string $network Network of that contact
2015 * @return string with protocol
2017 public static function getProtocol($url, $network)
2019 if ($network != Protocol::DFRN) {
2023 $apcontact = APContact::getByURL($url);
2024 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2025 return Protocol::ACTIVITYPUB;
2032 * Takes a $uid and a url/handle and adds a new contact
2034 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2035 * dfrn_request page.
2037 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2040 * $return['success'] boolean true if successful
2041 * $return['message'] error text if success is false.
2043 * Takes a $uid and a url/handle and adds a new contact
2045 * @param array $user The user the contact should be created for
2046 * @param string $url The profile URL of the contact
2047 * @param bool $interactive
2048 * @param string $network
2050 * @throws HTTPException\InternalServerErrorException
2051 * @throws HTTPException\NotFoundException
2052 * @throws \ImagickException
2054 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2056 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2058 // remove ajax junk, e.g. Twitter
2059 $url = str_replace('/#!/', '/', $url);
2061 if (!Network::isUrlAllowed($url)) {
2062 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2066 if (Network::isUrlBlocked($url)) {
2067 $result['message'] = DI::l10n()->t('Blocked domain');
2072 $result['message'] = DI::l10n()->t('Connect URL missing.');
2076 $arr = ['url' => $url, 'contact' => []];
2078 Hook::callAll('follow', $arr);
2081 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2085 if (!empty($arr['contact']['name'])) {
2086 $ret = $arr['contact'];
2088 $ret = Probe::uri($url, $network, $user['uid']);
2091 if (($network != '') && ($ret['network'] != $network)) {
2092 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2096 // check if we already have a contact
2097 // the poll url is more reliable than the profile url, as we may have
2098 // indirect links or webfinger links
2100 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2101 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2102 if (!DBA::isResult($contact)) {
2103 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2104 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2107 $protocol = self::getProtocol($ret['url'], $ret['network']);
2109 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2111 if (strlen(DI::baseUrl()->getUrlPath())) {
2112 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2114 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2117 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2121 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2122 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2123 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2127 // This extra param just confuses things, remove it
2128 if ($protocol === Protocol::DIASPORA) {
2129 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2132 // do we have enough information?
2133 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2134 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2135 if (empty($ret['poll'])) {
2136 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2138 if (empty($ret['name'])) {
2139 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2141 if (empty($ret['url'])) {
2142 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2144 if (strpos($ret['url'], '@') !== false) {
2145 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2146 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2151 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2152 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2153 $ret['notify'] = '';
2156 if (!$ret['notify']) {
2157 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2160 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2162 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2164 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2167 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2168 $pending = (bool)$ret['manually-approve'];
2171 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2175 if (DBA::isResult($contact)) {
2177 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2179 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2180 DBA::update('contact', $fields, ['id' => $contact['id']]);
2182 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2184 // create contact record
2186 'uid' => $user['uid'],
2187 'created' => DateTimeFormat::utcNow(),
2188 'url' => $ret['url'],
2189 'nurl' => Strings::normaliseLink($ret['url']),
2190 'addr' => $ret['addr'],
2191 'alias' => $ret['alias'],
2192 'batch' => $ret['batch'],
2193 'notify' => $ret['notify'],
2194 'poll' => $ret['poll'],
2195 'poco' => $ret['poco'],
2196 'name' => $ret['name'],
2197 'nick' => $ret['nick'],
2198 'network' => $ret['network'],
2199 'baseurl' => $ret['baseurl'],
2200 'gsid' => $ret['gsid'] ?? null,
2201 'protocol' => $protocol,
2202 'pubkey' => $ret['pubkey'],
2203 'rel' => $new_relation,
2204 'priority'=> $ret['priority'],
2205 'writable'=> $writeable,
2206 'hidden' => $hidden,
2209 'pending' => $pending,
2214 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2215 if (!DBA::isResult($contact)) {
2216 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2220 $contact_id = $contact['id'];
2221 $result['cid'] = $contact_id;
2223 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2225 // Update the avatar
2226 self::updateAvatar($contact_id, $ret['photo']);
2228 // pull feed and consume it, which should subscribe to the hub.
2230 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2232 $owner = User::getOwnerDataById($user['uid']);
2234 if (DBA::isResult($owner)) {
2235 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2236 // create a follow slap
2238 $item['verb'] = Activity::FOLLOW;
2239 $item['gravity'] = GRAVITY_ACTIVITY;
2240 $item['follow'] = $contact["url"];
2242 $item['title'] = '';
2244 $item['uri-id'] = 0;
2246 $slap = OStatus::salmon($item, $owner);
2248 if (!empty($contact['notify'])) {
2249 Salmon::slapper($owner, $contact['notify'], $slap);
2251 } elseif ($protocol == Protocol::DIASPORA) {
2252 $ret = Diaspora::sendShare($owner, $contact);
2253 Logger::log('share returns: ' . $ret);
2254 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2255 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2256 if (empty($activity_id)) {
2257 // This really should never happen
2261 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2262 Logger::log('Follow returns: ' . $ret);
2266 $result['success'] = true;
2271 * Updated contact's SSL policy
2273 * @param array $contact Contact array
2274 * @param string $new_policy New policy, valid: self,full
2276 * @return array Contact array with updated values
2277 * @throws \Exception
2279 public static function updateSslPolicy(array $contact, $new_policy)
2281 $ssl_changed = false;
2282 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2283 $ssl_changed = true;
2284 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2285 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2286 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2287 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2288 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2289 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2292 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2293 $ssl_changed = true;
2294 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2295 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2296 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2297 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2298 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2299 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2303 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2304 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2305 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2306 DBA::update('contact', $fields, ['id' => $contact['id']]);
2313 * @param array $importer Owner (local user) data
2314 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2315 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2316 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2317 * @param string $note Introduction additional message
2318 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2319 * @throws HTTPException\InternalServerErrorException
2320 * @throws \ImagickException
2322 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2324 // Should always be set
2325 if (empty($datarray['author-id'])) {
2329 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2330 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2331 if (!DBA::isResult($pub_contact)) {
2332 // Should never happen
2336 // Contact is blocked at node-level
2337 if (self::isBlocked($datarray['author-id'])) {
2341 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2342 $name = $pub_contact['name'];
2343 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2344 $nick = $pub_contact['nick'];
2345 $network = $pub_contact['network'];
2347 // Ensure that we don't create a new contact when there already is one
2348 $cid = self::getIdForURL($url, $importer['uid']);
2350 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2353 if (!empty($contact)) {
2354 if (!empty($contact['pending'])) {
2355 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2359 // Contact is blocked at user-level
2360 if (!empty($contact['id']) && !empty($importer['id']) &&
2361 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2365 // Make sure that the existing contact isn't archived
2366 self::unmarkForArchival($contact);
2368 if (($contact['rel'] == self::SHARING)
2369 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2370 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2371 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2374 // Ensure to always have the correct network type, independent from the connection request method
2375 self::updateFromProbe($contact['id']);
2379 // send email notification to owner?
2380 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2381 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2385 // create contact record
2386 DBA::insert('contact', [
2387 'uid' => $importer['uid'],
2388 'created' => DateTimeFormat::utcNow(),
2390 'nurl' => Strings::normaliseLink($url),
2393 'network' => $network,
2394 'rel' => self::FOLLOWER,
2401 $contact_id = DBA::lastInsertId();
2403 // Ensure to always have the correct network type, independent from the connection request method
2404 self::updateFromProbe($contact_id);
2406 self::updateAvatar($contact_id, $photo, true);
2408 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2410 /// @TODO Encapsulate this into a function/method
2411 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2412 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2413 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2414 // create notification
2415 $hash = Strings::getRandomHex();
2417 if (is_array($contact_record)) {
2418 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2419 'blocked' => false, 'knowyou' => false, 'note' => $note,
2420 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2423 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2425 if (($user['notify-flags'] & Type::INTRO) &&
2426 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2429 'type' => Type::INTRO,
2430 'notify_flags' => $user['notify-flags'],
2431 'language' => $user['language'],
2432 'to_name' => $user['username'],
2433 'to_email' => $user['email'],
2434 'uid' => $user['uid'],
2435 'link' => DI::baseUrl() . '/notifications/intros',
2436 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2437 'source_link' => $contact_record['url'],
2438 'source_photo' => $contact_record['photo'],
2439 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2443 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2444 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2445 self::createFromProbe($importer, $url, false, $network);
2448 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2449 $fields = ['pending' => false];
2450 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2451 $fields['rel'] = Contact::FRIEND;
2454 DBA::update('contact', $fields, $condition);
2463 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2465 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2466 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2468 Contact::remove($contact['id']);
2472 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2474 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2475 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2477 Contact::remove($contact['id']);
2482 * Create a birthday event.
2484 * Update the year and the birthday.
2486 public static function updateBirthdays()
2490 AND `bd` > "0001-01-01"
2491 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2492 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2493 AND NOT `contact`.`pending`
2494 AND NOT `contact`.`hidden`
2495 AND NOT `contact`.`blocked`
2496 AND NOT `contact`.`archive`
2497 AND NOT `contact`.`deleted`',
2502 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2504 while ($contact = DBA::fetch($contacts)) {
2505 Logger::log('update_contact_birthday: ' . $contact['bd']);
2507 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2509 if (Event::createBirthday($contact, $nextbd)) {
2513 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2514 ['id' => $contact['id']]
2518 DBA::close($contacts);
2522 * Remove the unavailable contact ids from the provided list
2524 * @param array $contact_ids Contact id list
2526 * @throws \Exception
2528 public static function pruneUnavailable(array $contact_ids)
2530 if (empty($contact_ids)) {
2534 $contacts = Contact::selectToArray(['id'], [
2535 'id' => $contact_ids,
2541 return array_column($contacts, 'id');
2545 * Returns a magic link to authenticate remote visitors
2547 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2549 * @param string $contact_url The address of the target contact profile
2550 * @param string $url An url that we will be redirected to after the authentication
2552 * @return string with "redir" link
2553 * @throws HTTPException\InternalServerErrorException
2554 * @throws \ImagickException
2556 public static function magicLink($contact_url, $url = '')
2558 if (!Session::isAuthenticated()) {
2559 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2562 $contact = self::getByURL($contact_url, false);
2563 if (empty($contact)) {
2564 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2567 // Prevents endless loop in case only a non-public contact exists for the contact URL
2568 unset($contact['uid']);
2570 return self::magicLinkByContact($contact, $url ?: $contact_url);
2574 * Returns a magic link to authenticate remote visitors
2576 * @param integer $cid The contact id of the target contact profile
2577 * @param string $url An url that we will be redirected to after the authentication
2579 * @return string with "redir" link
2580 * @throws HTTPException\InternalServerErrorException
2581 * @throws \ImagickException
2583 public static function magicLinkbyId($cid, $url = '')
2585 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2587 return self::magicLinkByContact($contact, $url);
2591 * Returns a magic link to authenticate remote visitors
2593 * @param array $contact The contact array with "uid", "network" and "url"
2594 * @param string $url An url that we will be redirected to after the authentication
2596 * @return string with "redir" link
2597 * @throws HTTPException\InternalServerErrorException
2598 * @throws \ImagickException
2600 public static function magicLinkByContact($contact, $url = '')
2602 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2604 if (!Session::isAuthenticated()) {
2605 return $destination;
2608 // Only redirections to the same host do make sense
2609 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2613 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2614 return 'contact/' . $contact['id'] . '/conversations';
2617 if ($contact['network'] != Protocol::DFRN) {
2618 return $destination;
2621 if (!empty($contact['uid'])) {
2622 return self::magicLink($contact['url'], $url);
2625 if (empty($contact['id'])) {
2626 return $destination;
2629 $redirect = 'redir/' . $contact['id'];
2631 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2632 $redirect .= '?url=' . $url;
2639 * Is the contact a forum?
2641 * @param integer $contactid ID of the contact
2643 * @return boolean "true" if it is a forum
2645 public static function isForum($contactid)
2647 $fields = ['forum', 'prv'];
2648 $condition = ['id' => $contactid];
2649 $contact = DBA::selectFirst('contact', $fields, $condition);
2650 if (!DBA::isResult($contact)) {
2655 return ($contact['forum'] || $contact['prv']);
2659 * Can the remote contact receive private messages?
2661 * @param array $contact
2664 public static function canReceivePrivateMessages(array $contact)
2666 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2667 $self = $contact['self'] ?? false;
2669 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2673 * Search contact table by nick or name
2675 * @param string $search Name or nick
2676 * @param string $mode Search mode (e.g. "community")
2678 * @return array with search results
2679 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2681 public static function searchByName($search, $mode = '')
2683 if (empty($search)) {
2687 // check supported networks
2688 if (DI::config()->get('system', 'diaspora_enabled')) {
2689 $diaspora = Protocol::DIASPORA;
2691 $diaspora = Protocol::DFRN;
2694 if (!DI::config()->get('system', 'ostatus_disabled')) {
2695 $ostatus = Protocol::OSTATUS;
2697 $ostatus = Protocol::DFRN;
2700 // check if we search only communities or every contact
2701 if ($mode === 'community') {
2702 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2709 $results = DBA::p("SELECT * FROM `contact`
2710 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2711 NOT `failed` AND `uid` = ? AND
2712 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2713 ORDER BY `nurl` DESC LIMIT 1000",
2714 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2717 $contacts = DBA::toArray($results);
2722 * Add public contacts from an array
2724 * @param array $urls
2725 * @return array result "count", "added" and "updated"
2727 public static function addByUrls(array $urls)
2734 foreach ($urls as $url) {
2735 $contact = Contact::getByURL($url, false, ['id', 'updated']);
2736 if (empty($contact['id'])) {
2737 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2739 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
2740 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2748 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
2752 * Returns a random, global contact of the current node
2754 * @return string The profile URL
2757 public static function getRandomUrl()
2759 $r = DBA::selectFirst('contact', ['url'], [
2760 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2761 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2762 ], ['order' => ['RAND()']]);
2764 if (DBA::isResult($r)) {