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;
141 const MIRROR_DEACTIVATED = 0;
142 const MIRROR_FORWARDED = 1;
143 const MIRROR_OWN_POST = 2;
144 const MIRROR_NATIVE_RESHARE = 3;
147 * @param array $fields Array of selected fields, empty for all
148 * @param array $condition Array of fields for condition
149 * @param array $params Array of several parameters
153 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
155 return DBA::selectToArray('contact', $fields, $condition, $params);
159 * @param array $fields Array of selected fields, empty for all
160 * @param array $condition Array of fields for condition
161 * @param array $params Array of several parameters
165 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
167 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
173 * Insert a row into the contact table
174 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
176 * @param array $fields field array
177 * @param int $duplicate_mode Do an update on a duplicate entry
179 * @return int id of the created contact
182 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT)
184 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
185 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
188 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
190 if (empty($fields['created'])) {
191 $fields['created'] = DateTimeFormat::utcNow();
194 DBA::insert('contact', $fields, $duplicate_mode);
195 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
196 if (!DBA::isResult($contact)) {
198 Logger::warning('Created contact could not be found', ['fields' => $fields]);
202 Contact\User::insertForContactArray($contact);
204 // Search for duplicated contacts and get rid of them
205 if (!$contact['self']) {
206 self::removeDuplicates($contact['nurl'], $contact['uid']);
209 return $contact['id'];
213 * Updates rows in the contact table
215 * @param array $fields contains the fields that are updated
216 * @param array $condition condition array with the key values
217 * @param array|boolean $old_fields array with the old field values that are about to be replaced (true = update on duplicate, false = don't update identical fields)
219 * @return boolean was the update successfull?
222 public static function update(array $fields, array $condition, $old_fields = [])
224 $ret = DBA::update('contact', $fields, $condition, $old_fields);
226 // Apply changes to the "user-contact" table on dedicated fields
227 Contact\User::updateByContactUpdate($fields, $condition);
233 * @param integer $id Contact ID
234 * @param array $fields Array of selected fields, empty for all
235 * @return array|boolean Contact record if it exists, false otherwise
238 public static function getById($id, $fields = [])
240 return DBA::selectFirst('contact', $fields, ['id' => $id]);
244 * Fetches a contact by a given url
246 * @param string $url profile url
247 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
248 * @param array $fields Field list
249 * @param integer $uid User ID of the contact
250 * @return array contact array
252 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
254 if ($update || is_null($update)) {
255 $cid = self::getIdForURL($url, $uid, $update);
260 $contact = self::getById($cid, $fields);
261 if (empty($contact)) {
267 // Add internal fields
269 if (!empty($fields)) {
270 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
271 if (!in_array($internal, $fields)) {
272 $fields[] = $internal;
273 $removal[] = $internal;
278 // We first try the nurl (http://server.tld/nick), most common case
279 $options = ['order' => ['id']];
280 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
282 // Then the addr (nick@server.tld)
283 if (!DBA::isResult($contact)) {
284 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
287 // Then the alias (which could be anything)
288 if (!DBA::isResult($contact)) {
289 // The link could be provided as http although we stored it as https
290 $ssl_url = str_replace('http://', 'https://', $url);
291 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
292 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
295 if (!DBA::isResult($contact)) {
299 // Update the contact in the background if needed
300 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
301 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
302 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
305 // Remove the internal fields
306 foreach ($removal as $internal) {
307 unset($contact[$internal]);
314 * Fetches a contact for a given user by a given url.
315 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
317 * @param string $url profile url
318 * @param integer $uid User ID of the contact
319 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
320 * @param array $fields Field list
321 * @return array contact array
323 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
326 $contact = self::getByURL($url, $update, $fields, $uid);
327 if (!empty($contact)) {
328 if (!empty($contact['id'])) {
329 $contact['cid'] = $contact['id'];
336 $contact = self::getByURL($url, $update, $fields);
337 if (!empty($contact['id'])) {
339 $contact['zid'] = $contact['id'];
345 * Tests if the given contact is a follower
347 * @param int $cid Either public contact id or user's contact id
348 * @param int $uid User ID
350 * @return boolean is the contact id a follower?
351 * @throws HTTPException\InternalServerErrorException
352 * @throws \ImagickException
354 public static function isFollower($cid, $uid)
356 if (Contact\User::isBlocked($cid, $uid)) {
360 $cdata = self::getPublicAndUserContactID($cid, $uid);
361 if (empty($cdata['user'])) {
365 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
366 return DBA::exists('contact', $condition);
370 * Tests if the given contact url is a follower
372 * @param string $url Contact URL
373 * @param int $uid User ID
375 * @return boolean is the contact id a follower?
376 * @throws HTTPException\InternalServerErrorException
377 * @throws \ImagickException
379 public static function isFollowerByURL($url, $uid)
381 $cid = self::getIdForURL($url, $uid);
387 return self::isFollower($cid, $uid);
391 * Tests if the given user follow the given contact
393 * @param int $cid Either public contact id or user's contact id
394 * @param int $uid User ID
396 * @return boolean is the contact url being followed?
397 * @throws HTTPException\InternalServerErrorException
398 * @throws \ImagickException
400 public static function isSharing($cid, $uid)
402 if (Contact\User::isBlocked($cid, $uid)) {
406 $cdata = self::getPublicAndUserContactID($cid, $uid);
407 if (empty($cdata['user'])) {
411 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
412 return DBA::exists('contact', $condition);
416 * Tests if the given user follow the given contact url
418 * @param string $url Contact URL
419 * @param int $uid User ID
421 * @return boolean is the contact url being followed?
422 * @throws HTTPException\InternalServerErrorException
423 * @throws \ImagickException
425 public static function isSharingByURL($url, $uid)
427 $cid = self::getIdForURL($url, $uid);
433 return self::isSharing($cid, $uid);
437 * Get the basepath for a given contact link
439 * @param string $url The contact link
440 * @param boolean $dont_update Don't update the contact
442 * @return string basepath
443 * @throws HTTPException\InternalServerErrorException
444 * @throws \ImagickException
446 public static function getBasepath($url, $dont_update = false)
448 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
449 if (!DBA::isResult($contact)) {
453 if (!empty($contact['baseurl'])) {
454 return $contact['baseurl'];
455 } elseif ($dont_update) {
459 // Update the existing contact
460 self::updateFromProbe($contact['id']);
462 // And fetch the result
463 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
464 if (empty($contact['baseurl'])) {
465 Logger::info('No baseurl for contact', ['url' => $url]);
469 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
470 return $contact['baseurl'];
474 * Check if the given contact url is on the same server
476 * @param string $url The contact link
478 * @return boolean Is it the same server?
480 public static function isLocal($url)
482 if (!parse_url($url, PHP_URL_SCHEME)) {
483 $addr_parts = explode('@', $url);
484 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
487 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
491 * Check if the given contact ID is on the same server
493 * @param string $url The contact link
495 * @return boolean Is it the same server?
497 public static function isLocalById(int $cid)
499 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
500 if (!DBA::isResult($contact)) {
504 if (empty($contact['baseurl'])) {
505 $baseurl = self::getBasepath($contact['url'], true);
507 $baseurl = $contact['baseurl'];
510 return Strings::compareLink($baseurl, DI::baseUrl());
514 * Returns the public contact id of the given user id
516 * @param integer $uid User ID
518 * @return integer|boolean Public contact id for given user id
521 public static function getPublicIdByUserId($uid)
523 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
524 if (!DBA::isResult($self)) {
527 return self::getIdForURL($self['url']);
531 * Returns the contact id for the user and the public contact id for a given contact id
533 * @param int $cid Either public contact id or user's contact id
534 * @param int $uid User ID
536 * @return array with public and user's contact id
537 * @throws HTTPException\InternalServerErrorException
538 * @throws \ImagickException
540 public static function getPublicAndUserContactID($cid, $uid)
542 // We have to use the legacy function as long as the post update hasn't finished
543 if (DI::config()->get('system', 'post_update_version') < 1427) {
544 return self::legacyGetPublicAndUserContactID($cid, $uid);
547 if (empty($uid) || empty($cid)) {
551 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
552 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
556 $pcid = $contact['pid'];
557 if ($contact['uid'] == $uid) {
558 $ucid = $contact['id'];
560 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
561 if (DBA::isResult($contact)) {
562 $ucid = $contact['id'];
568 return ['public' => $pcid, 'user' => $ucid];
572 * Helper function for "getPublicAndUserContactID"
574 * @param int $cid Either public contact id or user's contact id
575 * @param int $uid User ID
577 * @return array with public and user's contact id
578 * @throws HTTPException\InternalServerErrorException
579 * @throws \ImagickException
581 private static function legacyGetPublicAndUserContactID($cid, $uid)
583 if (empty($uid) || empty($cid)) {
587 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
588 if (!DBA::isResult($contact)) {
592 // We quit when the user id don't match the user id of the provided contact
593 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
597 if ($contact['uid'] != 0) {
598 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
602 $ucid = $contact['id'];
604 $pcid = $contact['id'];
605 $ucid = self::getIdForURL($contact['url'], $uid);
608 return ['public' => $pcid, 'user' => $ucid];
612 * Returns contact details for a given contact id in combination with a user id
614 * @param int $cid A contact ID
615 * @param int $uid The User ID
616 * @param array $fields The selected fields for the contact
618 * @return array The contact details
622 public static function getContactForUser($cid, $uid, array $fields = [])
624 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
626 if (!DBA::isResult($contact)) {
634 * Creates the self-contact for the provided user id
637 * @return bool Operation success
638 * @throws HTTPException\InternalServerErrorException
640 public static function createSelfFromUserId($uid)
642 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
643 ['uid' => $uid, 'account_expired' => false]);
644 if (!DBA::isResult($user)) {
649 'uid' => $user['uid'],
650 'created' => DateTimeFormat::utcNow(),
652 'name' => $user['username'],
653 'nick' => $user['nickname'],
654 'pubkey' => $user['pubkey'],
655 'prvkey' => $user['prvkey'],
656 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
657 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
658 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
661 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
662 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
663 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
664 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
665 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
666 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
667 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
668 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
669 'name-date' => DateTimeFormat::utcNow(),
670 'uri-date' => DateTimeFormat::utcNow(),
671 'avatar-date' => DateTimeFormat::utcNow(),
677 // Only create the entry if it doesn't exist yet
678 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
679 $return = (bool)self::insert($contact);
682 // Create the public contact
683 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
684 $contact['self'] = false;
686 $contact['prvkey'] = null;
688 self::insert($contact, Database::INSERT_IGNORE);
695 * Updates the self-contact for the provided user id
698 * @param boolean $update_avatar Force the avatar update
699 * @return bool "true" if updated
700 * @throws HTTPException\InternalServerErrorException
702 public static function updateSelfFromUserID($uid, $update_avatar = false)
704 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
705 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
706 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
707 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
708 if (!DBA::isResult($self)) {
712 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
713 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
714 if (!DBA::isResult($user)) {
718 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
719 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
720 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
721 if (!DBA::isResult($profile)) {
725 $file_suffix = 'jpg';
727 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
728 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
729 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
730 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
731 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp'], 'matrix' => $profile['matrix'], 'network' => Protocol::DFRN];
733 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
734 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
735 $fields['nurl'] = Strings::normaliseLink($fields['url']);
736 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
737 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
738 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
739 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
740 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
741 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
743 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
744 if (DBA::isResult($avatar)) {
745 if ($update_avatar) {
746 $fields['avatar-date'] = DateTimeFormat::utcNow();
749 // Creating the path to the avatar, beginning with the file suffix
750 $types = Images::supportedTypes();
751 if (isset($types[$avatar['type']])) {
752 $file_suffix = $types[$avatar['type']];
755 // We are adding a timestamp value so that other systems won't use cached content
756 $timestamp = strtotime($fields['avatar-date']);
758 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
759 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
761 $fields['photo'] = $prefix . '4' . $suffix;
762 $fields['thumb'] = $prefix . '5' . $suffix;
763 $fields['micro'] = $prefix . '6' . $suffix;
765 // We hadn't found a photo entry, so we use the default avatar
766 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
767 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
768 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
771 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
772 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
773 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
774 $fields['unsearchable'] = !$profile['net-publish'];
778 foreach ($fields as $field => $content) {
779 if ($self[$field] != $content) {
785 if ($fields['name'] != $self['name']) {
786 $fields['name-date'] = DateTimeFormat::utcNow();
788 $fields['updated'] = DateTimeFormat::utcNow();
789 self::update($fields, ['id' => $self['id']]);
791 // Update the public contact as well
792 $fields['prvkey'] = null;
793 $fields['self'] = false;
794 self::update($fields, ['uid' => 0, 'nurl' => $self['nurl']]);
796 // Update the profile
797 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
798 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
799 DBA::update('profile', $fields, ['uid' => $uid]);
806 * Marks a contact for removal
808 * @param int $id contact id
810 * @throws HTTPException\InternalServerErrorException
812 public static function remove($id)
814 // We want just to make sure that we don't delete our "self" contact
815 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
816 if (!DBA::isResult($contact)) {
820 // Archive the contact
821 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
823 // Delete it in the background
824 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
828 * Sends an unfriend message. Does not remove the contact
830 * @param array $user User unfriending
831 * @param array $contact Contact unfriended
832 * @param boolean $dissolve Remove the contact on the remote side
834 * @throws HTTPException\InternalServerErrorException
835 * @throws \ImagickException
837 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
839 if (empty($contact['network'])) {
843 $protocol = $contact['network'];
844 if (($protocol == Protocol::DFRN) && !empty($contact['protocol'])) {
845 $protocol = $contact['protocol'];
848 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
849 // create an unfollow slap
851 $item['verb'] = Activity::O_UNFOLLOW;
852 $item['gravity'] = GRAVITY_ACTIVITY;
853 $item['follow'] = $contact["url"];
858 $slap = OStatus::salmon($item, $user);
860 if (!empty($contact['notify'])) {
861 Salmon::slapper($user, $contact['notify'], $slap);
863 } elseif ($protocol == Protocol::DIASPORA) {
864 Diaspora::sendUnshare($user, $contact);
865 } elseif ($protocol == Protocol::ACTIVITYPUB) {
866 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
869 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
875 * Marks a contact for archival after a communication issue delay
877 * Contact has refused to recognise us as a friend. We will start a countdown.
878 * If they still don't recognise us in 32 days, the relationship is over,
879 * and we won't waste any more time trying to communicate with them.
880 * This provides for the possibility that their database is temporarily messed
881 * up or some other transient event and that there's a possibility we could recover from it.
883 * @param array $contact contact to mark for archival
885 * @throws HTTPException\InternalServerErrorException
887 public static function markForArchival(array $contact)
889 if (!isset($contact['url']) && !empty($contact['id'])) {
890 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
891 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
892 if (!DBA::isResult($contact)) {
895 } elseif (!isset($contact['url'])) {
896 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
899 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
901 // Contact already archived or "self" contact? => nothing to do
902 if ($contact['archive'] || $contact['self']) {
906 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
907 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
908 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
911 * We really should send a notification to the owner after 2-3 weeks
912 * so they won't be surprised when the contact vanishes and can take
913 * remedial action if this was a serious mistake or glitch
916 /// @todo Check for contact vitality via probing
917 $archival_days = DI::config()->get('system', 'archival_days', 32);
919 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
920 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
921 /* Relationship is really truly dead. archive them rather than
922 * delete, though if the owner tries to unarchive them we'll start
923 * the whole process over again.
925 self::update(['archive' => true], ['id' => $contact['id']]);
926 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
932 * Cancels the archival countdown
934 * @see Contact::markForArchival()
936 * @param array $contact contact to be unmarked for archival
940 public static function unmarkForArchival(array $contact)
942 // Always unarchive the relay contact entry
943 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
944 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
945 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
946 if (!DBA::exists('contact', array_merge($condition, $fields))) {
947 self::update($fields, $condition);
951 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
952 $exists = DBA::exists('contact', $condition);
954 // We don't need to update, we never marked this contact for archival
959 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
961 if (!isset($contact['url']) && !empty($contact['id'])) {
962 $fields = ['id', 'url', 'batch'];
963 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
964 if (!DBA::isResult($contact)) {
969 // It's a miracle. Our dead contact has inexplicably come back to life.
970 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
971 self::update($fields, ['id' => $contact['id']]);
972 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
976 * Returns the data array for the photo menu of a given contact
978 * @param array $contact contact
979 * @param int $uid optional, default 0
981 * @throws HTTPException\InternalServerErrorException
982 * @throws \ImagickException
984 public static function photoMenu(array $contact, $uid = 0)
989 $contact_drop_link = '';
996 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
998 $profile_link = self::magicLinkByContact($contact);
999 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1004 // Look for our own contact if the uid doesn't match and isn't public
1005 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1006 if (DBA::isResult($contact_own)) {
1007 return self::photoMenu($contact_own, $uid);
1012 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1014 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1016 $profile_link = $contact['url'];
1019 if ($profile_link === 'mailbox') {
1024 $status_link = $profile_link . '/status';
1025 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1026 $profile_link = $profile_link . '/profile';
1029 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1030 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1033 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1034 $poke_link = 'contact/' . $contact['id'] . '/poke';
1037 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1039 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1041 if (!$contact['self']) {
1042 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1046 $unfollow_link = '';
1047 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1048 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1049 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1050 } elseif(!$contact['pending']) {
1051 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1055 if (!empty($follow_link) || !empty($unfollow_link)) {
1056 $contact_drop_link = '';
1061 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1063 if (empty($contact['uid'])) {
1065 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1066 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1067 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1068 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1069 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1073 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1074 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1075 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1076 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1077 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1078 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1079 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1080 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1081 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1082 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1085 if (!empty($contact['pending'])) {
1086 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1087 if (DBA::isResult($intro)) {
1088 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1093 $args = ['contact' => $contact, 'menu' => &$menu];
1095 Hook::callAll('contact_photo_menu', $args);
1097 $menucondensed = [];
1099 foreach ($menu as $menuname => $menuitem) {
1100 if ($menuitem[1] != '') {
1101 $menucondensed[$menuname] = $menuitem;
1105 return $menucondensed;
1109 * Fetch the contact id for a given URL and user
1111 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1112 * `addr` or `alias`.
1114 * If there's no record and we aren't looking for a public contact, we quit.
1115 * If there's one, we check that it isn't time to update the picture else we
1116 * directly return the found contact id.
1118 * Second, we probe the provided $url whether it's http://server.tld/profile or
1119 * nick@server.tld. We quit if we can't get any info back.
1121 * Third, we create the contact record if it doesn't exist
1123 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1124 * if there's any updates
1126 * @param string $url Contact URL
1127 * @param integer $uid The user id for the contact (0 = public contact)
1128 * @param boolean $update true = always update, false = never update, null = update when not found
1129 * @param array $default Default value for creating the contact when everything else fails
1131 * @return integer Contact ID
1132 * @throws HTTPException\InternalServerErrorException
1133 * @throws \ImagickException
1135 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1140 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1144 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1146 if (!empty($contact)) {
1147 $contact_id = $contact["id"];
1149 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1150 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1153 } elseif ($uid != 0) {
1154 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1156 } elseif (empty($default) && !is_null($update) && !$update) {
1157 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1163 if (empty($default['network']) || $update) {
1164 $data = Probe::uri($url, "", $uid);
1166 // Take the default values when probing failed
1167 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1168 $data = array_merge($data, $default);
1170 } elseif (!empty($default['network'])) {
1174 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1175 // Fetch data for the public contact via the first found personal contact
1176 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1177 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1178 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1179 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1181 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1182 if (!DBA::isResult($personal_contact)) {
1183 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1186 if (DBA::isResult($personal_contact)) {
1187 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1188 $data = $personal_contact;
1189 $data['photo'] = $personal_contact['avatar'];
1190 $data['account-type'] = $personal_contact['contact-type'];
1191 $data['hide'] = $personal_contact['unsearchable'];
1192 unset($data['avatar']);
1193 unset($data['contact-type']);
1194 unset($data['unsearchable']);
1198 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1199 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1204 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1205 if (!empty($data['alias'])) {
1206 $urls[] = Strings::normaliseLink($data['alias']);
1208 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1209 if (!empty($contact['id'])) {
1210 $contact_id = $contact['id'];
1211 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1216 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1219 'url' => $data['url'],
1220 'nurl' => Strings::normaliseLink($data['url']),
1221 'network' => $data['network'],
1222 'created' => DateTimeFormat::utcNow(),
1223 'rel' => self::SHARING,
1229 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1231 // Before inserting we do check if the entry does exist now.
1232 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1233 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1234 if (DBA::isResult($contact)) {
1235 $contact_id = $contact['id'];
1236 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1238 $contact_id = self::insert($fields);
1240 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1243 DI::lock()->release(self::LOCK_INSERT);
1245 Logger::warning('Contact lock had not been acquired');
1249 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1253 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1256 self::updateFromProbeArray($contact_id, $data);
1258 // Don't return a number for a deleted account
1259 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1260 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1268 * Checks if the contact is archived
1270 * @param int $cid contact id
1272 * @return boolean Is the contact archived?
1273 * @throws HTTPException\InternalServerErrorException
1275 public static function isArchived(int $cid)
1281 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1282 if (!DBA::isResult($contact)) {
1286 if ($contact['archive']) {
1290 // Check status of ActivityPub endpoints
1291 $apcontact = APContact::getByURL($contact['url'], false);
1292 if (!empty($apcontact)) {
1293 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1297 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1302 // Check status of Diaspora endpoints
1303 if (!empty($contact['batch'])) {
1304 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1305 return DBA::exists('contact', $condition);
1312 * Checks if the contact is blocked
1314 * @param int $cid contact id
1316 * @return boolean Is the contact blocked?
1317 * @throws HTTPException\InternalServerErrorException
1319 public static function isBlocked($cid)
1325 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1326 if (!DBA::isResult($blocked)) {
1330 if (Network::isUrlBlocked($blocked['url'])) {
1334 return (bool) $blocked['blocked'];
1338 * Checks if the contact is hidden
1340 * @param int $cid contact id
1342 * @return boolean Is the contact hidden?
1343 * @throws \Exception
1345 public static function isHidden($cid)
1351 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1352 if (!DBA::isResult($hidden)) {
1355 return (bool) $hidden['hidden'];
1359 * Returns posts from a given contact url
1361 * @param string $contact_url Contact URL
1362 * @param bool $thread_mode
1363 * @param int $update Update mode
1364 * @param int $parent Item parent ID for the update mode
1365 * @return string posts in HTML
1366 * @throws \Exception
1368 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1370 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1374 * Returns posts from a given contact id
1376 * @param int $cid Contact ID
1377 * @param bool $thread_mode
1378 * @param int $update Update mode
1379 * @param int $parent Item parent ID for the update mode
1380 * @return string posts in HTML
1381 * @throws \Exception
1383 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1387 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1388 if (!DBA::isResult($contact)) {
1392 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1393 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1398 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1401 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1402 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1404 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1405 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1408 if (!empty($parent)) {
1409 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1411 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1412 if (!empty($last_received)) {
1413 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1417 if (DI::mode()->isMobile()) {
1418 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1419 DI::config()->get('system', 'itemspage_network_mobile'));
1421 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1422 DI::config()->get('system', 'itemspage_network'));
1425 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1427 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1429 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1430 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1431 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1437 $items = Post::toArray(Post::selectForUser(local_user(), ['uri-id', 'gravity', 'parent-uri-id', 'thr-parent-id', 'author-id'], $condition, $params));
1439 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1441 $items = Post::toArray(Post::selectForUser(local_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1443 $o .= conversation($a, $items, 'contact-posts', $update);
1447 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1448 $o .= HTML::scrollLoader();
1450 $o .= $pager->renderMinimal(count($items));
1458 * Returns the account type name
1460 * The function can be called with either the user or the contact array
1462 * @param array $contact contact or user array
1465 public static function getAccountType(array $contact)
1467 // There are several fields that indicate that the contact or user is a forum
1468 // "page-flags" is a field in the user table,
1469 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1470 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1471 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1472 || (isset($contact['forum']) && intval($contact['forum']))
1473 || (isset($contact['prv']) && intval($contact['prv']))
1474 || (isset($contact['community']) && intval($contact['community']))
1476 $type = self::TYPE_COMMUNITY;
1478 $type = self::TYPE_PERSON;
1481 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1482 if (isset($contact["contact-type"])) {
1483 $type = $contact["contact-type"];
1486 if (isset($contact["account-type"])) {
1487 $type = $contact["account-type"];
1491 case self::TYPE_ORGANISATION:
1492 $account_type = DI::l10n()->t("Organisation");
1495 case self::TYPE_NEWS:
1496 $account_type = DI::l10n()->t('News');
1499 case self::TYPE_COMMUNITY:
1500 $account_type = DI::l10n()->t("Forum");
1508 return $account_type;
1516 * @throws \Exception
1518 public static function block($cid, $reason = null)
1520 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1526 * Unblocks a contact
1530 * @throws \Exception
1532 public static function unblock($cid)
1534 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1540 * Ensure that cached avatar exist
1542 * @param integer $cid
1544 public static function checkAvatarCache(int $cid)
1546 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1547 if (!DBA::isResult($contact)) {
1551 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1555 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1557 self::updateAvatar($cid, $contact['avatar'], true);
1561 * Return the photo path for a given contact array in the given size
1563 * @param array $contact contact array
1564 * @param string $field Fieldname of the photo in the contact array
1565 * @param string $size Size of the avatar picture
1566 * @param string $avatar Avatar path that is displayed when no photo had been found
1567 * @param bool $no_update Don't perfom an update if no cached avatar was found
1568 * @return string photo path
1570 private static function getAvatarPath(array $contact, string $size, $no_update = false)
1572 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1573 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1577 * Return the photo path for a given contact array
1579 * @param array $contact Contact array
1580 * @param bool $no_update Don't perfom an update if no cached avatar was found
1581 * @return string photo path
1583 public static function getPhoto(array $contact, bool $no_update = false)
1585 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1589 * Return the photo path (thumb size) for a given contact array
1591 * @param array $contact Contact array
1592 * @param bool $no_update Don't perfom an update if no cached avatar was found
1593 * @return string photo path
1595 public static function getThumb(array $contact, bool $no_update = false)
1597 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1601 * Return the photo path (micro size) for a given contact array
1603 * @param array $contact Contact array
1604 * @param bool $no_update Don't perfom an update if no cached avatar was found
1605 * @return string photo path
1607 public static function getMicro(array $contact, bool $no_update = false)
1609 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1613 * Check the given contact array for avatar cache fields
1615 * @param array $contact
1616 * @param bool $no_update Don't perfom an update if no cached avatar was found
1617 * @return array contact array with avatar cache fields
1619 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false)
1622 $contact_fields = [];
1623 $fields = ['photo', 'thumb', 'micro'];
1624 foreach ($fields as $field) {
1625 if (isset($contact[$field])) {
1626 $contact_fields[] = $field;
1628 if (isset($contact[$field]) && empty($contact[$field])) {
1633 if (!$update || $no_update) {
1637 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1638 self::updateAvatar($contact['id'], $contact['avatar'], true);
1640 $new_contact = self::getById($contact['id'], $contact_fields);
1641 if (DBA::isResult($new_contact)) {
1642 // We only update the cache fields
1643 $contact = array_merge($contact, $new_contact);
1647 /// add the default avatars if the fields aren't filled
1648 if (isset($contact['photo']) && empty($contact['photo'])) {
1649 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1651 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1652 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1654 if (isset($contact['micro']) && empty($contact['micro'])) {
1655 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1662 * Fetch the default avatar for the given contact and size
1664 * @param array $contact contact array
1665 * @param string $size Size of the avatar picture
1666 * @return string avatar URL
1668 public static function getDefaultAvatar(array $contact, string $size)
1671 case Proxy::SIZE_MICRO:
1672 $avatar['size'] = 48;
1673 $default = self::DEFAULT_AVATAR_MICRO;
1676 case Proxy::SIZE_THUMB:
1677 $avatar['size'] = 80;
1678 $default = self::DEFAULT_AVATAR_THUMB;
1681 case Proxy::SIZE_SMALL:
1683 $avatar['size'] = 300;
1684 $default = self::DEFAULT_AVATAR_PHOTO;
1688 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1689 return DI::baseUrl() . $default;
1692 if (!empty($contact['xmpp'])) {
1693 $avatar['email'] = $contact['xmpp'];
1694 } elseif (!empty($contact['addr'])) {
1695 $avatar['email'] = $contact['addr'];
1696 } elseif (!empty($contact['url'])) {
1697 $avatar['email'] = $contact['url'];
1699 return DI::baseUrl() . $default;
1702 $avatar['url'] = '';
1703 $avatar['success'] = false;
1705 Hook::callAll('avatar_lookup', $avatar);
1707 if ($avatar['success'] && !empty($avatar['url'])) {
1708 return $avatar['url'];
1711 return DI::baseUrl() . $default;
1715 * Get avatar link for given contact id
1717 * @param integer $cid contact id
1718 * @param string $size One of the ProxyUtils::SIZE_* constants
1719 * @param string $updated Contact update date
1720 * @return string avatar link
1722 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = ''):string
1724 // We have to fetch the "updated" variable when it wasn't provided
1725 // The parameter can be provided to improve performance
1726 if (empty($updated)) {
1727 $contact = self::getById($cid, ['updated']);
1728 $updated = $contact['updated'] ?? '';
1731 $url = DI::baseUrl() . '/photo/contact/';
1733 case Proxy::SIZE_MICRO:
1734 $url .= Proxy::PIXEL_MICRO . '/';
1736 case Proxy::SIZE_THUMB:
1737 $url .= Proxy::PIXEL_THUMB . '/';
1739 case Proxy::SIZE_SMALL:
1740 $url .= Proxy::PIXEL_SMALL . '/';
1742 case Proxy::SIZE_MEDIUM:
1743 $url .= Proxy::PIXEL_MEDIUM . '/';
1745 case Proxy::SIZE_LARGE:
1746 $url .= Proxy::PIXEL_LARGE . '/';
1749 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1753 * Get avatar link for given contact URL
1755 * @param string $url contact url
1756 * @param integer $uid user id
1757 * @param string $size One of the ProxyUtils::SIZE_* constants
1758 * @return string avatar link
1760 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''):string
1762 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
1763 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
1764 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
1765 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1769 * Get header link for given contact id
1771 * @param integer $cid contact id
1772 * @param string $size One of the ProxyUtils::SIZE_* constants
1773 * @param string $updated Contact update date
1774 * @return string header link
1776 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = ''):string
1778 // We have to fetch the "updated" variable when it wasn't provided
1779 // The parameter can be provided to improve performance
1780 if (empty($updated)) {
1781 $contact = self::getById($cid, ['updated']);
1782 $updated = $contact['updated'] ?? '';
1785 $url = DI::baseUrl() . '/photo/header/';
1787 case Proxy::SIZE_MICRO:
1788 $url .= Proxy::PIXEL_MICRO . '/';
1790 case Proxy::SIZE_THUMB:
1791 $url .= Proxy::PIXEL_THUMB . '/';
1793 case Proxy::SIZE_SMALL:
1794 $url .= Proxy::PIXEL_SMALL . '/';
1796 case Proxy::SIZE_MEDIUM:
1797 $url .= Proxy::PIXEL_MEDIUM . '/';
1799 case Proxy::SIZE_LARGE:
1800 $url .= Proxy::PIXEL_LARGE . '/';
1804 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1808 * Updates the avatar links in a contact only if needed
1810 * @param int $cid Contact id
1811 * @param string $avatar Link to avatar picture
1812 * @param bool $force force picture update
1813 * @param bool $create_cache Enforces the creation of cached avatar fields
1816 * @throws HTTPException\InternalServerErrorException
1817 * @throws HTTPException\NotFoundException
1818 * @throws \ImagickException
1820 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1822 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network'],
1823 ['id' => $cid, 'self' => false]);
1824 if (!DBA::isResult($contact)) {
1828 $uid = $contact['uid'];
1830 // Only update the cached photo links of public contacts when they already are cached
1831 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1832 if ($contact['avatar'] != $avatar) {
1833 self::update(['avatar' => $avatar], ['id' => $cid]);
1834 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1839 // User contacts use are updated through the public contacts
1840 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1841 $pcid = self::getIdForURL($contact['url'], 0, false);
1842 if (!empty($pcid)) {
1843 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1844 self::updateAvatar($pcid, $avatar, $force, true);
1849 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
1851 if ($default_avatar) {
1852 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1855 if ($default_avatar && Proxy::isLocalImage($avatar)) {
1856 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1858 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
1859 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
1860 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1863 // Use the data from the self account
1864 if (empty($fields)) {
1865 $local_uid = User::getIdForURL($contact['url']);
1866 if (!empty($local_uid)) {
1867 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1868 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1872 if (empty($fields)) {
1873 $update = ($contact['avatar'] != $avatar) || $force;
1877 $contact['photo'] ?? '',
1878 $contact['thumb'] ?? '',
1879 $contact['micro'] ?? '',
1882 foreach ($data as $image_uri) {
1883 $image_rid = Photo::ridFromURI($image_uri);
1884 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1885 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1892 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1894 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1895 $update = !empty($fields);
1896 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1902 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1911 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1912 // Collect all user contacts of the given public contact
1913 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1914 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1915 while ($personal_contact = DBA::fetch($personal_contacts)) {
1916 $cids[] = $personal_contact['id'];
1917 $uids[] = $personal_contact['uid'];
1919 DBA::close($personal_contacts);
1921 if (!empty($cids)) {
1922 // Delete possibly existing cached user contact avatars
1923 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1929 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1930 self::update($fields, ['id' => $cids]);
1933 public static function deleteContactByUrl(string $url)
1935 // Update contact data for all users
1936 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
1937 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
1938 while ($contact = DBA::fetch($contacts)) {
1939 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
1940 self::remove($contact['id']);
1945 * Helper function for "updateFromProbe". Updates personal and public contact
1947 * @param integer $id contact id
1948 * @param integer $uid user id
1949 * @param string $old_url The previous profile URL of the contact
1950 * @param string $new_url The profile URL of the contact
1951 * @param array $fields The fields that are updated
1953 * @throws \Exception
1955 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
1957 if (!self::update($fields, ['id' => $id])) {
1958 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1962 // Search for duplicated contacts and get rid of them
1963 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
1967 // Archive or unarchive the contact.
1968 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1969 if (!DBA::isResult($contact)) {
1970 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1974 if (isset($fields['failed'])) {
1975 if ($fields['failed']) {
1976 self::markForArchival($contact);
1978 self::unmarkForArchival($contact);
1982 if ($contact['uid'] != 0) {
1986 // Update contact data for all users
1987 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
1989 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
1990 self::update($fields, $condition);
1992 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
1993 $condition['network'] = Protocol::OSTATUS;
1995 // If the contact failed, propagate the update fields to all contacts
1996 if (empty($fields['failed'])) {
1997 unset($fields['last-update']);
1998 unset($fields['success_update']);
1999 unset($fields['failure_update']);
2002 if (empty($fields)) {
2006 self::update($fields, $condition);
2010 * Remove duplicated contacts
2012 * @param string $nurl Normalised contact url
2013 * @param integer $uid User id
2015 * @throws \Exception
2017 public static function removeDuplicates(string $nurl, int $uid)
2019 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2020 $count = DBA::count('contact', $condition);
2025 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2026 if (!DBA::isResult($first_contact)) {
2027 // Shouldn't happen - so we handle it
2031 $first = $first_contact['id'];
2032 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2033 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2034 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2035 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2039 // Find all duplicates
2040 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2041 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2042 while ($duplicate = DBA::fetch($duplicates)) {
2043 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2047 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2049 DBA::close($duplicates);
2050 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2055 * @param integer $id contact id
2056 * @param string $network Optional network we are probing for
2058 * @throws HTTPException\InternalServerErrorException
2059 * @throws \ImagickException
2061 public static function updateFromProbe(int $id, string $network = '')
2063 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2064 if (!DBA::isResult($contact)) {
2068 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2069 return self::updateFromProbeArray($id, $ret);
2073 * @param integer $id contact id
2074 * @param array $ret Probed data
2076 * @throws HTTPException\InternalServerErrorException
2077 * @throws \ImagickException
2079 private static function updateFromProbeArray(int $id, array $ret)
2082 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2083 This will reliably kill your communication with old Friendica contacts.
2086 // These fields aren't updated by this routine:
2089 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2090 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2091 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix'];
2092 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2093 if (!DBA::isResult($contact)) {
2097 if (self::isLocal($ret['url'])) {
2098 if ($contact['uid'] == 0) {
2099 Logger::info('Local contacts are not updated here.');
2101 self::updateFromPublicContact($id, $contact);
2106 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2107 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2110 // Delete all contacts with the same URL
2111 self::deleteContactByUrl($ret['url']);
2115 $uid = $contact['uid'];
2116 unset($contact['uid']);
2118 $uriid = $contact['uri-id'];
2119 unset($contact['uri-id']);
2121 $pubkey = $contact['pubkey'];
2122 unset($contact['pubkey']);
2124 $contact['photo'] = $contact['avatar'];
2125 unset($contact['avatar']);
2127 $updated = DateTimeFormat::utcNow();
2129 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2130 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2131 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2135 // We must not try to update relay contacts via probe. They are no real contacts.
2136 // We check after the probing to be able to correct falsely detected contact types.
2137 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2138 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2139 self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2140 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2144 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2145 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2146 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2150 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2151 $cid = self::getIdForURL($ret['url'], 0, false);
2152 if (!empty($cid) && ($cid != $id)) {
2153 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2154 return self::updateFromProbeArray($cid, $ret);
2158 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2159 $ret['unsearchable'] = $ret['hide'];
2162 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2163 $ret['forum'] = false;
2164 $ret['prv'] = false;
2165 $ret['contact-type'] = $ret['account-type'];
2166 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2167 $ret['forum'] = (bool)!$ret['manually-approve'];
2168 $ret['prv'] = (bool)!$ret['forum'];
2172 $new_pubkey = $ret['pubkey'] ?? '';
2175 $ret['last-item'] = Probe::getLastUpdate($ret);
2176 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2180 $guid = $ret['guid'] ?? '';
2182 // make sure to not overwrite existing values with blank entries except some technical fields
2183 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2184 foreach ($ret as $key => $val) {
2185 if (!array_key_exists($key, $contact)) {
2187 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2188 $ret[$key] = $contact[$key];
2189 } elseif ($ret[$key] != $contact[$key]) {
2194 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2197 unset($ret['last-item']);
2200 if (empty($uriid)) {
2204 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2205 self::updateAvatar($id, $ret['photo'], $update);
2209 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2211 if (Contact\Relation::isDiscoverable($ret['url'])) {
2212 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2215 // Update the public contact
2217 $contact = self::getByURL($ret['url'], false, ['id']);
2218 if (!empty($contact['id'])) {
2219 self::updateFromProbeArray($contact['id'], $ret);
2227 $ret['uri-id'] = ItemURI::getIdByURI($ret['url']);
2229 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2232 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2233 $ret['updated'] = $updated;
2234 $ret['failed'] = false;
2236 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2237 if (empty($pubkey) && !empty($new_pubkey)) {
2238 $ret['pubkey'] = $new_pubkey;
2241 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2242 $ret['uri-date'] = $updated;
2245 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2246 $ret['name-date'] = $updated;
2249 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2250 $ret['last-update'] = $updated;
2251 $ret['success_update'] = $updated;
2254 unset($ret['photo']);
2256 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2258 if (Contact\Relation::isDiscoverable($ret['url'])) {
2259 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2265 private static function updateFromPublicContact(int $id, array $contact)
2267 $public = self::getByURL($contact['url'], false);
2271 foreach ($contact as $field => $value) {
2272 if ($field == 'uid') {
2275 if ($public[$field] != $value) {
2276 $fields[$field] = $public[$field];
2279 if (!empty($fields)) {
2280 self::update($fields, ['id' => $id, 'self' => false]);
2281 Logger::info('Updating local contact', ['id' => $id]);
2286 * @param integer $url contact url
2287 * @return integer Contact id
2288 * @throws HTTPException\InternalServerErrorException
2289 * @throws \ImagickException
2291 public static function updateFromProbeByURL($url)
2293 $id = self::getIdForURL($url);
2299 self::updateFromProbe($id);
2305 * Detects the communication protocol for a given contact url.
2306 * This is used to detect Friendica contacts that we can communicate via AP.
2308 * @param string $url contact url
2309 * @param string $network Network of that contact
2310 * @return string with protocol
2312 public static function getProtocol($url, $network)
2314 if ($network != Protocol::DFRN) {
2318 $apcontact = APContact::getByURL($url);
2319 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2320 return Protocol::ACTIVITYPUB;
2327 * Takes a $uid and a url/handle and adds a new contact
2329 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2330 * dfrn_request page.
2332 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2335 * $return['success'] boolean true if successful
2336 * $return['message'] error text if success is false.
2338 * Takes a $uid and a url/handle and adds a new contact
2340 * @param int $uid The user id the contact should be created for
2341 * @param string $url The profile URL of the contact
2342 * @param string $network
2344 * @throws HTTPException\InternalServerErrorException
2345 * @throws HTTPException\NotFoundException
2346 * @throws \ImagickException
2348 public static function createFromProbeForUser(int $uid, $url, $network = '')
2350 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2352 // remove ajax junk, e.g. Twitter
2353 $url = str_replace('/#!/', '/', $url);
2355 if (!Network::isUrlAllowed($url)) {
2356 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2360 if (Network::isUrlBlocked($url)) {
2361 $result['message'] = DI::l10n()->t('Blocked domain');
2366 $result['message'] = DI::l10n()->t('Connect URL missing.');
2370 $arr = ['url' => $url, 'contact' => []];
2372 Hook::callAll('follow', $arr);
2375 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2379 if (!empty($arr['contact']['name'])) {
2381 $ret = $arr['contact'];
2384 $ret = Probe::uri($url, $network, $uid);
2387 if (($network != '') && ($ret['network'] != $network)) {
2388 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2392 // check if we already have a contact
2393 // the poll url is more reliable than the profile url, as we may have
2394 // indirect links or webfinger links
2396 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2397 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2398 if (!DBA::isResult($contact)) {
2399 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2400 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2403 $protocol = self::getProtocol($ret['url'], $ret['network']);
2405 // This extra param just confuses things, remove it
2406 if ($protocol === Protocol::DIASPORA) {
2407 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2410 // do we have enough information?
2411 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2412 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2413 if (empty($ret['poll'])) {
2414 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2416 if (empty($ret['name'])) {
2417 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2419 if (empty($ret['url'])) {
2420 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2422 if (strpos($ret['url'], '@') !== false) {
2423 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2424 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2429 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2430 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2431 $ret['notify'] = '';
2434 if (!$ret['notify']) {
2435 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2438 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2440 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2442 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2445 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2446 $pending = (bool)$ret['manually-approve'];
2449 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2453 if (DBA::isResult($contact)) {
2455 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2457 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2458 self::update($fields, ['id' => $contact['id']]);
2460 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2462 // create contact record
2465 'created' => DateTimeFormat::utcNow(),
2466 'url' => $ret['url'],
2467 'nurl' => Strings::normaliseLink($ret['url']),
2468 'addr' => $ret['addr'],
2469 'alias' => $ret['alias'],
2470 'batch' => $ret['batch'],
2471 'notify' => $ret['notify'],
2472 'poll' => $ret['poll'],
2473 'poco' => $ret['poco'],
2474 'name' => $ret['name'],
2475 'nick' => $ret['nick'],
2476 'network' => $ret['network'],
2477 'baseurl' => $ret['baseurl'],
2478 'gsid' => $ret['gsid'] ?? null,
2479 'protocol' => $protocol,
2480 'pubkey' => $ret['pubkey'],
2481 'rel' => $new_relation,
2482 'priority'=> $ret['priority'],
2483 'writable'=> $writeable,
2484 'hidden' => $hidden,
2487 'pending' => $pending,
2492 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2493 if (!DBA::isResult($contact)) {
2494 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2498 $contact_id = $contact['id'];
2499 $result['cid'] = $contact_id;
2501 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2503 // Update the avatar
2504 self::updateAvatar($contact_id, $ret['photo']);
2506 // pull feed and consume it, which should subscribe to the hub.
2507 if ($contact['network'] == Protocol::OSTATUS) {
2508 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2512 self::updateFromProbeArray($contact_id, $ret);
2514 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2517 $owner = User::getOwnerDataById($uid);
2519 if (DBA::isResult($owner)) {
2520 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2521 // create a follow slap
2523 $item['verb'] = Activity::FOLLOW;
2524 $item['gravity'] = GRAVITY_ACTIVITY;
2525 $item['follow'] = $contact["url"];
2527 $item['title'] = '';
2529 $item['uri-id'] = 0;
2531 $slap = OStatus::salmon($item, $owner);
2533 if (!empty($contact['notify'])) {
2534 Salmon::slapper($owner, $contact['notify'], $slap);
2536 } elseif ($protocol == Protocol::DIASPORA) {
2537 $ret = Diaspora::sendShare($owner, $contact);
2538 Logger::log('share returns: ' . $ret);
2539 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2540 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2541 if (empty($activity_id)) {
2542 // This really should never happen
2546 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2547 Logger::log('Follow returns: ' . $ret);
2551 $result['success'] = true;
2556 * Updated contact's SSL policy
2558 * @param array $contact Contact array
2559 * @param string $new_policy New policy, valid: self,full
2561 * @return array Contact array with updated values
2562 * @throws \Exception
2564 public static function updateSslPolicy(array $contact, $new_policy)
2566 $ssl_changed = false;
2567 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2568 $ssl_changed = true;
2569 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2570 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2571 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2572 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2573 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2574 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2577 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2578 $ssl_changed = true;
2579 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2580 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2581 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2582 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2583 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2584 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2588 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2589 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2590 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2591 self::update($fields, ['id' => $contact['id']]);
2600 * @param int $cid Public contact id
2601 * @param int $uid User ID
2603 * @return bool "true" if following had been successful
2605 public static function follow(int $cid, int $uid)
2607 $contact = self::getById($cid, ['url']);
2609 $result = self::createFromProbeForUser($uid, $contact['url']);
2611 return $result['cid'];
2615 * Unfollow a contact
2617 * @param int $cid Public contact id
2618 * @param int $uid User ID
2620 * @return bool "true" if unfollowing had been successful
2622 public static function unfollow(int $cid, int $uid)
2624 $cdata = self::getPublicAndUserContactID($cid, $uid);
2625 if (empty($cdata['user'])) {
2629 $contact = self::getById($cdata['user']);
2631 self::removeSharer([], $contact);
2637 * @param array $importer Owner (local user) data
2638 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2639 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2640 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2641 * @param string $note Introduction additional message
2642 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2643 * @throws HTTPException\InternalServerErrorException
2644 * @throws \ImagickException
2646 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2648 // Should always be set
2649 if (empty($datarray['author-id'])) {
2653 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2654 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2655 if (!DBA::isResult($pub_contact)) {
2656 // Should never happen
2660 // Contact is blocked at node-level
2661 if (self::isBlocked($datarray['author-id'])) {
2665 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2666 $name = $pub_contact['name'];
2667 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2668 $nick = $pub_contact['nick'];
2669 $network = $pub_contact['network'];
2671 // Ensure that we don't create a new contact when there already is one
2672 $cid = self::getIdForURL($url, $importer['uid']);
2674 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2677 if (!empty($contact)) {
2678 if (!empty($contact['pending'])) {
2679 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2683 // Contact is blocked at user-level
2684 if (!empty($contact['id']) && !empty($importer['id']) &&
2685 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2689 // Make sure that the existing contact isn't archived
2690 self::unmarkForArchival($contact);
2692 if (($contact['rel'] == self::SHARING)
2693 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2694 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2695 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2698 // Ensure to always have the correct network type, independent from the connection request method
2699 self::updateFromProbe($contact['id']);
2701 Post\UserNotification::insertNotication($contact['id'], Verb::getID(Activity::FOLLOW), $importer['uid']);
2705 // send email notification to owner?
2706 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2707 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2711 // create contact record
2712 $contact_id = self::insert([
2713 'uid' => $importer['uid'],
2714 'created' => DateTimeFormat::utcNow(),
2716 'nurl' => Strings::normaliseLink($url),
2719 'network' => $network,
2720 'rel' => self::FOLLOWER,
2727 // Ensure to always have the correct network type, independent from the connection request method
2728 self::updateFromProbe($contact_id);
2730 self::updateAvatar($contact_id, $photo, true);
2732 Post\UserNotification::insertNotication($contact_id, Verb::getID(Activity::FOLLOW), $importer['uid']);
2734 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2736 /// @TODO Encapsulate this into a function/method
2737 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2738 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2739 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2740 // create notification
2741 $hash = Strings::getRandomHex();
2743 if (is_array($contact_record)) {
2744 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2745 'blocked' => false, 'knowyou' => false, 'note' => $note,
2746 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2749 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2751 if (($user['notify-flags'] & Notification\Type::INTRO) &&
2752 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2755 'type' => Notification\Type::INTRO,
2756 'otype' => Notification\ObjectType::INTRO,
2757 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2758 'uid' => $user['uid'],
2759 'cid' => $contact_record['id'],
2760 'link' => DI::baseUrl() . '/notifications/intros',
2763 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2764 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2765 self::createFromProbeForUser($importer['uid'], $url, $network);
2768 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2769 $fields = ['pending' => false];
2770 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2771 $fields['rel'] = self::FRIEND;
2774 self::update($fields, $condition);
2783 public static function removeFollower($importer, $contact)
2785 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2786 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
2788 self::remove($contact['id']);
2792 public static function removeSharer($importer, $contact)
2794 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2795 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2797 self::remove($contact['id']);
2802 * Create a birthday event.
2804 * Update the year and the birthday.
2806 public static function updateBirthdays()
2810 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2811 AND NOT `contact`.`pending`
2812 AND NOT `contact`.`hidden`
2813 AND NOT `contact`.`blocked`
2814 AND NOT `contact`.`archive`
2815 AND NOT `contact`.`deleted`',
2821 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2823 while ($contact = DBA::fetch($contacts)) {
2824 Logger::log('update_contact_birthday: ' . $contact['bd']);
2826 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2828 if (Event::createBirthday($contact, $nextbd)) {
2832 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2833 ['id' => $contact['id']]
2837 DBA::close($contacts);
2841 * Remove the unavailable contact ids from the provided list
2843 * @param array $contact_ids Contact id list
2845 * @throws \Exception
2847 public static function pruneUnavailable(array $contact_ids)
2849 if (empty($contact_ids)) {
2853 $contacts = self::selectToArray(['id'], [
2854 'id' => $contact_ids,
2860 return array_column($contacts, 'id');
2864 * Returns a magic link to authenticate remote visitors
2866 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2868 * @param string $contact_url The address of the target contact profile
2869 * @param string $url An url that we will be redirected to after the authentication
2871 * @return string with "redir" link
2872 * @throws HTTPException\InternalServerErrorException
2873 * @throws \ImagickException
2875 public static function magicLink($contact_url, $url = '')
2877 if (!Session::isAuthenticated()) {
2878 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2881 $contact = self::getByURL($contact_url, false);
2882 if (empty($contact)) {
2883 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2886 // Prevents endless loop in case only a non-public contact exists for the contact URL
2887 unset($contact['uid']);
2889 return self::magicLinkByContact($contact, $url ?: $contact_url);
2893 * Returns a magic link to authenticate remote visitors
2895 * @param integer $cid The contact id of the target contact profile
2896 * @param string $url An url that we will be redirected to after the authentication
2898 * @return string with "redir" link
2899 * @throws HTTPException\InternalServerErrorException
2900 * @throws \ImagickException
2902 public static function magicLinkById($cid, $url = '')
2904 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2906 return self::magicLinkByContact($contact, $url);
2910 * Returns a magic link to authenticate remote visitors
2912 * @param array $contact The contact array with "uid", "network" and "url"
2913 * @param string $url An url that we will be redirected to after the authentication
2915 * @return string with "redir" link
2916 * @throws HTTPException\InternalServerErrorException
2917 * @throws \ImagickException
2919 public static function magicLinkByContact($contact, $url = '')
2921 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2923 if (!Session::isAuthenticated()) {
2924 return $destination;
2927 // Only redirections to the same host do make sense
2928 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2932 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2933 return 'contact/' . $contact['id'] . '/conversations';
2936 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
2937 return $destination;
2940 if (empty($contact['id'])) {
2941 return $destination;
2944 $redirect = 'redir/' . $contact['id'];
2946 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2947 $redirect .= '?url=' . $url;
2954 * Is the contact a forum?
2956 * @param integer $contactid ID of the contact
2958 * @return boolean "true" if it is a forum
2960 public static function isForum($contactid)
2962 $fields = ['forum', 'prv'];
2963 $condition = ['id' => $contactid];
2964 $contact = DBA::selectFirst('contact', $fields, $condition);
2965 if (!DBA::isResult($contact)) {
2970 return ($contact['forum'] || $contact['prv']);
2974 * Can the remote contact receive private messages?
2976 * @param array $contact
2979 public static function canReceivePrivateMessages(array $contact)
2981 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2982 $self = $contact['self'] ?? false;
2984 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2988 * Search contact table by nick or name
2990 * @param string $search Name or nick
2991 * @param string $mode Search mode (e.g. "community")
2992 * @param int $uid User ID
2994 * @return array with search results
2995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2997 public static function searchByName(string $search, string $mode = '', int $uid = 0)
2999 if (empty($search)) {
3003 // check supported networks
3004 if (DI::config()->get('system', 'diaspora_enabled')) {
3005 $diaspora = Protocol::DIASPORA;
3007 $diaspora = Protocol::DFRN;
3010 if (!DI::config()->get('system', 'ostatus_disabled')) {
3011 $ostatus = Protocol::OSTATUS;
3013 $ostatus = Protocol::DFRN;
3016 // check if we search only communities or every contact
3017 if ($mode === 'community') {
3018 $extra_sql = sprintf(' AND `contact-type` = %d', self::TYPE_COMMUNITY);
3025 $results = DBA::p("SELECT * FROM `contact`
3026 WHERE (NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` where `publish` OR `net-publish`))
3027 AND `network` IN (?, ?, ?, ?) AND
3028 NOT `failed` AND `uid` = ? AND
3029 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
3030 ORDER BY `nurl` DESC LIMIT 1000",
3031 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $uid, $search, $search, $search
3034 $contacts = DBA::toArray($results);
3039 * Add public contacts from an array
3041 * @param array $urls
3042 * @return array result "count", "added" and "updated"
3044 public static function addByUrls(array $urls)
3051 foreach ($urls as $url) {
3052 if (empty($url) || !is_string($url)) {
3055 $contact = self::getByURL($url, false, ['id', 'updated']);
3056 if (empty($contact['id'])) {
3057 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3059 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3060 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3068 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3072 * Returns a random, global contact array of the current node
3074 * @return array The profile array
3077 public static function getRandomContact()
3079 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3080 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3081 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3082 ], ['order' => ['RAND()']]);
3084 if (DBA::isResult($contact)) {