3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\Database;
35 use Friendica\Database\DBA;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Diaspora;
42 use Friendica\Protocol\OStatus;
43 use Friendica\Protocol\Salmon;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Images;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
51 * functions for interacting with a contact
55 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
56 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
57 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
60 * @deprecated since version 2019.03
61 * @see User::PAGE_FLAGS_NORMAL
63 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
65 * @deprecated since version 2019.03
66 * @see User::PAGE_FLAGS_SOAPBOX
68 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
70 * @deprecated since version 2019.03
71 * @see User::PAGE_FLAGS_COMMUNITY
73 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
75 * @deprecated since version 2019.03
76 * @see User::PAGE_FLAGS_FREELOVE
78 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
80 * @deprecated since version 2019.03
81 * @see User::PAGE_FLAGS_BLOG
83 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
85 * @deprecated since version 2019.03
86 * @see User::PAGE_FLAGS_PRVGROUP
88 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
93 const LOCK_INSERT = 'contact-insert';
98 * TYPE_UNKNOWN - unknown type
100 * TYPE_PERSON - the account belongs to a person
101 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
103 * TYPE_ORGANISATION - the account belongs to an organisation
104 * Associated page type: PAGE_SOAPBOX
106 * TYPE_NEWS - the account is a news reflector
107 * Associated page type: PAGE_SOAPBOX
109 * TYPE_COMMUNITY - the account is community forum
110 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
112 * TYPE_RELAY - the account is a relay
113 * This will only be assigned to contacts, not to user accounts
116 const TYPE_UNKNOWN = -1;
117 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
118 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
119 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
120 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
121 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
140 const MIRROR_DEACTIVATED = 0;
141 const MIRROR_FORWARDED = 1;
142 const MIRROR_OWN_POST = 2;
143 const MIRROR_NATIVE_RESHARE = 3;
146 * @param array $fields Array of selected fields, empty for all
147 * @param array $condition Array of fields for condition
148 * @param array $params Array of several parameters
152 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
154 return DBA::selectToArray('contact', $fields, $condition, $params);
158 * @param array $fields Array of selected fields, empty for all
159 * @param array $condition Array of fields for condition
160 * @param array $params Array of several parameters
164 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
166 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
172 * Insert a row into the contact table
173 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
175 * @param array $fields field array
176 * @param int $duplicate_mode Do an update on a duplicate entry
178 * @return int id of the created contact
181 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT)
183 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
184 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
187 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
189 if (empty($fields['created'])) {
190 $fields['created'] = DateTimeFormat::utcNow();
193 DBA::insert('contact', $fields, $duplicate_mode);
194 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
195 if (!DBA::isResult($contact)) {
197 Logger::warning('Created contact could not be found', ['fields' => $fields]);
201 Contact\User::insertForContactArray($contact);
203 // Search for duplicated contacts and get rid of them
204 if (!$contact['self']) {
205 self::removeDuplicates($contact['nurl'], $contact['uid']);
208 return $contact['id'];
212 * @param integer $id Contact ID
213 * @param array $fields Array of selected fields, empty for all
214 * @return array|boolean Contact record if it exists, false otherwise
217 public static function getById($id, $fields = [])
219 return DBA::selectFirst('contact', $fields, ['id' => $id]);
223 * Fetches a contact by a given url
225 * @param string $url profile url
226 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
227 * @param array $fields Field list
228 * @param integer $uid User ID of the contact
229 * @return array contact array
231 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
233 if ($update || is_null($update)) {
234 $cid = self::getIdForURL($url, $uid, $update);
239 $contact = self::getById($cid, $fields);
240 if (empty($contact)) {
246 // Add internal fields
248 if (!empty($fields)) {
249 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
250 if (!in_array($internal, $fields)) {
251 $fields[] = $internal;
252 $removal[] = $internal;
257 // We first try the nurl (http://server.tld/nick), most common case
258 $options = ['order' => ['id']];
259 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
261 // Then the addr (nick@server.tld)
262 if (!DBA::isResult($contact)) {
263 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
266 // Then the alias (which could be anything)
267 if (!DBA::isResult($contact)) {
268 // The link could be provided as http although we stored it as https
269 $ssl_url = str_replace('http://', 'https://', $url);
270 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
271 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
274 if (!DBA::isResult($contact)) {
278 // Update the contact in the background if needed
279 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
280 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
281 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
284 // Remove the internal fields
285 foreach ($removal as $internal) {
286 unset($contact[$internal]);
293 * Fetches a contact for a given user by a given url.
294 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
296 * @param string $url profile url
297 * @param integer $uid User ID of the contact
298 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
299 * @param array $fields Field list
300 * @return array contact array
302 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
305 $contact = self::getByURL($url, $update, $fields, $uid);
306 if (!empty($contact)) {
307 if (!empty($contact['id'])) {
308 $contact['cid'] = $contact['id'];
315 $contact = self::getByURL($url, $update, $fields);
316 if (!empty($contact['id'])) {
318 $contact['zid'] = $contact['id'];
324 * Tests if the given contact is a follower
326 * @param int $cid Either public contact id or user's contact id
327 * @param int $uid User ID
329 * @return boolean is the contact id a follower?
330 * @throws HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 public static function isFollower($cid, $uid)
335 if (Contact\User::isBlocked($cid, $uid)) {
339 $cdata = self::getPublicAndUserContactID($cid, $uid);
340 if (empty($cdata['user'])) {
344 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
345 return DBA::exists('contact', $condition);
349 * Tests if the given contact url is a follower
351 * @param string $url Contact URL
352 * @param int $uid User ID
354 * @return boolean is the contact id a follower?
355 * @throws HTTPException\InternalServerErrorException
356 * @throws \ImagickException
358 public static function isFollowerByURL($url, $uid)
360 $cid = self::getIdForURL($url, $uid);
366 return self::isFollower($cid, $uid);
370 * Tests if the given user follow the given contact
372 * @param int $cid Either public contact id or user's contact id
373 * @param int $uid User ID
375 * @return boolean is the contact url being followed?
376 * @throws HTTPException\InternalServerErrorException
377 * @throws \ImagickException
379 public static function isSharing($cid, $uid)
381 if (Contact\User::isBlocked($cid, $uid)) {
385 $cdata = self::getPublicAndUserContactID($cid, $uid);
386 if (empty($cdata['user'])) {
390 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
391 return DBA::exists('contact', $condition);
395 * Tests if the given user follow the given contact url
397 * @param string $url Contact URL
398 * @param int $uid User ID
400 * @return boolean is the contact url being followed?
401 * @throws HTTPException\InternalServerErrorException
402 * @throws \ImagickException
404 public static function isSharingByURL($url, $uid)
406 $cid = self::getIdForURL($url, $uid);
412 return self::isSharing($cid, $uid);
416 * Get the basepath for a given contact link
418 * @param string $url The contact link
419 * @param boolean $dont_update Don't update the contact
421 * @return string basepath
422 * @throws HTTPException\InternalServerErrorException
423 * @throws \ImagickException
425 public static function getBasepath($url, $dont_update = false)
427 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
428 if (!DBA::isResult($contact)) {
432 if (!empty($contact['baseurl'])) {
433 return $contact['baseurl'];
434 } elseif ($dont_update) {
438 // Update the existing contact
439 self::updateFromProbe($contact['id']);
441 // And fetch the result
442 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
443 if (empty($contact['baseurl'])) {
444 Logger::info('No baseurl for contact', ['url' => $url]);
448 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
449 return $contact['baseurl'];
453 * Check if the given contact url is on the same server
455 * @param string $url The contact link
457 * @return boolean Is it the same server?
459 public static function isLocal($url)
461 if (!parse_url($url, PHP_URL_SCHEME)) {
462 $addr_parts = explode('@', $url);
463 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
466 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
470 * Check if the given contact ID is on the same server
472 * @param string $url The contact link
474 * @return boolean Is it the same server?
476 public static function isLocalById(int $cid)
478 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
479 if (!DBA::isResult($contact)) {
483 if (empty($contact['baseurl'])) {
484 $baseurl = self::getBasepath($contact['url'], true);
486 $baseurl = $contact['baseurl'];
489 return Strings::compareLink($baseurl, DI::baseUrl());
493 * Returns the public contact id of the given user id
495 * @param integer $uid User ID
497 * @return integer|boolean Public contact id for given user id
500 public static function getPublicIdByUserId($uid)
502 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
503 if (!DBA::isResult($self)) {
506 return self::getIdForURL($self['url']);
510 * Returns the contact id for the user and the public contact id for a given contact id
512 * @param int $cid Either public contact id or user's contact id
513 * @param int $uid User ID
515 * @return array with public and user's contact id
516 * @throws HTTPException\InternalServerErrorException
517 * @throws \ImagickException
519 public static function getPublicAndUserContactID($cid, $uid)
521 // We have to use the legacy function as long as the post update hasn't finished
522 if (DI::config()->get('system', 'post_update_version') < 1427) {
523 return self::legacyGetPublicAndUserContactID($cid, $uid);
526 if (empty($uid) || empty($cid)) {
530 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
531 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
535 $pcid = $contact['pid'];
536 if ($contact['uid'] == $uid) {
537 $ucid = $contact['id'];
539 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
540 if (DBA::isResult($contact)) {
541 $ucid = $contact['id'];
547 return ['public' => $pcid, 'user' => $ucid];
551 * Helper function for "getPublicAndUserContactID"
553 * @param int $cid Either public contact id or user's contact id
554 * @param int $uid User ID
556 * @return array with public and user's contact id
557 * @throws HTTPException\InternalServerErrorException
558 * @throws \ImagickException
560 private static function legacyGetPublicAndUserContactID($cid, $uid)
562 if (empty($uid) || empty($cid)) {
566 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
567 if (!DBA::isResult($contact)) {
571 // We quit when the user id don't match the user id of the provided contact
572 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
576 if ($contact['uid'] != 0) {
577 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
581 $ucid = $contact['id'];
583 $pcid = $contact['id'];
584 $ucid = self::getIdForURL($contact['url'], $uid);
587 return ['public' => $pcid, 'user' => $ucid];
591 * Returns contact details for a given contact id in combination with a user id
593 * @param int $cid A contact ID
594 * @param int $uid The User ID
595 * @param array $fields The selected fields for the contact
597 * @return array The contact details
601 public static function getContactForUser($cid, $uid, array $fields = [])
603 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
605 if (!DBA::isResult($contact)) {
613 * Creates the self-contact for the provided user id
616 * @return bool Operation success
617 * @throws HTTPException\InternalServerErrorException
619 public static function createSelfFromUserId($uid)
621 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
622 ['uid' => $uid, 'account_expired' => false]);
623 if (!DBA::isResult($user)) {
628 'uid' => $user['uid'],
629 'created' => DateTimeFormat::utcNow(),
631 'name' => $user['username'],
632 'nick' => $user['nickname'],
633 'pubkey' => $user['pubkey'],
634 'prvkey' => $user['prvkey'],
635 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
636 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
637 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
640 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
641 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
642 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
643 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
644 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
645 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
646 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
647 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
648 'name-date' => DateTimeFormat::utcNow(),
649 'uri-date' => DateTimeFormat::utcNow(),
650 'avatar-date' => DateTimeFormat::utcNow(),
656 // Only create the entry if it doesn't exist yet
657 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
658 $return = (bool)self::insert($contact);
661 // Create the public contact
662 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
663 $contact['self'] = false;
665 $contact['prvkey'] = null;
667 self::insert($contact, Database::INSERT_IGNORE);
674 * Updates the self-contact for the provided user id
677 * @param boolean $update_avatar Force the avatar update
678 * @return bool "true" if updated
679 * @throws HTTPException\InternalServerErrorException
681 public static function updateSelfFromUserID($uid, $update_avatar = false)
683 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
684 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
685 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
686 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
687 if (!DBA::isResult($self)) {
691 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
692 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
693 if (!DBA::isResult($user)) {
697 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
698 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
699 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
700 if (!DBA::isResult($profile)) {
704 $file_suffix = 'jpg';
706 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
707 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
708 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
709 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
710 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp'], 'matrix' => $profile['matrix'], 'network' => Protocol::DFRN];
712 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
713 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
714 $fields['nurl'] = Strings::normaliseLink($fields['url']);
715 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
716 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
717 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
718 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
719 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
720 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
722 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
723 if (DBA::isResult($avatar)) {
724 if ($update_avatar) {
725 $fields['avatar-date'] = DateTimeFormat::utcNow();
728 // Creating the path to the avatar, beginning with the file suffix
729 $types = Images::supportedTypes();
730 if (isset($types[$avatar['type']])) {
731 $file_suffix = $types[$avatar['type']];
734 // We are adding a timestamp value so that other systems won't use cached content
735 $timestamp = strtotime($fields['avatar-date']);
737 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
738 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
740 $fields['photo'] = $prefix . '4' . $suffix;
741 $fields['thumb'] = $prefix . '5' . $suffix;
742 $fields['micro'] = $prefix . '6' . $suffix;
744 // We hadn't found a photo entry, so we use the default avatar
745 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
746 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
747 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
750 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
751 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
752 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
753 $fields['unsearchable'] = !$profile['net-publish'];
757 foreach ($fields as $field => $content) {
758 if ($self[$field] != $content) {
764 if ($fields['name'] != $self['name']) {
765 $fields['name-date'] = DateTimeFormat::utcNow();
767 $fields['updated'] = DateTimeFormat::utcNow();
768 DBA::update('contact', $fields, ['id' => $self['id']]);
770 // Update the public contact as well
771 $fields['prvkey'] = null;
772 $fields['self'] = false;
773 DBA::update('contact', $fields, ['uid' => 0, 'nurl' => $self['nurl']]);
775 // Update the profile
776 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
777 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
778 DBA::update('profile', $fields, ['uid' => $uid]);
785 * Marks a contact for removal
787 * @param int $id contact id
789 * @throws HTTPException\InternalServerErrorException
791 public static function remove($id)
793 // We want just to make sure that we don't delete our "self" contact
794 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
795 if (!DBA::isResult($contact)) {
799 // Archive the contact
800 DBA::update('contact', ['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
802 // Delete it in the background
803 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
807 * Sends an unfriend message. Does not remove the contact
809 * @param array $user User unfriending
810 * @param array $contact Contact unfriended
811 * @param boolean $dissolve Remove the contact on the remote side
813 * @throws HTTPException\InternalServerErrorException
814 * @throws \ImagickException
816 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
818 if (empty($contact['network'])) {
822 $protocol = $contact['network'];
823 if (($protocol == Protocol::DFRN) && !empty($contact['protocol'])) {
824 $protocol = $contact['protocol'];
827 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
828 // create an unfollow slap
830 $item['verb'] = Activity::O_UNFOLLOW;
831 $item['gravity'] = GRAVITY_ACTIVITY;
832 $item['follow'] = $contact["url"];
837 $slap = OStatus::salmon($item, $user);
839 if (!empty($contact['notify'])) {
840 Salmon::slapper($user, $contact['notify'], $slap);
842 } elseif ($protocol == Protocol::DIASPORA) {
843 Diaspora::sendUnshare($user, $contact);
844 } elseif ($protocol == Protocol::ACTIVITYPUB) {
845 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
848 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
854 * Marks a contact for archival after a communication issue delay
856 * Contact has refused to recognise us as a friend. We will start a countdown.
857 * If they still don't recognise us in 32 days, the relationship is over,
858 * and we won't waste any more time trying to communicate with them.
859 * This provides for the possibility that their database is temporarily messed
860 * up or some other transient event and that there's a possibility we could recover from it.
862 * @param array $contact contact to mark for archival
864 * @throws HTTPException\InternalServerErrorException
866 public static function markForArchival(array $contact)
868 if (!isset($contact['url']) && !empty($contact['id'])) {
869 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
870 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
871 if (!DBA::isResult($contact)) {
874 } elseif (!isset($contact['url'])) {
875 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
878 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
880 // Contact already archived or "self" contact? => nothing to do
881 if ($contact['archive'] || $contact['self']) {
885 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
886 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
887 DBA::update('contact', ['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
890 * We really should send a notification to the owner after 2-3 weeks
891 * so they won't be surprised when the contact vanishes and can take
892 * remedial action if this was a serious mistake or glitch
895 /// @todo Check for contact vitality via probing
896 $archival_days = DI::config()->get('system', 'archival_days', 32);
898 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
899 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
900 /* Relationship is really truly dead. archive them rather than
901 * delete, though if the owner tries to unarchive them we'll start
902 * the whole process over again.
904 DBA::update('contact', ['archive' => true], ['id' => $contact['id']]);
905 DBA::update('contact', ['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
911 * Cancels the archival countdown
913 * @see Contact::markForArchival()
915 * @param array $contact contact to be unmarked for archival
919 public static function unmarkForArchival(array $contact)
921 // Always unarchive the relay contact entry
922 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
923 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
924 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
925 if (!DBA::exists('contact', array_merge($condition, $fields))) {
926 DBA::update('contact', $fields, $condition);
930 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
931 $exists = DBA::exists('contact', $condition);
933 // We don't need to update, we never marked this contact for archival
938 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
940 if (!isset($contact['url']) && !empty($contact['id'])) {
941 $fields = ['id', 'url', 'batch'];
942 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
943 if (!DBA::isResult($contact)) {
948 // It's a miracle. Our dead contact has inexplicably come back to life.
949 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
950 DBA::update('contact', $fields, ['id' => $contact['id']]);
951 DBA::update('contact', $fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
955 * Returns the data array for the photo menu of a given contact
957 * @param array $contact contact
958 * @param int $uid optional, default 0
960 * @throws HTTPException\InternalServerErrorException
961 * @throws \ImagickException
963 public static function photoMenu(array $contact, $uid = 0)
968 $contact_drop_link = '';
975 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
977 $profile_link = self::magicLinkByContact($contact);
978 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
983 // Look for our own contact if the uid doesn't match and isn't public
984 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
985 if (DBA::isResult($contact_own)) {
986 return self::photoMenu($contact_own, $uid);
991 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
993 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
995 $profile_link = $contact['url'];
998 if ($profile_link === 'mailbox') {
1003 $status_link = $profile_link . '/status';
1004 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1005 $profile_link = $profile_link . '/profile';
1008 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1009 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1012 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1013 $poke_link = 'contact/' . $contact['id'] . '/poke';
1016 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1018 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1020 if (!$contact['self']) {
1021 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1025 $unfollow_link = '';
1026 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1027 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1028 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1029 } elseif(!$contact['pending']) {
1030 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1034 if (!empty($follow_link) || !empty($unfollow_link)) {
1035 $contact_drop_link = '';
1040 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1042 if (empty($contact['uid'])) {
1044 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1045 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1046 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1047 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1048 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1052 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1053 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1054 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1055 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1056 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1057 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1058 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1059 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1060 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1061 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1064 if (!empty($contact['pending'])) {
1065 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1066 if (DBA::isResult($intro)) {
1067 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1072 $args = ['contact' => $contact, 'menu' => &$menu];
1074 Hook::callAll('contact_photo_menu', $args);
1076 $menucondensed = [];
1078 foreach ($menu as $menuname => $menuitem) {
1079 if ($menuitem[1] != '') {
1080 $menucondensed[$menuname] = $menuitem;
1084 return $menucondensed;
1088 * Fetch the contact id for a given URL and user
1090 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1091 * `addr` or `alias`.
1093 * If there's no record and we aren't looking for a public contact, we quit.
1094 * If there's one, we check that it isn't time to update the picture else we
1095 * directly return the found contact id.
1097 * Second, we probe the provided $url whether it's http://server.tld/profile or
1098 * nick@server.tld. We quit if we can't get any info back.
1100 * Third, we create the contact record if it doesn't exist
1102 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1103 * if there's any updates
1105 * @param string $url Contact URL
1106 * @param integer $uid The user id for the contact (0 = public contact)
1107 * @param boolean $update true = always update, false = never update, null = update when not found
1108 * @param array $default Default value for creating the contact when everything else fails
1110 * @return integer Contact ID
1111 * @throws HTTPException\InternalServerErrorException
1112 * @throws \ImagickException
1114 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1119 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1123 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1125 if (!empty($contact)) {
1126 $contact_id = $contact["id"];
1128 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1129 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1132 } elseif ($uid != 0) {
1133 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1135 } elseif (empty($default) && !is_null($update) && !$update) {
1136 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1142 if (empty($default['network']) || $update) {
1143 $data = Probe::uri($url, "", $uid);
1145 // Take the default values when probing failed
1146 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1147 $data = array_merge($data, $default);
1149 } elseif (!empty($default['network'])) {
1153 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1154 // Fetch data for the public contact via the first found personal contact
1155 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1156 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1157 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1158 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1160 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1161 if (!DBA::isResult($personal_contact)) {
1162 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1165 if (DBA::isResult($personal_contact)) {
1166 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1167 $data = $personal_contact;
1168 $data['photo'] = $personal_contact['avatar'];
1169 $data['account-type'] = $personal_contact['contact-type'];
1170 $data['hide'] = $personal_contact['unsearchable'];
1171 unset($data['avatar']);
1172 unset($data['contact-type']);
1173 unset($data['unsearchable']);
1177 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1178 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1183 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1184 if (!empty($data['alias'])) {
1185 $urls[] = Strings::normaliseLink($data['alias']);
1187 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1188 if (!empty($contact['id'])) {
1189 $contact_id = $contact['id'];
1190 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1195 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1198 'url' => $data['url'],
1199 'nurl' => Strings::normaliseLink($data['url']),
1200 'network' => $data['network'],
1201 'created' => DateTimeFormat::utcNow(),
1202 'rel' => self::SHARING,
1208 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1210 // Before inserting we do check if the entry does exist now.
1211 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1212 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1213 if (DBA::isResult($contact)) {
1214 $contact_id = $contact['id'];
1215 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1217 $contact_id = self::insert($fields);
1219 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1222 DI::lock()->release(self::LOCK_INSERT);
1224 Logger::warning('Contact lock had not been acquired');
1228 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1232 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1235 self::updateFromProbeArray($contact_id, $data);
1237 // Don't return a number for a deleted account
1238 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1239 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1247 * Checks if the contact is archived
1249 * @param int $cid contact id
1251 * @return boolean Is the contact archived?
1252 * @throws HTTPException\InternalServerErrorException
1254 public static function isArchived(int $cid)
1260 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1261 if (!DBA::isResult($contact)) {
1265 if ($contact['archive']) {
1269 // Check status of ActivityPub endpoints
1270 $apcontact = APContact::getByURL($contact['url'], false);
1271 if (!empty($apcontact)) {
1272 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1276 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1281 // Check status of Diaspora endpoints
1282 if (!empty($contact['batch'])) {
1283 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1284 return DBA::exists('contact', $condition);
1291 * Checks if the contact is blocked
1293 * @param int $cid contact id
1295 * @return boolean Is the contact blocked?
1296 * @throws HTTPException\InternalServerErrorException
1298 public static function isBlocked($cid)
1304 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1305 if (!DBA::isResult($blocked)) {
1309 if (Network::isUrlBlocked($blocked['url'])) {
1313 return (bool) $blocked['blocked'];
1317 * Checks if the contact is hidden
1319 * @param int $cid contact id
1321 * @return boolean Is the contact hidden?
1322 * @throws \Exception
1324 public static function isHidden($cid)
1330 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1331 if (!DBA::isResult($hidden)) {
1334 return (bool) $hidden['hidden'];
1338 * Returns posts from a given contact url
1340 * @param string $contact_url Contact URL
1341 * @param bool $thread_mode
1342 * @param int $update Update mode
1343 * @param int $parent Item parent ID for the update mode
1344 * @return string posts in HTML
1345 * @throws \Exception
1347 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1349 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1353 * Returns posts from a given contact id
1355 * @param int $cid Contact ID
1356 * @param bool $thread_mode
1357 * @param int $update Update mode
1358 * @param int $parent Item parent ID for the update mode
1359 * @return string posts in HTML
1360 * @throws \Exception
1362 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1366 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1367 if (!DBA::isResult($contact)) {
1371 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1372 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1377 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1380 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1381 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1383 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1384 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1387 if (!empty($parent)) {
1388 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1390 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1391 if (!empty($last_received)) {
1392 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1396 if (DI::mode()->isMobile()) {
1397 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1398 DI::config()->get('system', 'itemspage_network_mobile'));
1400 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1401 DI::config()->get('system', 'itemspage_network'));
1404 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1406 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1408 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1409 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1410 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1416 $items = Post::toArray(Post::selectForUser(local_user(), ['uri-id', 'gravity', 'parent-uri-id', 'thr-parent-id', 'author-id'], $condition, $params));
1418 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1420 $items = Post::toArray(Post::selectForUser(local_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1422 $o .= conversation($a, $items, 'contact-posts', $update);
1426 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1427 $o .= HTML::scrollLoader();
1429 $o .= $pager->renderMinimal(count($items));
1437 * Returns the account type name
1439 * The function can be called with either the user or the contact array
1441 * @param array $contact contact or user array
1444 public static function getAccountType(array $contact)
1446 // There are several fields that indicate that the contact or user is a forum
1447 // "page-flags" is a field in the user table,
1448 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1449 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1450 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1451 || (isset($contact['forum']) && intval($contact['forum']))
1452 || (isset($contact['prv']) && intval($contact['prv']))
1453 || (isset($contact['community']) && intval($contact['community']))
1455 $type = self::TYPE_COMMUNITY;
1457 $type = self::TYPE_PERSON;
1460 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1461 if (isset($contact["contact-type"])) {
1462 $type = $contact["contact-type"];
1465 if (isset($contact["account-type"])) {
1466 $type = $contact["account-type"];
1470 case self::TYPE_ORGANISATION:
1471 $account_type = DI::l10n()->t("Organisation");
1474 case self::TYPE_NEWS:
1475 $account_type = DI::l10n()->t('News');
1478 case self::TYPE_COMMUNITY:
1479 $account_type = DI::l10n()->t("Forum");
1487 return $account_type;
1495 * @throws \Exception
1497 public static function block($cid, $reason = null)
1499 $return = DBA::update('contact', ['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1505 * Unblocks a contact
1509 * @throws \Exception
1511 public static function unblock($cid)
1513 $return = DBA::update('contact', ['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1519 * Ensure that cached avatar exist
1521 * @param integer $cid
1523 public static function checkAvatarCache(int $cid)
1525 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1526 if (!DBA::isResult($contact)) {
1530 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1534 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1536 self::updateAvatar($cid, $contact['avatar'], true);
1540 * Return the photo path for a given contact array in the given size
1542 * @param array $contact contact array
1543 * @param string $field Fieldname of the photo in the contact array
1544 * @param string $size Size of the avatar picture
1545 * @param string $avatar Avatar path that is displayed when no photo had been found
1546 * @param bool $no_update Don't perfom an update if no cached avatar was found
1547 * @return string photo path
1549 private static function getAvatarPath(array $contact, string $size, $no_update = false)
1551 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1552 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1556 * Return the photo path for a given contact array
1558 * @param array $contact Contact array
1559 * @param bool $no_update Don't perfom an update if no cached avatar was found
1560 * @return string photo path
1562 public static function getPhoto(array $contact, bool $no_update = false)
1564 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1568 * Return the photo path (thumb size) for a given contact array
1570 * @param array $contact Contact array
1571 * @param bool $no_update Don't perfom an update if no cached avatar was found
1572 * @return string photo path
1574 public static function getThumb(array $contact, bool $no_update = false)
1576 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1580 * Return the photo path (micro size) for a given contact array
1582 * @param array $contact Contact array
1583 * @param bool $no_update Don't perfom an update if no cached avatar was found
1584 * @return string photo path
1586 public static function getMicro(array $contact, bool $no_update = false)
1588 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1592 * Check the given contact array for avatar cache fields
1594 * @param array $contact
1595 * @param bool $no_update Don't perfom an update if no cached avatar was found
1596 * @return array contact array with avatar cache fields
1598 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false)
1601 $contact_fields = [];
1602 $fields = ['photo', 'thumb', 'micro'];
1603 foreach ($fields as $field) {
1604 if (isset($contact[$field])) {
1605 $contact_fields[] = $field;
1607 if (isset($contact[$field]) && empty($contact[$field])) {
1612 if (!$update || $no_update) {
1616 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1617 self::updateAvatar($contact['id'], $contact['avatar'], true);
1619 $new_contact = self::getById($contact['id'], $contact_fields);
1620 if (DBA::isResult($new_contact)) {
1621 // We only update the cache fields
1622 $contact = array_merge($contact, $new_contact);
1626 /// add the default avatars if the fields aren't filled
1627 if (isset($contact['photo']) && empty($contact['photo'])) {
1628 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1630 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1631 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1633 if (isset($contact['micro']) && empty($contact['micro'])) {
1634 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1641 * Fetch the default avatar for the given contact and size
1643 * @param array $contact contact array
1644 * @param string $size Size of the avatar picture
1645 * @return string avatar URL
1647 public static function getDefaultAvatar(array $contact, string $size)
1650 case Proxy::SIZE_MICRO:
1651 $avatar['size'] = 48;
1652 $default = self::DEFAULT_AVATAR_MICRO;
1655 case Proxy::SIZE_THUMB:
1656 $avatar['size'] = 80;
1657 $default = self::DEFAULT_AVATAR_THUMB;
1660 case Proxy::SIZE_SMALL:
1662 $avatar['size'] = 300;
1663 $default = self::DEFAULT_AVATAR_PHOTO;
1667 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1668 return DI::baseUrl() . $default;
1671 if (!empty($contact['xmpp'])) {
1672 $avatar['email'] = $contact['xmpp'];
1673 } elseif (!empty($contact['addr'])) {
1674 $avatar['email'] = $contact['addr'];
1675 } elseif (!empty($contact['url'])) {
1676 $avatar['email'] = $contact['url'];
1678 return DI::baseUrl() . $default;
1681 $avatar['url'] = '';
1682 $avatar['success'] = false;
1684 Hook::callAll('avatar_lookup', $avatar);
1686 if ($avatar['success'] && !empty($avatar['url'])) {
1687 return $avatar['url'];
1690 return DI::baseUrl() . $default;
1694 * Get avatar link for given contact id
1696 * @param integer $cid contact id
1697 * @param string $size One of the ProxyUtils::SIZE_* constants
1698 * @param string $updated Contact update date
1699 * @return string avatar link
1701 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = ''):string
1703 // We have to fetch the "updated" variable when it wasn't provided
1704 // The parameter can be provided to improve performance
1705 if (empty($updated)) {
1706 $contact = self::getById($cid, ['updated']);
1707 $updated = $contact['updated'] ?? '';
1710 $url = DI::baseUrl() . '/photo/contact/';
1712 case Proxy::SIZE_MICRO:
1713 $url .= Proxy::PIXEL_MICRO . '/';
1715 case Proxy::SIZE_THUMB:
1716 $url .= Proxy::PIXEL_THUMB . '/';
1718 case Proxy::SIZE_SMALL:
1719 $url .= Proxy::PIXEL_SMALL . '/';
1721 case Proxy::SIZE_MEDIUM:
1722 $url .= Proxy::PIXEL_MEDIUM . '/';
1724 case Proxy::SIZE_LARGE:
1725 $url .= Proxy::PIXEL_LARGE . '/';
1728 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1732 * Get avatar link for given contact URL
1734 * @param string $url contact url
1735 * @param integer $uid user id
1736 * @param string $size One of the ProxyUtils::SIZE_* constants
1737 * @return string avatar link
1739 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''):string
1741 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
1742 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
1743 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
1744 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1748 * Get header link for given contact id
1750 * @param integer $cid contact id
1751 * @param string $size One of the ProxyUtils::SIZE_* constants
1752 * @param string $updated Contact update date
1753 * @return string header link
1755 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = ''):string
1757 // We have to fetch the "updated" variable when it wasn't provided
1758 // The parameter can be provided to improve performance
1759 if (empty($updated)) {
1760 $contact = self::getById($cid, ['updated']);
1761 $updated = $contact['updated'] ?? '';
1764 $url = DI::baseUrl() . '/photo/header/';
1766 case Proxy::SIZE_MICRO:
1767 $url .= Proxy::PIXEL_MICRO . '/';
1769 case Proxy::SIZE_THUMB:
1770 $url .= Proxy::PIXEL_THUMB . '/';
1772 case Proxy::SIZE_SMALL:
1773 $url .= Proxy::PIXEL_SMALL . '/';
1775 case Proxy::SIZE_MEDIUM:
1776 $url .= Proxy::PIXEL_MEDIUM . '/';
1778 case Proxy::SIZE_LARGE:
1779 $url .= Proxy::PIXEL_LARGE . '/';
1783 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1787 * Updates the avatar links in a contact only if needed
1789 * @param int $cid Contact id
1790 * @param string $avatar Link to avatar picture
1791 * @param bool $force force picture update
1792 * @param bool $create_cache Enforces the creation of cached avatar fields
1795 * @throws HTTPException\InternalServerErrorException
1796 * @throws HTTPException\NotFoundException
1797 * @throws \ImagickException
1799 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1801 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network'],
1802 ['id' => $cid, 'self' => false]);
1803 if (!DBA::isResult($contact)) {
1807 $uid = $contact['uid'];
1809 // Only update the cached photo links of public contacts when they already are cached
1810 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1811 if ($contact['avatar'] != $avatar) {
1812 DBA::update('contact', ['avatar' => $avatar], ['id' => $cid]);
1813 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1818 // User contacts use are updated through the public contacts
1819 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1820 $pcid = self::getIdForURL($contact['url'], 0, false);
1821 if (!empty($pcid)) {
1822 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1823 self::updateAvatar($pcid, $avatar, $force, true);
1828 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
1830 if ($default_avatar) {
1831 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1834 if ($default_avatar && Proxy::isLocalImage($avatar)) {
1835 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1837 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
1838 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
1839 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1842 // Use the data from the self account
1843 if (empty($fields)) {
1844 $local_uid = User::getIdForURL($contact['url']);
1845 if (!empty($local_uid)) {
1846 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1847 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1851 if (empty($fields)) {
1852 $update = ($contact['avatar'] != $avatar) || $force;
1856 $contact['photo'] ?? '',
1857 $contact['thumb'] ?? '',
1858 $contact['micro'] ?? '',
1861 foreach ($data as $image_uri) {
1862 $image_rid = Photo::ridFromURI($image_uri);
1863 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1864 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1871 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1873 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1874 $update = !empty($fields);
1875 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1881 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1890 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1891 // Collect all user contacts of the given public contact
1892 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1893 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1894 while ($personal_contact = DBA::fetch($personal_contacts)) {
1895 $cids[] = $personal_contact['id'];
1896 $uids[] = $personal_contact['uid'];
1898 DBA::close($personal_contacts);
1900 if (!empty($cids)) {
1901 // Delete possibly existing cached user contact avatars
1902 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1908 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1909 DBA::update('contact', $fields, ['id' => $cids]);
1912 public static function deleteContactByUrl(string $url)
1914 // Update contact data for all users
1915 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
1916 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
1917 while ($contact = DBA::fetch($contacts)) {
1918 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
1919 self::remove($contact['id']);
1924 * Helper function for "updateFromProbe". Updates personal and public contact
1926 * @param integer $id contact id
1927 * @param integer $uid user id
1928 * @param string $old_url The previous profile URL of the contact
1929 * @param string $new_url The profile URL of the contact
1930 * @param array $fields The fields that are updated
1932 * @throws \Exception
1934 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
1936 if (!DBA::update('contact', $fields, ['id' => $id])) {
1937 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1941 // Search for duplicated contacts and get rid of them
1942 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
1946 // Archive or unarchive the contact.
1947 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1948 if (!DBA::isResult($contact)) {
1949 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1953 if (isset($fields['failed'])) {
1954 if ($fields['failed']) {
1955 self::markForArchival($contact);
1957 self::unmarkForArchival($contact);
1961 if ($contact['uid'] != 0) {
1965 // Update contact data for all users
1966 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
1968 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
1969 DBA::update('contact', $fields, $condition);
1971 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
1972 $condition['network'] = Protocol::OSTATUS;
1974 // If the contact failed, propagate the update fields to all contacts
1975 if (empty($fields['failed'])) {
1976 unset($fields['last-update']);
1977 unset($fields['success_update']);
1978 unset($fields['failure_update']);
1981 if (empty($fields)) {
1985 DBA::update('contact', $fields, $condition);
1989 * Remove duplicated contacts
1991 * @param string $nurl Normalised contact url
1992 * @param integer $uid User id
1994 * @throws \Exception
1996 public static function removeDuplicates(string $nurl, int $uid)
1998 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
1999 $count = DBA::count('contact', $condition);
2004 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2005 if (!DBA::isResult($first_contact)) {
2006 // Shouldn't happen - so we handle it
2010 $first = $first_contact['id'];
2011 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2012 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2013 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2014 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2018 // Find all duplicates
2019 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2020 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2021 while ($duplicate = DBA::fetch($duplicates)) {
2022 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2026 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2028 DBA::close($duplicates);
2029 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2034 * @param integer $id contact id
2035 * @param string $network Optional network we are probing for
2037 * @throws HTTPException\InternalServerErrorException
2038 * @throws \ImagickException
2040 public static function updateFromProbe(int $id, string $network = '')
2042 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2043 if (!DBA::isResult($contact)) {
2047 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2048 return self::updateFromProbeArray($id, $ret);
2052 * @param integer $id contact id
2053 * @param array $ret Probed data
2055 * @throws HTTPException\InternalServerErrorException
2056 * @throws \ImagickException
2058 private static function updateFromProbeArray(int $id, array $ret)
2061 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2062 This will reliably kill your communication with old Friendica contacts.
2065 // These fields aren't updated by this routine:
2068 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2069 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2070 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix'];
2071 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2072 if (!DBA::isResult($contact)) {
2076 if (self::isLocal($ret['url'])) {
2077 if ($contact['uid'] == 0) {
2078 Logger::info('Local contacts are not updated here.');
2080 self::updateFromPublicContact($id, $contact);
2085 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2086 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2089 // Delete all contacts with the same URL
2090 self::deleteContactByUrl($ret['url']);
2094 $uid = $contact['uid'];
2095 unset($contact['uid']);
2097 $uriid = $contact['uri-id'];
2098 unset($contact['uri-id']);
2100 $pubkey = $contact['pubkey'];
2101 unset($contact['pubkey']);
2103 $contact['photo'] = $contact['avatar'];
2104 unset($contact['avatar']);
2106 $updated = DateTimeFormat::utcNow();
2108 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2109 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2110 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2114 // We must not try to update relay contacts via probe. They are no real contacts.
2115 // We check after the probing to be able to correct falsely detected contact types.
2116 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2117 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2118 self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2119 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2123 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2124 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2125 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2129 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2130 $cid = self::getIdForURL($ret['url'], 0, false);
2131 if (!empty($cid) && ($cid != $id)) {
2132 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2133 return self::updateFromProbeArray($cid, $ret);
2137 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2138 $ret['unsearchable'] = $ret['hide'];
2141 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2142 $ret['forum'] = false;
2143 $ret['prv'] = false;
2144 $ret['contact-type'] = $ret['account-type'];
2145 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2146 $ret['forum'] = (bool)!$ret['manually-approve'];
2147 $ret['prv'] = (bool)!$ret['forum'];
2151 $new_pubkey = $ret['pubkey'] ?? '';
2154 $ret['last-item'] = Probe::getLastUpdate($ret);
2155 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2159 $guid = $ret['guid'] ?? '';
2161 // make sure to not overwrite existing values with blank entries except some technical fields
2162 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2163 foreach ($ret as $key => $val) {
2164 if (!array_key_exists($key, $contact)) {
2166 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2167 $ret[$key] = $contact[$key];
2168 } elseif ($ret[$key] != $contact[$key]) {
2173 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2176 unset($ret['last-item']);
2179 if (empty($uriid)) {
2183 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2184 self::updateAvatar($id, $ret['photo'], $update);
2188 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2190 if (Contact\Relation::isDiscoverable($ret['url'])) {
2191 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2194 // Update the public contact
2196 $contact = self::getByURL($ret['url'], false, ['id']);
2197 if (!empty($contact['id'])) {
2198 self::updateFromProbeArray($contact['id'], $ret);
2206 $ret['uri-id'] = ItemURI::getIdByURI($ret['url']);
2208 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2211 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2212 $ret['updated'] = $updated;
2213 $ret['failed'] = false;
2215 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2216 if (empty($pubkey) && !empty($new_pubkey)) {
2217 $ret['pubkey'] = $new_pubkey;
2220 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2221 $ret['uri-date'] = $updated;
2224 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2225 $ret['name-date'] = $updated;
2228 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2229 $ret['last-update'] = $updated;
2230 $ret['success_update'] = $updated;
2233 unset($ret['photo']);
2235 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2237 if (Contact\Relation::isDiscoverable($ret['url'])) {
2238 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2244 private static function updateFromPublicContact(int $id, array $contact)
2246 $public = self::getByURL($contact['url'], false);
2250 foreach ($contact as $field => $value) {
2251 if ($field == 'uid') {
2254 if ($public[$field] != $value) {
2255 $fields[$field] = $public[$field];
2258 if (!empty($fields)) {
2259 DBA::update('contact', $fields, ['id' => $id, 'self' => false]);
2260 Logger::info('Updating local contact', ['id' => $id]);
2265 * @param integer $url contact url
2266 * @return integer Contact id
2267 * @throws HTTPException\InternalServerErrorException
2268 * @throws \ImagickException
2270 public static function updateFromProbeByURL($url)
2272 $id = self::getIdForURL($url);
2278 self::updateFromProbe($id);
2284 * Detects the communication protocol for a given contact url.
2285 * This is used to detect Friendica contacts that we can communicate via AP.
2287 * @param string $url contact url
2288 * @param string $network Network of that contact
2289 * @return string with protocol
2291 public static function getProtocol($url, $network)
2293 if ($network != Protocol::DFRN) {
2297 $apcontact = APContact::getByURL($url);
2298 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2299 return Protocol::ACTIVITYPUB;
2306 * Takes a $uid and a url/handle and adds a new contact
2308 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2309 * dfrn_request page.
2311 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2314 * $return['success'] boolean true if successful
2315 * $return['message'] error text if success is false.
2317 * Takes a $uid and a url/handle and adds a new contact
2319 * @param int $uid The user id the contact should be created for
2320 * @param string $url The profile URL of the contact
2321 * @param string $network
2323 * @throws HTTPException\InternalServerErrorException
2324 * @throws HTTPException\NotFoundException
2325 * @throws \ImagickException
2327 public static function createFromProbeForUser(int $uid, $url, $network = '')
2329 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2331 // remove ajax junk, e.g. Twitter
2332 $url = str_replace('/#!/', '/', $url);
2334 if (!Network::isUrlAllowed($url)) {
2335 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2339 if (Network::isUrlBlocked($url)) {
2340 $result['message'] = DI::l10n()->t('Blocked domain');
2345 $result['message'] = DI::l10n()->t('Connect URL missing.');
2349 $arr = ['url' => $url, 'contact' => []];
2351 Hook::callAll('follow', $arr);
2354 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2358 if (!empty($arr['contact']['name'])) {
2360 $ret = $arr['contact'];
2363 $ret = Probe::uri($url, $network, $uid);
2366 if (($network != '') && ($ret['network'] != $network)) {
2367 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2371 // check if we already have a contact
2372 // the poll url is more reliable than the profile url, as we may have
2373 // indirect links or webfinger links
2375 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2376 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2377 if (!DBA::isResult($contact)) {
2378 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2379 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2382 $protocol = self::getProtocol($ret['url'], $ret['network']);
2384 // This extra param just confuses things, remove it
2385 if ($protocol === Protocol::DIASPORA) {
2386 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2389 // do we have enough information?
2390 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2391 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2392 if (empty($ret['poll'])) {
2393 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2395 if (empty($ret['name'])) {
2396 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2398 if (empty($ret['url'])) {
2399 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2401 if (strpos($ret['url'], '@') !== false) {
2402 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2403 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2408 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2409 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2410 $ret['notify'] = '';
2413 if (!$ret['notify']) {
2414 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2417 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2419 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2421 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2424 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2425 $pending = (bool)$ret['manually-approve'];
2428 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2432 if (DBA::isResult($contact)) {
2434 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2436 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2437 DBA::update('contact', $fields, ['id' => $contact['id']]);
2439 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2441 // create contact record
2444 'created' => DateTimeFormat::utcNow(),
2445 'url' => $ret['url'],
2446 'nurl' => Strings::normaliseLink($ret['url']),
2447 'addr' => $ret['addr'],
2448 'alias' => $ret['alias'],
2449 'batch' => $ret['batch'],
2450 'notify' => $ret['notify'],
2451 'poll' => $ret['poll'],
2452 'poco' => $ret['poco'],
2453 'name' => $ret['name'],
2454 'nick' => $ret['nick'],
2455 'network' => $ret['network'],
2456 'baseurl' => $ret['baseurl'],
2457 'gsid' => $ret['gsid'] ?? null,
2458 'protocol' => $protocol,
2459 'pubkey' => $ret['pubkey'],
2460 'rel' => $new_relation,
2461 'priority'=> $ret['priority'],
2462 'writable'=> $writeable,
2463 'hidden' => $hidden,
2466 'pending' => $pending,
2471 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2472 if (!DBA::isResult($contact)) {
2473 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2477 $contact_id = $contact['id'];
2478 $result['cid'] = $contact_id;
2480 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2482 // Update the avatar
2483 self::updateAvatar($contact_id, $ret['photo']);
2485 // pull feed and consume it, which should subscribe to the hub.
2486 if ($contact['network'] == Protocol::OSTATUS) {
2487 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2491 self::updateFromProbeArray($contact_id, $ret);
2493 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2496 $owner = User::getOwnerDataById($uid);
2498 if (DBA::isResult($owner)) {
2499 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2500 // create a follow slap
2502 $item['verb'] = Activity::FOLLOW;
2503 $item['gravity'] = GRAVITY_ACTIVITY;
2504 $item['follow'] = $contact["url"];
2506 $item['title'] = '';
2508 $item['uri-id'] = 0;
2510 $slap = OStatus::salmon($item, $owner);
2512 if (!empty($contact['notify'])) {
2513 Salmon::slapper($owner, $contact['notify'], $slap);
2515 } elseif ($protocol == Protocol::DIASPORA) {
2516 $ret = Diaspora::sendShare($owner, $contact);
2517 Logger::log('share returns: ' . $ret);
2518 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2519 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2520 if (empty($activity_id)) {
2521 // This really should never happen
2525 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2526 Logger::log('Follow returns: ' . $ret);
2530 $result['success'] = true;
2535 * Updated contact's SSL policy
2537 * @param array $contact Contact array
2538 * @param string $new_policy New policy, valid: self,full
2540 * @return array Contact array with updated values
2541 * @throws \Exception
2543 public static function updateSslPolicy(array $contact, $new_policy)
2545 $ssl_changed = false;
2546 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2547 $ssl_changed = true;
2548 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2549 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2550 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2551 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2552 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2553 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2556 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2557 $ssl_changed = true;
2558 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2559 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2560 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2561 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2562 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2563 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2567 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2568 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2569 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2570 DBA::update('contact', $fields, ['id' => $contact['id']]);
2579 * @param int $cid Public contact id
2580 * @param int $uid User ID
2582 * @return bool "true" if following had been successful
2584 public static function follow(int $cid, int $uid)
2586 $contact = self::getById($cid, ['url']);
2588 $result = self::createFromProbeForUser($uid, $contact['url']);
2590 return $result['cid'];
2594 * Unfollow a contact
2596 * @param int $cid Public contact id
2597 * @param int $uid User ID
2599 * @return bool "true" if unfollowing had been successful
2601 public static function unfollow(int $cid, int $uid)
2603 $cdata = self::getPublicAndUserContactID($cid, $uid);
2604 if (empty($cdata['user'])) {
2608 $contact = self::getById($cdata['user']);
2610 self::removeSharer([], $contact);
2616 * @param array $importer Owner (local user) data
2617 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2618 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2619 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2620 * @param string $note Introduction additional message
2621 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2622 * @throws HTTPException\InternalServerErrorException
2623 * @throws \ImagickException
2625 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2627 // Should always be set
2628 if (empty($datarray['author-id'])) {
2632 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2633 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2634 if (!DBA::isResult($pub_contact)) {
2635 // Should never happen
2639 // Contact is blocked at node-level
2640 if (self::isBlocked($datarray['author-id'])) {
2644 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2645 $name = $pub_contact['name'];
2646 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2647 $nick = $pub_contact['nick'];
2648 $network = $pub_contact['network'];
2650 // Ensure that we don't create a new contact when there already is one
2651 $cid = self::getIdForURL($url, $importer['uid']);
2653 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2656 if (!empty($contact)) {
2657 if (!empty($contact['pending'])) {
2658 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2662 // Contact is blocked at user-level
2663 if (!empty($contact['id']) && !empty($importer['id']) &&
2664 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2668 // Make sure that the existing contact isn't archived
2669 self::unmarkForArchival($contact);
2671 if (($contact['rel'] == self::SHARING)
2672 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2673 DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2674 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2677 // Ensure to always have the correct network type, independent from the connection request method
2678 self::updateFromProbe($contact['id']);
2680 Post\UserNotification::insertNotication($contact['id'], Verb::getID(Activity::FOLLOW), $importer['uid']);
2684 // send email notification to owner?
2685 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2686 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2690 // create contact record
2691 $contact_id = self::insert([
2692 'uid' => $importer['uid'],
2693 'created' => DateTimeFormat::utcNow(),
2695 'nurl' => Strings::normaliseLink($url),
2698 'network' => $network,
2699 'rel' => self::FOLLOWER,
2706 // Ensure to always have the correct network type, independent from the connection request method
2707 self::updateFromProbe($contact_id);
2709 self::updateAvatar($contact_id, $photo, true);
2711 Post\UserNotification::insertNotication($contact_id, Verb::getID(Activity::FOLLOW), $importer['uid']);
2713 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2715 /// @TODO Encapsulate this into a function/method
2716 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2717 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2718 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2719 // create notification
2720 $hash = Strings::getRandomHex();
2722 if (is_array($contact_record)) {
2723 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2724 'blocked' => false, 'knowyou' => false, 'note' => $note,
2725 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2728 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2730 if (($user['notify-flags'] & Notification\Type::INTRO) &&
2731 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2734 'type' => Notification\Type::INTRO,
2735 'otype' => Notification\ObjectType::INTRO,
2736 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2737 'uid' => $user['uid'],
2738 'cid' => $contact_record['id'],
2739 'link' => DI::baseUrl() . '/notifications/intros',
2742 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2743 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2744 self::createFromProbeForUser($importer['uid'], $url, $network);
2747 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2748 $fields = ['pending' => false];
2749 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2750 $fields['rel'] = self::FRIEND;
2753 DBA::update('contact', $fields, $condition);
2762 public static function removeFollower($importer, $contact)
2764 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2765 DBA::update('contact', ['rel' => self::SHARING], ['id' => $contact['id']]);
2767 self::remove($contact['id']);
2771 public static function removeSharer($importer, $contact)
2773 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2774 DBA::update('contact', ['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2776 self::remove($contact['id']);
2781 * Create a birthday event.
2783 * Update the year and the birthday.
2785 public static function updateBirthdays()
2789 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2790 AND NOT `contact`.`pending`
2791 AND NOT `contact`.`hidden`
2792 AND NOT `contact`.`blocked`
2793 AND NOT `contact`.`archive`
2794 AND NOT `contact`.`deleted`',
2800 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2802 while ($contact = DBA::fetch($contacts)) {
2803 Logger::log('update_contact_birthday: ' . $contact['bd']);
2805 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2807 if (Event::createBirthday($contact, $nextbd)) {
2811 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2812 ['id' => $contact['id']]
2816 DBA::close($contacts);
2820 * Remove the unavailable contact ids from the provided list
2822 * @param array $contact_ids Contact id list
2824 * @throws \Exception
2826 public static function pruneUnavailable(array $contact_ids)
2828 if (empty($contact_ids)) {
2832 $contacts = self::selectToArray(['id'], [
2833 'id' => $contact_ids,
2839 return array_column($contacts, 'id');
2843 * Returns a magic link to authenticate remote visitors
2845 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2847 * @param string $contact_url The address of the target contact profile
2848 * @param string $url An url that we will be redirected to after the authentication
2850 * @return string with "redir" link
2851 * @throws HTTPException\InternalServerErrorException
2852 * @throws \ImagickException
2854 public static function magicLink($contact_url, $url = '')
2856 if (!Session::isAuthenticated()) {
2857 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2860 $contact = self::getByURL($contact_url, false);
2861 if (empty($contact)) {
2862 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2865 // Prevents endless loop in case only a non-public contact exists for the contact URL
2866 unset($contact['uid']);
2868 return self::magicLinkByContact($contact, $url ?: $contact_url);
2872 * Returns a magic link to authenticate remote visitors
2874 * @param integer $cid The contact id of the target contact profile
2875 * @param string $url An url that we will be redirected to after the authentication
2877 * @return string with "redir" link
2878 * @throws HTTPException\InternalServerErrorException
2879 * @throws \ImagickException
2881 public static function magicLinkById($cid, $url = '')
2883 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2885 return self::magicLinkByContact($contact, $url);
2889 * Returns a magic link to authenticate remote visitors
2891 * @param array $contact The contact array with "uid", "network" and "url"
2892 * @param string $url An url that we will be redirected to after the authentication
2894 * @return string with "redir" link
2895 * @throws HTTPException\InternalServerErrorException
2896 * @throws \ImagickException
2898 public static function magicLinkByContact($contact, $url = '')
2900 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2902 if (!Session::isAuthenticated()) {
2903 return $destination;
2906 // Only redirections to the same host do make sense
2907 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2911 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2912 return 'contact/' . $contact['id'] . '/conversations';
2915 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
2916 return $destination;
2919 if (empty($contact['id'])) {
2920 return $destination;
2923 $redirect = 'redir/' . $contact['id'];
2925 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2926 $redirect .= '?url=' . $url;
2933 * Is the contact a forum?
2935 * @param integer $contactid ID of the contact
2937 * @return boolean "true" if it is a forum
2939 public static function isForum($contactid)
2941 $fields = ['forum', 'prv'];
2942 $condition = ['id' => $contactid];
2943 $contact = DBA::selectFirst('contact', $fields, $condition);
2944 if (!DBA::isResult($contact)) {
2949 return ($contact['forum'] || $contact['prv']);
2953 * Can the remote contact receive private messages?
2955 * @param array $contact
2958 public static function canReceivePrivateMessages(array $contact)
2960 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2961 $self = $contact['self'] ?? false;
2963 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2967 * Search contact table by nick or name
2969 * @param string $search Name or nick
2970 * @param string $mode Search mode (e.g. "community")
2971 * @param int $uid User ID
2973 * @return array with search results
2974 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2976 public static function searchByName(string $search, string $mode = '', int $uid = 0)
2978 if (empty($search)) {
2982 // check supported networks
2983 if (DI::config()->get('system', 'diaspora_enabled')) {
2984 $diaspora = Protocol::DIASPORA;
2986 $diaspora = Protocol::DFRN;
2989 if (!DI::config()->get('system', 'ostatus_disabled')) {
2990 $ostatus = Protocol::OSTATUS;
2992 $ostatus = Protocol::DFRN;
2995 // check if we search only communities or every contact
2996 if ($mode === 'community') {
2997 $extra_sql = sprintf(' AND `contact-type` = %d', self::TYPE_COMMUNITY);
3004 $results = DBA::p("SELECT * FROM `contact`
3005 WHERE (NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` where `publish` OR `net-publish`))
3006 AND `network` IN (?, ?, ?, ?) AND
3007 NOT `failed` AND `uid` = ? AND
3008 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
3009 ORDER BY `nurl` DESC LIMIT 1000",
3010 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $uid, $search, $search, $search
3013 $contacts = DBA::toArray($results);
3018 * Add public contacts from an array
3020 * @param array $urls
3021 * @return array result "count", "added" and "updated"
3023 public static function addByUrls(array $urls)
3030 foreach ($urls as $url) {
3031 if (empty($url) || !is_string($url)) {
3034 $contact = self::getByURL($url, false, ['id', 'updated']);
3035 if (empty($contact['id'])) {
3036 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3038 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3039 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3047 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3051 * Returns a random, global contact array of the current node
3053 * @return array The profile array
3056 public static function getRandomContact()
3058 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3059 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3060 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3061 ], ['order' => ['RAND()']]);
3063 if (DBA::isResult($contact)) {