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;
139 * @param array $fields Array of selected fields, empty for all
140 * @param array $condition Array of fields for condition
141 * @param array $params Array of several parameters
145 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
147 return DBA::selectToArray('contact', $fields, $condition, $params);
151 * @param array $fields Array of selected fields, empty for all
152 * @param array $condition Array of fields for condition
153 * @param array $params Array of several parameters
157 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
159 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
165 * Insert a row into the contact table
166 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
168 * @param array $fields field array
169 * @param bool $on_duplicate_update Do an update on a duplicate entry
171 * @return boolean was the insert successful?
174 public static function insert(array $fields, bool $on_duplicate_update = false)
176 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
177 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
178 if (!DBA::isResult($contact)) {
183 // Search for duplicated contacts and get rid of them
184 self::removeDuplicates($contact['nurl'], $contact['uid']);
190 * @param integer $id Contact ID
191 * @param array $fields Array of selected fields, empty for all
192 * @return array|boolean Contact record if it exists, false otherwise
195 public static function getById($id, $fields = [])
197 return DBA::selectFirst('contact', $fields, ['id' => $id]);
201 * Fetches a contact by a given url
203 * @param string $url profile url
204 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
205 * @param array $fields Field list
206 * @param integer $uid User ID of the contact
207 * @return array contact array
209 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
211 if ($update || is_null($update)) {
212 $cid = self::getIdForURL($url, $uid, $update);
217 $contact = self::getById($cid, $fields);
218 if (empty($contact)) {
224 // Add internal fields
226 if (!empty($fields)) {
227 foreach (['id', 'avatar', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
228 if (!in_array($internal, $fields)) {
229 $fields[] = $internal;
230 $removal[] = $internal;
235 // We first try the nurl (http://server.tld/nick), most common case
236 $options = ['order' => ['id']];
237 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
239 // Then the addr (nick@server.tld)
240 if (!DBA::isResult($contact)) {
241 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
244 // Then the alias (which could be anything)
245 if (!DBA::isResult($contact)) {
246 // The link could be provided as http although we stored it as https
247 $ssl_url = str_replace('http://', 'https://', $url);
248 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
249 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
252 if (!DBA::isResult($contact)) {
256 // Update the contact in the background if needed
257 $updated = max($contact['success_update'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
258 if ((($updated < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
259 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 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1290 if (!empty($last_received)) {
1291 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1294 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1295 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
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()]];
1312 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1313 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1314 $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 ($thread_mode && 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 (Contact\Relation::isDiscoverable($ret['url'])) {
1862 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1865 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1866 $ret['unsearchable'] = $ret['hide'];
1869 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1870 $ret['forum'] = false;
1871 $ret['prv'] = false;
1872 $ret['contact-type'] = $ret['account-type'];
1873 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1874 $ret['forum'] = (bool)!$ret['manually-approve'];
1875 $ret['prv'] = (bool)!$ret['forum'];
1879 $new_pubkey = $ret['pubkey'] ?? '';
1882 $ret['last-item'] = Probe::getLastUpdate($ret);
1883 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1888 // make sure to not overwrite existing values with blank entries except some technical fields
1889 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1890 foreach ($ret as $key => $val) {
1891 if (!array_key_exists($key, $contact)) {
1893 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1894 $ret[$key] = $contact[$key];
1895 } elseif ($ret[$key] != $contact[$key]) {
1900 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1903 unset($ret['last-item']);
1906 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1907 self::updateAvatar($id, $ret['photo'], $update);
1911 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
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);
1954 * @param integer $url contact url
1955 * @return integer Contact id
1956 * @throws HTTPException\InternalServerErrorException
1957 * @throws \ImagickException
1959 public static function updateFromProbeByURL($url)
1961 $id = self::getIdForURL($url);
1967 self::updateFromProbe($id);
1973 * Detects if a given contact array belongs to a legacy DFRN connection
1975 * @param array $contact
1978 public static function isLegacyDFRNContact($contact)
1980 // Newer Friendica contacts are connected via AP, then these fields aren't set
1981 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1985 * Detects the communication protocol for a given contact url.
1986 * This is used to detect Friendica contacts that we can communicate via AP.
1988 * @param string $url contact url
1989 * @param string $network Network of that contact
1990 * @return string with protocol
1992 public static function getProtocol($url, $network)
1994 if ($network != Protocol::DFRN) {
1998 $apcontact = APContact::getByURL($url);
1999 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2000 return Protocol::ACTIVITYPUB;
2007 * Takes a $uid and a url/handle and adds a new contact
2009 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2010 * dfrn_request page.
2012 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2015 * $return['success'] boolean true if successful
2016 * $return['message'] error text if success is false.
2018 * Takes a $uid and a url/handle and adds a new contact
2020 * @param array $user The user the contact should be created for
2021 * @param string $url The profile URL of the contact
2022 * @param bool $interactive
2023 * @param string $network
2025 * @throws HTTPException\InternalServerErrorException
2026 * @throws HTTPException\NotFoundException
2027 * @throws \ImagickException
2029 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2031 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2033 // remove ajax junk, e.g. Twitter
2034 $url = str_replace('/#!/', '/', $url);
2036 if (!Network::isUrlAllowed($url)) {
2037 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2041 if (Network::isUrlBlocked($url)) {
2042 $result['message'] = DI::l10n()->t('Blocked domain');
2047 $result['message'] = DI::l10n()->t('Connect URL missing.');
2051 $arr = ['url' => $url, 'contact' => []];
2053 Hook::callAll('follow', $arr);
2056 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2060 if (!empty($arr['contact']['name'])) {
2061 $ret = $arr['contact'];
2063 $ret = Probe::uri($url, $network, $user['uid']);
2066 if (($network != '') && ($ret['network'] != $network)) {
2067 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2071 // check if we already have a contact
2072 // the poll url is more reliable than the profile url, as we may have
2073 // indirect links or webfinger links
2075 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2076 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2077 if (!DBA::isResult($contact)) {
2078 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2079 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2082 $protocol = self::getProtocol($ret['url'], $ret['network']);
2084 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2086 if (strlen(DI::baseUrl()->getUrlPath())) {
2087 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2089 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2092 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2096 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2097 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2098 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2102 // This extra param just confuses things, remove it
2103 if ($protocol === Protocol::DIASPORA) {
2104 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2107 // do we have enough information?
2108 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2109 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2110 if (empty($ret['poll'])) {
2111 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2113 if (empty($ret['name'])) {
2114 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2116 if (empty($ret['url'])) {
2117 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2119 if (strpos($ret['url'], '@') !== false) {
2120 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2121 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2126 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2127 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2128 $ret['notify'] = '';
2131 if (!$ret['notify']) {
2132 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2135 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2137 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2139 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2142 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2143 $pending = (bool)$ret['manually-approve'];
2146 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2150 if (DBA::isResult($contact)) {
2152 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2154 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2155 DBA::update('contact', $fields, ['id' => $contact['id']]);
2157 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2159 // create contact record
2161 'uid' => $user['uid'],
2162 'created' => DateTimeFormat::utcNow(),
2163 'url' => $ret['url'],
2164 'nurl' => Strings::normaliseLink($ret['url']),
2165 'addr' => $ret['addr'],
2166 'alias' => $ret['alias'],
2167 'batch' => $ret['batch'],
2168 'notify' => $ret['notify'],
2169 'poll' => $ret['poll'],
2170 'poco' => $ret['poco'],
2171 'name' => $ret['name'],
2172 'nick' => $ret['nick'],
2173 'network' => $ret['network'],
2174 'baseurl' => $ret['baseurl'],
2175 'gsid' => $ret['gsid'] ?? null,
2176 'protocol' => $protocol,
2177 'pubkey' => $ret['pubkey'],
2178 'rel' => $new_relation,
2179 'priority'=> $ret['priority'],
2180 'writable'=> $writeable,
2181 'hidden' => $hidden,
2184 'pending' => $pending,
2189 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2190 if (!DBA::isResult($contact)) {
2191 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2195 $contact_id = $contact['id'];
2196 $result['cid'] = $contact_id;
2198 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2200 // Update the avatar
2201 self::updateAvatar($contact_id, $ret['photo']);
2203 // pull feed and consume it, which should subscribe to the hub.
2205 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2207 $owner = User::getOwnerDataById($user['uid']);
2209 if (DBA::isResult($owner)) {
2210 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2211 // create a follow slap
2213 $item['verb'] = Activity::FOLLOW;
2214 $item['gravity'] = GRAVITY_ACTIVITY;
2215 $item['follow'] = $contact["url"];
2217 $item['title'] = '';
2219 $item['uri-id'] = 0;
2220 $item['attach'] = '';
2222 $slap = OStatus::salmon($item, $owner);
2224 if (!empty($contact['notify'])) {
2225 Salmon::slapper($owner, $contact['notify'], $slap);
2227 } elseif ($protocol == Protocol::DIASPORA) {
2228 $ret = Diaspora::sendShare($owner, $contact);
2229 Logger::log('share returns: ' . $ret);
2230 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2231 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2232 if (empty($activity_id)) {
2233 // This really should never happen
2237 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2238 Logger::log('Follow returns: ' . $ret);
2242 $result['success'] = true;
2247 * Updated contact's SSL policy
2249 * @param array $contact Contact array
2250 * @param string $new_policy New policy, valid: self,full
2252 * @return array Contact array with updated values
2253 * @throws \Exception
2255 public static function updateSslPolicy(array $contact, $new_policy)
2257 $ssl_changed = false;
2258 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2259 $ssl_changed = true;
2260 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2261 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2262 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2263 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2264 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2265 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2268 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2269 $ssl_changed = true;
2270 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2271 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2272 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2273 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2274 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2275 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2279 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2280 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2281 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2282 DBA::update('contact', $fields, ['id' => $contact['id']]);
2289 * @param array $importer Owner (local user) data
2290 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2291 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2292 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2293 * @param string $note Introduction additional message
2294 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2295 * @throws HTTPException\InternalServerErrorException
2296 * @throws \ImagickException
2298 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2300 // Should always be set
2301 if (empty($datarray['author-id'])) {
2305 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2306 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2307 if (!DBA::isResult($pub_contact)) {
2308 // Should never happen
2312 // Contact is blocked at node-level
2313 if (self::isBlocked($datarray['author-id'])) {
2317 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2318 $name = $pub_contact['name'];
2319 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2320 $nick = $pub_contact['nick'];
2321 $network = $pub_contact['network'];
2323 // Ensure that we don't create a new contact when there already is one
2324 $cid = self::getIdForURL($url, $importer['uid']);
2326 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2329 if (!empty($contact)) {
2330 if (!empty($contact['pending'])) {
2331 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2335 // Contact is blocked at user-level
2336 if (!empty($contact['id']) && !empty($importer['id']) &&
2337 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2341 // Make sure that the existing contact isn't archived
2342 self::unmarkForArchival($contact);
2344 if (($contact['rel'] == self::SHARING)
2345 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2346 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2347 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2350 // Ensure to always have the correct network type, independent from the connection request method
2351 self::updateFromProbe($contact['id']);
2355 // send email notification to owner?
2356 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2357 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2361 // create contact record
2362 DBA::insert('contact', [
2363 'uid' => $importer['uid'],
2364 'created' => DateTimeFormat::utcNow(),
2366 'nurl' => Strings::normaliseLink($url),
2369 'network' => $network,
2370 'rel' => self::FOLLOWER,
2377 $contact_id = DBA::lastInsertId();
2379 // Ensure to always have the correct network type, independent from the connection request method
2380 self::updateFromProbe($contact_id);
2382 self::updateAvatar($contact_id, $photo, true);
2384 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2386 /// @TODO Encapsulate this into a function/method
2387 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2388 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2389 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2390 // create notification
2391 $hash = Strings::getRandomHex();
2393 if (is_array($contact_record)) {
2394 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2395 'blocked' => false, 'knowyou' => false, 'note' => $note,
2396 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2399 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2401 if (($user['notify-flags'] & Type::INTRO) &&
2402 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2405 'type' => Type::INTRO,
2406 'notify_flags' => $user['notify-flags'],
2407 'language' => $user['language'],
2408 'to_name' => $user['username'],
2409 'to_email' => $user['email'],
2410 'uid' => $user['uid'],
2411 'link' => DI::baseUrl() . '/notifications/intros',
2412 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2413 'source_link' => $contact_record['url'],
2414 'source_photo' => $contact_record['photo'],
2415 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2419 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2420 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2421 self::createFromProbe($importer, $url, false, $network);
2424 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2425 $fields = ['pending' => false];
2426 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2427 $fields['rel'] = Contact::FRIEND;
2430 DBA::update('contact', $fields, $condition);
2439 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2441 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2442 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2444 Contact::remove($contact['id']);
2448 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2450 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2451 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2453 Contact::remove($contact['id']);
2458 * Create a birthday event.
2460 * Update the year and the birthday.
2462 public static function updateBirthdays()
2466 AND `bd` > "0001-01-01"
2467 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2468 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2469 AND NOT `contact`.`pending`
2470 AND NOT `contact`.`hidden`
2471 AND NOT `contact`.`blocked`
2472 AND NOT `contact`.`archive`
2473 AND NOT `contact`.`deleted`',
2478 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2480 while ($contact = DBA::fetch($contacts)) {
2481 Logger::log('update_contact_birthday: ' . $contact['bd']);
2483 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2485 if (Event::createBirthday($contact, $nextbd)) {
2489 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2490 ['id' => $contact['id']]
2494 DBA::close($contacts);
2498 * Remove the unavailable contact ids from the provided list
2500 * @param array $contact_ids Contact id list
2502 * @throws \Exception
2504 public static function pruneUnavailable(array $contact_ids)
2506 if (empty($contact_ids)) {
2510 $contacts = Contact::selectToArray(['id'], [
2511 'id' => $contact_ids,
2517 return array_column($contacts, 'id');
2521 * Returns a magic link to authenticate remote visitors
2523 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2525 * @param string $contact_url The address of the target contact profile
2526 * @param string $url An url that we will be redirected to after the authentication
2528 * @return string with "redir" link
2529 * @throws HTTPException\InternalServerErrorException
2530 * @throws \ImagickException
2532 public static function magicLink($contact_url, $url = '')
2534 if (!Session::isAuthenticated()) {
2535 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2538 $contact = self::getByURL($contact_url, false);
2539 if (empty($contact)) {
2540 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2543 // Prevents endless loop in case only a non-public contact exists for the contact URL
2544 unset($contact['uid']);
2546 return self::magicLinkByContact($contact, $url ?: $contact_url);
2550 * Returns a magic link to authenticate remote visitors
2552 * @param integer $cid The contact id of the target contact profile
2553 * @param string $url An url that we will be redirected to after the authentication
2555 * @return string with "redir" link
2556 * @throws HTTPException\InternalServerErrorException
2557 * @throws \ImagickException
2559 public static function magicLinkbyId($cid, $url = '')
2561 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2563 return self::magicLinkByContact($contact, $url);
2567 * Returns a magic link to authenticate remote visitors
2569 * @param array $contact The contact array with "uid", "network" and "url"
2570 * @param string $url An url that we will be redirected to after the authentication
2572 * @return string with "redir" link
2573 * @throws HTTPException\InternalServerErrorException
2574 * @throws \ImagickException
2576 public static function magicLinkByContact($contact, $url = '')
2578 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2580 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2581 return $destination;
2584 // Only redirections to the same host do make sense
2585 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2589 if (!empty($contact['uid'])) {
2590 return self::magicLink($contact['url'], $url);
2593 if (empty($contact['id'])) {
2594 return $destination;
2597 $redirect = 'redir/' . $contact['id'];
2599 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2600 $redirect .= '?url=' . $url;
2607 * Is the contact a forum?
2609 * @param integer $contactid ID of the contact
2611 * @return boolean "true" if it is a forum
2613 public static function isForum($contactid)
2615 $fields = ['forum', 'prv'];
2616 $condition = ['id' => $contactid];
2617 $contact = DBA::selectFirst('contact', $fields, $condition);
2618 if (!DBA::isResult($contact)) {
2623 return ($contact['forum'] || $contact['prv']);
2627 * Can the remote contact receive private messages?
2629 * @param array $contact
2632 public static function canReceivePrivateMessages(array $contact)
2634 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2635 $self = $contact['self'] ?? false;
2637 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2641 * Search contact table by nick or name
2643 * @param string $search Name or nick
2644 * @param string $mode Search mode (e.g. "community")
2646 * @return array with search results
2647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2649 public static function searchByName($search, $mode = '')
2651 if (empty($search)) {
2655 // check supported networks
2656 if (DI::config()->get('system', 'diaspora_enabled')) {
2657 $diaspora = Protocol::DIASPORA;
2659 $diaspora = Protocol::DFRN;
2662 if (!DI::config()->get('system', 'ostatus_disabled')) {
2663 $ostatus = Protocol::OSTATUS;
2665 $ostatus = Protocol::DFRN;
2668 // check if we search only communities or every contact
2669 if ($mode === 'community') {
2670 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2677 $results = DBA::p("SELECT * FROM `contact`
2678 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2679 NOT `failed` AND `uid` = ? AND
2680 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2681 ORDER BY `nurl` DESC LIMIT 1000",
2682 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2685 $contacts = DBA::toArray($results);
2690 * Add public contacts from an array
2692 * @param array $urls
2693 * @return array result "count", "added" and "updated"
2695 public static function addByUrls(array $urls)
2701 foreach ($urls as $url) {
2702 $contact = Contact::getByURL($url, false, ['id']);
2703 if (empty($contact['id'])) {
2704 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2707 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2713 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2717 * Returns a random, global contact of the current node
2719 * @return string The profile URL
2722 public static function getRandomUrl()
2724 $r = DBA::selectFirst('contact', ['url'], [
2725 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2726 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2727 ], ['order' => ['RAND()']]);
2729 if (DBA::isResult($r)) {