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;
97 * TYPE_UNKNOWN - unknown type
99 * TYPE_PERSON - the account belongs to a person
100 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
102 * TYPE_ORGANISATION - the account belongs to an organisation
103 * Associated page type: PAGE_SOAPBOX
105 * TYPE_NEWS - the account is a news reflector
106 * Associated page type: PAGE_SOAPBOX
108 * TYPE_COMMUNITY - the account is community forum
109 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
111 * TYPE_RELAY - the account is a relay
112 * This will only be assigned to contacts, not to user accounts
115 const TYPE_UNKNOWN = -1;
116 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
117 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
118 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
119 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
120 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
140 * @param array $fields Array of selected fields, empty for all
141 * @param array $condition Array of fields for condition
142 * @param array $params Array of several parameters
146 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
148 return DBA::selectToArray('contact', $fields, $condition, $params);
152 * @param array $fields Array of selected fields, empty for all
153 * @param array $condition Array of fields for condition
154 * @param array $params Array of several parameters
158 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
160 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
166 * Insert a row into the contact table
167 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
169 * @param array $fields field array
170 * @param bool $on_duplicate_update Do an update on a duplicate entry
172 * @return boolean was the insert successful?
175 public static function insert(array $fields, bool $on_duplicate_update = false)
177 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
178 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
179 if (!DBA::isResult($contact)) {
184 // Search for duplicated contacts and get rid of them
185 self::removeDuplicates($contact['nurl'], $contact['uid']);
191 * @param integer $id Contact ID
192 * @param array $fields Array of selected fields, empty for all
193 * @return array|boolean Contact record if it exists, false otherwise
196 public static function getById($id, $fields = [])
198 return DBA::selectFirst('contact', $fields, ['id' => $id]);
202 * Fetches a contact by a given url
204 * @param string $url profile url
205 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
206 * @param array $fields Field list
207 * @param integer $uid User ID of the contact
208 * @return array contact array
210 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
212 if ($update || is_null($update)) {
213 $cid = self::getIdForURL($url, $uid, $update);
218 $contact = self::getById($cid, $fields);
219 if (empty($contact)) {
225 // Add internal fields
227 if (!empty($fields)) {
228 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
229 if (!in_array($internal, $fields)) {
230 $fields[] = $internal;
231 $removal[] = $internal;
236 // We first try the nurl (http://server.tld/nick), most common case
237 $options = ['order' => ['id']];
238 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
240 // Then the addr (nick@server.tld)
241 if (!DBA::isResult($contact)) {
242 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
245 // Then the alias (which could be anything)
246 if (!DBA::isResult($contact)) {
247 // The link could be provided as http although we stored it as https
248 $ssl_url = str_replace('http://', 'https://', $url);
249 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
250 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
253 if (!DBA::isResult($contact)) {
257 // Update the contact in the background if needed
258 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
259 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED)) {
260 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
263 // Remove the internal fields
264 foreach ($removal as $internal) {
265 unset($contact[$internal]);
272 * Fetches a contact for a given user by a given url.
273 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
275 * @param string $url profile url
276 * @param integer $uid User ID of the contact
277 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
278 * @param array $fields Field list
279 * @return array contact array
281 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
284 $contact = self::getByURL($url, $update, $fields, $uid);
285 if (!empty($contact)) {
286 if (!empty($contact['id'])) {
287 $contact['cid'] = $contact['id'];
294 $contact = self::getByURL($url, $update, $fields);
295 if (!empty($contact['id'])) {
297 $contact['zid'] = $contact['id'];
303 * Tests if the given contact is a follower
305 * @param int $cid Either public contact id or user's contact id
306 * @param int $uid User ID
308 * @return boolean is the contact id a follower?
309 * @throws HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 public static function isFollower($cid, $uid)
314 if (Contact\User::isBlocked($cid, $uid)) {
318 $cdata = self::getPublicAndUserContacID($cid, $uid);
319 if (empty($cdata['user'])) {
323 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
324 return DBA::exists('contact', $condition);
328 * Tests if the given contact url is a follower
330 * @param string $url Contact URL
331 * @param int $uid User ID
333 * @return boolean is the contact id a follower?
334 * @throws HTTPException\InternalServerErrorException
335 * @throws \ImagickException
337 public static function isFollowerByURL($url, $uid)
339 $cid = self::getIdForURL($url, $uid);
345 return self::isFollower($cid, $uid);
349 * Tests if the given user follow the given contact
351 * @param int $cid Either public contact id or user's contact id
352 * @param int $uid User ID
354 * @return boolean is the contact url being followed?
355 * @throws HTTPException\InternalServerErrorException
356 * @throws \ImagickException
358 public static function isSharing($cid, $uid)
360 if (Contact\User::isBlocked($cid, $uid)) {
364 $cdata = self::getPublicAndUserContacID($cid, $uid);
365 if (empty($cdata['user'])) {
369 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
370 return DBA::exists('contact', $condition);
374 * Tests if the given user follow the given contact url
376 * @param string $url Contact URL
377 * @param int $uid User ID
379 * @return boolean is the contact url being followed?
380 * @throws HTTPException\InternalServerErrorException
381 * @throws \ImagickException
383 public static function isSharingByURL($url, $uid)
385 $cid = self::getIdForURL($url, $uid);
391 return self::isSharing($cid, $uid);
395 * Get the basepath for a given contact link
397 * @param string $url The contact link
398 * @param boolean $dont_update Don't update the contact
400 * @return string basepath
401 * @throws HTTPException\InternalServerErrorException
402 * @throws \ImagickException
404 public static function getBasepath($url, $dont_update = false)
406 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
407 if (!DBA::isResult($contact)) {
411 if (!empty($contact['baseurl'])) {
412 return $contact['baseurl'];
413 } elseif ($dont_update) {
417 // Update the existing contact
418 self::updateFromProbe($contact['id']);
420 // And fetch the result
421 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
422 if (empty($contact['baseurl'])) {
423 Logger::info('No baseurl for contact', ['url' => $url]);
427 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
428 return $contact['baseurl'];
432 * Check if the given contact url is on the same server
434 * @param string $url The contact link
436 * @return boolean Is it the same server?
438 public static function isLocal($url)
440 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
444 * Check if the given contact ID is on the same server
446 * @param string $url The contact link
448 * @return boolean Is it the same server?
450 public static function isLocalById(int $cid)
452 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
453 if (!DBA::isResult($contact)) {
457 if (empty($contact['baseurl'])) {
458 $baseurl = self::getBasepath($contact['url'], true);
460 $baseurl = $contact['baseurl'];
463 return Strings::compareLink($baseurl, DI::baseUrl());
467 * Returns the public contact id of the given user id
469 * @param integer $uid User ID
471 * @return integer|boolean Public contact id for given user id
474 public static function getPublicIdByUserId($uid)
476 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
477 if (!DBA::isResult($self)) {
480 return self::getIdForURL($self['url']);
484 * Returns the contact id for the user and the public contact id for a given contact id
486 * @param int $cid Either public contact id or user's contact id
487 * @param int $uid User ID
489 * @return array with public and user's contact id
490 * @throws HTTPException\InternalServerErrorException
491 * @throws \ImagickException
493 public static function getPublicAndUserContacID($cid, $uid)
495 if (empty($uid) || empty($cid)) {
499 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
500 if (!DBA::isResult($contact)) {
504 // We quit when the user id don't match the user id of the provided contact
505 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
509 if ($contact['uid'] != 0) {
510 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
514 $ucid = $contact['id'];
516 $pcid = $contact['id'];
517 $ucid = Contact::getIdForURL($contact['url'], $uid);
520 return ['public' => $pcid, 'user' => $ucid];
524 * Returns contact details for a given contact id in combination with a user id
526 * @param int $cid A contact ID
527 * @param int $uid The User ID
528 * @param array $fields The selected fields for the contact
530 * @return array The contact details
534 public static function getContactForUser($cid, $uid, array $fields = [])
536 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
538 if (!DBA::isResult($contact)) {
546 * Creates the self-contact for the provided user id
549 * @return bool Operation success
550 * @throws HTTPException\InternalServerErrorException
552 public static function createSelfFromUserId($uid)
554 // Only create the entry if it doesn't exist yet
555 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
559 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'], ['uid' => $uid]);
560 if (!DBA::isResult($user)) {
564 $return = DBA::insert('contact', [
565 'uid' => $user['uid'],
566 'created' => DateTimeFormat::utcNow(),
568 'name' => $user['username'],
569 'nick' => $user['nickname'],
570 'pubkey' => $user['pubkey'],
571 'prvkey' => $user['prvkey'],
572 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
573 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
574 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
577 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
578 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
579 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
580 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
581 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
582 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
583 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
584 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
585 'name-date' => DateTimeFormat::utcNow(),
586 'uri-date' => DateTimeFormat::utcNow(),
587 'avatar-date' => DateTimeFormat::utcNow(),
595 * Updates the self-contact for the provided user id
598 * @param boolean $update_avatar Force the avatar update
599 * @throws HTTPException\InternalServerErrorException
601 public static function updateSelfFromUserID($uid, $update_avatar = false)
603 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
604 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
605 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
606 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
607 if (!DBA::isResult($self)) {
611 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
612 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
613 if (!DBA::isResult($user)) {
617 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
618 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
619 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
620 if (!DBA::isResult($profile)) {
624 $file_suffix = 'jpg';
626 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
627 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
628 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
629 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
630 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp']];
632 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
633 if (DBA::isResult($avatar)) {
634 if ($update_avatar) {
635 $fields['avatar-date'] = DateTimeFormat::utcNow();
638 // Creating the path to the avatar, beginning with the file suffix
639 $types = Images::supportedTypes();
640 if (isset($types[$avatar['type']])) {
641 $file_suffix = $types[$avatar['type']];
644 // We are adding a timestamp value so that other systems won't use cached content
645 $timestamp = strtotime($fields['avatar-date']);
647 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
648 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
650 $fields['photo'] = $prefix . '4' . $suffix;
651 $fields['thumb'] = $prefix . '5' . $suffix;
652 $fields['micro'] = $prefix . '6' . $suffix;
654 // We hadn't found a photo entry, so we use the default avatar
655 $fields['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
656 $fields['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
657 $fields['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
660 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
661 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
662 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
663 $fields['unsearchable'] = !$profile['net-publish'];
665 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
666 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
667 $fields['nurl'] = Strings::normaliseLink($fields['url']);
668 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
669 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
670 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
671 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
672 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
673 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
677 foreach ($fields as $field => $content) {
678 if ($self[$field] != $content) {
684 if ($fields['name'] != $self['name']) {
685 $fields['name-date'] = DateTimeFormat::utcNow();
687 $fields['updated'] = DateTimeFormat::utcNow();
688 DBA::update('contact', $fields, ['id' => $self['id']]);
690 // Update the public contact as well
691 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
693 // Update the profile
694 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
695 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
696 DBA::update('profile', $fields, ['uid' => $uid]);
701 * Marks a contact for removal
703 * @param int $id contact id
705 * @throws HTTPException\InternalServerErrorException
707 public static function remove($id)
709 // We want just to make sure that we don't delete our "self" contact
710 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
711 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
715 // Archive the contact
716 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
718 // Delete it in the background
719 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
723 * Sends an unfriend message. Does not remove the contact
725 * @param array $user User unfriending
726 * @param array $contact Contact unfriended
727 * @param boolean $dissolve Remove the contact on the remote side
729 * @throws HTTPException\InternalServerErrorException
730 * @throws \ImagickException
732 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
734 if (empty($contact['network'])) {
738 $protocol = $contact['network'];
739 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
740 $protocol = Protocol::ACTIVITYPUB;
743 if (($protocol == Protocol::DFRN) && $dissolve) {
744 DFRN::deliver($user, $contact, 'placeholder', true);
745 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
746 // create an unfollow slap
748 $item['verb'] = Activity::O_UNFOLLOW;
749 $item['gravity'] = GRAVITY_ACTIVITY;
750 $item['follow'] = $contact["url"];
755 $item['attach'] = '';
756 $slap = OStatus::salmon($item, $user);
758 if (!empty($contact['notify'])) {
759 Salmon::slapper($user, $contact['notify'], $slap);
761 } elseif ($protocol == Protocol::DIASPORA) {
762 Diaspora::sendUnshare($user, $contact);
763 } elseif ($protocol == Protocol::ACTIVITYPUB) {
764 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
767 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
773 * Marks a contact for archival after a communication issue delay
775 * Contact has refused to recognise us as a friend. We will start a countdown.
776 * If they still don't recognise us in 32 days, the relationship is over,
777 * and we won't waste any more time trying to communicate with them.
778 * This provides for the possibility that their database is temporarily messed
779 * up or some other transient event and that there's a possibility we could recover from it.
781 * @param array $contact contact to mark for archival
783 * @throws HTTPException\InternalServerErrorException
785 public static function markForArchival(array $contact)
787 if (!isset($contact['url']) && !empty($contact['id'])) {
788 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
789 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
790 if (!DBA::isResult($contact)) {
793 } elseif (!isset($contact['url'])) {
794 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
797 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
799 // Contact already archived or "self" contact? => nothing to do
800 if ($contact['archive'] || $contact['self']) {
804 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
805 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
806 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
809 * We really should send a notification to the owner after 2-3 weeks
810 * so they won't be surprised when the contact vanishes and can take
811 * remedial action if this was a serious mistake or glitch
814 /// @todo Check for contact vitality via probing
815 $archival_days = DI::config()->get('system', 'archival_days', 32);
817 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
818 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
819 /* Relationship is really truly dead. archive them rather than
820 * delete, though if the owner tries to unarchive them we'll start
821 * the whole process over again.
823 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
824 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
830 * Cancels the archival countdown
832 * @see Contact::markForArchival()
834 * @param array $contact contact to be unmarked for archival
838 public static function unmarkForArchival(array $contact)
840 // Always unarchive the relay contact entry
841 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
842 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
843 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
844 DBA::update('contact', $fields, $condition);
847 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
848 $exists = DBA::exists('contact', $condition);
850 // We don't need to update, we never marked this contact for archival
855 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
857 if (!isset($contact['url']) && !empty($contact['id'])) {
858 $fields = ['id', 'url', 'batch'];
859 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
860 if (!DBA::isResult($contact)) {
865 // It's a miracle. Our dead contact has inexplicably come back to life.
866 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
867 DBA::update('contact', $fields, ['id' => $contact['id']]);
868 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
872 * Returns the data array for the photo menu of a given contact
874 * @param array $contact contact
875 * @param int $uid optional, default 0
877 * @throws HTTPException\InternalServerErrorException
878 * @throws \ImagickException
880 public static function photoMenu(array $contact, $uid = 0)
885 $contact_drop_link = '';
892 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
894 $profile_link = self::magicLink($contact['url']);
895 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
900 // Look for our own contact if the uid doesn't match and isn't public
901 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
902 if (DBA::isResult($contact_own)) {
903 return self::photoMenu($contact_own, $uid);
908 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
910 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
912 $profile_link = $contact['url'];
915 if ($profile_link === 'mailbox') {
920 $status_link = $profile_link . '/status';
921 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
922 $profile_link = $profile_link . '/profile';
925 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
926 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
929 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
930 $poke_link = 'contact/' . $contact['id'] . '/poke';
933 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
935 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
937 if (!$contact['self']) {
938 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
943 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
944 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
945 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
946 } elseif(!$contact['pending']) {
947 $follow_link = 'follow?url=' . urlencode($contact['url']);
951 if (!empty($follow_link) || !empty($unfollow_link)) {
952 $contact_drop_link = '';
957 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
959 if (empty($contact['uid'])) {
961 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
962 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
963 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
964 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
965 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
969 'status' => [DI::l10n()->t('View Status') , $status_link , true],
970 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
971 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
972 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
973 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
974 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
975 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
976 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
977 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
978 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
981 if (!empty($contact['pending'])) {
982 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
983 if (DBA::isResult($intro)) {
984 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
989 $args = ['contact' => $contact, 'menu' => &$menu];
991 Hook::callAll('contact_photo_menu', $args);
995 foreach ($menu as $menuname => $menuitem) {
996 if ($menuitem[1] != '') {
997 $menucondensed[$menuname] = $menuitem;
1001 return $menucondensed;
1005 * Fetch the contact id for a given URL and user
1007 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1008 * `addr` or `alias`.
1010 * If there's no record and we aren't looking for a public contact, we quit.
1011 * If there's one, we check that it isn't time to update the picture else we
1012 * directly return the found contact id.
1014 * Second, we probe the provided $url whether it's http://server.tld/profile or
1015 * nick@server.tld. We quit if we can't get any info back.
1017 * Third, we create the contact record if it doesn't exist
1019 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1020 * if there's any updates
1022 * @param string $url Contact URL
1023 * @param integer $uid The user id for the contact (0 = public contact)
1024 * @param boolean $update true = always update, false = never update, null = update when not found
1025 * @param array $default Default value for creating the contact when everything else fails
1027 * @return integer Contact ID
1028 * @throws HTTPException\InternalServerErrorException
1029 * @throws \ImagickException
1031 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1036 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1040 $contact = self::getByURL($url, false, ['id', 'network'], $uid);
1042 if (!empty($contact)) {
1043 $contact_id = $contact["id"];
1045 if (empty($update)) {
1046 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1049 } elseif ($uid != 0) {
1050 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1052 } elseif (empty($default) && !is_null($update) && !$update) {
1053 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1059 if (empty($default['network']) || $update) {
1060 $data = Probe::uri($url, "", $uid);
1062 // Take the default values when probing failed
1063 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1064 $data = array_merge($data, $default);
1066 } elseif (!empty($default['network'])) {
1070 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1071 // Fetch data for the public contact via the first found personal contact
1072 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1073 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'contact-type',
1074 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1075 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1077 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1078 if (!DBA::isResult($personal_contact)) {
1079 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1082 if (DBA::isResult($personal_contact)) {
1083 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1084 $data = $personal_contact;
1085 $data['photo'] = $personal_contact['avatar'];
1086 $data['account-type'] = $personal_contact['contact-type'];
1087 $data['hide'] = $personal_contact['unsearchable'];
1088 unset($data['avatar']);
1089 unset($data['contact-type']);
1090 unset($data['unsearchable']);
1094 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1095 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1100 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1101 if (!empty($data['alias'])) {
1102 $urls[] = Strings::normaliseLink($data['alias']);
1104 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1105 if (!empty($contact['id'])) {
1106 $contact_id = $contact['id'];
1107 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'probed_url' => $data['url'], 'alias' => $data['alias'], 'addr' => $data['addr']]);
1112 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1115 'url' => $data['url'],
1116 'nurl' => Strings::normaliseLink($data['url']),
1117 'network' => $data['network'],
1118 'created' => DateTimeFormat::utcNow(),
1119 'rel' => self::SHARING,
1125 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1127 // Before inserting we do check if the entry does exist now.
1128 DBA::lock('contact');
1129 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1130 if (DBA::isResult($contact)) {
1131 $contact_id = $contact['id'];
1132 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1134 DBA::insert('contact', $fields);
1135 $contact_id = DBA::lastInsertId();
1137 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1142 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1146 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1149 self::updateFromProbeArray($contact_id, $data);
1155 * Checks if the contact is archived
1157 * @param int $cid contact id
1159 * @return boolean Is the contact archived?
1160 * @throws HTTPException\InternalServerErrorException
1162 public static function isArchived(int $cid)
1168 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1169 if (!DBA::isResult($contact)) {
1173 if ($contact['archive']) {
1177 // Check status of ActivityPub endpoints
1178 $apcontact = APContact::getByURL($contact['url'], false);
1179 if (!empty($apcontact)) {
1180 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1184 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1189 // Check status of Diaspora endpoints
1190 if (!empty($contact['batch'])) {
1191 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1192 return DBA::exists('contact', $condition);
1199 * Checks if the contact is blocked
1201 * @param int $cid contact id
1203 * @return boolean Is the contact blocked?
1204 * @throws HTTPException\InternalServerErrorException
1206 public static function isBlocked($cid)
1212 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1213 if (!DBA::isResult($blocked)) {
1217 if (Network::isUrlBlocked($blocked['url'])) {
1221 return (bool) $blocked['blocked'];
1225 * Checks if the contact is hidden
1227 * @param int $cid contact id
1229 * @return boolean Is the contact hidden?
1230 * @throws \Exception
1232 public static function isHidden($cid)
1238 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1239 if (!DBA::isResult($hidden)) {
1242 return (bool) $hidden['hidden'];
1246 * Returns posts from a given contact url
1248 * @param string $contact_url Contact URL
1249 * @param bool $thread_mode
1250 * @param int $update
1251 * @return string posts in HTML
1252 * @throws \Exception
1254 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1256 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1260 * Returns posts from a given contact id
1262 * @param integer $cid
1263 * @param bool $thread_mode
1264 * @param integer $update
1265 * @return string posts in HTML
1266 * @throws \Exception
1268 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1272 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1273 if (!DBA::isResult($contact)) {
1277 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1278 $sql = "`item`.`uid` IN (0, ?)";
1280 $sql = "`item`.`uid` = ?";
1283 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1286 $condition = ["(`$contact_field` = ? OR (`causer-id` = ? AND `post-type` = ?)) AND `gravity` = ? AND " . $sql,
1287 $cid, $cid, Item::PT_ANNOUNCEMENT, GRAVITY_PARENT, local_user()];
1289 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1290 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1293 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1294 if (!empty($last_received)) {
1295 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1298 if (DI::mode()->isMobile()) {
1299 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1300 DI::config()->get('system', 'itemspage_network_mobile'));
1302 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1303 DI::config()->get('system', 'itemspage_network'));
1306 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1308 $params = ['order' => ['received' => true], 'group_by' => ['uri-id'],
1309 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1311 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1312 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1313 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1319 $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1321 while ($item = DBA::fetch($r)) {
1322 if ($item['gravity'] != GRAVITY_PARENT) {
1323 $item['uri'] = $item['parent-uri'];
1325 unset($item['parent-uri']);
1326 unset($item['gravity']);
1332 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1334 $r = Item::selectForUser(local_user(), [], $condition, $params);
1336 $items = Item::inArray($r);
1338 $o .= conversation($a, $items, 'contact-posts', false);
1342 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1343 $o .= HTML::scrollLoader();
1345 $o .= $pager->renderMinimal(count($items));
1353 * Returns the account type name
1355 * The function can be called with either the user or the contact array
1357 * @param array $contact contact or user array
1360 public static function getAccountType(array $contact)
1362 // There are several fields that indicate that the contact or user is a forum
1363 // "page-flags" is a field in the user table,
1364 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1365 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1366 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1367 || (isset($contact['forum']) && intval($contact['forum']))
1368 || (isset($contact['prv']) && intval($contact['prv']))
1369 || (isset($contact['community']) && intval($contact['community']))
1371 $type = self::TYPE_COMMUNITY;
1373 $type = self::TYPE_PERSON;
1376 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1377 if (isset($contact["contact-type"])) {
1378 $type = $contact["contact-type"];
1381 if (isset($contact["account-type"])) {
1382 $type = $contact["account-type"];
1386 case self::TYPE_ORGANISATION:
1387 $account_type = DI::l10n()->t("Organisation");
1390 case self::TYPE_NEWS:
1391 $account_type = DI::l10n()->t('News');
1394 case self::TYPE_COMMUNITY:
1395 $account_type = DI::l10n()->t("Forum");
1403 return $account_type;
1411 * @throws \Exception
1413 public static function block($cid, $reason = null)
1415 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1421 * Unblocks a contact
1425 * @throws \Exception
1427 public static function unblock($cid)
1429 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1435 * Ensure that cached avatar exist
1437 * @param integer $cid
1439 public static function checkAvatarCache(int $cid)
1441 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1442 if (!DBA::isResult($contact)) {
1446 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1450 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1452 self::updateAvatar($cid, $contact['avatar'], true);
1456 * Return the photo path for a given contact array in the given size
1458 * @param array $contact contact array
1459 * @param string $field Fieldname of the photo in the contact array
1460 * @param string $default Default path when no picture had been found
1461 * @param string $size Size of the avatar picture
1462 * @param string $avatar Avatar path that is displayed when no photo had been found
1463 * @return string photo path
1465 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1467 if (!empty($contact)) {
1468 $contact = self::checkAvatarCacheByArray($contact);
1469 if (!empty($contact[$field])) {
1470 $avatar = $contact[$field];
1474 if (empty($avatar)) {
1478 if (Proxy::isLocalImage($avatar)) {
1481 return Proxy::proxifyUrl($avatar, false, $size);
1486 * Return the photo path for a given contact array
1488 * @param array $contact Contact array
1489 * @param string $avatar Avatar path that is displayed when no photo had been found
1490 * @return string photo path
1492 public static function getPhoto(array $contact, string $avatar = '')
1494 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO, Proxy::SIZE_SMALL, $avatar);
1498 * Return the photo path (thumb size) for a given contact array
1500 * @param array $contact Contact array
1501 * @param string $avatar Avatar path that is displayed when no photo had been found
1502 * @return string photo path
1504 public static function getThumb(array $contact, string $avatar = '')
1506 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . self::DEFAULT_AVATAR_THUMB, Proxy::SIZE_THUMB, $avatar);
1510 * Return the photo path (micro size) for a given contact array
1512 * @param array $contact Contact array
1513 * @param string $avatar Avatar path that is displayed when no photo had been found
1514 * @return string photo path
1516 public static function getMicro(array $contact, string $avatar = '')
1518 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . self::DEFAULT_AVATAR_MICRO, Proxy::SIZE_MICRO, $avatar);
1522 * Check the given contact array for avatar cache fields
1524 * @param array $contact
1525 * @return array contact array with avatar cache fields
1527 private static function checkAvatarCacheByArray(array $contact)
1530 $contact_fields = [];
1531 $fields = ['photo', 'thumb', 'micro'];
1532 foreach ($fields as $field) {
1533 if (isset($contact[$field])) {
1534 $contact_fields[] = $field;
1536 if (isset($contact[$field]) && empty($contact[$field])) {
1545 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1546 self::updateAvatar($contact['id'], $contact['avatar'], true);
1548 $new_contact = self::getById($contact['id'], $contact_fields);
1549 if (DBA::isResult($new_contact)) {
1550 // We only update the cache fields
1551 $contact = array_merge($contact, $new_contact);
1555 /// add the default avatars if the fields aren't filled
1556 if (isset($contact['photo']) && empty($contact['photo'])) {
1557 $contact['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
1559 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1560 $contact['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
1562 if (isset($contact['micro']) && empty($contact['micro'])) {
1563 $contact['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
1570 * Updates the avatar links in a contact only if needed
1572 * @param int $cid Contact id
1573 * @param string $avatar Link to avatar picture
1574 * @param bool $force force picture update
1575 * @param bool $create_cache Enforces the creation of cached avatar fields
1578 * @throws HTTPException\InternalServerErrorException
1579 * @throws HTTPException\NotFoundException
1580 * @throws \ImagickException
1582 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1584 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl', 'url', 'network'], ['id' => $cid, 'self' => false]);
1585 if (!DBA::isResult($contact)) {
1589 $uid = $contact['uid'];
1591 // Only update the cached photo links of public contacts when they already are cached
1592 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1593 if ($contact['avatar'] != $avatar) {
1594 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1595 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1600 // User contacts use are updated through the public contacts
1601 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1602 $pcid = self::getIdForURL($contact['url'], false);
1603 if (!empty($pcid)) {
1604 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1605 self::updateAvatar($pcid, $avatar, $force, true);
1610 // Replace cached avatar pictures from the default avatar with the default avatars in different sizes
1611 if (strpos($avatar, self::DEFAULT_AVATAR_PHOTO)) {
1612 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1613 'photo' => DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO,
1614 'thumb' => DI::baseUrl() . self::DEFAULT_AVATAR_THUMB,
1615 'micro' => DI::baseUrl() . self::DEFAULT_AVATAR_MICRO];
1616 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1619 // Use the data from the self account
1620 if (empty($fields)) {
1621 $local_uid = User::getIdForURL($contact['url']);
1622 if (!empty($local_uid)) {
1623 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1624 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1628 if (empty($fields)) {
1629 $update = ($contact['avatar'] != $avatar) || $force;
1633 $contact['photo'] ?? '',
1634 $contact['thumb'] ?? '',
1635 $contact['micro'] ?? '',
1638 foreach ($data as $image_uri) {
1639 $image_rid = Photo::ridFromURI($image_uri);
1640 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1641 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1648 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1650 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1651 $update = !empty($fields);
1652 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1658 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1667 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1668 // Collect all user contacts of the given public contact
1669 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1670 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1671 while ($personal_contact = DBA::fetch($personal_contacts)) {
1672 $cids[] = $personal_contact['id'];
1673 $uids[] = $personal_contact['uid'];
1675 DBA::close($personal_contacts);
1677 if (!empty($cids)) {
1678 // Delete possibly existing cached user contact avatars
1679 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1685 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1686 DBA::update('contact', $fields, ['id' => $cids]);
1690 * Helper function for "updateFromProbe". Updates personal and public contact
1692 * @param integer $id contact id
1693 * @param integer $uid user id
1694 * @param string $url The profile URL of the contact
1695 * @param array $fields The fields that are updated
1697 * @throws \Exception
1699 private static function updateContact($id, $uid, $url, array $fields)
1701 if (!DBA::update('contact', $fields, ['id' => $id])) {
1702 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1706 // Search for duplicated contacts and get rid of them
1707 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1711 // Archive or unarchive the contact. We only need to do this for the public contact.
1712 // The archive/unarchive function will update the personal contacts by themselves.
1713 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1714 if (!DBA::isResult($contact)) {
1715 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1719 if (!empty($fields['success_update'])) {
1720 self::unmarkForArchival($contact);
1721 } elseif (!empty($fields['failure_update'])) {
1722 self::markForArchival($contact);
1725 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1727 // These contacts are sharing with us, we don't poll them.
1728 // This means that we don't set the update fields in "OnePoll.php".
1729 $condition['rel'] = self::SHARING;
1730 DBA::update('contact', $fields, $condition);
1732 unset($fields['last-update']);
1733 unset($fields['success_update']);
1734 unset($fields['failure_update']);
1736 if (empty($fields)) {
1740 // We are polling these contacts, so we mustn't set the update fields here.
1741 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1742 DBA::update('contact', $fields, $condition);
1746 * Remove duplicated contacts
1748 * @param string $nurl Normalised contact url
1749 * @param integer $uid User id
1751 * @throws \Exception
1753 public static function removeDuplicates(string $nurl, int $uid)
1755 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1756 $count = DBA::count('contact', $condition);
1761 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1762 if (!DBA::isResult($first_contact)) {
1763 // Shouldn't happen - so we handle it
1767 $first = $first_contact['id'];
1768 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1769 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1770 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1771 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1775 // Find all duplicates
1776 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1777 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1778 while ($duplicate = DBA::fetch($duplicates)) {
1779 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1783 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1785 DBA::close($duplicates);
1786 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1791 * @param integer $id contact id
1792 * @param string $network Optional network we are probing for
1794 * @throws HTTPException\InternalServerErrorException
1795 * @throws \ImagickException
1797 public static function updateFromProbe(int $id, string $network = '')
1799 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1800 if (!DBA::isResult($contact)) {
1804 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1805 return self::updateFromProbeArray($id, $ret);
1809 * @param integer $id contact id
1810 * @param array $ret Probed data
1812 * @throws HTTPException\InternalServerErrorException
1813 * @throws \ImagickException
1815 private static function updateFromProbeArray(int $id, array $ret)
1818 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1819 This will reliably kill your communication with old Friendica contacts.
1822 // These fields aren't updated by this routine:
1823 // 'xmpp', 'sensitive'
1825 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe', 'manually-approve',
1826 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1827 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1828 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1829 if (!DBA::isResult($contact)) {
1833 $uid = $contact['uid'];
1834 unset($contact['uid']);
1836 $pubkey = $contact['pubkey'];
1837 unset($contact['pubkey']);
1839 $contact['photo'] = $contact['avatar'];
1840 unset($contact['avatar']);
1842 $updated = DateTimeFormat::utcNow();
1844 // We must not try to update relay contacts via probe. They are no real contacts.
1845 // We check after the probing to be able to correct falsely detected contact types.
1846 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1847 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1848 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1849 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1853 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1854 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1856 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1861 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1862 $ret['unsearchable'] = $ret['hide'];
1865 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1866 $ret['forum'] = false;
1867 $ret['prv'] = false;
1868 $ret['contact-type'] = $ret['account-type'];
1869 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1870 $ret['forum'] = (bool)!$ret['manually-approve'];
1871 $ret['prv'] = (bool)!$ret['forum'];
1875 $new_pubkey = $ret['pubkey'] ?? '';
1878 $ret['last-item'] = Probe::getLastUpdate($ret);
1879 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1884 // make sure to not overwrite existing values with blank entries except some technical fields
1885 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1886 foreach ($ret as $key => $val) {
1887 if (!array_key_exists($key, $contact)) {
1889 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1890 $ret[$key] = $contact[$key];
1891 } elseif ($ret[$key] != $contact[$key]) {
1896 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1899 unset($ret['last-item']);
1902 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1903 self::updateAvatar($id, $ret['photo'], $update);
1907 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1909 if (Contact\Relation::isDiscoverable($ret['url'])) {
1910 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1913 // Update the public contact
1915 $contact = self::getByURL($ret['url'], false, ['id']);
1916 if (!empty($contact['id'])) {
1917 self::updateFromProbeArray($contact['id'], $ret);
1924 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1925 $ret['updated'] = $updated;
1927 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1928 if (empty($pubkey) && !empty($new_pubkey)) {
1929 $ret['pubkey'] = $new_pubkey;
1932 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1933 $ret['uri-date'] = DateTimeFormat::utcNow();
1936 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1937 $ret['name-date'] = $updated;
1941 $ret['last-update'] = $updated;
1942 $ret['success_update'] = $updated;
1943 $ret['failed'] = false;
1946 unset($ret['photo']);
1948 self::updateContact($id, $uid, $ret['url'], $ret);
1950 if (Contact\Relation::isDiscoverable($ret['url'])) {
1951 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1958 * @param integer $url contact url
1959 * @return integer Contact id
1960 * @throws HTTPException\InternalServerErrorException
1961 * @throws \ImagickException
1963 public static function updateFromProbeByURL($url)
1965 $id = self::getIdForURL($url);
1971 self::updateFromProbe($id);
1977 * Detects if a given contact array belongs to a legacy DFRN connection
1979 * @param array $contact
1982 public static function isLegacyDFRNContact($contact)
1984 // Newer Friendica contacts are connected via AP, then these fields aren't set
1985 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1989 * Detects the communication protocol for a given contact url.
1990 * This is used to detect Friendica contacts that we can communicate via AP.
1992 * @param string $url contact url
1993 * @param string $network Network of that contact
1994 * @return string with protocol
1996 public static function getProtocol($url, $network)
1998 if ($network != Protocol::DFRN) {
2002 $apcontact = APContact::getByURL($url);
2003 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2004 return Protocol::ACTIVITYPUB;
2011 * Takes a $uid and a url/handle and adds a new contact
2013 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2014 * dfrn_request page.
2016 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2019 * $return['success'] boolean true if successful
2020 * $return['message'] error text if success is false.
2022 * Takes a $uid and a url/handle and adds a new contact
2024 * @param array $user The user the contact should be created for
2025 * @param string $url The profile URL of the contact
2026 * @param bool $interactive
2027 * @param string $network
2029 * @throws HTTPException\InternalServerErrorException
2030 * @throws HTTPException\NotFoundException
2031 * @throws \ImagickException
2033 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2035 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2037 // remove ajax junk, e.g. Twitter
2038 $url = str_replace('/#!/', '/', $url);
2040 if (!Network::isUrlAllowed($url)) {
2041 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2045 if (Network::isUrlBlocked($url)) {
2046 $result['message'] = DI::l10n()->t('Blocked domain');
2051 $result['message'] = DI::l10n()->t('Connect URL missing.');
2055 $arr = ['url' => $url, 'contact' => []];
2057 Hook::callAll('follow', $arr);
2060 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2064 if (!empty($arr['contact']['name'])) {
2065 $ret = $arr['contact'];
2067 $ret = Probe::uri($url, $network, $user['uid']);
2070 if (($network != '') && ($ret['network'] != $network)) {
2071 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2075 // check if we already have a contact
2076 // the poll url is more reliable than the profile url, as we may have
2077 // indirect links or webfinger links
2079 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2080 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2081 if (!DBA::isResult($contact)) {
2082 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2083 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2086 $protocol = self::getProtocol($ret['url'], $ret['network']);
2088 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2090 if (strlen(DI::baseUrl()->getUrlPath())) {
2091 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2093 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2096 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2100 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2101 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2102 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2106 // This extra param just confuses things, remove it
2107 if ($protocol === Protocol::DIASPORA) {
2108 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2111 // do we have enough information?
2112 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2113 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2114 if (empty($ret['poll'])) {
2115 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2117 if (empty($ret['name'])) {
2118 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2120 if (empty($ret['url'])) {
2121 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2123 if (strpos($ret['url'], '@') !== false) {
2124 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2125 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2130 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2131 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2132 $ret['notify'] = '';
2135 if (!$ret['notify']) {
2136 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2139 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2141 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2143 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2146 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2147 $pending = (bool)$ret['manually-approve'];
2150 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2154 if (DBA::isResult($contact)) {
2156 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2158 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2159 DBA::update('contact', $fields, ['id' => $contact['id']]);
2161 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2163 // create contact record
2165 'uid' => $user['uid'],
2166 'created' => DateTimeFormat::utcNow(),
2167 'url' => $ret['url'],
2168 'nurl' => Strings::normaliseLink($ret['url']),
2169 'addr' => $ret['addr'],
2170 'alias' => $ret['alias'],
2171 'batch' => $ret['batch'],
2172 'notify' => $ret['notify'],
2173 'poll' => $ret['poll'],
2174 'poco' => $ret['poco'],
2175 'name' => $ret['name'],
2176 'nick' => $ret['nick'],
2177 'network' => $ret['network'],
2178 'baseurl' => $ret['baseurl'],
2179 'gsid' => $ret['gsid'] ?? null,
2180 'protocol' => $protocol,
2181 'pubkey' => $ret['pubkey'],
2182 'rel' => $new_relation,
2183 'priority'=> $ret['priority'],
2184 'writable'=> $writeable,
2185 'hidden' => $hidden,
2188 'pending' => $pending,
2193 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2194 if (!DBA::isResult($contact)) {
2195 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2199 $contact_id = $contact['id'];
2200 $result['cid'] = $contact_id;
2202 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2204 // Update the avatar
2205 self::updateAvatar($contact_id, $ret['photo']);
2207 // pull feed and consume it, which should subscribe to the hub.
2209 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2211 $owner = User::getOwnerDataById($user['uid']);
2213 if (DBA::isResult($owner)) {
2214 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2215 // create a follow slap
2217 $item['verb'] = Activity::FOLLOW;
2218 $item['gravity'] = GRAVITY_ACTIVITY;
2219 $item['follow'] = $contact["url"];
2221 $item['title'] = '';
2223 $item['uri-id'] = 0;
2224 $item['attach'] = '';
2226 $slap = OStatus::salmon($item, $owner);
2228 if (!empty($contact['notify'])) {
2229 Salmon::slapper($owner, $contact['notify'], $slap);
2231 } elseif ($protocol == Protocol::DIASPORA) {
2232 $ret = Diaspora::sendShare($owner, $contact);
2233 Logger::log('share returns: ' . $ret);
2234 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2235 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2236 if (empty($activity_id)) {
2237 // This really should never happen
2241 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2242 Logger::log('Follow returns: ' . $ret);
2246 $result['success'] = true;
2251 * Updated contact's SSL policy
2253 * @param array $contact Contact array
2254 * @param string $new_policy New policy, valid: self,full
2256 * @return array Contact array with updated values
2257 * @throws \Exception
2259 public static function updateSslPolicy(array $contact, $new_policy)
2261 $ssl_changed = false;
2262 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2263 $ssl_changed = true;
2264 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2265 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2266 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2267 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2268 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2269 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2272 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2273 $ssl_changed = true;
2274 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2275 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2276 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2277 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2278 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2279 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2283 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2284 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2285 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2286 DBA::update('contact', $fields, ['id' => $contact['id']]);
2293 * @param array $importer Owner (local user) data
2294 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2295 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2296 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2297 * @param string $note Introduction additional message
2298 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2299 * @throws HTTPException\InternalServerErrorException
2300 * @throws \ImagickException
2302 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2304 // Should always be set
2305 if (empty($datarray['author-id'])) {
2309 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2310 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2311 if (!DBA::isResult($pub_contact)) {
2312 // Should never happen
2316 // Contact is blocked at node-level
2317 if (self::isBlocked($datarray['author-id'])) {
2321 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2322 $name = $pub_contact['name'];
2323 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2324 $nick = $pub_contact['nick'];
2325 $network = $pub_contact['network'];
2327 // Ensure that we don't create a new contact when there already is one
2328 $cid = self::getIdForURL($url, $importer['uid']);
2330 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2333 if (!empty($contact)) {
2334 if (!empty($contact['pending'])) {
2335 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2339 // Contact is blocked at user-level
2340 if (!empty($contact['id']) && !empty($importer['id']) &&
2341 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2345 // Make sure that the existing contact isn't archived
2346 self::unmarkForArchival($contact);
2348 if (($contact['rel'] == self::SHARING)
2349 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2350 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2351 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2354 // Ensure to always have the correct network type, independent from the connection request method
2355 self::updateFromProbe($contact['id']);
2359 // send email notification to owner?
2360 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2361 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2365 // create contact record
2366 DBA::insert('contact', [
2367 'uid' => $importer['uid'],
2368 'created' => DateTimeFormat::utcNow(),
2370 'nurl' => Strings::normaliseLink($url),
2373 'network' => $network,
2374 'rel' => self::FOLLOWER,
2381 $contact_id = DBA::lastInsertId();
2383 // Ensure to always have the correct network type, independent from the connection request method
2384 self::updateFromProbe($contact_id);
2386 self::updateAvatar($contact_id, $photo, true);
2388 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2390 /// @TODO Encapsulate this into a function/method
2391 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2392 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2393 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2394 // create notification
2395 $hash = Strings::getRandomHex();
2397 if (is_array($contact_record)) {
2398 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2399 'blocked' => false, 'knowyou' => false, 'note' => $note,
2400 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2403 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2405 if (($user['notify-flags'] & Type::INTRO) &&
2406 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2409 'type' => Type::INTRO,
2410 'notify_flags' => $user['notify-flags'],
2411 'language' => $user['language'],
2412 'to_name' => $user['username'],
2413 'to_email' => $user['email'],
2414 'uid' => $user['uid'],
2415 'link' => DI::baseUrl() . '/notifications/intros',
2416 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2417 'source_link' => $contact_record['url'],
2418 'source_photo' => $contact_record['photo'],
2419 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2423 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2424 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2425 self::createFromProbe($importer, $url, false, $network);
2428 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2429 $fields = ['pending' => false];
2430 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2431 $fields['rel'] = Contact::FRIEND;
2434 DBA::update('contact', $fields, $condition);
2443 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2445 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2446 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2448 Contact::remove($contact['id']);
2452 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2454 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2455 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2457 Contact::remove($contact['id']);
2462 * Create a birthday event.
2464 * Update the year and the birthday.
2466 public static function updateBirthdays()
2470 AND `bd` > "0001-01-01"
2471 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2472 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2473 AND NOT `contact`.`pending`
2474 AND NOT `contact`.`hidden`
2475 AND NOT `contact`.`blocked`
2476 AND NOT `contact`.`archive`
2477 AND NOT `contact`.`deleted`',
2482 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2484 while ($contact = DBA::fetch($contacts)) {
2485 Logger::log('update_contact_birthday: ' . $contact['bd']);
2487 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2489 if (Event::createBirthday($contact, $nextbd)) {
2493 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2494 ['id' => $contact['id']]
2498 DBA::close($contacts);
2502 * Remove the unavailable contact ids from the provided list
2504 * @param array $contact_ids Contact id list
2506 * @throws \Exception
2508 public static function pruneUnavailable(array $contact_ids)
2510 if (empty($contact_ids)) {
2514 $contacts = Contact::selectToArray(['id'], [
2515 'id' => $contact_ids,
2521 return array_column($contacts, 'id');
2525 * Returns a magic link to authenticate remote visitors
2527 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2529 * @param string $contact_url The address of the target contact profile
2530 * @param string $url An url that we will be redirected to after the authentication
2532 * @return string with "redir" link
2533 * @throws HTTPException\InternalServerErrorException
2534 * @throws \ImagickException
2536 public static function magicLink($contact_url, $url = '')
2538 if (!Session::isAuthenticated()) {
2539 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2542 $contact = self::getByURL($contact_url, false);
2543 if (empty($contact)) {
2544 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2547 // Prevents endless loop in case only a non-public contact exists for the contact URL
2548 unset($contact['uid']);
2550 return self::magicLinkByContact($contact, $url ?: $contact_url);
2554 * Returns a magic link to authenticate remote visitors
2556 * @param integer $cid The contact id of the target contact profile
2557 * @param string $url An url that we will be redirected to after the authentication
2559 * @return string with "redir" link
2560 * @throws HTTPException\InternalServerErrorException
2561 * @throws \ImagickException
2563 public static function magicLinkbyId($cid, $url = '')
2565 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2567 return self::magicLinkByContact($contact, $url);
2571 * Returns a magic link to authenticate remote visitors
2573 * @param array $contact The contact array with "uid", "network" and "url"
2574 * @param string $url An url that we will be redirected to after the authentication
2576 * @return string with "redir" link
2577 * @throws HTTPException\InternalServerErrorException
2578 * @throws \ImagickException
2580 public static function magicLinkByContact($contact, $url = '')
2582 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2584 if (!Session::isAuthenticated()) {
2585 return $destination;
2588 // Only redirections to the same host do make sense
2589 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2593 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2594 return 'contact/' . $contact['id'] . '/conversations';
2597 if ($contact['network'] != Protocol::DFRN) {
2598 return $destination;
2601 if (!empty($contact['uid'])) {
2602 return self::magicLink($contact['url'], $url);
2605 if (empty($contact['id'])) {
2606 return $destination;
2609 $redirect = 'redir/' . $contact['id'];
2611 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2612 $redirect .= '?url=' . $url;
2619 * Is the contact a forum?
2621 * @param integer $contactid ID of the contact
2623 * @return boolean "true" if it is a forum
2625 public static function isForum($contactid)
2627 $fields = ['forum', 'prv'];
2628 $condition = ['id' => $contactid];
2629 $contact = DBA::selectFirst('contact', $fields, $condition);
2630 if (!DBA::isResult($contact)) {
2635 return ($contact['forum'] || $contact['prv']);
2639 * Can the remote contact receive private messages?
2641 * @param array $contact
2644 public static function canReceivePrivateMessages(array $contact)
2646 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2647 $self = $contact['self'] ?? false;
2649 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2653 * Search contact table by nick or name
2655 * @param string $search Name or nick
2656 * @param string $mode Search mode (e.g. "community")
2658 * @return array with search results
2659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2661 public static function searchByName($search, $mode = '')
2663 if (empty($search)) {
2667 // check supported networks
2668 if (DI::config()->get('system', 'diaspora_enabled')) {
2669 $diaspora = Protocol::DIASPORA;
2671 $diaspora = Protocol::DFRN;
2674 if (!DI::config()->get('system', 'ostatus_disabled')) {
2675 $ostatus = Protocol::OSTATUS;
2677 $ostatus = Protocol::DFRN;
2680 // check if we search only communities or every contact
2681 if ($mode === 'community') {
2682 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2689 $results = DBA::p("SELECT * FROM `contact`
2690 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2691 NOT `failed` AND `uid` = ? AND
2692 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2693 ORDER BY `nurl` DESC LIMIT 1000",
2694 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2697 $contacts = DBA::toArray($results);
2702 * Add public contacts from an array
2704 * @param array $urls
2705 * @return array result "count", "added" and "updated"
2707 public static function addByUrls(array $urls)
2714 foreach ($urls as $url) {
2715 $contact = Contact::getByURL($url, false, ['id', 'updated']);
2716 if (empty($contact['id'])) {
2717 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2719 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
2720 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2728 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
2732 * Returns a random, global contact of the current node
2734 * @return string The profile URL
2737 public static function getRandomUrl()
2739 $r = DBA::selectFirst('contact', ['url'], [
2740 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2741 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2742 ], ['order' => ['RAND()']]);
2744 if (DBA::isResult($r)) {