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', '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['updated'], $contact['last-update'], $contact['failure_update']);
259 if ((($updated < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
260 in_array($contact['network'], Protocol::FEDERATED)) {
261 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
264 // Remove the internal fields
265 foreach ($removal as $internal) {
266 unset($contact[$internal]);
273 * Fetches a contact for a given user by a given url.
274 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
276 * @param string $url profile url
277 * @param integer $uid User ID of the contact
278 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
279 * @param array $fields Field list
280 * @return array contact array
282 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
285 $contact = self::getByURL($url, $update, $fields, $uid);
286 if (!empty($contact)) {
287 if (!empty($contact['id'])) {
288 $contact['cid'] = $contact['id'];
295 $contact = self::getByURL($url, $update, $fields);
296 if (!empty($contact['id'])) {
298 $contact['zid'] = $contact['id'];
304 * Tests if the given contact is a follower
306 * @param int $cid Either public contact id or user's contact id
307 * @param int $uid User ID
309 * @return boolean is the contact id a follower?
310 * @throws HTTPException\InternalServerErrorException
311 * @throws \ImagickException
313 public static function isFollower($cid, $uid)
315 if (Contact\User::isBlocked($cid, $uid)) {
319 $cdata = self::getPublicAndUserContacID($cid, $uid);
320 if (empty($cdata['user'])) {
324 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
325 return DBA::exists('contact', $condition);
329 * Tests if the given contact url is a follower
331 * @param string $url Contact URL
332 * @param int $uid User ID
334 * @return boolean is the contact id a follower?
335 * @throws HTTPException\InternalServerErrorException
336 * @throws \ImagickException
338 public static function isFollowerByURL($url, $uid)
340 $cid = self::getIdForURL($url, $uid);
346 return self::isFollower($cid, $uid);
350 * Tests if the given user follow the given contact
352 * @param int $cid Either public contact id or user's contact id
353 * @param int $uid User ID
355 * @return boolean is the contact url being followed?
356 * @throws HTTPException\InternalServerErrorException
357 * @throws \ImagickException
359 public static function isSharing($cid, $uid)
361 if (Contact\User::isBlocked($cid, $uid)) {
365 $cdata = self::getPublicAndUserContacID($cid, $uid);
366 if (empty($cdata['user'])) {
370 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
371 return DBA::exists('contact', $condition);
375 * Tests if the given user follow the given contact url
377 * @param string $url Contact URL
378 * @param int $uid User ID
380 * @return boolean is the contact url being followed?
381 * @throws HTTPException\InternalServerErrorException
382 * @throws \ImagickException
384 public static function isSharingByURL($url, $uid)
386 $cid = self::getIdForURL($url, $uid);
392 return self::isSharing($cid, $uid);
396 * Get the basepath for a given contact link
398 * @param string $url The contact link
399 * @param boolean $dont_update Don't update the contact
401 * @return string basepath
402 * @throws HTTPException\InternalServerErrorException
403 * @throws \ImagickException
405 public static function getBasepath($url, $dont_update = false)
407 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
408 if (!DBA::isResult($contact)) {
412 if (!empty($contact['baseurl'])) {
413 return $contact['baseurl'];
414 } elseif ($dont_update) {
418 // Update the existing contact
419 self::updateFromProbe($contact['id']);
421 // And fetch the result
422 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
423 if (empty($contact['baseurl'])) {
424 Logger::info('No baseurl for contact', ['url' => $url]);
428 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
429 return $contact['baseurl'];
433 * Check if the given contact url is on the same server
435 * @param string $url The contact link
437 * @return boolean Is it the same server?
439 public static function isLocal($url)
441 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
445 * Check if the given contact ID is on the same server
447 * @param string $url The contact link
449 * @return boolean Is it the same server?
451 public static function isLocalById(int $cid)
453 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
454 if (!DBA::isResult($contact)) {
458 if (empty($contact['baseurl'])) {
459 $baseurl = self::getBasepath($contact['url'], true);
461 $baseurl = $contact['baseurl'];
464 return Strings::compareLink($baseurl, DI::baseUrl());
468 * Returns the public contact id of the given user id
470 * @param integer $uid User ID
472 * @return integer|boolean Public contact id for given user id
475 public static function getPublicIdByUserId($uid)
477 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
478 if (!DBA::isResult($self)) {
481 return self::getIdForURL($self['url']);
485 * Returns the contact id for the user and the public contact id for a given contact id
487 * @param int $cid Either public contact id or user's contact id
488 * @param int $uid User ID
490 * @return array with public and user's contact id
491 * @throws HTTPException\InternalServerErrorException
492 * @throws \ImagickException
494 public static function getPublicAndUserContacID($cid, $uid)
496 if (empty($uid) || empty($cid)) {
500 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
501 if (!DBA::isResult($contact)) {
505 // We quit when the user id don't match the user id of the provided contact
506 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
510 if ($contact['uid'] != 0) {
511 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
515 $ucid = $contact['id'];
517 $pcid = $contact['id'];
518 $ucid = Contact::getIdForURL($contact['url'], $uid);
521 return ['public' => $pcid, 'user' => $ucid];
525 * Returns contact details for a given contact id in combination with a user id
527 * @param int $cid A contact ID
528 * @param int $uid The User ID
529 * @param array $fields The selected fields for the contact
531 * @return array The contact details
535 public static function getContactForUser($cid, $uid, array $fields = [])
537 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
539 if (!DBA::isResult($contact)) {
547 * Creates the self-contact for the provided user id
550 * @return bool Operation success
551 * @throws HTTPException\InternalServerErrorException
553 public static function createSelfFromUserId($uid)
555 // Only create the entry if it doesn't exist yet
556 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
560 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'], ['uid' => $uid]);
561 if (!DBA::isResult($user)) {
565 $return = DBA::insert('contact', [
566 'uid' => $user['uid'],
567 'created' => DateTimeFormat::utcNow(),
569 'name' => $user['username'],
570 'nick' => $user['nickname'],
571 'pubkey' => $user['pubkey'],
572 'prvkey' => $user['prvkey'],
573 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
574 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
575 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
578 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
579 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
580 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
581 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
582 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
583 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
584 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
585 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
586 'name-date' => DateTimeFormat::utcNow(),
587 'uri-date' => DateTimeFormat::utcNow(),
588 'avatar-date' => DateTimeFormat::utcNow(),
596 * Updates the self-contact for the provided user id
599 * @param boolean $update_avatar Force the avatar update
600 * @throws HTTPException\InternalServerErrorException
602 public static function updateSelfFromUserID($uid, $update_avatar = false)
604 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
605 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
606 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
607 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
608 if (!DBA::isResult($self)) {
612 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
613 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
614 if (!DBA::isResult($user)) {
618 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
619 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
620 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
621 if (!DBA::isResult($profile)) {
625 $file_suffix = 'jpg';
627 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
628 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
629 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
630 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
631 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp']];
633 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
634 if (DBA::isResult($avatar)) {
635 if ($update_avatar) {
636 $fields['avatar-date'] = DateTimeFormat::utcNow();
639 // Creating the path to the avatar, beginning with the file suffix
640 $types = Images::supportedTypes();
641 if (isset($types[$avatar['type']])) {
642 $file_suffix = $types[$avatar['type']];
645 // We are adding a timestamp value so that other systems won't use cached content
646 $timestamp = strtotime($fields['avatar-date']);
648 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
649 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
651 $fields['photo'] = $prefix . '4' . $suffix;
652 $fields['thumb'] = $prefix . '5' . $suffix;
653 $fields['micro'] = $prefix . '6' . $suffix;
655 // We hadn't found a photo entry, so we use the default avatar
656 $fields['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
657 $fields['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
658 $fields['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
661 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
662 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
663 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
664 $fields['unsearchable'] = !$profile['net-publish'];
666 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
667 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
668 $fields['nurl'] = Strings::normaliseLink($fields['url']);
669 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
670 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
671 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
672 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
673 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
674 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
678 foreach ($fields as $field => $content) {
679 if ($self[$field] != $content) {
685 if ($fields['name'] != $self['name']) {
686 $fields['name-date'] = DateTimeFormat::utcNow();
688 $fields['updated'] = DateTimeFormat::utcNow();
689 DBA::update('contact', $fields, ['id' => $self['id']]);
691 // Update the public contact as well
692 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
694 // Update the profile
695 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
696 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
697 DBA::update('profile', $fields, ['uid' => $uid]);
702 * Marks a contact for removal
704 * @param int $id contact id
706 * @throws HTTPException\InternalServerErrorException
708 public static function remove($id)
710 // We want just to make sure that we don't delete our "self" contact
711 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
712 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
716 // Archive the contact
717 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
719 // Delete it in the background
720 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
724 * Sends an unfriend message. Does not remove the contact
726 * @param array $user User unfriending
727 * @param array $contact Contact unfriended
728 * @param boolean $dissolve Remove the contact on the remote side
730 * @throws HTTPException\InternalServerErrorException
731 * @throws \ImagickException
733 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
735 if (empty($contact['network'])) {
739 $protocol = $contact['network'];
740 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
741 $protocol = Protocol::ACTIVITYPUB;
744 if (($protocol == Protocol::DFRN) && $dissolve) {
745 DFRN::deliver($user, $contact, 'placeholder', true);
746 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
747 // create an unfollow slap
749 $item['verb'] = Activity::O_UNFOLLOW;
750 $item['gravity'] = GRAVITY_ACTIVITY;
751 $item['follow'] = $contact["url"];
756 $item['attach'] = '';
757 $slap = OStatus::salmon($item, $user);
759 if (!empty($contact['notify'])) {
760 Salmon::slapper($user, $contact['notify'], $slap);
762 } elseif ($protocol == Protocol::DIASPORA) {
763 Diaspora::sendUnshare($user, $contact);
764 } elseif ($protocol == Protocol::ACTIVITYPUB) {
765 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
768 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
774 * Marks a contact for archival after a communication issue delay
776 * Contact has refused to recognise us as a friend. We will start a countdown.
777 * If they still don't recognise us in 32 days, the relationship is over,
778 * and we won't waste any more time trying to communicate with them.
779 * This provides for the possibility that their database is temporarily messed
780 * up or some other transient event and that there's a possibility we could recover from it.
782 * @param array $contact contact to mark for archival
784 * @throws HTTPException\InternalServerErrorException
786 public static function markForArchival(array $contact)
788 if (!isset($contact['url']) && !empty($contact['id'])) {
789 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
790 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
791 if (!DBA::isResult($contact)) {
794 } elseif (!isset($contact['url'])) {
795 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
798 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
800 // Contact already archived or "self" contact? => nothing to do
801 if ($contact['archive'] || $contact['self']) {
805 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
806 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
807 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
810 * We really should send a notification to the owner after 2-3 weeks
811 * so they won't be surprised when the contact vanishes and can take
812 * remedial action if this was a serious mistake or glitch
815 /// @todo Check for contact vitality via probing
816 $archival_days = DI::config()->get('system', 'archival_days', 32);
818 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
819 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
820 /* Relationship is really truly dead. archive them rather than
821 * delete, though if the owner tries to unarchive them we'll start
822 * the whole process over again.
824 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
825 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
831 * Cancels the archival countdown
833 * @see Contact::markForArchival()
835 * @param array $contact contact to be unmarked for archival
839 public static function unmarkForArchival(array $contact)
841 // Always unarchive the relay contact entry
842 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
843 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
844 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
845 DBA::update('contact', $fields, $condition);
848 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
849 $exists = DBA::exists('contact', $condition);
851 // We don't need to update, we never marked this contact for archival
856 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
858 if (!isset($contact['url']) && !empty($contact['id'])) {
859 $fields = ['id', 'url', 'batch'];
860 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
861 if (!DBA::isResult($contact)) {
866 // It's a miracle. Our dead contact has inexplicably come back to life.
867 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
868 DBA::update('contact', $fields, ['id' => $contact['id']]);
869 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
873 * Returns the data array for the photo menu of a given contact
875 * @param array $contact contact
876 * @param int $uid optional, default 0
878 * @throws HTTPException\InternalServerErrorException
879 * @throws \ImagickException
881 public static function photoMenu(array $contact, $uid = 0)
886 $contact_drop_link = '';
893 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
895 $profile_link = self::magicLink($contact['url']);
896 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
901 // Look for our own contact if the uid doesn't match and isn't public
902 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
903 if (DBA::isResult($contact_own)) {
904 return self::photoMenu($contact_own, $uid);
909 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
911 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
913 $profile_link = $contact['url'];
916 if ($profile_link === 'mailbox') {
921 $status_link = $profile_link . '/status';
922 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
923 $profile_link = $profile_link . '/profile';
926 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
927 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
930 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
931 $poke_link = 'contact/' . $contact['id'] . '/poke';
934 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
936 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
938 if (!$contact['self']) {
939 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
944 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
945 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
946 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
947 } elseif(!$contact['pending']) {
948 $follow_link = 'follow?url=' . urlencode($contact['url']);
952 if (!empty($follow_link) || !empty($unfollow_link)) {
953 $contact_drop_link = '';
958 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
960 if (empty($contact['uid'])) {
962 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
963 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
964 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
965 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
966 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
970 'status' => [DI::l10n()->t('View Status') , $status_link , true],
971 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
972 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
973 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
974 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
975 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
976 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
977 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
978 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
979 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
982 if (!empty($contact['pending'])) {
983 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
984 if (DBA::isResult($intro)) {
985 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
990 $args = ['contact' => $contact, 'menu' => &$menu];
992 Hook::callAll('contact_photo_menu', $args);
996 foreach ($menu as $menuname => $menuitem) {
997 if ($menuitem[1] != '') {
998 $menucondensed[$menuname] = $menuitem;
1002 return $menucondensed;
1006 * Fetch the contact id for a given URL and user
1008 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1009 * `addr` or `alias`.
1011 * If there's no record and we aren't looking for a public contact, we quit.
1012 * If there's one, we check that it isn't time to update the picture else we
1013 * directly return the found contact id.
1015 * Second, we probe the provided $url whether it's http://server.tld/profile or
1016 * nick@server.tld. We quit if we can't get any info back.
1018 * Third, we create the contact record if it doesn't exist
1020 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1021 * if there's any updates
1023 * @param string $url Contact URL
1024 * @param integer $uid The user id for the contact (0 = public contact)
1025 * @param boolean $update true = always update, false = never update, null = update when not found
1026 * @param array $default Default value for creating the contact when everything else fails
1028 * @return integer Contact ID
1029 * @throws HTTPException\InternalServerErrorException
1030 * @throws \ImagickException
1032 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1037 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1041 $contact = self::getByURL($url, false, ['id', 'network'], $uid);
1043 if (!empty($contact)) {
1044 $contact_id = $contact["id"];
1046 if (empty($update)) {
1047 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1050 } elseif ($uid != 0) {
1051 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1053 } elseif (empty($default) && !is_null($update) && !$update) {
1054 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1060 if (empty($default['network']) || $update) {
1061 $data = Probe::uri($url, "", $uid);
1063 // Take the default values when probing failed
1064 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1065 $data = array_merge($data, $default);
1067 } elseif (!empty($default['network'])) {
1071 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1072 // Fetch data for the public contact via the first found personal contact
1073 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1074 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'contact-type',
1075 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1076 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1078 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1079 if (!DBA::isResult($personal_contact)) {
1080 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1083 if (DBA::isResult($personal_contact)) {
1084 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1085 $data = $personal_contact;
1086 $data['photo'] = $personal_contact['avatar'];
1087 $data['account-type'] = $personal_contact['contact-type'];
1088 $data['hide'] = $personal_contact['unsearchable'];
1089 unset($data['avatar']);
1090 unset($data['contact-type']);
1091 unset($data['unsearchable']);
1095 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1096 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1101 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1102 if (!empty($data['alias'])) {
1103 $urls[] = Strings::normaliseLink($data['alias']);
1105 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1106 if (!empty($contact['id'])) {
1107 $contact_id = $contact['id'];
1108 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'probed_url' => $data['url'], 'alias' => $data['alias'], 'addr' => $data['addr']]);
1113 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1116 'url' => $data['url'],
1117 'nurl' => Strings::normaliseLink($data['url']),
1118 'network' => $data['network'],
1119 'created' => DateTimeFormat::utcNow(),
1120 'rel' => self::SHARING,
1126 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1128 // Before inserting we do check if the entry does exist now.
1129 DBA::lock('contact');
1130 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1131 if (DBA::isResult($contact)) {
1132 $contact_id = $contact['id'];
1133 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1135 DBA::insert('contact', $fields);
1136 $contact_id = DBA::lastInsertId();
1138 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1143 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1147 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1150 self::updateFromProbeArray($contact_id, $data);
1156 * Checks if the contact is archived
1158 * @param int $cid contact id
1160 * @return boolean Is the contact archived?
1161 * @throws HTTPException\InternalServerErrorException
1163 public static function isArchived(int $cid)
1169 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1170 if (!DBA::isResult($contact)) {
1174 if ($contact['archive']) {
1178 // Check status of ActivityPub endpoints
1179 $apcontact = APContact::getByURL($contact['url'], false);
1180 if (!empty($apcontact)) {
1181 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1185 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1190 // Check status of Diaspora endpoints
1191 if (!empty($contact['batch'])) {
1192 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1193 return DBA::exists('contact', $condition);
1200 * Checks if the contact is blocked
1202 * @param int $cid contact id
1204 * @return boolean Is the contact blocked?
1205 * @throws HTTPException\InternalServerErrorException
1207 public static function isBlocked($cid)
1213 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1214 if (!DBA::isResult($blocked)) {
1218 if (Network::isUrlBlocked($blocked['url'])) {
1222 return (bool) $blocked['blocked'];
1226 * Checks if the contact is hidden
1228 * @param int $cid contact id
1230 * @return boolean Is the contact hidden?
1231 * @throws \Exception
1233 public static function isHidden($cid)
1239 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1240 if (!DBA::isResult($hidden)) {
1243 return (bool) $hidden['hidden'];
1247 * Returns posts from a given contact url
1249 * @param string $contact_url Contact URL
1250 * @param bool $thread_mode
1251 * @param int $update
1252 * @return string posts in HTML
1253 * @throws \Exception
1255 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1257 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1261 * Returns posts from a given contact id
1263 * @param integer $cid
1264 * @param bool $thread_mode
1265 * @param integer $update
1266 * @return string posts in HTML
1267 * @throws \Exception
1269 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1273 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1274 if (!DBA::isResult($contact)) {
1278 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1279 $sql = "`item`.`uid` IN (0, ?)";
1281 $sql = "`item`.`uid` = ?";
1284 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1287 $condition = ["(`$contact_field` = ? OR (`causer-id` = ? AND `post-type` = ?)) AND `gravity` = ? AND " . $sql,
1288 $cid, $cid, Item::PT_ANNOUNCEMENT, GRAVITY_PARENT, local_user()];
1290 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1291 if (!empty($last_received)) {
1292 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1295 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1296 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1299 if (DI::mode()->isMobile()) {
1300 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1301 DI::config()->get('system', 'itemspage_network_mobile'));
1303 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1304 DI::config()->get('system', 'itemspage_network'));
1307 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1309 $params = ['order' => ['received' => true], 'group_by' => ['uri-id'],
1310 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1313 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1314 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1315 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1320 $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1322 while ($item = DBA::fetch($r)) {
1323 if ($item['gravity'] != GRAVITY_PARENT) {
1324 $item['uri'] = $item['parent-uri'];
1326 unset($item['parent-uri']);
1327 unset($item['gravity']);
1333 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1335 $r = Item::selectForUser(local_user(), [], $condition, $params);
1337 $items = Item::inArray($r);
1339 $o = conversation($a, $items, 'contact-posts', false);
1343 if ($thread_mode && DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1344 $o .= HTML::scrollLoader();
1346 $o .= $pager->renderMinimal(count($items));
1354 * Returns the account type name
1356 * The function can be called with either the user or the contact array
1358 * @param array $contact contact or user array
1361 public static function getAccountType(array $contact)
1363 // There are several fields that indicate that the contact or user is a forum
1364 // "page-flags" is a field in the user table,
1365 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1366 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1367 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1368 || (isset($contact['forum']) && intval($contact['forum']))
1369 || (isset($contact['prv']) && intval($contact['prv']))
1370 || (isset($contact['community']) && intval($contact['community']))
1372 $type = self::TYPE_COMMUNITY;
1374 $type = self::TYPE_PERSON;
1377 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1378 if (isset($contact["contact-type"])) {
1379 $type = $contact["contact-type"];
1382 if (isset($contact["account-type"])) {
1383 $type = $contact["account-type"];
1387 case self::TYPE_ORGANISATION:
1388 $account_type = DI::l10n()->t("Organisation");
1391 case self::TYPE_NEWS:
1392 $account_type = DI::l10n()->t('News');
1395 case self::TYPE_COMMUNITY:
1396 $account_type = DI::l10n()->t("Forum");
1404 return $account_type;
1412 * @throws \Exception
1414 public static function block($cid, $reason = null)
1416 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1422 * Unblocks a contact
1426 * @throws \Exception
1428 public static function unblock($cid)
1430 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1436 * Ensure that cached avatar exist
1438 * @param integer $cid
1440 public static function checkAvatarCache(int $cid)
1442 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1443 if (!DBA::isResult($contact)) {
1447 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1451 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1453 self::updateAvatar($cid, $contact['avatar'], true);
1457 * Return the photo path for a given contact array in the given size
1459 * @param array $contact contact array
1460 * @param string $field Fieldname of the photo in the contact array
1461 * @param string $default Default path when no picture had been found
1462 * @param string $size Size of the avatar picture
1463 * @param string $avatar Avatar path that is displayed when no photo had been found
1464 * @return string photo path
1466 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1468 if (!empty($contact)) {
1469 $contact = self::checkAvatarCacheByArray($contact);
1470 if (!empty($contact[$field])) {
1471 $avatar = $contact[$field];
1475 if (empty($avatar)) {
1479 if (Proxy::isLocalImage($avatar)) {
1482 return Proxy::proxifyUrl($avatar, false, $size);
1487 * Return the photo path for a given contact array
1489 * @param array $contact Contact array
1490 * @param string $avatar Avatar path that is displayed when no photo had been found
1491 * @return string photo path
1493 public static function getPhoto(array $contact, string $avatar = '')
1495 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO, Proxy::SIZE_SMALL, $avatar);
1499 * Return the photo path (thumb size) for a given contact array
1501 * @param array $contact Contact array
1502 * @param string $avatar Avatar path that is displayed when no photo had been found
1503 * @return string photo path
1505 public static function getThumb(array $contact, string $avatar = '')
1507 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . self::DEFAULT_AVATAR_THUMB, Proxy::SIZE_THUMB, $avatar);
1511 * Return the photo path (micro size) for a given contact array
1513 * @param array $contact Contact array
1514 * @param string $avatar Avatar path that is displayed when no photo had been found
1515 * @return string photo path
1517 public static function getMicro(array $contact, string $avatar = '')
1519 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . self::DEFAULT_AVATAR_MICRO, Proxy::SIZE_MICRO, $avatar);
1523 * Check the given contact array for avatar cache fields
1525 * @param array $contact
1526 * @return array contact array with avatar cache fields
1528 private static function checkAvatarCacheByArray(array $contact)
1531 $contact_fields = [];
1532 $fields = ['photo', 'thumb', 'micro'];
1533 foreach ($fields as $field) {
1534 if (isset($contact[$field])) {
1535 $contact_fields[] = $field;
1537 if (isset($contact[$field]) && empty($contact[$field])) {
1546 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1547 self::updateAvatar($contact['id'], $contact['avatar'], true);
1549 $new_contact = self::getById($contact['id'], $contact_fields);
1550 if (DBA::isResult($new_contact)) {
1551 // We only update the cache fields
1552 $contact = array_merge($contact, $new_contact);
1556 /// add the default avatars if the fields aren't filled
1557 if (isset($contact['photo']) && empty($contact['photo'])) {
1558 $contact['photo'] = DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO;
1560 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1561 $contact['thumb'] = DI::baseUrl() . self::DEFAULT_AVATAR_THUMB;
1563 if (isset($contact['micro']) && empty($contact['micro'])) {
1564 $contact['micro'] = DI::baseUrl() . self::DEFAULT_AVATAR_MICRO;
1571 * Updates the avatar links in a contact only if needed
1573 * @param int $cid Contact id
1574 * @param string $avatar Link to avatar picture
1575 * @param bool $force force picture update
1576 * @param bool $create_cache Enforces the creation of cached avatar fields
1579 * @throws HTTPException\InternalServerErrorException
1580 * @throws HTTPException\NotFoundException
1581 * @throws \ImagickException
1583 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1585 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl', 'url', 'network'], ['id' => $cid, 'self' => false]);
1586 if (!DBA::isResult($contact)) {
1590 $uid = $contact['uid'];
1592 // Only update the cached photo links of public contacts when they already are cached
1593 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1594 if ($contact['avatar'] != $avatar) {
1595 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1596 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1601 // User contacts use are updated through the public contacts
1602 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1603 $pcid = self::getIdForURL($contact['url'], false);
1604 if (!empty($pcid)) {
1605 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1606 self::updateAvatar($pcid, $avatar, $force, true);
1611 // Replace cached avatar pictures from the default avatar with the default avatars in different sizes
1612 if (strpos($avatar, self::DEFAULT_AVATAR_PHOTO)) {
1613 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1614 'photo' => DI::baseUrl() . self::DEFAULT_AVATAR_PHOTO,
1615 'thumb' => DI::baseUrl() . self::DEFAULT_AVATAR_THUMB,
1616 'micro' => DI::baseUrl() . self::DEFAULT_AVATAR_MICRO];
1617 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1620 // Use the data from the self account
1621 if (empty($fields)) {
1622 $local_uid = User::getIdForURL($contact['url']);
1623 if (!empty($local_uid)) {
1624 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1625 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1629 if (empty($fields)) {
1630 $update = ($contact['avatar'] != $avatar) || $force;
1634 $contact['photo'] ?? '',
1635 $contact['thumb'] ?? '',
1636 $contact['micro'] ?? '',
1639 foreach ($data as $image_uri) {
1640 $image_rid = Photo::ridFromURI($image_uri);
1641 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1642 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1649 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1651 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1652 $update = !empty($fields);
1653 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1659 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1668 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1669 // Collect all user contacts of the given public contact
1670 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1671 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1672 while ($personal_contact = DBA::fetch($personal_contacts)) {
1673 $cids[] = $personal_contact['id'];
1674 $uids[] = $personal_contact['uid'];
1676 DBA::close($personal_contacts);
1678 if (!empty($cids)) {
1679 // Delete possibly existing cached user contact avatars
1680 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1686 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1687 DBA::update('contact', $fields, ['id' => $cids]);
1691 * Helper function for "updateFromProbe". Updates personal and public contact
1693 * @param integer $id contact id
1694 * @param integer $uid user id
1695 * @param string $url The profile URL of the contact
1696 * @param array $fields The fields that are updated
1698 * @throws \Exception
1700 private static function updateContact($id, $uid, $url, array $fields)
1702 if (!DBA::update('contact', $fields, ['id' => $id])) {
1703 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1707 // Search for duplicated contacts and get rid of them
1708 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1712 // Archive or unarchive the contact. We only need to do this for the public contact.
1713 // The archive/unarchive function will update the personal contacts by themselves.
1714 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1715 if (!DBA::isResult($contact)) {
1716 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1720 if (!empty($fields['success_update'])) {
1721 self::unmarkForArchival($contact);
1722 } elseif (!empty($fields['failure_update'])) {
1723 self::markForArchival($contact);
1726 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1728 // These contacts are sharing with us, we don't poll them.
1729 // This means that we don't set the update fields in "OnePoll.php".
1730 $condition['rel'] = self::SHARING;
1731 DBA::update('contact', $fields, $condition);
1733 unset($fields['last-update']);
1734 unset($fields['success_update']);
1735 unset($fields['failure_update']);
1737 if (empty($fields)) {
1741 // We are polling these contacts, so we mustn't set the update fields here.
1742 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1743 DBA::update('contact', $fields, $condition);
1747 * Remove duplicated contacts
1749 * @param string $nurl Normalised contact url
1750 * @param integer $uid User id
1752 * @throws \Exception
1754 public static function removeDuplicates(string $nurl, int $uid)
1756 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1757 $count = DBA::count('contact', $condition);
1762 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1763 if (!DBA::isResult($first_contact)) {
1764 // Shouldn't happen - so we handle it
1768 $first = $first_contact['id'];
1769 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1770 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1771 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1772 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1776 // Find all duplicates
1777 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1778 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1779 while ($duplicate = DBA::fetch($duplicates)) {
1780 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1784 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1786 DBA::close($duplicates);
1787 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1792 * @param integer $id contact id
1793 * @param string $network Optional network we are probing for
1795 * @throws HTTPException\InternalServerErrorException
1796 * @throws \ImagickException
1798 public static function updateFromProbe(int $id, string $network = '')
1800 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1801 if (!DBA::isResult($contact)) {
1805 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1806 return self::updateFromProbeArray($id, $ret);
1810 * @param integer $id contact id
1811 * @param array $ret Probed data
1813 * @throws HTTPException\InternalServerErrorException
1814 * @throws \ImagickException
1816 private static function updateFromProbeArray(int $id, array $ret)
1819 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1820 This will reliably kill your communication with old Friendica contacts.
1823 // These fields aren't updated by this routine:
1824 // 'xmpp', 'sensitive'
1826 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe', 'manually-approve',
1827 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1828 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1829 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1830 if (!DBA::isResult($contact)) {
1834 $uid = $contact['uid'];
1835 unset($contact['uid']);
1837 $pubkey = $contact['pubkey'];
1838 unset($contact['pubkey']);
1840 $contact['photo'] = $contact['avatar'];
1841 unset($contact['avatar']);
1843 $updated = DateTimeFormat::utcNow();
1845 // We must not try to update relay contacts via probe. They are no real contacts.
1846 // We check after the probing to be able to correct falsely detected contact types.
1847 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1848 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1849 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1850 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1854 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1855 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1857 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1862 if (Contact\Relation::isDiscoverable($ret['url'])) {
1863 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1866 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1867 $ret['unsearchable'] = $ret['hide'];
1870 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1871 $ret['forum'] = false;
1872 $ret['prv'] = false;
1873 $ret['contact-type'] = $ret['account-type'];
1874 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
1875 $ret['forum'] = (bool)!$ret['manually-approve'];
1876 $ret['prv'] = (bool)!$ret['forum'];
1880 $new_pubkey = $ret['pubkey'] ?? '';
1883 $ret['last-item'] = Probe::getLastUpdate($ret);
1884 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1889 // make sure to not overwrite existing values with blank entries except some technical fields
1890 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1891 foreach ($ret as $key => $val) {
1892 if (!array_key_exists($key, $contact)) {
1894 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1895 $ret[$key] = $contact[$key];
1896 } elseif ($ret[$key] != $contact[$key]) {
1901 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1904 unset($ret['last-item']);
1907 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1908 self::updateAvatar($id, $ret['photo'], $update);
1912 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1914 // Update the public contact
1916 $contact = self::getByURL($ret['url'], false, ['id']);
1917 if (!empty($contact['id'])) {
1918 self::updateFromProbeArray($contact['id'], $ret);
1925 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1926 $ret['updated'] = $updated;
1928 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1929 if (empty($pubkey) && !empty($new_pubkey)) {
1930 $ret['pubkey'] = $new_pubkey;
1933 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1934 $ret['uri-date'] = DateTimeFormat::utcNow();
1937 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1938 $ret['name-date'] = $updated;
1942 $ret['last-update'] = $updated;
1943 $ret['success_update'] = $updated;
1944 $ret['failed'] = false;
1947 unset($ret['photo']);
1949 self::updateContact($id, $uid, $ret['url'], $ret);
1955 * @param integer $url contact url
1956 * @return integer Contact id
1957 * @throws HTTPException\InternalServerErrorException
1958 * @throws \ImagickException
1960 public static function updateFromProbeByURL($url)
1962 $id = self::getIdForURL($url);
1968 self::updateFromProbe($id);
1974 * Detects if a given contact array belongs to a legacy DFRN connection
1976 * @param array $contact
1979 public static function isLegacyDFRNContact($contact)
1981 // Newer Friendica contacts are connected via AP, then these fields aren't set
1982 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1986 * Detects the communication protocol for a given contact url.
1987 * This is used to detect Friendica contacts that we can communicate via AP.
1989 * @param string $url contact url
1990 * @param string $network Network of that contact
1991 * @return string with protocol
1993 public static function getProtocol($url, $network)
1995 if ($network != Protocol::DFRN) {
1999 $apcontact = APContact::getByURL($url);
2000 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2001 return Protocol::ACTIVITYPUB;
2008 * Takes a $uid and a url/handle and adds a new contact
2010 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2011 * dfrn_request page.
2013 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2016 * $return['success'] boolean true if successful
2017 * $return['message'] error text if success is false.
2019 * Takes a $uid and a url/handle and adds a new contact
2021 * @param array $user The user the contact should be created for
2022 * @param string $url The profile URL of the contact
2023 * @param bool $interactive
2024 * @param string $network
2026 * @throws HTTPException\InternalServerErrorException
2027 * @throws HTTPException\NotFoundException
2028 * @throws \ImagickException
2030 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
2032 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2034 // remove ajax junk, e.g. Twitter
2035 $url = str_replace('/#!/', '/', $url);
2037 if (!Network::isUrlAllowed($url)) {
2038 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2042 if (Network::isUrlBlocked($url)) {
2043 $result['message'] = DI::l10n()->t('Blocked domain');
2048 $result['message'] = DI::l10n()->t('Connect URL missing.');
2052 $arr = ['url' => $url, 'contact' => []];
2054 Hook::callAll('follow', $arr);
2057 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2061 if (!empty($arr['contact']['name'])) {
2062 $ret = $arr['contact'];
2064 $ret = Probe::uri($url, $network, $user['uid']);
2067 if (($network != '') && ($ret['network'] != $network)) {
2068 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2072 // check if we already have a contact
2073 // the poll url is more reliable than the profile url, as we may have
2074 // indirect links or webfinger links
2076 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2077 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2078 if (!DBA::isResult($contact)) {
2079 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2080 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2083 $protocol = self::getProtocol($ret['url'], $ret['network']);
2085 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2087 if (strlen(DI::baseUrl()->getUrlPath())) {
2088 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2090 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2093 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2097 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2098 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2099 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2103 // This extra param just confuses things, remove it
2104 if ($protocol === Protocol::DIASPORA) {
2105 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2108 // do we have enough information?
2109 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2110 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2111 if (empty($ret['poll'])) {
2112 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2114 if (empty($ret['name'])) {
2115 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2117 if (empty($ret['url'])) {
2118 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2120 if (strpos($ret['url'], '@') !== false) {
2121 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2122 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2127 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2128 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2129 $ret['notify'] = '';
2132 if (!$ret['notify']) {
2133 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2136 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2138 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2140 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2143 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2144 $pending = (bool)$ret['manually-approve'];
2147 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2151 if (DBA::isResult($contact)) {
2153 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2155 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2156 DBA::update('contact', $fields, ['id' => $contact['id']]);
2158 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2160 // create contact record
2162 'uid' => $user['uid'],
2163 'created' => DateTimeFormat::utcNow(),
2164 'url' => $ret['url'],
2165 'nurl' => Strings::normaliseLink($ret['url']),
2166 'addr' => $ret['addr'],
2167 'alias' => $ret['alias'],
2168 'batch' => $ret['batch'],
2169 'notify' => $ret['notify'],
2170 'poll' => $ret['poll'],
2171 'poco' => $ret['poco'],
2172 'name' => $ret['name'],
2173 'nick' => $ret['nick'],
2174 'network' => $ret['network'],
2175 'baseurl' => $ret['baseurl'],
2176 'gsid' => $ret['gsid'] ?? null,
2177 'protocol' => $protocol,
2178 'pubkey' => $ret['pubkey'],
2179 'rel' => $new_relation,
2180 'priority'=> $ret['priority'],
2181 'writable'=> $writeable,
2182 'hidden' => $hidden,
2185 'pending' => $pending,
2190 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2191 if (!DBA::isResult($contact)) {
2192 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2196 $contact_id = $contact['id'];
2197 $result['cid'] = $contact_id;
2199 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2201 // Update the avatar
2202 self::updateAvatar($contact_id, $ret['photo']);
2204 // pull feed and consume it, which should subscribe to the hub.
2206 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2208 $owner = User::getOwnerDataById($user['uid']);
2210 if (DBA::isResult($owner)) {
2211 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2212 // create a follow slap
2214 $item['verb'] = Activity::FOLLOW;
2215 $item['gravity'] = GRAVITY_ACTIVITY;
2216 $item['follow'] = $contact["url"];
2218 $item['title'] = '';
2220 $item['uri-id'] = 0;
2221 $item['attach'] = '';
2223 $slap = OStatus::salmon($item, $owner);
2225 if (!empty($contact['notify'])) {
2226 Salmon::slapper($owner, $contact['notify'], $slap);
2228 } elseif ($protocol == Protocol::DIASPORA) {
2229 $ret = Diaspora::sendShare($owner, $contact);
2230 Logger::log('share returns: ' . $ret);
2231 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2232 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2233 if (empty($activity_id)) {
2234 // This really should never happen
2238 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2239 Logger::log('Follow returns: ' . $ret);
2243 $result['success'] = true;
2248 * Updated contact's SSL policy
2250 * @param array $contact Contact array
2251 * @param string $new_policy New policy, valid: self,full
2253 * @return array Contact array with updated values
2254 * @throws \Exception
2256 public static function updateSslPolicy(array $contact, $new_policy)
2258 $ssl_changed = false;
2259 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2260 $ssl_changed = true;
2261 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2262 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2263 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2264 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2265 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2266 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2269 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2270 $ssl_changed = true;
2271 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2272 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2273 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2274 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2275 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2276 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2280 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2281 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2282 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2283 DBA::update('contact', $fields, ['id' => $contact['id']]);
2290 * @param array $importer Owner (local user) data
2291 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2292 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2293 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2294 * @param string $note Introduction additional message
2295 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2296 * @throws HTTPException\InternalServerErrorException
2297 * @throws \ImagickException
2299 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2301 // Should always be set
2302 if (empty($datarray['author-id'])) {
2306 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2307 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2308 if (!DBA::isResult($pub_contact)) {
2309 // Should never happen
2313 // Contact is blocked at node-level
2314 if (self::isBlocked($datarray['author-id'])) {
2318 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2319 $name = $pub_contact['name'];
2320 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2321 $nick = $pub_contact['nick'];
2322 $network = $pub_contact['network'];
2324 // Ensure that we don't create a new contact when there already is one
2325 $cid = self::getIdForURL($url, $importer['uid']);
2327 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2330 if (!empty($contact)) {
2331 if (!empty($contact['pending'])) {
2332 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2336 // Contact is blocked at user-level
2337 if (!empty($contact['id']) && !empty($importer['id']) &&
2338 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2342 // Make sure that the existing contact isn't archived
2343 self::unmarkForArchival($contact);
2345 if (($contact['rel'] == self::SHARING)
2346 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2347 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2348 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2351 // Ensure to always have the correct network type, independent from the connection request method
2352 self::updateFromProbe($contact['id']);
2356 // send email notification to owner?
2357 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2358 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2362 // create contact record
2363 DBA::insert('contact', [
2364 'uid' => $importer['uid'],
2365 'created' => DateTimeFormat::utcNow(),
2367 'nurl' => Strings::normaliseLink($url),
2370 'network' => $network,
2371 'rel' => self::FOLLOWER,
2378 $contact_id = DBA::lastInsertId();
2380 // Ensure to always have the correct network type, independent from the connection request method
2381 self::updateFromProbe($contact_id);
2383 self::updateAvatar($contact_id, $photo, true);
2385 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2387 /// @TODO Encapsulate this into a function/method
2388 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2389 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2390 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2391 // create notification
2392 $hash = Strings::getRandomHex();
2394 if (is_array($contact_record)) {
2395 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2396 'blocked' => false, 'knowyou' => false, 'note' => $note,
2397 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2400 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2402 if (($user['notify-flags'] & Type::INTRO) &&
2403 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2406 'type' => Type::INTRO,
2407 'notify_flags' => $user['notify-flags'],
2408 'language' => $user['language'],
2409 'to_name' => $user['username'],
2410 'to_email' => $user['email'],
2411 'uid' => $user['uid'],
2412 'link' => DI::baseUrl() . '/notifications/intros',
2413 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2414 'source_link' => $contact_record['url'],
2415 'source_photo' => $contact_record['photo'],
2416 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2420 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2421 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2422 self::createFromProbe($importer, $url, false, $network);
2425 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2426 $fields = ['pending' => false];
2427 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2428 $fields['rel'] = Contact::FRIEND;
2431 DBA::update('contact', $fields, $condition);
2440 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2442 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2443 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2445 Contact::remove($contact['id']);
2449 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2451 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2452 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2454 Contact::remove($contact['id']);
2459 * Create a birthday event.
2461 * Update the year and the birthday.
2463 public static function updateBirthdays()
2467 AND `bd` > "0001-01-01"
2468 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2469 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2470 AND NOT `contact`.`pending`
2471 AND NOT `contact`.`hidden`
2472 AND NOT `contact`.`blocked`
2473 AND NOT `contact`.`archive`
2474 AND NOT `contact`.`deleted`',
2479 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2481 while ($contact = DBA::fetch($contacts)) {
2482 Logger::log('update_contact_birthday: ' . $contact['bd']);
2484 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2486 if (Event::createBirthday($contact, $nextbd)) {
2490 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2491 ['id' => $contact['id']]
2495 DBA::close($contacts);
2499 * Remove the unavailable contact ids from the provided list
2501 * @param array $contact_ids Contact id list
2503 * @throws \Exception
2505 public static function pruneUnavailable(array $contact_ids)
2507 if (empty($contact_ids)) {
2511 $contacts = Contact::selectToArray(['id'], [
2512 'id' => $contact_ids,
2518 return array_column($contacts, 'id');
2522 * Returns a magic link to authenticate remote visitors
2524 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2526 * @param string $contact_url The address of the target contact profile
2527 * @param string $url An url that we will be redirected to after the authentication
2529 * @return string with "redir" link
2530 * @throws HTTPException\InternalServerErrorException
2531 * @throws \ImagickException
2533 public static function magicLink($contact_url, $url = '')
2535 if (!Session::isAuthenticated()) {
2536 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2539 $contact = self::getByURL($contact_url, false);
2540 if (empty($contact)) {
2541 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2544 // Prevents endless loop in case only a non-public contact exists for the contact URL
2545 unset($contact['uid']);
2547 return self::magicLinkByContact($contact, $url ?: $contact_url);
2551 * Returns a magic link to authenticate remote visitors
2553 * @param integer $cid The contact id of the target contact profile
2554 * @param string $url An url that we will be redirected to after the authentication
2556 * @return string with "redir" link
2557 * @throws HTTPException\InternalServerErrorException
2558 * @throws \ImagickException
2560 public static function magicLinkbyId($cid, $url = '')
2562 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2564 return self::magicLinkByContact($contact, $url);
2568 * Returns a magic link to authenticate remote visitors
2570 * @param array $contact The contact array with "uid", "network" and "url"
2571 * @param string $url An url that we will be redirected to after the authentication
2573 * @return string with "redir" link
2574 * @throws HTTPException\InternalServerErrorException
2575 * @throws \ImagickException
2577 public static function magicLinkByContact($contact, $url = '')
2579 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2581 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2582 return $destination;
2585 // Only redirections to the same host do make sense
2586 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2590 if (!empty($contact['uid'])) {
2591 return self::magicLink($contact['url'], $url);
2594 if (empty($contact['id'])) {
2595 return $destination;
2598 $redirect = 'redir/' . $contact['id'];
2600 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2601 $redirect .= '?url=' . $url;
2608 * Is the contact a forum?
2610 * @param integer $contactid ID of the contact
2612 * @return boolean "true" if it is a forum
2614 public static function isForum($contactid)
2616 $fields = ['forum', 'prv'];
2617 $condition = ['id' => $contactid];
2618 $contact = DBA::selectFirst('contact', $fields, $condition);
2619 if (!DBA::isResult($contact)) {
2624 return ($contact['forum'] || $contact['prv']);
2628 * Can the remote contact receive private messages?
2630 * @param array $contact
2633 public static function canReceivePrivateMessages(array $contact)
2635 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2636 $self = $contact['self'] ?? false;
2638 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2642 * Search contact table by nick or name
2644 * @param string $search Name or nick
2645 * @param string $mode Search mode (e.g. "community")
2647 * @return array with search results
2648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2650 public static function searchByName($search, $mode = '')
2652 if (empty($search)) {
2656 // check supported networks
2657 if (DI::config()->get('system', 'diaspora_enabled')) {
2658 $diaspora = Protocol::DIASPORA;
2660 $diaspora = Protocol::DFRN;
2663 if (!DI::config()->get('system', 'ostatus_disabled')) {
2664 $ostatus = Protocol::OSTATUS;
2666 $ostatus = Protocol::DFRN;
2669 // check if we search only communities or every contact
2670 if ($mode === 'community') {
2671 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2678 $results = DBA::p("SELECT * FROM `contact`
2679 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2680 NOT `failed` AND `uid` = ? AND
2681 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2682 ORDER BY `nurl` DESC LIMIT 1000",
2683 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2686 $contacts = DBA::toArray($results);
2691 * Add public contacts from an array
2693 * @param array $urls
2694 * @return array result "count", "added" and "updated"
2696 public static function addByUrls(array $urls)
2702 foreach ($urls as $url) {
2703 $contact = Contact::getByURL($url, false, ['id']);
2704 if (empty($contact['id'])) {
2705 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2708 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2714 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2718 * Returns a random, global contact of the current node
2720 * @return string The profile URL
2723 public static function getRandomUrl()
2725 $r = DBA::selectFirst('contact', ['url'], [
2726 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2727 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2728 ], ['order' => ['RAND()']]);
2730 if (DBA::isResult($r)) {