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\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Session;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\Notify\Type;
35 use Friendica\Network\HTTPException;
36 use Friendica\Network\Probe;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\DFRN;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\OStatus;
42 use Friendica\Protocol\Salmon;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Images;
45 use Friendica\Util\Network;
46 use Friendica\Util\Proxy;
47 use Friendica\Util\Strings;
50 * functions for interacting with a contact
55 * @deprecated since version 2019.03
56 * @see User::PAGE_FLAGS_NORMAL
58 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
60 * @deprecated since version 2019.03
61 * @see User::PAGE_FLAGS_SOAPBOX
63 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
65 * @deprecated since version 2019.03
66 * @see User::PAGE_FLAGS_COMMUNITY
68 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
70 * @deprecated since version 2019.03
71 * @see User::PAGE_FLAGS_FREELOVE
73 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
75 * @deprecated since version 2019.03
76 * @see User::PAGE_FLAGS_BLOG
78 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
80 * @deprecated since version 2019.03
81 * @see User::PAGE_FLAGS_PRVGROUP
83 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
91 * TYPE_UNKNOWN - unknown type
93 * TYPE_PERSON - the account belongs to a person
94 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
96 * TYPE_ORGANISATION - the account belongs to an organisation
97 * Associated page type: PAGE_SOAPBOX
99 * TYPE_NEWS - the account is a news reflector
100 * Associated page type: PAGE_SOAPBOX
102 * TYPE_COMMUNITY - the account is community forum
103 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
105 * TYPE_RELAY - the account is a relay
106 * This will only be assigned to contacts, not to user accounts
109 const TYPE_UNKNOWN = -1;
110 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
111 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
112 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
113 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
114 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
133 * @param array $fields Array of selected fields, empty for all
134 * @param array $condition Array of fields for condition
135 * @param array $params Array of several parameters
139 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
141 return DBA::selectToArray('contact', $fields, $condition, $params);
145 * @param array $fields Array of selected fields, empty for all
146 * @param array $condition Array of fields for condition
147 * @param array $params Array of several parameters
151 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
153 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
159 * Insert a row into the contact table
160 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
162 * @param array $fields field array
163 * @param bool $on_duplicate_update Do an update on a duplicate entry
165 * @return boolean was the insert successful?
168 public static function insert(array $fields, bool $on_duplicate_update = false)
170 $ret = DBA::insert('contact', $fields, $on_duplicate_update);
171 $contact = DBA::selectFirst('contact', ['nurl', 'uid'], ['id' => DBA::lastInsertId()]);
172 if (!DBA::isResult($contact)) {
177 // Search for duplicated contacts and get rid of them
178 self::removeDuplicates($contact['nurl'], $contact['uid']);
184 * @param integer $id Contact ID
185 * @param array $fields Array of selected fields, empty for all
186 * @return array|boolean Contact record if it exists, false otherwise
189 public static function getById($id, $fields = [])
191 return DBA::selectFirst('contact', $fields, ['id' => $id]);
195 * Fetches a contact by a given url
197 * @param string $url profile url
198 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
199 * @param array $fields Field list
200 * @param integer $uid User ID of the contact
201 * @return array contact array
203 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
205 if ($update || is_null($update)) {
206 $cid = self::getIdForURL($url, $uid, $update);
211 $contact = self::getById($cid, $fields);
212 if (empty($contact)) {
218 // Add internal fields
220 if (!empty($fields)) {
221 foreach (['id', 'avatar', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
222 if (!in_array($internal, $fields)) {
223 $fields[] = $internal;
224 $removal[] = $internal;
229 // We first try the nurl (http://server.tld/nick), most common case
230 $options = ['order' => ['id']];
231 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
233 // Then the addr (nick@server.tld)
234 if (!DBA::isResult($contact)) {
235 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
238 // Then the alias (which could be anything)
239 if (!DBA::isResult($contact)) {
240 // The link could be provided as http although we stored it as https
241 $ssl_url = str_replace('http://', 'https://', $url);
242 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
243 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
246 if (!DBA::isResult($contact)) {
250 // Update the contact in the background if needed
251 $updated = max($contact['success_update'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
252 if ((($updated < DateTimeFormat::utc('now -7 days')) || empty($contact['avatar'])) &&
253 in_array($contact['network'], Protocol::FEDERATED)) {
254 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
257 // Remove the internal fields
258 foreach ($removal as $internal) {
259 unset($contact[$internal]);
266 * Fetches a contact for a given user by a given url.
267 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
269 * @param string $url profile url
270 * @param integer $uid User ID of the contact
271 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
272 * @param array $fields Field list
273 * @return array contact array
275 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
278 $contact = self::getByURL($url, $update, $fields, $uid);
279 if (!empty($contact)) {
280 if (!empty($contact['id'])) {
281 $contact['cid'] = $contact['id'];
288 $contact = self::getByURL($url, $update, $fields);
289 if (!empty($contact['id'])) {
291 $contact['zid'] = $contact['id'];
297 * Tests if the given contact is a follower
299 * @param int $cid Either public contact id or user's contact id
300 * @param int $uid User ID
302 * @return boolean is the contact id a follower?
303 * @throws HTTPException\InternalServerErrorException
304 * @throws \ImagickException
306 public static function isFollower($cid, $uid)
308 if (Contact\User::isBlocked($cid, $uid)) {
312 $cdata = self::getPublicAndUserContacID($cid, $uid);
313 if (empty($cdata['user'])) {
317 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
318 return DBA::exists('contact', $condition);
322 * Tests if the given contact url is a follower
324 * @param string $url Contact URL
325 * @param int $uid User ID
327 * @return boolean is the contact id a follower?
328 * @throws HTTPException\InternalServerErrorException
329 * @throws \ImagickException
331 public static function isFollowerByURL($url, $uid)
333 $cid = self::getIdForURL($url, $uid);
339 return self::isFollower($cid, $uid);
343 * Tests if the given user follow the given contact
345 * @param int $cid Either public contact id or user's contact id
346 * @param int $uid User ID
348 * @return boolean is the contact url being followed?
349 * @throws HTTPException\InternalServerErrorException
350 * @throws \ImagickException
352 public static function isSharing($cid, $uid)
354 if (Contact\User::isBlocked($cid, $uid)) {
358 $cdata = self::getPublicAndUserContacID($cid, $uid);
359 if (empty($cdata['user'])) {
363 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
364 return DBA::exists('contact', $condition);
368 * Tests if the given user follow the given contact url
370 * @param string $url Contact URL
371 * @param int $uid User ID
373 * @return boolean is the contact url being followed?
374 * @throws HTTPException\InternalServerErrorException
375 * @throws \ImagickException
377 public static function isSharingByURL($url, $uid)
379 $cid = self::getIdForURL($url, $uid);
385 return self::isSharing($cid, $uid);
389 * Get the basepath for a given contact link
391 * @param string $url The contact link
392 * @param boolean $dont_update Don't update the contact
394 * @return string basepath
395 * @throws HTTPException\InternalServerErrorException
396 * @throws \ImagickException
398 public static function getBasepath($url, $dont_update = false)
400 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
401 if (!DBA::isResult($contact)) {
405 if (!empty($contact['baseurl'])) {
406 return $contact['baseurl'];
407 } elseif ($dont_update) {
411 // Update the existing contact
412 self::updateFromProbe($contact['id']);
414 // And fetch the result
415 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
416 if (empty($contact['baseurl'])) {
417 Logger::info('No baseurl for contact', ['url' => $url]);
421 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
422 return $contact['baseurl'];
426 * Check if the given contact url is on the same server
428 * @param string $url The contact link
430 * @return boolean Is it the same server?
432 public static function isLocal($url)
434 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
438 * Check if the given contact ID is on the same server
440 * @param string $url The contact link
442 * @return boolean Is it the same server?
444 public static function isLocalById(int $cid)
446 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
447 if (!DBA::isResult($contact)) {
451 if (empty($contact['baseurl'])) {
452 $baseurl = self::getBasepath($contact['url'], true);
454 $baseurl = $contact['baseurl'];
457 return Strings::compareLink($baseurl, DI::baseUrl());
461 * Returns the public contact id of the given user id
463 * @param integer $uid User ID
465 * @return integer|boolean Public contact id for given user id
468 public static function getPublicIdByUserId($uid)
470 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
471 if (!DBA::isResult($self)) {
474 return self::getIdForURL($self['url']);
478 * Returns the contact id for the user and the public contact id for a given contact id
480 * @param int $cid Either public contact id or user's contact id
481 * @param int $uid User ID
483 * @return array with public and user's contact id
484 * @throws HTTPException\InternalServerErrorException
485 * @throws \ImagickException
487 public static function getPublicAndUserContacID($cid, $uid)
489 if (empty($uid) || empty($cid)) {
493 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
494 if (!DBA::isResult($contact)) {
498 // We quit when the user id don't match the user id of the provided contact
499 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
503 if ($contact['uid'] != 0) {
504 $pcid = Contact::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
508 $ucid = $contact['id'];
510 $pcid = $contact['id'];
511 $ucid = Contact::getIdForURL($contact['url'], $uid);
514 return ['public' => $pcid, 'user' => $ucid];
518 * Returns contact details for a given contact id in combination with a user id
520 * @param int $cid A contact ID
521 * @param int $uid The User ID
522 * @param array $fields The selected fields for the contact
524 * @return array The contact details
528 public static function getContactForUser($cid, $uid, array $fields = [])
530 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
532 if (!DBA::isResult($contact)) {
540 * Creates the self-contact for the provided user id
543 * @return bool Operation success
544 * @throws HTTPException\InternalServerErrorException
546 public static function createSelfFromUserId($uid)
548 // Only create the entry if it doesn't exist yet
549 if (DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
553 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
554 if (!DBA::isResult($user)) {
558 $return = DBA::insert('contact', [
559 'uid' => $user['uid'],
560 'created' => DateTimeFormat::utcNow(),
562 'name' => $user['username'],
563 'nick' => $user['nickname'],
564 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
565 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
566 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
569 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
570 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
571 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
572 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
573 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
574 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
575 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
576 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
577 'name-date' => DateTimeFormat::utcNow(),
578 'uri-date' => DateTimeFormat::utcNow(),
579 'avatar-date' => DateTimeFormat::utcNow(),
587 * Updates the self-contact for the provided user id
590 * @param boolean $update_avatar Force the avatar update
591 * @throws HTTPException\InternalServerErrorException
593 public static function updateSelfFromUserID($uid, $update_avatar = false)
595 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar',
596 'xmpp', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
597 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco'];
598 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
599 if (!DBA::isResult($self)) {
603 $fields = ['nickname', 'page-flags', 'account-type'];
604 $user = DBA::selectFirst('user', $fields, ['uid' => $uid]);
605 if (!DBA::isResult($user)) {
609 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
610 'country-name', 'pub_keywords', 'xmpp', 'net-publish'];
611 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
612 if (!DBA::isResult($profile)) {
616 $file_suffix = 'jpg';
618 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
619 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
620 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
621 'contact-type' => $user['account-type'],
622 'xmpp' => $profile['xmpp']];
624 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
625 if (DBA::isResult($avatar)) {
626 if ($update_avatar) {
627 $fields['avatar-date'] = DateTimeFormat::utcNow();
630 // Creating the path to the avatar, beginning with the file suffix
631 $types = Images::supportedTypes();
632 if (isset($types[$avatar['type']])) {
633 $file_suffix = $types[$avatar['type']];
636 // We are adding a timestamp value so that other systems won't use cached content
637 $timestamp = strtotime($fields['avatar-date']);
639 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
640 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
642 $fields['photo'] = $prefix . '4' . $suffix;
643 $fields['thumb'] = $prefix . '5' . $suffix;
644 $fields['micro'] = $prefix . '6' . $suffix;
646 // We hadn't found a photo entry, so we use the default avatar
647 $fields['photo'] = DI::baseUrl() . '/images/person-300.jpg';
648 $fields['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
649 $fields['micro'] = DI::baseUrl() . '/images/person-48.jpg';
652 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
653 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
654 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
655 $fields['unsearchable'] = !$profile['net-publish'];
657 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
658 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
659 $fields['nurl'] = Strings::normaliseLink($fields['url']);
660 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
661 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
662 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
663 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
664 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
665 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
669 foreach ($fields as $field => $content) {
670 if ($self[$field] != $content) {
676 if ($fields['name'] != $self['name']) {
677 $fields['name-date'] = DateTimeFormat::utcNow();
679 $fields['updated'] = DateTimeFormat::utcNow();
680 DBA::update('contact', $fields, ['id' => $self['id']]);
682 // Update the public contact as well
683 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
685 // Update the profile
686 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
687 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
688 DBA::update('profile', $fields, ['uid' => $uid]);
693 * Marks a contact for removal
695 * @param int $id contact id
697 * @throws HTTPException\InternalServerErrorException
699 public static function remove($id)
701 // We want just to make sure that we don't delete our "self" contact
702 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
703 if (!DBA::isResult($contact) || !intval($contact['uid'])) {
707 // Archive the contact
708 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
710 // Delete it in the background
711 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
715 * Sends an unfriend message. Does not remove the contact
717 * @param array $user User unfriending
718 * @param array $contact Contact unfriended
719 * @param boolean $dissolve Remove the contact on the remote side
721 * @throws HTTPException\InternalServerErrorException
722 * @throws \ImagickException
724 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
726 if (empty($contact['network'])) {
730 $protocol = $contact['network'];
731 if (($protocol == Protocol::DFRN) && !self::isLegacyDFRNContact($contact)) {
732 $protocol = Protocol::ACTIVITYPUB;
735 if (($protocol == Protocol::DFRN) && $dissolve) {
736 DFRN::deliver($user, $contact, 'placeholder', true);
737 } elseif (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
738 // create an unfollow slap
740 $item['verb'] = Activity::O_UNFOLLOW;
741 $item['gravity'] = GRAVITY_ACTIVITY;
742 $item['follow'] = $contact["url"];
747 $item['attach'] = '';
748 $slap = OStatus::salmon($item, $user);
750 if (!empty($contact['notify'])) {
751 Salmon::slapper($user, $contact['notify'], $slap);
753 } elseif ($protocol == Protocol::DIASPORA) {
754 Diaspora::sendUnshare($user, $contact);
755 } elseif ($protocol == Protocol::ACTIVITYPUB) {
756 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
759 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
765 * Marks a contact for archival after a communication issue delay
767 * Contact has refused to recognise us as a friend. We will start a countdown.
768 * If they still don't recognise us in 32 days, the relationship is over,
769 * and we won't waste any more time trying to communicate with them.
770 * This provides for the possibility that their database is temporarily messed
771 * up or some other transient event and that there's a possibility we could recover from it.
773 * @param array $contact contact to mark for archival
775 * @throws HTTPException\InternalServerErrorException
777 public static function markForArchival(array $contact)
779 if (!isset($contact['url']) && !empty($contact['id'])) {
780 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
781 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
782 if (!DBA::isResult($contact)) {
785 } elseif (!isset($contact['url'])) {
786 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
789 Logger::info('Contact is marked for archival', ['id' => $contact['id']]);
791 // Contact already archived or "self" contact? => nothing to do
792 if ($contact['archive'] || $contact['self']) {
796 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
797 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
798 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
801 * We really should send a notification to the owner after 2-3 weeks
802 * so they won't be surprised when the contact vanishes and can take
803 * remedial action if this was a serious mistake or glitch
806 /// @todo Check for contact vitality via probing
807 $archival_days = DI::config()->get('system', 'archival_days', 32);
809 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
810 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
811 /* Relationship is really truly dead. archive them rather than
812 * delete, though if the owner tries to unarchive them we'll start
813 * the whole process over again.
815 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
816 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
822 * Cancels the archival countdown
824 * @see Contact::markForArchival()
826 * @param array $contact contact to be unmarked for archival
830 public static function unmarkForArchival(array $contact)
832 // Always unarchive the relay contact entry
833 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
834 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
835 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
836 DBA::update('contact', $fields, $condition);
839 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
840 $exists = DBA::exists('contact', $condition);
842 // We don't need to update, we never marked this contact for archival
847 Logger::info('Contact is marked as vital again', ['id' => $contact['id']]);
849 if (!isset($contact['url']) && !empty($contact['id'])) {
850 $fields = ['id', 'url', 'batch'];
851 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
852 if (!DBA::isResult($contact)) {
857 // It's a miracle. Our dead contact has inexplicably come back to life.
858 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
859 DBA::update('contact', $fields, ['id' => $contact['id']]);
860 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
864 * Returns the data array for the photo menu of a given contact
866 * @param array $contact contact
867 * @param int $uid optional, default 0
869 * @throws HTTPException\InternalServerErrorException
870 * @throws \ImagickException
872 public static function photoMenu(array $contact, $uid = 0)
877 $contact_drop_link = '';
884 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
886 $profile_link = self::magicLink($contact['url']);
887 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
892 // Look for our own contact if the uid doesn't match and isn't public
893 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
894 if (DBA::isResult($contact_own)) {
895 return self::photoMenu($contact_own, $uid);
900 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
902 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
904 $profile_link = $contact['url'];
907 if ($profile_link === 'mailbox') {
912 $status_link = $profile_link . '/status';
913 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
914 $profile_link = $profile_link . '/profile';
917 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
918 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
921 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
922 $poke_link = 'contact/' . $contact['id'] . '/poke';
925 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
927 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
929 if (!$contact['self']) {
930 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
935 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
936 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
937 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']);
938 } elseif(!$contact['pending']) {
939 $follow_link = 'follow?url=' . urlencode($contact['url']);
943 if (!empty($follow_link) || !empty($unfollow_link)) {
944 $contact_drop_link = '';
949 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
951 if (empty($contact['uid'])) {
953 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
954 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
955 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
956 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
957 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
961 'status' => [DI::l10n()->t('View Status') , $status_link , true],
962 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
963 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
964 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
965 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
966 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
967 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
968 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
969 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
970 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
973 if (!empty($contact['pending'])) {
974 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
975 if (DBA::isResult($intro)) {
976 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
981 $args = ['contact' => $contact, 'menu' => &$menu];
983 Hook::callAll('contact_photo_menu', $args);
987 foreach ($menu as $menuname => $menuitem) {
988 if ($menuitem[1] != '') {
989 $menucondensed[$menuname] = $menuitem;
993 return $menucondensed;
997 * Fetch the contact id for a given URL and user
999 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1000 * `addr` or `alias`.
1002 * If there's no record and we aren't looking for a public contact, we quit.
1003 * If there's one, we check that it isn't time to update the picture else we
1004 * directly return the found contact id.
1006 * Second, we probe the provided $url whether it's http://server.tld/profile or
1007 * nick@server.tld. We quit if we can't get any info back.
1009 * Third, we create the contact record if it doesn't exist
1011 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1012 * if there's any updates
1014 * @param string $url Contact URL
1015 * @param integer $uid The user id for the contact (0 = public contact)
1016 * @param boolean $update true = always update, false = never update, null = update when not found
1017 * @param array $default Default value for creating the contact when everything else fails
1019 * @return integer Contact ID
1020 * @throws HTTPException\InternalServerErrorException
1021 * @throws \ImagickException
1023 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1028 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1032 $contact = self::getByURL($url, false, ['id', 'network'], $uid);
1034 if (!empty($contact)) {
1035 $contact_id = $contact["id"];
1037 if (empty($update)) {
1038 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1041 } elseif ($uid != 0) {
1042 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1044 } elseif (empty($default) && !is_null($update) && !$update) {
1045 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1051 if (empty($default['network']) || $update) {
1052 $data = Probe::uri($url, "", $uid);
1054 // Take the default values when probing failed
1055 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1056 $data = array_merge($data, $default);
1058 } elseif (!empty($default['network'])) {
1062 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1063 // Fetch data for the public contact via the first found personal contact
1064 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1065 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'contact-type',
1066 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1067 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1069 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1070 if (!DBA::isResult($personal_contact)) {
1071 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1074 if (DBA::isResult($personal_contact)) {
1075 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1076 $data = $personal_contact;
1077 $data['photo'] = $personal_contact['avatar'];
1078 $data['account-type'] = $personal_contact['contact-type'];
1079 $data['hide'] = $personal_contact['unsearchable'];
1080 unset($data['avatar']);
1081 unset($data['contact-type']);
1082 unset($data['unsearchable']);
1086 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1087 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1092 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1093 if (!empty($data['alias'])) {
1094 $urls[] = Strings::normaliseLink($data['alias']);
1096 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1097 if (!empty($contact['id'])) {
1098 $contact_id = $contact['id'];
1099 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'probed_url' => $data['url'], 'alias' => $data['alias'], 'addr' => $data['addr']]);
1104 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1107 'url' => $data['url'],
1108 'nurl' => Strings::normaliseLink($data['url']),
1109 'network' => $data['network'],
1110 'created' => DateTimeFormat::utcNow(),
1111 'rel' => self::SHARING,
1117 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1119 // Before inserting we do check if the entry does exist now.
1120 DBA::lock('contact');
1121 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1122 if (DBA::isResult($contact)) {
1123 $contact_id = $contact['id'];
1124 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1126 DBA::insert('contact', $fields);
1127 $contact_id = DBA::lastInsertId();
1129 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1134 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1138 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1141 self::updateFromProbeArray($contact_id, $data);
1147 * Checks if the contact is archived
1149 * @param int $cid contact id
1151 * @return boolean Is the contact archived?
1152 * @throws HTTPException\InternalServerErrorException
1154 public static function isArchived(int $cid)
1160 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1161 if (!DBA::isResult($contact)) {
1165 if ($contact['archive']) {
1169 // Check status of ActivityPub endpoints
1170 $apcontact = APContact::getByURL($contact['url'], false);
1171 if (!empty($apcontact)) {
1172 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1176 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1181 // Check status of Diaspora endpoints
1182 if (!empty($contact['batch'])) {
1183 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1184 return DBA::exists('contact', $condition);
1191 * Checks if the contact is blocked
1193 * @param int $cid contact id
1195 * @return boolean Is the contact blocked?
1196 * @throws HTTPException\InternalServerErrorException
1198 public static function isBlocked($cid)
1204 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1205 if (!DBA::isResult($blocked)) {
1209 if (Network::isUrlBlocked($blocked['url'])) {
1213 return (bool) $blocked['blocked'];
1217 * Checks if the contact is hidden
1219 * @param int $cid contact id
1221 * @return boolean Is the contact hidden?
1222 * @throws \Exception
1224 public static function isHidden($cid)
1230 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1231 if (!DBA::isResult($hidden)) {
1234 return (bool) $hidden['hidden'];
1238 * Returns posts from a given contact url
1240 * @param string $contact_url Contact URL
1241 * @param bool $thread_mode
1242 * @param int $update
1243 * @return string posts in HTML
1244 * @throws \Exception
1246 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0)
1248 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update);
1252 * Returns posts from a given contact id
1254 * @param integer $cid
1255 * @param bool $thread_mode
1256 * @param integer $update
1257 * @return string posts in HTML
1258 * @throws \Exception
1260 public static function getPostsFromId($cid, $thread_mode = false, $update = 0)
1264 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1265 if (!DBA::isResult($contact)) {
1269 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1270 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
1272 $sql = "`item`.`uid` = ?";
1275 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1278 $condition = ["`$contact_field` = ? AND (`gravity` = ? OR (`gravity` = ? AND `vid` = ?)) AND " . $sql,
1279 $cid, GRAVITY_PARENT, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1281 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1282 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1285 if (DI::mode()->isMobile()) {
1286 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1287 DI::config()->get('system', 'itemspage_network_mobile'));
1289 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1290 DI::config()->get('system', 'itemspage_network'));
1293 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1295 $params = ['order' => ['received' => true],
1296 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1299 $r = Item::selectForUser(local_user(), ['uri', 'gravity', 'parent-uri'], $condition, $params);
1301 while ($item = DBA::fetch($r)) {
1302 if ($item['gravity'] != GRAVITY_PARENT) {
1303 $item['uri'] = $item['parent-uri'];
1305 unset($item['parent-uri']);
1306 unset($item['gravity']);
1312 $o = conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1314 $r = Item::selectForUser(local_user(), [], $condition, $params);
1316 $items = Item::inArray($r);
1318 $o = conversation($a, $items, 'contact-posts', false);
1322 $o .= $pager->renderMinimal(count($items));
1329 * Returns the account type name
1331 * The function can be called with either the user or the contact array
1333 * @param array $contact contact or user array
1336 public static function getAccountType(array $contact)
1338 // There are several fields that indicate that the contact or user is a forum
1339 // "page-flags" is a field in the user table,
1340 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1341 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1342 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1343 || (isset($contact['forum']) && intval($contact['forum']))
1344 || (isset($contact['prv']) && intval($contact['prv']))
1345 || (isset($contact['community']) && intval($contact['community']))
1347 $type = self::TYPE_COMMUNITY;
1349 $type = self::TYPE_PERSON;
1352 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1353 if (isset($contact["contact-type"])) {
1354 $type = $contact["contact-type"];
1357 if (isset($contact["account-type"])) {
1358 $type = $contact["account-type"];
1362 case self::TYPE_ORGANISATION:
1363 $account_type = DI::l10n()->t("Organisation");
1366 case self::TYPE_NEWS:
1367 $account_type = DI::l10n()->t('News');
1370 case self::TYPE_COMMUNITY:
1371 $account_type = DI::l10n()->t("Forum");
1379 return $account_type;
1387 * @throws \Exception
1389 public static function block($cid, $reason = null)
1391 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1397 * Unblocks a contact
1401 * @throws \Exception
1403 public static function unblock($cid)
1405 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1411 * Ensure that cached avatar exist
1413 * @param integer $cid
1415 public static function checkAvatarCache(int $cid)
1417 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1418 if (!DBA::isResult($contact)) {
1422 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1426 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1428 self::updateAvatar($cid, $contact['avatar'], true);
1432 * Return the photo path for a given contact array in the given size
1434 * @param array $contact contact array
1435 * @param string $field Fieldname of the photo in the contact array
1436 * @param string $default Default path when no picture had been found
1437 * @param string $size Size of the avatar picture
1438 * @param string $avatar Avatar path that is displayed when no photo had been found
1439 * @return string photo path
1441 private static function getAvatarPath(array $contact, string $field, string $default, string $size, string $avatar)
1443 if (!empty($contact)) {
1444 $contact = self::checkAvatarCacheByArray($contact);
1445 if (!empty($contact[$field])) {
1446 $avatar = $contact[$field];
1450 if (empty($avatar)) {
1454 if (Proxy::isLocalImage($avatar)) {
1457 return Proxy::proxifyUrl($avatar, false, $size);
1462 * Return the photo path for a given contact array
1464 * @param array $contact Contact array
1465 * @param string $avatar Avatar path that is displayed when no photo had been found
1466 * @return string photo path
1468 public static function getPhoto(array $contact, string $avatar = '')
1470 return self::getAvatarPath($contact, 'photo', DI::baseUrl() . '/images/person-300.jpg', Proxy::SIZE_SMALL, $avatar);
1474 * Return the photo path (thumb size) for a given contact array
1476 * @param array $contact Contact array
1477 * @param string $avatar Avatar path that is displayed when no photo had been found
1478 * @return string photo path
1480 public static function getThumb(array $contact, string $avatar = '')
1482 return self::getAvatarPath($contact, 'thumb', DI::baseUrl() . '/images/person-80.jpg', Proxy::SIZE_THUMB, $avatar);
1486 * Return the photo path (micro size) 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 getMicro(array $contact, string $avatar = '')
1494 return self::getAvatarPath($contact, 'micro', DI::baseUrl() . '/images/person-48.jpg', Proxy::SIZE_MICRO, $avatar);
1498 * Check the given contact array for avatar cache fields
1500 * @param array $contact
1501 * @return array contact array with avatar cache fields
1503 private static function checkAvatarCacheByArray(array $contact)
1506 $contact_fields = [];
1507 $fields = ['photo', 'thumb', 'micro'];
1508 foreach ($fields as $field) {
1509 if (isset($contact[$field])) {
1510 $contact_fields[] = $field;
1512 if (isset($contact[$field]) && empty($contact[$field])) {
1521 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1522 self::updateAvatar($contact['id'], $contact['avatar'], true);
1524 $new_contact = self::getById($contact['id'], $contact_fields);
1525 if (DBA::isResult($new_contact)) {
1526 // We only update the cache fields
1527 $contact = array_merge($contact, $new_contact);
1531 /// add the default avatars if the fields aren't filled
1532 if (isset($contact['photo']) && empty($contact['photo'])) {
1533 $contact['photo'] = DI::baseUrl() . '/images/person-300.jpg';
1535 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1536 $contact['thumb'] = DI::baseUrl() . '/images/person-80.jpg';
1538 if (isset($contact['micro']) && empty($contact['micro'])) {
1539 $contact['micro'] = DI::baseUrl() . '/images/person-48.jpg';
1546 * Updates the avatar links in a contact only if needed
1548 * @param int $cid Contact id
1549 * @param string $avatar Link to avatar picture
1550 * @param bool $force force picture update
1553 * @throws HTTPException\InternalServerErrorException
1554 * @throws HTTPException\NotFoundException
1555 * @throws \ImagickException
1557 public static function updateAvatar(int $cid, string $avatar, bool $force = false)
1559 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid, 'self' => false]);
1560 if (!DBA::isResult($contact)) {
1564 $uid = $contact['uid'];
1566 // Only update the cached photo links of public contacts when they already are cached
1567 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro'])) {
1568 if ($contact['avatar'] != $avatar) {
1569 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1570 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1576 $contact['photo'] ?? '',
1577 $contact['thumb'] ?? '',
1578 $contact['micro'] ?? '',
1581 $update = ($contact['avatar'] != $avatar) || $force;
1584 foreach ($data as $image_uri) {
1585 $image_rid = Photo::ridFromURI($image_uri);
1586 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1587 Logger::info('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1594 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1596 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1597 DBA::update('contact', $fields, ['id' => $cid]);
1598 } elseif (empty($contact['avatar'])) {
1599 // Ensure that the avatar field is set
1600 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1601 Logger::info('Failed profile import', ['id' => $cid, 'force' => $force, 'avatar' => $avatar, 'contact' => $contact]);
1607 * Helper function for "updateFromProbe". Updates personal and public contact
1609 * @param integer $id contact id
1610 * @param integer $uid user id
1611 * @param string $url The profile URL of the contact
1612 * @param array $fields The fields that are updated
1614 * @throws \Exception
1616 private static function updateContact($id, $uid, $url, array $fields)
1618 if (!DBA::update('contact', $fields, ['id' => $id])) {
1619 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1623 // Search for duplicated contacts and get rid of them
1624 if (self::removeDuplicates(Strings::normaliseLink($url), $uid) || ($uid != 0)) {
1628 // Archive or unarchive the contact. We only need to do this for the public contact.
1629 // The archive/unarchive function will update the personal contacts by themselves.
1630 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1631 if (!DBA::isResult($contact)) {
1632 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1636 if (!empty($fields['success_update'])) {
1637 self::unmarkForArchival($contact);
1638 } elseif (!empty($fields['failure_update'])) {
1639 self::markForArchival($contact);
1642 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url), 'network' => Protocol::FEDERATED];
1644 // These contacts are sharing with us, we don't poll them.
1645 // This means that we don't set the update fields in "OnePoll.php".
1646 $condition['rel'] = self::SHARING;
1647 DBA::update('contact', $fields, $condition);
1649 unset($fields['last-update']);
1650 unset($fields['success_update']);
1651 unset($fields['failure_update']);
1653 if (empty($fields)) {
1657 // We are polling these contacts, so we mustn't set the update fields here.
1658 $condition['rel'] = [self::FOLLOWER, self::FRIEND];
1659 DBA::update('contact', $fields, $condition);
1663 * Remove duplicated contacts
1665 * @param string $nurl Normalised contact url
1666 * @param integer $uid User id
1668 * @throws \Exception
1670 public static function removeDuplicates(string $nurl, int $uid)
1672 $condition = ['nurl' => $nurl, 'uid' => $uid, 'deleted' => false, 'network' => Protocol::FEDERATED];
1673 $count = DBA::count('contact', $condition);
1678 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
1679 if (!DBA::isResult($first_contact)) {
1680 // Shouldn't happen - so we handle it
1684 $first = $first_contact['id'];
1685 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
1686 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
1687 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
1688 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
1692 // Find all duplicates
1693 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
1694 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
1695 while ($duplicate = DBA::fetch($duplicates)) {
1696 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
1700 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
1702 DBA::close($duplicates);
1703 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
1708 * @param integer $id contact id
1709 * @param string $network Optional network we are probing for
1711 * @throws HTTPException\InternalServerErrorException
1712 * @throws \ImagickException
1714 public static function updateFromProbe(int $id, string $network = '')
1716 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
1717 if (!DBA::isResult($contact)) {
1721 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
1722 return self::updateFromProbeArray($id, $ret);
1726 * @param integer $id contact id
1727 * @param array $ret Probed data
1729 * @throws HTTPException\InternalServerErrorException
1730 * @throws \ImagickException
1732 private static function updateFromProbeArray(int $id, array $ret)
1735 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1736 This will reliably kill your communication with old Friendica contacts.
1739 // These fields aren't updated by this routine:
1740 // 'xmpp', 'sensitive'
1742 $fields = ['uid', 'avatar', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
1743 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
1744 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item'];
1745 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
1746 if (!DBA::isResult($contact)) {
1750 $uid = $contact['uid'];
1751 unset($contact['uid']);
1753 $pubkey = $contact['pubkey'];
1754 unset($contact['pubkey']);
1756 $contact['photo'] = $contact['avatar'];
1757 unset($contact['avatar']);
1759 $updated = DateTimeFormat::utcNow();
1761 // We must not try to update relay contacts via probe. They are no real contacts.
1762 // We check after the probing to be able to correct falsely detected contact types.
1763 if (($contact['contact-type'] == self::TYPE_RELAY) &&
1764 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
1765 self::updateContact($id, $uid, $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1766 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
1770 // If Probe::uri fails the network code will be different ("feed" or "unkn")
1771 if (in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]) && ($ret['network'] != $contact['network'])) {
1773 self::updateContact($id, $uid, $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
1778 if (Contact\Relation::isDiscoverable($ret['url'])) {
1779 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
1782 if (isset($ret['hide']) && is_bool($ret['hide'])) {
1783 $ret['unsearchable'] = $ret['hide'];
1786 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
1787 $ret['forum'] = false;
1788 $ret['prv'] = false;
1789 $ret['contact-type'] = $ret['account-type'];
1790 if ($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1791 $apcontact = APContact::getByURL($ret['url'], false);
1792 if (isset($apcontact['manually-approve'])) {
1793 $ret['forum'] = (bool)!$apcontact['manually-approve'];
1794 $ret['prv'] = (bool)!$ret['forum'];
1799 $new_pubkey = $ret['pubkey'] ?? '';
1802 $ret['last-item'] = Probe::getLastUpdate($ret);
1803 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
1808 // make sure to not overwrite existing values with blank entries except some technical fields
1809 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
1810 foreach ($ret as $key => $val) {
1811 if (!array_key_exists($key, $contact)) {
1813 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
1814 $ret[$key] = $contact[$key];
1815 } elseif ($ret[$key] != $contact[$key]) {
1820 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
1823 unset($ret['last-item']);
1826 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
1827 self::updateAvatar($id, $ret['photo'], $update);
1831 self::updateContact($id, $uid, $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
1833 // Update the public contact
1835 $contact = self::getByURL($ret['url'], false, ['id']);
1836 if (!empty($contact['id'])) {
1837 self::updateFromProbeArray($contact['id'], $ret);
1844 $ret['nurl'] = Strings::normaliseLink($ret['url']);
1845 $ret['updated'] = $updated;
1847 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
1848 if (empty($pubkey) && !empty($new_pubkey)) {
1849 $ret['pubkey'] = $new_pubkey;
1852 if (($ret['addr'] != $contact['addr']) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
1853 $ret['uri-date'] = DateTimeFormat::utcNow();
1856 if (($ret['name'] != $contact['name']) || ($ret['nick'] != $contact['nick'])) {
1857 $ret['name-date'] = $updated;
1861 $ret['last-update'] = $updated;
1862 $ret['success_update'] = $updated;
1863 $ret['failed'] = false;
1866 unset($ret['photo']);
1868 self::updateContact($id, $uid, $ret['url'], $ret);
1874 * @param integer $url contact url
1875 * @return integer Contact id
1876 * @throws HTTPException\InternalServerErrorException
1877 * @throws \ImagickException
1879 public static function updateFromProbeByURL($url)
1881 $id = self::getIdForURL($url);
1887 self::updateFromProbe($id);
1893 * Detects if a given contact array belongs to a legacy DFRN connection
1895 * @param array $contact
1898 public static function isLegacyDFRNContact($contact)
1900 // Newer Friendica contacts are connected via AP, then these fields aren't set
1901 return !empty($contact['dfrn-id']) || !empty($contact['issued-id']);
1905 * Detects the communication protocol for a given contact url.
1906 * This is used to detect Friendica contacts that we can communicate via AP.
1908 * @param string $url contact url
1909 * @param string $network Network of that contact
1910 * @return string with protocol
1912 public static function getProtocol($url, $network)
1914 if ($network != Protocol::DFRN) {
1918 $apcontact = APContact::getByURL($url);
1919 if (!empty($apcontact) && !empty($apcontact['generator'])) {
1920 return Protocol::ACTIVITYPUB;
1927 * Takes a $uid and a url/handle and adds a new contact
1929 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1930 * dfrn_request page.
1932 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1935 * $return['success'] boolean true if successful
1936 * $return['message'] error text if success is false.
1938 * Takes a $uid and a url/handle and adds a new contact
1940 * @param array $user The user the contact should be created for
1941 * @param string $url The profile URL of the contact
1942 * @param bool $interactive
1943 * @param string $network
1945 * @throws HTTPException\InternalServerErrorException
1946 * @throws HTTPException\NotFoundException
1947 * @throws \ImagickException
1949 public static function createFromProbe(array $user, $url, $interactive = false, $network = '')
1951 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1953 // remove ajax junk, e.g. Twitter
1954 $url = str_replace('/#!/', '/', $url);
1956 if (!Network::isUrlAllowed($url)) {
1957 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
1961 if (Network::isUrlBlocked($url)) {
1962 $result['message'] = DI::l10n()->t('Blocked domain');
1967 $result['message'] = DI::l10n()->t('Connect URL missing.');
1971 $arr = ['url' => $url, 'contact' => []];
1973 Hook::callAll('follow', $arr);
1976 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
1980 if (!empty($arr['contact']['name'])) {
1981 $ret = $arr['contact'];
1983 $ret = Probe::uri($url, $network, $user['uid']);
1986 if (($network != '') && ($ret['network'] != $network)) {
1987 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1991 // check if we already have a contact
1992 // the poll url is more reliable than the profile url, as we may have
1993 // indirect links or webfinger links
1995 $condition = ['uid' => $user['uid'], 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
1996 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
1997 if (!DBA::isResult($contact)) {
1998 $condition = ['uid' => $user['uid'], 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
1999 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2002 $protocol = self::getProtocol($ret['url'], $ret['network']);
2004 if (($protocol === Protocol::DFRN) && !DBA::isResult($contact)) {
2006 if (strlen(DI::baseUrl()->getUrlPath())) {
2007 $myaddr = bin2hex(DI::baseUrl() . '/profile/' . $user['nickname']);
2009 $myaddr = bin2hex($user['nickname'] . '@' . DI::baseUrl()->getHostname());
2012 DI::baseUrl()->redirect($ret['request'] . "&addr=$myaddr");
2016 } elseif (DI::config()->get('system', 'dfrn_only') && ($ret['network'] != Protocol::DFRN)) {
2017 $result['message'] = DI::l10n()->t('This site is not configured to allow communications with other networks.') . EOL;
2018 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2022 // This extra param just confuses things, remove it
2023 if ($protocol === Protocol::DIASPORA) {
2024 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2027 // do we have enough information?
2028 if (empty($ret['name']) || empty($ret['poll']) || (empty($ret['url']) && empty($ret['addr']))) {
2029 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2030 if (empty($ret['poll'])) {
2031 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2033 if (empty($ret['name'])) {
2034 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2036 if (empty($ret['url'])) {
2037 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2039 if (strpos($ret['url'], '@') !== false) {
2040 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2041 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2046 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2047 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2048 $ret['notify'] = '';
2051 if (!$ret['notify']) {
2052 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2055 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2057 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2059 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2062 if ($protocol == Protocol::ACTIVITYPUB) {
2063 $apcontact = APContact::getByURL($ret['url'], false);
2064 if (isset($apcontact['manually-approve'])) {
2065 $pending = (bool)$apcontact['manually-approve'];
2069 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2073 if (DBA::isResult($contact)) {
2075 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2077 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2078 DBA::update('contact', $fields, ['id' => $contact['id']]);
2080 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2082 // create contact record
2084 'uid' => $user['uid'],
2085 'created' => DateTimeFormat::utcNow(),
2086 'url' => $ret['url'],
2087 'nurl' => Strings::normaliseLink($ret['url']),
2088 'addr' => $ret['addr'],
2089 'alias' => $ret['alias'],
2090 'batch' => $ret['batch'],
2091 'notify' => $ret['notify'],
2092 'poll' => $ret['poll'],
2093 'poco' => $ret['poco'],
2094 'name' => $ret['name'],
2095 'nick' => $ret['nick'],
2096 'network' => $ret['network'],
2097 'baseurl' => $ret['baseurl'],
2098 'gsid' => $ret['gsid'] ?? null,
2099 'protocol' => $protocol,
2100 'pubkey' => $ret['pubkey'],
2101 'rel' => $new_relation,
2102 'priority'=> $ret['priority'],
2103 'writable'=> $writeable,
2104 'hidden' => $hidden,
2107 'pending' => $pending,
2112 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $user['uid']]);
2113 if (!DBA::isResult($contact)) {
2114 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2118 $contact_id = $contact['id'];
2119 $result['cid'] = $contact_id;
2121 Group::addMember(User::getDefaultGroup($user['uid'], $contact["network"]), $contact_id);
2123 // Update the avatar
2124 self::updateAvatar($contact_id, $ret['photo']);
2126 // pull feed and consume it, which should subscribe to the hub.
2128 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
2130 $owner = User::getOwnerDataById($user['uid']);
2132 if (DBA::isResult($owner)) {
2133 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2134 // create a follow slap
2136 $item['verb'] = Activity::FOLLOW;
2137 $item['gravity'] = GRAVITY_ACTIVITY;
2138 $item['follow'] = $contact["url"];
2140 $item['title'] = '';
2142 $item['uri-id'] = 0;
2143 $item['attach'] = '';
2145 $slap = OStatus::salmon($item, $owner);
2147 if (!empty($contact['notify'])) {
2148 Salmon::slapper($owner, $contact['notify'], $slap);
2150 } elseif ($protocol == Protocol::DIASPORA) {
2151 $ret = Diaspora::sendShare($owner, $contact);
2152 Logger::log('share returns: ' . $ret);
2153 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2154 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2155 if (empty($activity_id)) {
2156 // This really should never happen
2160 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $user['uid'], $activity_id);
2161 Logger::log('Follow returns: ' . $ret);
2165 $result['success'] = true;
2170 * Updated contact's SSL policy
2172 * @param array $contact Contact array
2173 * @param string $new_policy New policy, valid: self,full
2175 * @return array Contact array with updated values
2176 * @throws \Exception
2178 public static function updateSslPolicy(array $contact, $new_policy)
2180 $ssl_changed = false;
2181 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2182 $ssl_changed = true;
2183 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2184 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2185 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2186 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2187 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2188 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2191 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2192 $ssl_changed = true;
2193 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2194 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2195 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2196 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2197 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2198 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2202 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2203 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2204 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2205 DBA::update('contact', $fields, ['id' => $contact['id']]);
2212 * @param array $importer Owner (local user) data
2213 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2214 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2215 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2216 * @param string $note Introduction additional message
2217 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2218 * @throws HTTPException\InternalServerErrorException
2219 * @throws \ImagickException
2221 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2223 // Should always be set
2224 if (empty($datarray['author-id'])) {
2228 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2229 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2230 if (!DBA::isResult($pub_contact)) {
2231 // Should never happen
2235 // Contact is blocked at node-level
2236 if (self::isBlocked($datarray['author-id'])) {
2240 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2241 $name = $pub_contact['name'];
2242 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2243 $nick = $pub_contact['nick'];
2244 $network = $pub_contact['network'];
2246 // Ensure that we don't create a new contact when there already is one
2247 $cid = self::getIdForURL($url, $importer['uid']);
2249 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2252 if (!empty($contact)) {
2253 if (!empty($contact['pending'])) {
2254 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2258 // Contact is blocked at user-level
2259 if (!empty($contact['id']) && !empty($importer['id']) &&
2260 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2264 // Make sure that the existing contact isn't archived
2265 self::unmarkForArchival($contact);
2267 if (($contact['rel'] == self::SHARING)
2268 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2269 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2270 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2273 // Ensure to always have the correct network type, independent from the connection request method
2274 self::updateFromProbe($contact['id']);
2278 // send email notification to owner?
2279 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2280 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2284 // create contact record
2285 DBA::insert('contact', [
2286 'uid' => $importer['uid'],
2287 'created' => DateTimeFormat::utcNow(),
2289 'nurl' => Strings::normaliseLink($url),
2292 'network' => $network,
2293 'rel' => self::FOLLOWER,
2300 $contact_id = DBA::lastInsertId();
2302 // Ensure to always have the correct network type, independent from the connection request method
2303 self::updateFromProbe($contact_id);
2305 self::updateAvatar($contact_id, $photo, true);
2307 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2309 /// @TODO Encapsulate this into a function/method
2310 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2311 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2312 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2313 // create notification
2314 $hash = Strings::getRandomHex();
2316 if (is_array($contact_record)) {
2317 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2318 'blocked' => false, 'knowyou' => false, 'note' => $note,
2319 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2322 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2324 if (($user['notify-flags'] & Type::INTRO) &&
2325 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2328 'type' => Type::INTRO,
2329 'notify_flags' => $user['notify-flags'],
2330 'language' => $user['language'],
2331 'to_name' => $user['username'],
2332 'to_email' => $user['email'],
2333 'uid' => $user['uid'],
2334 'link' => DI::baseUrl() . '/notifications/intros',
2335 'source_name' => ((strlen(stripslashes($contact_record['name']))) ? stripslashes($contact_record['name']) : DI::l10n()->t('[Name Withheld]')),
2336 'source_link' => $contact_record['url'],
2337 'source_photo' => $contact_record['photo'],
2338 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2342 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2343 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2344 self::createFromProbe($importer, $url, false, $network);
2347 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2348 $fields = ['pending' => false];
2349 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2350 $fields['rel'] = Contact::FRIEND;
2353 DBA::update('contact', $fields, $condition);
2362 public static function removeFollower($importer, $contact, array $datarray = [], $item = "")
2364 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2365 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2367 Contact::remove($contact['id']);
2371 public static function removeSharer($importer, $contact, array $datarray = [], $item = "")
2373 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2374 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2376 Contact::remove($contact['id']);
2381 * Create a birthday event.
2383 * Update the year and the birthday.
2385 public static function updateBirthdays()
2389 AND `bd` > "0001-01-01"
2390 AND SUBSTRING(`bd`, 1, 4) != `bdyear`
2391 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2392 AND NOT `contact`.`pending`
2393 AND NOT `contact`.`hidden`
2394 AND NOT `contact`.`blocked`
2395 AND NOT `contact`.`archive`
2396 AND NOT `contact`.`deleted`',
2401 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2403 while ($contact = DBA::fetch($contacts)) {
2404 Logger::log('update_contact_birthday: ' . $contact['bd']);
2406 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2408 if (Event::createBirthday($contact, $nextbd)) {
2412 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2413 ['id' => $contact['id']]
2417 DBA::close($contacts);
2421 * Remove the unavailable contact ids from the provided list
2423 * @param array $contact_ids Contact id list
2425 * @throws \Exception
2427 public static function pruneUnavailable(array $contact_ids)
2429 if (empty($contact_ids)) {
2433 $contacts = Contact::selectToArray(['id'], [
2434 'id' => $contact_ids,
2440 return array_column($contacts, 'id');
2444 * Returns a magic link to authenticate remote visitors
2446 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2448 * @param string $contact_url The address of the target contact profile
2449 * @param string $url An url that we will be redirected to after the authentication
2451 * @return string with "redir" link
2452 * @throws HTTPException\InternalServerErrorException
2453 * @throws \ImagickException
2455 public static function magicLink($contact_url, $url = '')
2457 if (!Session::isAuthenticated()) {
2458 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2461 $contact = self::getByURL($contact_url, false);
2462 if (empty($contact)) {
2463 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2466 // Prevents endless loop in case only a non-public contact exists for the contact URL
2467 unset($contact['uid']);
2469 return self::magicLinkByContact($contact, $url ?: $contact_url);
2473 * Returns a magic link to authenticate remote visitors
2475 * @param integer $cid The contact id of the target contact profile
2476 * @param string $url An url that we will be redirected to after the authentication
2478 * @return string with "redir" link
2479 * @throws HTTPException\InternalServerErrorException
2480 * @throws \ImagickException
2482 public static function magicLinkbyId($cid, $url = '')
2484 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2486 return self::magicLinkByContact($contact, $url);
2490 * Returns a magic link to authenticate remote visitors
2492 * @param array $contact The contact array with "uid", "network" and "url"
2493 * @param string $url An url that we will be redirected to after the authentication
2495 * @return string with "redir" link
2496 * @throws HTTPException\InternalServerErrorException
2497 * @throws \ImagickException
2499 public static function magicLinkByContact($contact, $url = '')
2501 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2503 if (!Session::isAuthenticated() || ($contact['network'] != Protocol::DFRN)) {
2504 return $destination;
2507 // Only redirections to the same host do make sense
2508 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2512 if (!empty($contact['uid'])) {
2513 return self::magicLink($contact['url'], $url);
2516 if (empty($contact['id'])) {
2517 return $destination;
2520 $redirect = 'redir/' . $contact['id'];
2522 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2523 $redirect .= '?url=' . $url;
2530 * Is the contact a forum?
2532 * @param integer $contactid ID of the contact
2534 * @return boolean "true" if it is a forum
2536 public static function isForum($contactid)
2538 $fields = ['forum', 'prv'];
2539 $condition = ['id' => $contactid];
2540 $contact = DBA::selectFirst('contact', $fields, $condition);
2541 if (!DBA::isResult($contact)) {
2546 return ($contact['forum'] || $contact['prv']);
2550 * Can the remote contact receive private messages?
2552 * @param array $contact
2555 public static function canReceivePrivateMessages(array $contact)
2557 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2558 $self = $contact['self'] ?? false;
2560 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2564 * Search contact table by nick or name
2566 * @param string $search Name or nick
2567 * @param string $mode Search mode (e.g. "community")
2569 * @return array with search results
2570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2572 public static function searchByName($search, $mode = '')
2574 if (empty($search)) {
2578 // check supported networks
2579 if (DI::config()->get('system', 'diaspora_enabled')) {
2580 $diaspora = Protocol::DIASPORA;
2582 $diaspora = Protocol::DFRN;
2585 if (!DI::config()->get('system', 'ostatus_disabled')) {
2586 $ostatus = Protocol::OSTATUS;
2588 $ostatus = Protocol::DFRN;
2591 // check if we search only communities or every contact
2592 if ($mode === 'community') {
2593 $extra_sql = sprintf(' AND `contact-type` = %d', Contact::TYPE_COMMUNITY);
2600 $results = DBA::p("SELECT * FROM `contact`
2601 WHERE NOT `unsearchable` AND `network` IN (?, ?, ?, ?) AND
2602 NOT `failed` AND `uid` = ? AND
2603 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
2604 ORDER BY `nurl` DESC LIMIT 1000",
2605 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, 0, $search, $search, $search
2608 $contacts = DBA::toArray($results);
2613 * Add public contacts from an array
2615 * @param array $urls
2616 * @return array result "count", "added" and "updated"
2618 public static function addByUrls(array $urls)
2624 foreach ($urls as $url) {
2625 $contact = Contact::getByURL($url, false, ['id']);
2626 if (empty($contact['id'])) {
2627 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
2630 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
2636 return ['count' => $count, 'added' => $added, 'updated' => $updated];
2640 * Returns a random, global contact of the current node
2642 * @return string The profile URL
2645 public static function getRandomUrl()
2647 $r = DBA::selectFirst('contact', ['url'], [
2648 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
2649 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
2650 ], ['order' => ['RAND()']]);
2652 if (DBA::isResult($r)) {