3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Model;
24 use Friendica\App\BaseURL;
25 use Friendica\Content\Pager;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Renderer;
31 use Friendica\Core\Session;
32 use Friendica\Core\System;
33 use Friendica\Core\Worker;
34 use Friendica\Database\Database;
35 use Friendica\Database\DBA;
37 use Friendica\Network\HTTPException;
38 use Friendica\Network\Probe;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Diaspora;
42 use Friendica\Protocol\OStatus;
43 use Friendica\Protocol\Salmon;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Images;
46 use Friendica\Util\Network;
47 use Friendica\Util\Proxy;
48 use Friendica\Util\Strings;
51 * functions for interacting with a contact
55 const DEFAULT_AVATAR_PHOTO = '/images/person-300.jpg';
56 const DEFAULT_AVATAR_THUMB = '/images/person-80.jpg';
57 const DEFAULT_AVATAR_MICRO = '/images/person-48.jpg';
60 * @deprecated since version 2019.03
61 * @see User::PAGE_FLAGS_NORMAL
63 const PAGE_NORMAL = User::PAGE_FLAGS_NORMAL;
65 * @deprecated since version 2019.03
66 * @see User::PAGE_FLAGS_SOAPBOX
68 const PAGE_SOAPBOX = User::PAGE_FLAGS_SOAPBOX;
70 * @deprecated since version 2019.03
71 * @see User::PAGE_FLAGS_COMMUNITY
73 const PAGE_COMMUNITY = User::PAGE_FLAGS_COMMUNITY;
75 * @deprecated since version 2019.03
76 * @see User::PAGE_FLAGS_FREELOVE
78 const PAGE_FREELOVE = User::PAGE_FLAGS_FREELOVE;
80 * @deprecated since version 2019.03
81 * @see User::PAGE_FLAGS_BLOG
83 const PAGE_BLOG = User::PAGE_FLAGS_BLOG;
85 * @deprecated since version 2019.03
86 * @see User::PAGE_FLAGS_PRVGROUP
88 const PAGE_PRVGROUP = User::PAGE_FLAGS_PRVGROUP;
93 const LOCK_INSERT = 'contact-insert';
98 * TYPE_UNKNOWN - unknown type
100 * TYPE_PERSON - the account belongs to a person
101 * Associated page types: PAGE_NORMAL, PAGE_SOAPBOX, PAGE_FREELOVE
103 * TYPE_ORGANISATION - the account belongs to an organisation
104 * Associated page type: PAGE_SOAPBOX
106 * TYPE_NEWS - the account is a news reflector
107 * Associated page type: PAGE_SOAPBOX
109 * TYPE_COMMUNITY - the account is community forum
110 * Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
112 * TYPE_RELAY - the account is a relay
113 * This will only be assigned to contacts, not to user accounts
116 const TYPE_UNKNOWN = -1;
117 const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON;
118 const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION;
119 const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS;
120 const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY;
121 const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY;
140 const MIRROR_DEACTIVATED = 0;
141 const MIRROR_FORWARDED = 1;
142 const MIRROR_OWN_POST = 2;
143 const MIRROR_NATIVE_RESHARE = 3;
146 * @param array $fields Array of selected fields, empty for all
147 * @param array $condition Array of fields for condition
148 * @param array $params Array of several parameters
152 public static function selectToArray(array $fields = [], array $condition = [], array $params = [])
154 return DBA::selectToArray('contact', $fields, $condition, $params);
158 * @param array $fields Array of selected fields, empty for all
159 * @param array $condition Array of fields for condition
160 * @param array $params Array of several parameters
164 public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
166 $contact = DBA::selectFirst('contact', $fields, $condition, $params);
172 * Insert a row into the contact table
173 * Important: You can't use DBA::lastInsertId() after this call since it will be set to 0.
175 * @param array $fields field array
176 * @param int $duplicate_mode Do an update on a duplicate entry
178 * @return int id of the created contact
181 public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT)
183 if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
184 $fields['gsid'] = GServer::getID($fields['baseurl'], true);
187 $fields['uri-id'] = ItemURI::getIdByURI($fields['url']);
189 if (empty($fields['created'])) {
190 $fields['created'] = DateTimeFormat::utcNow();
193 DBA::insert('contact', $fields, $duplicate_mode);
194 $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
195 if (!DBA::isResult($contact)) {
197 Logger::warning('Created contact could not be found', ['fields' => $fields]);
201 Contact\User::insertForContactArray($contact);
203 // Search for duplicated contacts and get rid of them
204 if (!$contact['self']) {
205 self::removeDuplicates($contact['nurl'], $contact['uid']);
208 return $contact['id'];
212 * Updates rows in the contact table
214 * @param array $fields contains the fields that are updated
215 * @param array $condition condition array with the key values
216 * @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)
218 * @return boolean was the update successfull?
221 public static function update(array $fields, array $condition, $old_fields = [])
223 $ret = DBA::update('contact', $fields, $condition, $old_fields);
225 // Apply changes to the "user-contact" table on dedicated fields
226 Contact\User::UpdateByContactUpdate($fields, $condition);
232 * @param integer $id Contact ID
233 * @param array $fields Array of selected fields, empty for all
234 * @return array|boolean Contact record if it exists, false otherwise
237 public static function getById($id, $fields = [])
239 return DBA::selectFirst('contact', $fields, ['id' => $id]);
243 * Fetches a contact by a given url
245 * @param string $url profile url
246 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
247 * @param array $fields Field list
248 * @param integer $uid User ID of the contact
249 * @return array contact array
251 public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0)
253 if ($update || is_null($update)) {
254 $cid = self::getIdForURL($url, $uid, $update);
259 $contact = self::getById($cid, $fields);
260 if (empty($contact)) {
266 // Add internal fields
268 if (!empty($fields)) {
269 foreach (['id', 'avatar', 'created', 'updated', 'last-update', 'success_update', 'failure_update', 'network'] as $internal) {
270 if (!in_array($internal, $fields)) {
271 $fields[] = $internal;
272 $removal[] = $internal;
277 // We first try the nurl (http://server.tld/nick), most common case
278 $options = ['order' => ['id']];
279 $contact = DBA::selectFirst('contact', $fields, ['nurl' => Strings::normaliseLink($url), 'uid' => $uid, 'deleted' => false], $options);
281 // Then the addr (nick@server.tld)
282 if (!DBA::isResult($contact)) {
283 $contact = DBA::selectFirst('contact', $fields, ['addr' => str_replace('acct:', '', $url), 'uid' => $uid, 'deleted' => false], $options);
286 // Then the alias (which could be anything)
287 if (!DBA::isResult($contact)) {
288 // The link could be provided as http although we stored it as https
289 $ssl_url = str_replace('http://', 'https://', $url);
290 $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid];
291 $contact = DBA::selectFirst('contact', $fields, $condition, $options);
294 if (!DBA::isResult($contact)) {
298 // Update the contact in the background if needed
299 $updated = max($contact['success_update'], $contact['created'], $contact['updated'], $contact['last-update'], $contact['failure_update']);
300 if (($updated < DateTimeFormat::utc('now -7 days')) && in_array($contact['network'], Protocol::FEDERATED) && !self::isLocalById($contact['id'])) {
301 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
304 // Remove the internal fields
305 foreach ($removal as $internal) {
306 unset($contact[$internal]);
313 * Fetches a contact for a given user by a given url.
314 * In difference to "getByURL" the function will fetch a public contact when no user contact had been found.
316 * @param string $url profile url
317 * @param integer $uid User ID of the contact
318 * @param boolean $update true = always update, false = never update, null = update when not found or outdated
319 * @param array $fields Field list
320 * @return array contact array
322 public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = [])
325 $contact = self::getByURL($url, $update, $fields, $uid);
326 if (!empty($contact)) {
327 if (!empty($contact['id'])) {
328 $contact['cid'] = $contact['id'];
335 $contact = self::getByURL($url, $update, $fields);
336 if (!empty($contact['id'])) {
338 $contact['zid'] = $contact['id'];
344 * Tests if the given contact is a follower
346 * @param int $cid Either public contact id or user's contact id
347 * @param int $uid User ID
349 * @return boolean is the contact id a follower?
350 * @throws HTTPException\InternalServerErrorException
351 * @throws \ImagickException
353 public static function isFollower($cid, $uid)
355 if (Contact\User::isBlocked($cid, $uid)) {
359 $cdata = self::getPublicAndUserContactID($cid, $uid);
360 if (empty($cdata['user'])) {
364 $condition = ['id' => $cdata['user'], 'rel' => [self::FOLLOWER, self::FRIEND]];
365 return DBA::exists('contact', $condition);
369 * Tests if the given contact url is a follower
371 * @param string $url Contact URL
372 * @param int $uid User ID
374 * @return boolean is the contact id a follower?
375 * @throws HTTPException\InternalServerErrorException
376 * @throws \ImagickException
378 public static function isFollowerByURL($url, $uid)
380 $cid = self::getIdForURL($url, $uid);
386 return self::isFollower($cid, $uid);
390 * Tests if the given user follow the given contact
392 * @param int $cid Either public contact id or user's contact id
393 * @param int $uid User ID
395 * @return boolean is the contact url being followed?
396 * @throws HTTPException\InternalServerErrorException
397 * @throws \ImagickException
399 public static function isSharing($cid, $uid)
401 if (Contact\User::isBlocked($cid, $uid)) {
405 $cdata = self::getPublicAndUserContactID($cid, $uid);
406 if (empty($cdata['user'])) {
410 $condition = ['id' => $cdata['user'], 'rel' => [self::SHARING, self::FRIEND]];
411 return DBA::exists('contact', $condition);
415 * Tests if the given user follow the given contact url
417 * @param string $url Contact URL
418 * @param int $uid User ID
420 * @return boolean is the contact url being followed?
421 * @throws HTTPException\InternalServerErrorException
422 * @throws \ImagickException
424 public static function isSharingByURL($url, $uid)
426 $cid = self::getIdForURL($url, $uid);
432 return self::isSharing($cid, $uid);
436 * Get the basepath for a given contact link
438 * @param string $url The contact link
439 * @param boolean $dont_update Don't update the contact
441 * @return string basepath
442 * @throws HTTPException\InternalServerErrorException
443 * @throws \ImagickException
445 public static function getBasepath($url, $dont_update = false)
447 $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
448 if (!DBA::isResult($contact)) {
452 if (!empty($contact['baseurl'])) {
453 return $contact['baseurl'];
454 } elseif ($dont_update) {
458 // Update the existing contact
459 self::updateFromProbe($contact['id']);
461 // And fetch the result
462 $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
463 if (empty($contact['baseurl'])) {
464 Logger::info('No baseurl for contact', ['url' => $url]);
468 Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
469 return $contact['baseurl'];
473 * Check if the given contact url is on the same server
475 * @param string $url The contact link
477 * @return boolean Is it the same server?
479 public static function isLocal($url)
481 if (!parse_url($url, PHP_URL_SCHEME)) {
482 $addr_parts = explode('@', $url);
483 return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
486 return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
490 * Check if the given contact ID is on the same server
492 * @param string $url The contact link
494 * @return boolean Is it the same server?
496 public static function isLocalById(int $cid)
498 $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
499 if (!DBA::isResult($contact)) {
503 if (empty($contact['baseurl'])) {
504 $baseurl = self::getBasepath($contact['url'], true);
506 $baseurl = $contact['baseurl'];
509 return Strings::compareLink($baseurl, DI::baseUrl());
513 * Returns the public contact id of the given user id
515 * @param integer $uid User ID
517 * @return integer|boolean Public contact id for given user id
520 public static function getPublicIdByUserId($uid)
522 $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
523 if (!DBA::isResult($self)) {
526 return self::getIdForURL($self['url']);
530 * Returns the contact id for the user and the public contact id for a given contact id
532 * @param int $cid Either public contact id or user's contact id
533 * @param int $uid User ID
535 * @return array with public and user's contact id
536 * @throws HTTPException\InternalServerErrorException
537 * @throws \ImagickException
539 public static function getPublicAndUserContactID($cid, $uid)
541 // We have to use the legacy function as long as the post update hasn't finished
542 if (DI::config()->get('system', 'post_update_version') < 1427) {
543 return self::legacyGetPublicAndUserContactID($cid, $uid);
546 if (empty($uid) || empty($cid)) {
550 $contact = DBA::selectFirst('account-user-view', ['id', 'uid', 'pid'], ['id' => $cid]);
551 if (!DBA::isResult($contact) || !in_array($contact['uid'], [0, $uid])) {
555 $pcid = $contact['pid'];
556 if ($contact['uid'] == $uid) {
557 $ucid = $contact['id'];
559 $contact = DBA::selectFirst('account-user-view', ['id', 'uid'], ['pid' => $cid, 'uid' => $uid]);
560 if (DBA::isResult($contact)) {
561 $ucid = $contact['id'];
567 return ['public' => $pcid, 'user' => $ucid];
571 * Helper function for "getPublicAndUserContactID"
573 * @param int $cid Either public contact id or user's contact id
574 * @param int $uid User ID
576 * @return array with public and user's contact id
577 * @throws HTTPException\InternalServerErrorException
578 * @throws \ImagickException
580 private static function legacyGetPublicAndUserContactID($cid, $uid)
582 if (empty($uid) || empty($cid)) {
586 $contact = DBA::selectFirst('contact', ['id', 'uid', 'url'], ['id' => $cid]);
587 if (!DBA::isResult($contact)) {
591 // We quit when the user id don't match the user id of the provided contact
592 if (($contact['uid'] != $uid) && ($contact['uid'] != 0)) {
596 if ($contact['uid'] != 0) {
597 $pcid = self::getIdForURL($contact['url'], 0, false, ['url' => $contact['url']]);
601 $ucid = $contact['id'];
603 $pcid = $contact['id'];
604 $ucid = self::getIdForURL($contact['url'], $uid);
607 return ['public' => $pcid, 'user' => $ucid];
611 * Returns contact details for a given contact id in combination with a user id
613 * @param int $cid A contact ID
614 * @param int $uid The User ID
615 * @param array $fields The selected fields for the contact
617 * @return array The contact details
621 public static function getContactForUser($cid, $uid, array $fields = [])
623 $contact = DBA::selectFirst('contact', $fields, ['id' => $cid, 'uid' => $uid]);
625 if (!DBA::isResult($contact)) {
633 * Creates the self-contact for the provided user id
636 * @return bool Operation success
637 * @throws HTTPException\InternalServerErrorException
639 public static function createSelfFromUserId($uid)
641 $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
642 ['uid' => $uid, 'account_expired' => false]);
643 if (!DBA::isResult($user)) {
648 'uid' => $user['uid'],
649 'created' => DateTimeFormat::utcNow(),
651 'name' => $user['username'],
652 'nick' => $user['nickname'],
653 'pubkey' => $user['pubkey'],
654 'prvkey' => $user['prvkey'],
655 'photo' => DI::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
656 'thumb' => DI::baseUrl() . '/photo/avatar/' . $user['uid'] . '.jpg',
657 'micro' => DI::baseUrl() . '/photo/micro/' . $user['uid'] . '.jpg',
660 'url' => DI::baseUrl() . '/profile/' . $user['nickname'],
661 'nurl' => Strings::normaliseLink(DI::baseUrl() . '/profile/' . $user['nickname']),
662 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
663 'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
664 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
665 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
666 'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
667 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
668 'name-date' => DateTimeFormat::utcNow(),
669 'uri-date' => DateTimeFormat::utcNow(),
670 'avatar-date' => DateTimeFormat::utcNow(),
676 // Only create the entry if it doesn't exist yet
677 if (!DBA::exists('contact', ['uid' => $uid, 'self' => true])) {
678 $return = (bool)self::insert($contact);
681 // Create the public contact
682 if (!DBA::exists('contact', ['nurl' => $contact['nurl'], 'uid' => 0])) {
683 $contact['self'] = false;
685 $contact['prvkey'] = null;
687 self::insert($contact, Database::INSERT_IGNORE);
694 * Updates the self-contact for the provided user id
697 * @param boolean $update_avatar Force the avatar update
698 * @return bool "true" if updated
699 * @throws HTTPException\InternalServerErrorException
701 public static function updateSelfFromUserID($uid, $update_avatar = false)
703 $fields = ['id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey',
704 'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
705 'photo', 'thumb', 'micro', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
706 $self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
707 if (!DBA::isResult($self)) {
711 $fields = ['nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
712 $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
713 if (!DBA::isResult($user)) {
717 $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
718 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
719 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
720 if (!DBA::isResult($profile)) {
724 $file_suffix = 'jpg';
726 $fields = ['name' => $profile['name'], 'nick' => $user['nickname'],
727 'avatar-date' => $self['avatar-date'], 'location' => Profile::formatLocation($profile),
728 'about' => $profile['about'], 'keywords' => $profile['pub_keywords'],
729 'contact-type' => $user['account-type'], 'prvkey' => $user['prvkey'],
730 'pubkey' => $user['pubkey'], 'xmpp' => $profile['xmpp'], 'matrix' => $profile['matrix'], 'network' => Protocol::DFRN];
732 // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine.
733 $fields['url'] = DI::baseUrl() . '/profile/' . $user['nickname'];
734 $fields['nurl'] = Strings::normaliseLink($fields['url']);
735 $fields['addr'] = $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
736 $fields['request'] = DI::baseUrl() . '/dfrn_request/' . $user['nickname'];
737 $fields['notify'] = DI::baseUrl() . '/dfrn_notify/' . $user['nickname'];
738 $fields['poll'] = DI::baseUrl() . '/dfrn_poll/'. $user['nickname'];
739 $fields['confirm'] = DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'];
740 $fields['poco'] = DI::baseUrl() . '/poco/' . $user['nickname'];
742 $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
743 if (DBA::isResult($avatar)) {
744 if ($update_avatar) {
745 $fields['avatar-date'] = DateTimeFormat::utcNow();
748 // Creating the path to the avatar, beginning with the file suffix
749 $types = Images::supportedTypes();
750 if (isset($types[$avatar['type']])) {
751 $file_suffix = $types[$avatar['type']];
754 // We are adding a timestamp value so that other systems won't use cached content
755 $timestamp = strtotime($fields['avatar-date']);
757 $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
758 $suffix = '.' . $file_suffix . '?ts=' . $timestamp;
760 $fields['photo'] = $prefix . '4' . $suffix;
761 $fields['thumb'] = $prefix . '5' . $suffix;
762 $fields['micro'] = $prefix . '6' . $suffix;
764 // We hadn't found a photo entry, so we use the default avatar
765 $fields['photo'] = self::getDefaultAvatar($fields, Proxy::SIZE_SMALL);
766 $fields['thumb'] = self::getDefaultAvatar($fields, Proxy::SIZE_THUMB);
767 $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO);
770 $fields['avatar'] = DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix;
771 $fields['forum'] = $user['page-flags'] == User::PAGE_FLAGS_COMMUNITY;
772 $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP;
773 $fields['unsearchable'] = !$profile['net-publish'];
777 foreach ($fields as $field => $content) {
778 if ($self[$field] != $content) {
784 if ($fields['name'] != $self['name']) {
785 $fields['name-date'] = DateTimeFormat::utcNow();
787 $fields['updated'] = DateTimeFormat::utcNow();
788 self::update($fields, ['id' => $self['id']]);
790 // Update the public contact as well
791 $fields['prvkey'] = null;
792 $fields['self'] = false;
793 self::update($fields, ['uid' => 0, 'nurl' => $self['nurl']]);
795 // Update the profile
796 $fields = ['photo' => DI::baseUrl() . '/photo/profile/' .$uid . '.' . $file_suffix,
797 'thumb' => DI::baseUrl() . '/photo/avatar/' . $uid .'.' . $file_suffix];
798 DBA::update('profile', $fields, ['uid' => $uid]);
805 * Marks a contact for removal
807 * @param int $id contact id
809 * @throws HTTPException\InternalServerErrorException
811 public static function remove($id)
813 // We want just to make sure that we don't delete our "self" contact
814 $contact = DBA::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
815 if (!DBA::isResult($contact)) {
819 // Archive the contact
820 self::update(['archive' => true, 'network' => Protocol::PHANTOM, 'deleted' => true], ['id' => $id]);
822 // Delete it in the background
823 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $id);
827 * Sends an unfriend message. Does not remove the contact
829 * @param array $user User unfriending
830 * @param array $contact Contact unfriended
831 * @param boolean $dissolve Remove the contact on the remote side
833 * @throws HTTPException\InternalServerErrorException
834 * @throws \ImagickException
836 public static function terminateFriendship(array $user, array $contact, $dissolve = false)
838 if (empty($contact['network'])) {
842 $protocol = $contact['network'];
843 if (($protocol == Protocol::DFRN) && !empty($contact['protocol'])) {
844 $protocol = $contact['protocol'];
847 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
848 // create an unfollow slap
850 $item['verb'] = Activity::O_UNFOLLOW;
851 $item['gravity'] = GRAVITY_ACTIVITY;
852 $item['follow'] = $contact["url"];
857 $slap = OStatus::salmon($item, $user);
859 if (!empty($contact['notify'])) {
860 Salmon::slapper($user, $contact['notify'], $slap);
862 } elseif ($protocol == Protocol::DIASPORA) {
863 Diaspora::sendUnshare($user, $contact);
864 } elseif ($protocol == Protocol::ACTIVITYPUB) {
865 ActivityPub\Transmitter::sendContactUndo($contact['url'], $contact['id'], $user['uid']);
868 ActivityPub\Transmitter::sendContactReject($contact['url'], $contact['hub-verify'], $user['uid']);
874 * Marks a contact for archival after a communication issue delay
876 * Contact has refused to recognise us as a friend. We will start a countdown.
877 * If they still don't recognise us in 32 days, the relationship is over,
878 * and we won't waste any more time trying to communicate with them.
879 * This provides for the possibility that their database is temporarily messed
880 * up or some other transient event and that there's a possibility we could recover from it.
882 * @param array $contact contact to mark for archival
884 * @throws HTTPException\InternalServerErrorException
886 public static function markForArchival(array $contact)
888 if (!isset($contact['url']) && !empty($contact['id'])) {
889 $fields = ['id', 'url', 'archive', 'self', 'term-date'];
890 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
891 if (!DBA::isResult($contact)) {
894 } elseif (!isset($contact['url'])) {
895 Logger::info('Empty contact', ['contact' => $contact, 'callstack' => System::callstack(20)]);
898 Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
900 // Contact already archived or "self" contact? => nothing to do
901 if ($contact['archive'] || $contact['self']) {
905 if ($contact['term-date'] <= DBA::NULL_DATETIME) {
906 self::update(['term-date' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
907 self::update(['term-date' => DateTimeFormat::utcNow()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', Strings::normaliseLink($contact['url']), DBA::NULL_DATETIME]);
910 * We really should send a notification to the owner after 2-3 weeks
911 * so they won't be surprised when the contact vanishes and can take
912 * remedial action if this was a serious mistake or glitch
915 /// @todo Check for contact vitality via probing
916 $archival_days = DI::config()->get('system', 'archival_days', 32);
918 $expiry = $contact['term-date'] . ' + ' . $archival_days . ' days ';
919 if (DateTimeFormat::utcNow() > DateTimeFormat::utc($expiry)) {
920 /* Relationship is really truly dead. archive them rather than
921 * delete, though if the owner tries to unarchive them we'll start
922 * the whole process over again.
924 self::update(['archive' => true], ['id' => $contact['id']]);
925 self::update(['archive' => true], ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
931 * Cancels the archival countdown
933 * @see Contact::markForArchival()
935 * @param array $contact contact to be unmarked for archival
939 public static function unmarkForArchival(array $contact)
941 // Always unarchive the relay contact entry
942 if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) {
943 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
944 $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
945 if (!DBA::exists('contact', array_merge($condition, $fields))) {
946 self::update($fields, $condition);
950 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], DBA::NULL_DATETIME];
951 $exists = DBA::exists('contact', $condition);
953 // We don't need to update, we never marked this contact for archival
958 Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date']]);
960 if (!isset($contact['url']) && !empty($contact['id'])) {
961 $fields = ['id', 'url', 'batch'];
962 $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]);
963 if (!DBA::isResult($contact)) {
968 // It's a miracle. Our dead contact has inexplicably come back to life.
969 $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
970 self::update($fields, ['id' => $contact['id']]);
971 self::update($fields, ['nurl' => Strings::normaliseLink($contact['url']), 'self' => false]);
975 * Returns the data array for the photo menu of a given contact
977 * @param array $contact contact
978 * @param int $uid optional, default 0
980 * @throws HTTPException\InternalServerErrorException
981 * @throws \ImagickException
983 public static function photoMenu(array $contact, $uid = 0)
988 $contact_drop_link = '';
995 if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
997 $profile_link = self::magicLinkByContact($contact);
998 $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
1003 // Look for our own contact if the uid doesn't match and isn't public
1004 $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
1005 if (DBA::isResult($contact_own)) {
1006 return self::photoMenu($contact_own, $uid);
1011 if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1013 $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
1015 $profile_link = $contact['url'];
1018 if ($profile_link === 'mailbox') {
1023 $status_link = $profile_link . '/status';
1024 $photos_link = str_replace('/profile/', '/photos/', $profile_link);
1025 $profile_link = $profile_link . '/profile';
1028 if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
1029 $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
1032 if (($contact['network'] == Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
1033 $poke_link = 'contact/' . $contact['id'] . '/poke';
1036 $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
1038 $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
1040 if (!$contact['self']) {
1041 $contact_drop_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/drop?confirm=1';
1045 $unfollow_link = '';
1046 if (!$contact['self'] && in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
1047 if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
1048 $unfollow_link = 'unfollow?url=' . urlencode($contact['url']) . '&auto=1';
1049 } elseif(!$contact['pending']) {
1050 $follow_link = 'follow?url=' . urlencode($contact['url']) . '&auto=1';
1054 if (!empty($follow_link) || !empty($unfollow_link)) {
1055 $contact_drop_link = '';
1060 * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
1062 if (empty($contact['uid'])) {
1064 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1065 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1066 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1067 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1068 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link, true],
1072 'status' => [DI::l10n()->t('View Status') , $status_link , true],
1073 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
1074 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
1075 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
1076 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
1077 'drop' => [DI::l10n()->t('Drop Contact') , $contact_drop_link, false],
1078 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
1079 'poke' => [DI::l10n()->t('Poke') , $poke_link , false],
1080 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
1081 'unfollow'=> [DI::l10n()->t('UnFollow') , $unfollow_link , true],
1084 if (!empty($contact['pending'])) {
1085 $intro = DBA::selectFirst('intro', ['id'], ['contact-id' => $contact['id']]);
1086 if (DBA::isResult($intro)) {
1087 $menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro['id'], true];
1092 $args = ['contact' => $contact, 'menu' => &$menu];
1094 Hook::callAll('contact_photo_menu', $args);
1096 $menucondensed = [];
1098 foreach ($menu as $menuname => $menuitem) {
1099 if ($menuitem[1] != '') {
1100 $menucondensed[$menuname] = $menuitem;
1104 return $menucondensed;
1108 * Fetch the contact id for a given URL and user
1110 * First lookup in the contact table to find a record matching either `url`, `nurl`,
1111 * `addr` or `alias`.
1113 * If there's no record and we aren't looking for a public contact, we quit.
1114 * If there's one, we check that it isn't time to update the picture else we
1115 * directly return the found contact id.
1117 * Second, we probe the provided $url whether it's http://server.tld/profile or
1118 * nick@server.tld. We quit if we can't get any info back.
1120 * Third, we create the contact record if it doesn't exist
1122 * Fourth, we update the existing record with the new data (avatar, alias, nick)
1123 * if there's any updates
1125 * @param string $url Contact URL
1126 * @param integer $uid The user id for the contact (0 = public contact)
1127 * @param boolean $update true = always update, false = never update, null = update when not found
1128 * @param array $default Default value for creating the contact when everything else fails
1130 * @return integer Contact ID
1131 * @throws HTTPException\InternalServerErrorException
1132 * @throws \ImagickException
1134 public static function getIdForURL($url, $uid = 0, $update = null, $default = [])
1139 Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
1143 $contact = self::getByURL($url, false, ['id', 'network', 'uri-id'], $uid);
1145 if (!empty($contact)) {
1146 $contact_id = $contact["id"];
1148 if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
1149 Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1152 } elseif ($uid != 0) {
1153 Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1155 } elseif (empty($default) && !is_null($update) && !$update) {
1156 Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
1162 if (empty($default['network']) || $update) {
1163 $data = Probe::uri($url, "", $uid);
1165 // Take the default values when probing failed
1166 if (!empty($default) && !in_array($data["network"], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::PUMPIO]))) {
1167 $data = array_merge($data, $default);
1169 } elseif (!empty($default['network'])) {
1173 if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
1174 // Fetch data for the public contact via the first found personal contact
1175 /// @todo Check if this case can happen at all (possibly with mail accounts?)
1176 $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
1177 'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
1178 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
1180 $personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
1181 if (!DBA::isResult($personal_contact)) {
1182 $personal_contact = DBA::selectFirst('contact', $fields, ["`nurl` = ? AND `uid` != 0", Strings::normaliseLink($url)]);
1185 if (DBA::isResult($personal_contact)) {
1186 Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact, 'callstack' => System::callstack(20)]);
1187 $data = $personal_contact;
1188 $data['photo'] = $personal_contact['avatar'];
1189 $data['account-type'] = $personal_contact['contact-type'];
1190 $data['hide'] = $personal_contact['unsearchable'];
1191 unset($data['avatar']);
1192 unset($data['contact-type']);
1193 unset($data['unsearchable']);
1197 if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
1198 Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update, 'callstack' => System::callstack(20)]);
1203 $urls = [Strings::normaliseLink($url), Strings::normaliseLink($data['url'])];
1204 if (!empty($data['alias'])) {
1205 $urls[] = Strings::normaliseLink($data['alias']);
1207 $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
1208 if (!empty($contact['id'])) {
1209 $contact_id = $contact['id'];
1210 Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
1215 // We only insert the basic data. The rest will be done in "updateFromProbeArray"
1218 'url' => $data['url'],
1219 'nurl' => Strings::normaliseLink($data['url']),
1220 'network' => $data['network'],
1221 'created' => DateTimeFormat::utcNow(),
1222 'rel' => self::SHARING,
1228 $condition = ['nurl' => Strings::normaliseLink($data["url"]), 'uid' => $uid, 'deleted' => false];
1230 // Before inserting we do check if the entry does exist now.
1231 if (DI::lock()->acquire(self::LOCK_INSERT, 0)) {
1232 $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
1233 if (DBA::isResult($contact)) {
1234 $contact_id = $contact['id'];
1235 Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1237 $contact_id = self::insert($fields);
1239 Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
1242 DI::lock()->release(self::LOCK_INSERT);
1244 Logger::warning('Contact lock had not been acquired');
1248 Logger::info('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
1252 Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
1255 self::updateFromProbeArray($contact_id, $data);
1257 // Don't return a number for a deleted account
1258 if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
1259 Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
1267 * Checks if the contact is archived
1269 * @param int $cid contact id
1271 * @return boolean Is the contact archived?
1272 * @throws HTTPException\InternalServerErrorException
1274 public static function isArchived(int $cid)
1280 $contact = DBA::selectFirst('contact', ['archive', 'url', 'batch'], ['id' => $cid]);
1281 if (!DBA::isResult($contact)) {
1285 if ($contact['archive']) {
1289 // Check status of ActivityPub endpoints
1290 $apcontact = APContact::getByURL($contact['url'], false);
1291 if (!empty($apcontact)) {
1292 if (!empty($apcontact['inbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['inbox']])) {
1296 if (!empty($apcontact['sharedinbox']) && DBA::exists('inbox-status', ['archive' => true, 'url' => $apcontact['sharedinbox']])) {
1301 // Check status of Diaspora endpoints
1302 if (!empty($contact['batch'])) {
1303 $condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
1304 return DBA::exists('contact', $condition);
1311 * Checks if the contact is blocked
1313 * @param int $cid contact id
1315 * @return boolean Is the contact blocked?
1316 * @throws HTTPException\InternalServerErrorException
1318 public static function isBlocked($cid)
1324 $blocked = DBA::selectFirst('contact', ['blocked', 'url'], ['id' => $cid]);
1325 if (!DBA::isResult($blocked)) {
1329 if (Network::isUrlBlocked($blocked['url'])) {
1333 return (bool) $blocked['blocked'];
1337 * Checks if the contact is hidden
1339 * @param int $cid contact id
1341 * @return boolean Is the contact hidden?
1342 * @throws \Exception
1344 public static function isHidden($cid)
1350 $hidden = DBA::selectFirst('contact', ['hidden'], ['id' => $cid]);
1351 if (!DBA::isResult($hidden)) {
1354 return (bool) $hidden['hidden'];
1358 * Returns posts from a given contact url
1360 * @param string $contact_url Contact URL
1361 * @param bool $thread_mode
1362 * @param int $update Update mode
1363 * @param int $parent Item parent ID for the update mode
1364 * @return string posts in HTML
1365 * @throws \Exception
1367 public static function getPostsFromUrl($contact_url, $thread_mode = false, $update = 0, $parent = 0)
1369 return self::getPostsFromId(self::getIdForURL($contact_url), $thread_mode, $update, $parent);
1373 * Returns posts from a given contact id
1375 * @param int $cid Contact ID
1376 * @param bool $thread_mode
1377 * @param int $update Update mode
1378 * @param int $parent Item parent ID for the update mode
1379 * @return string posts in HTML
1380 * @throws \Exception
1382 public static function getPostsFromId($cid, $thread_mode = false, $update = 0, $parent = 0)
1386 $contact = DBA::selectFirst('contact', ['contact-type', 'network'], ['id' => $cid]);
1387 if (!DBA::isResult($contact)) {
1391 if (empty($contact["network"]) || in_array($contact["network"], Protocol::FEDERATED)) {
1392 $sql = "(`uid` = 0 OR (`uid` = ? AND NOT `global`))";
1397 $contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
1400 $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ?)) AND " . $sql,
1401 $cid, GRAVITY_PARENT, $cid, GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), local_user()];
1403 $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
1404 $cid, GRAVITY_PARENT, GRAVITY_COMMENT, local_user()];
1407 if (!empty($parent)) {
1408 $condition = DBA::mergeConditions($condition, ['parent' => $parent]);
1410 $last_received = isset($_GET['last_received']) ? DateTimeFormat::utc($_GET['last_received']) : '';
1411 if (!empty($last_received)) {
1412 $condition = DBA::mergeConditions($condition, ["`received` < ?", $last_received]);
1416 if (DI::mode()->isMobile()) {
1417 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_mobile_network',
1418 DI::config()->get('system', 'itemspage_network_mobile'));
1420 $itemsPerPage = DI::pConfig()->get(local_user(), 'system', 'itemspage_network',
1421 DI::config()->get('system', 'itemspage_network'));
1424 $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
1426 $params = ['order' => ['received' => true], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]];
1428 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1429 $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl');
1430 $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]);
1436 $items = Post::toArray(Post::selectForUser(local_user(), ['uri-id', 'gravity', 'parent-uri-id', 'thr-parent-id', 'author-id'], $condition, $params));
1438 $o .= conversation($a, $items, 'contacts', $update, false, 'commented', local_user());
1440 $items = Post::toArray(Post::selectForUser(local_user(), Item::DISPLAY_FIELDLIST, $condition, $params));
1442 $o .= conversation($a, $items, 'contact-posts', $update);
1446 if (DI::pConfig()->get(local_user(), 'system', 'infinite_scroll')) {
1447 $o .= HTML::scrollLoader();
1449 $o .= $pager->renderMinimal(count($items));
1457 * Returns the account type name
1459 * The function can be called with either the user or the contact array
1461 * @param array $contact contact or user array
1464 public static function getAccountType(array $contact)
1466 // There are several fields that indicate that the contact or user is a forum
1467 // "page-flags" is a field in the user table,
1468 // "forum" and "prv" are used in the contact table. They stand for User::PAGE_FLAGS_COMMUNITY and User::PAGE_FLAGS_PRVGROUP.
1469 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_COMMUNITY))
1470 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == User::PAGE_FLAGS_PRVGROUP))
1471 || (isset($contact['forum']) && intval($contact['forum']))
1472 || (isset($contact['prv']) && intval($contact['prv']))
1473 || (isset($contact['community']) && intval($contact['community']))
1475 $type = self::TYPE_COMMUNITY;
1477 $type = self::TYPE_PERSON;
1480 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
1481 if (isset($contact["contact-type"])) {
1482 $type = $contact["contact-type"];
1485 if (isset($contact["account-type"])) {
1486 $type = $contact["account-type"];
1490 case self::TYPE_ORGANISATION:
1491 $account_type = DI::l10n()->t("Organisation");
1494 case self::TYPE_NEWS:
1495 $account_type = DI::l10n()->t('News');
1498 case self::TYPE_COMMUNITY:
1499 $account_type = DI::l10n()->t("Forum");
1507 return $account_type;
1515 * @throws \Exception
1517 public static function block($cid, $reason = null)
1519 $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
1525 * Unblocks a contact
1529 * @throws \Exception
1531 public static function unblock($cid)
1533 $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
1539 * Ensure that cached avatar exist
1541 * @param integer $cid
1543 public static function checkAvatarCache(int $cid)
1545 $contact = DBA::selectFirst('contact', ['url', 'avatar', 'photo', 'thumb', 'micro'], ['id' => $cid, 'uid' => 0, 'self' => false]);
1546 if (!DBA::isResult($contact)) {
1550 if (empty($contact['avatar']) || (!empty($contact['photo']) && !empty($contact['thumb']) && !empty($contact['micro']))) {
1554 Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
1556 self::updateAvatar($cid, $contact['avatar'], true);
1560 * Return the photo path for a given contact array in the given size
1562 * @param array $contact contact array
1563 * @param string $field Fieldname of the photo in the contact array
1564 * @param string $size Size of the avatar picture
1565 * @param string $avatar Avatar path that is displayed when no photo had been found
1566 * @param bool $no_update Don't perfom an update if no cached avatar was found
1567 * @return string photo path
1569 private static function getAvatarPath(array $contact, string $size, $no_update = false)
1571 $contact = self::checkAvatarCacheByArray($contact, $no_update);
1572 return self::getAvatarUrlForId($contact['id'], $size, $contact['updated'] ?? '');
1576 * Return the photo path for a given contact array
1578 * @param array $contact Contact array
1579 * @param bool $no_update Don't perfom an update if no cached avatar was found
1580 * @return string photo path
1582 public static function getPhoto(array $contact, bool $no_update = false)
1584 return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
1588 * Return the photo path (thumb size) for a given contact array
1590 * @param array $contact Contact array
1591 * @param bool $no_update Don't perfom an update if no cached avatar was found
1592 * @return string photo path
1594 public static function getThumb(array $contact, bool $no_update = false)
1596 return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
1600 * Return the photo path (micro size) for a given contact array
1602 * @param array $contact Contact array
1603 * @param bool $no_update Don't perfom an update if no cached avatar was found
1604 * @return string photo path
1606 public static function getMicro(array $contact, bool $no_update = false)
1608 return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
1612 * Check the given contact array for avatar cache fields
1614 * @param array $contact
1615 * @param bool $no_update Don't perfom an update if no cached avatar was found
1616 * @return array contact array with avatar cache fields
1618 private static function checkAvatarCacheByArray(array $contact, bool $no_update = false)
1621 $contact_fields = [];
1622 $fields = ['photo', 'thumb', 'micro'];
1623 foreach ($fields as $field) {
1624 if (isset($contact[$field])) {
1625 $contact_fields[] = $field;
1627 if (isset($contact[$field]) && empty($contact[$field])) {
1632 if (!$update || $no_update) {
1636 if (!empty($contact['id']) && !empty($contact['avatar'])) {
1637 self::updateAvatar($contact['id'], $contact['avatar'], true);
1639 $new_contact = self::getById($contact['id'], $contact_fields);
1640 if (DBA::isResult($new_contact)) {
1641 // We only update the cache fields
1642 $contact = array_merge($contact, $new_contact);
1646 /// add the default avatars if the fields aren't filled
1647 if (isset($contact['photo']) && empty($contact['photo'])) {
1648 $contact['photo'] = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1650 if (isset($contact['thumb']) && empty($contact['thumb'])) {
1651 $contact['thumb'] = self::getDefaultAvatar($contact, Proxy::SIZE_THUMB);
1653 if (isset($contact['micro']) && empty($contact['micro'])) {
1654 $contact['micro'] = self::getDefaultAvatar($contact, Proxy::SIZE_MICRO);
1661 * Fetch the default avatar for the given contact and size
1663 * @param array $contact contact array
1664 * @param string $size Size of the avatar picture
1665 * @return string avatar URL
1667 public static function getDefaultAvatar(array $contact, string $size)
1670 case Proxy::SIZE_MICRO:
1671 $avatar['size'] = 48;
1672 $default = self::DEFAULT_AVATAR_MICRO;
1675 case Proxy::SIZE_THUMB:
1676 $avatar['size'] = 80;
1677 $default = self::DEFAULT_AVATAR_THUMB;
1680 case Proxy::SIZE_SMALL:
1682 $avatar['size'] = 300;
1683 $default = self::DEFAULT_AVATAR_PHOTO;
1687 if (!DI::config()->get('system', 'remote_avatar_lookup')) {
1688 return DI::baseUrl() . $default;
1691 if (!empty($contact['xmpp'])) {
1692 $avatar['email'] = $contact['xmpp'];
1693 } elseif (!empty($contact['addr'])) {
1694 $avatar['email'] = $contact['addr'];
1695 } elseif (!empty($contact['url'])) {
1696 $avatar['email'] = $contact['url'];
1698 return DI::baseUrl() . $default;
1701 $avatar['url'] = '';
1702 $avatar['success'] = false;
1704 Hook::callAll('avatar_lookup', $avatar);
1706 if ($avatar['success'] && !empty($avatar['url'])) {
1707 return $avatar['url'];
1710 return DI::baseUrl() . $default;
1714 * Get avatar link for given contact id
1716 * @param integer $cid contact id
1717 * @param string $size One of the ProxyUtils::SIZE_* constants
1718 * @param string $updated Contact update date
1719 * @return string avatar link
1721 public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = ''):string
1723 // We have to fetch the "updated" variable when it wasn't provided
1724 // The parameter can be provided to improve performance
1725 if (empty($updated)) {
1726 $contact = self::getById($cid, ['updated']);
1727 $updated = $contact['updated'] ?? '';
1730 $url = DI::baseUrl() . '/photo/contact/';
1732 case Proxy::SIZE_MICRO:
1733 $url .= Proxy::PIXEL_MICRO . '/';
1735 case Proxy::SIZE_THUMB:
1736 $url .= Proxy::PIXEL_THUMB . '/';
1738 case Proxy::SIZE_SMALL:
1739 $url .= Proxy::PIXEL_SMALL . '/';
1741 case Proxy::SIZE_MEDIUM:
1742 $url .= Proxy::PIXEL_MEDIUM . '/';
1744 case Proxy::SIZE_LARGE:
1745 $url .= Proxy::PIXEL_LARGE . '/';
1748 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1752 * Get avatar link for given contact URL
1754 * @param string $url contact url
1755 * @param integer $uid user id
1756 * @param string $size One of the ProxyUtils::SIZE_* constants
1757 * @return string avatar link
1759 public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''):string
1761 $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
1762 Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
1763 $contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
1764 return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
1768 * Get header link for given contact id
1770 * @param integer $cid contact id
1771 * @param string $size One of the ProxyUtils::SIZE_* constants
1772 * @param string $updated Contact update date
1773 * @return string header link
1775 public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = ''):string
1777 // We have to fetch the "updated" variable when it wasn't provided
1778 // The parameter can be provided to improve performance
1779 if (empty($updated)) {
1780 $contact = self::getById($cid, ['updated']);
1781 $updated = $contact['updated'] ?? '';
1784 $url = DI::baseUrl() . '/photo/header/';
1786 case Proxy::SIZE_MICRO:
1787 $url .= Proxy::PIXEL_MICRO . '/';
1789 case Proxy::SIZE_THUMB:
1790 $url .= Proxy::PIXEL_THUMB . '/';
1792 case Proxy::SIZE_SMALL:
1793 $url .= Proxy::PIXEL_SMALL . '/';
1795 case Proxy::SIZE_MEDIUM:
1796 $url .= Proxy::PIXEL_MEDIUM . '/';
1798 case Proxy::SIZE_LARGE:
1799 $url .= Proxy::PIXEL_LARGE . '/';
1803 return $url . $cid . ($updated ? '?ts=' . strtotime($updated) : '');
1807 * Updates the avatar links in a contact only if needed
1809 * @param int $cid Contact id
1810 * @param string $avatar Link to avatar picture
1811 * @param bool $force force picture update
1812 * @param bool $create_cache Enforces the creation of cached avatar fields
1815 * @throws HTTPException\InternalServerErrorException
1816 * @throws HTTPException\NotFoundException
1817 * @throws \ImagickException
1819 public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
1821 $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network'],
1822 ['id' => $cid, 'self' => false]);
1823 if (!DBA::isResult($contact)) {
1827 $uid = $contact['uid'];
1829 // Only update the cached photo links of public contacts when they already are cached
1830 if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
1831 if ($contact['avatar'] != $avatar) {
1832 self::update(['avatar' => $avatar], ['id' => $cid]);
1833 Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
1838 // User contacts use are updated through the public contacts
1839 if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1840 $pcid = self::getIdForURL($contact['url'], 0, false);
1841 if (!empty($pcid)) {
1842 Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
1843 self::updateAvatar($pcid, $avatar, $force, true);
1848 $default_avatar = empty($avatar) || strpos($avatar, self::DEFAULT_AVATAR_PHOTO);
1850 if ($default_avatar) {
1851 $avatar = self::getDefaultAvatar($contact, Proxy::SIZE_SMALL);
1854 if ($default_avatar && Proxy::isLocalImage($avatar)) {
1855 $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
1857 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
1858 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
1859 Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
1862 // Use the data from the self account
1863 if (empty($fields)) {
1864 $local_uid = User::getIdForURL($contact['url']);
1865 if (!empty($local_uid)) {
1866 $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
1867 Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1871 if (empty($fields)) {
1872 $update = ($contact['avatar'] != $avatar) || $force;
1876 $contact['photo'] ?? '',
1877 $contact['thumb'] ?? '',
1878 $contact['micro'] ?? '',
1881 foreach ($data as $image_uri) {
1882 $image_rid = Photo::ridFromURI($image_uri);
1883 if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
1884 Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
1891 $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1893 $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
1894 $update = !empty($fields);
1895 Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
1901 $update = ($fields['photo'] . $fields['thumb'] . $fields['micro'] != $contact['photo'] . $contact['thumb'] . $contact['micro']) || $force;
1910 if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
1911 // Collect all user contacts of the given public contact
1912 $personal_contacts = DBA::select('contact', ['id', 'uid'],
1913 ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
1914 while ($personal_contact = DBA::fetch($personal_contacts)) {
1915 $cids[] = $personal_contact['id'];
1916 $uids[] = $personal_contact['uid'];
1918 DBA::close($personal_contacts);
1920 if (!empty($cids)) {
1921 // Delete possibly existing cached user contact avatars
1922 Photo::delete(['uid' => $uids, 'contact-id' => $cids, 'album' => Photo::CONTACT_PHOTOS]);
1928 Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
1929 self::update($fields, ['id' => $cids]);
1932 public static function deleteContactByUrl(string $url)
1934 // Update contact data for all users
1935 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
1936 $contacts = DBA::select('contact', ['id', 'uid'], $condition);
1937 while ($contact = DBA::fetch($contacts)) {
1938 Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
1939 self::remove($contact['id']);
1944 * Helper function for "updateFromProbe". Updates personal and public contact
1946 * @param integer $id contact id
1947 * @param integer $uid user id
1948 * @param string $old_url The previous profile URL of the contact
1949 * @param string $new_url The profile URL of the contact
1950 * @param array $fields The fields that are updated
1952 * @throws \Exception
1954 private static function updateContact(int $id, int $uid, string $old_url, string $new_url, array $fields)
1956 if (!self::update($fields, ['id' => $id])) {
1957 Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
1961 // Search for duplicated contacts and get rid of them
1962 if (self::removeDuplicates(Strings::normaliseLink($new_url), $uid)) {
1966 // Archive or unarchive the contact.
1967 $contact = DBA::selectFirst('contact', [], ['id' => $id]);
1968 if (!DBA::isResult($contact)) {
1969 Logger::info('Couldn\'t select contact for archival.', ['id' => $id]);
1973 if (isset($fields['failed'])) {
1974 if ($fields['failed']) {
1975 self::markForArchival($contact);
1977 self::unmarkForArchival($contact);
1981 if ($contact['uid'] != 0) {
1985 // Update contact data for all users
1986 $condition = ['self' => false, 'nurl' => Strings::normaliseLink($old_url)];
1988 $condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
1989 self::update($fields, $condition);
1991 // We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
1992 $condition['network'] = Protocol::OSTATUS;
1994 // If the contact failed, propagate the update fields to all contacts
1995 if (empty($fields['failed'])) {
1996 unset($fields['last-update']);
1997 unset($fields['success_update']);
1998 unset($fields['failure_update']);
2001 if (empty($fields)) {
2005 self::update($fields, $condition);
2009 * Remove duplicated contacts
2011 * @param string $nurl Normalised contact url
2012 * @param integer $uid User id
2014 * @throws \Exception
2016 public static function removeDuplicates(string $nurl, int $uid)
2018 $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED];
2019 $count = DBA::count('contact', $condition);
2024 $first_contact = DBA::selectFirst('contact', ['id', 'network'], $condition, ['order' => ['id']]);
2025 if (!DBA::isResult($first_contact)) {
2026 // Shouldn't happen - so we handle it
2030 $first = $first_contact['id'];
2031 Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
2032 if (($uid != 0 && ($first_contact['network'] == Protocol::DFRN))) {
2033 // Don't handle non public DFRN duplicates by now (legacy DFRN is very special because of the key handling)
2034 Logger::info('Not handling non public DFRN duplicate', ['uid' => $uid, 'nurl' => $nurl]);
2038 // Find all duplicates
2039 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
2040 $duplicates = DBA::select('contact', ['id', 'network'], $condition);
2041 while ($duplicate = DBA::fetch($duplicates)) {
2042 if (!in_array($duplicate['network'], Protocol::FEDERATED)) {
2046 Worker::add(PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
2048 DBA::close($duplicates);
2049 Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl, 'callstack' => System::callstack(20)]);
2054 * @param integer $id contact id
2055 * @param string $network Optional network we are probing for
2057 * @throws HTTPException\InternalServerErrorException
2058 * @throws \ImagickException
2060 public static function updateFromProbe(int $id, string $network = '')
2062 $contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
2063 if (!DBA::isResult($contact)) {
2067 $ret = Probe::uri($contact['url'], $network, $contact['uid']);
2068 return self::updateFromProbeArray($id, $ret);
2072 * @param integer $id contact id
2073 * @param array $ret Probed data
2075 * @throws HTTPException\InternalServerErrorException
2076 * @throws \ImagickException
2078 private static function updateFromProbeArray(int $id, array $ret)
2081 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
2082 This will reliably kill your communication with old Friendica contacts.
2085 // These fields aren't updated by this routine:
2088 $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
2089 'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
2090 'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix'];
2091 $contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
2092 if (!DBA::isResult($contact)) {
2096 if (self::isLocal($ret['url'])) {
2097 if ($contact['uid'] == 0) {
2098 Logger::info('Local contacts are not updated here.');
2100 self::updateFromPublicContact($id, $contact);
2105 if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
2106 Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
2109 // Delete all contacts with the same URL
2110 self::deleteContactByUrl($ret['url']);
2114 $uid = $contact['uid'];
2115 unset($contact['uid']);
2117 $uriid = $contact['uri-id'];
2118 unset($contact['uri-id']);
2120 $pubkey = $contact['pubkey'];
2121 unset($contact['pubkey']);
2123 $contact['photo'] = $contact['avatar'];
2124 unset($contact['avatar']);
2126 $updated = DateTimeFormat::utcNow();
2128 if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
2129 Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
2130 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2134 // We must not try to update relay contacts via probe. They are no real contacts.
2135 // We check after the probing to be able to correct falsely detected contact types.
2136 if (($contact['contact-type'] == self::TYPE_RELAY) &&
2137 (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
2138 self::updateContact($id, $uid, $contact['url'], $contact['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2139 Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
2143 // If Probe::uri fails the network code will be different ("feed" or "unkn")
2144 if (($ret['network'] == Protocol::PHANTOM) || (($ret['network'] == Protocol::FEED) && ($ret['network'] != $contact['network']))) {
2145 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => true, 'last-update' => $updated, 'failure_update' => $updated]);
2149 if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
2150 $cid = self::getIdForURL($ret['url'], 0, false);
2151 if (!empty($cid) && ($cid != $id)) {
2152 Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
2153 return self::updateFromProbeArray($cid, $ret);
2157 if (isset($ret['hide']) && is_bool($ret['hide'])) {
2158 $ret['unsearchable'] = $ret['hide'];
2161 if (isset($ret['account-type']) && is_int($ret['account-type'])) {
2162 $ret['forum'] = false;
2163 $ret['prv'] = false;
2164 $ret['contact-type'] = $ret['account-type'];
2165 if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) {
2166 $ret['forum'] = (bool)!$ret['manually-approve'];
2167 $ret['prv'] = (bool)!$ret['forum'];
2171 $new_pubkey = $ret['pubkey'] ?? '';
2174 $ret['last-item'] = Probe::getLastUpdate($ret);
2175 Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item'], 'callstack' => System::callstack(20)]);
2179 $guid = $ret['guid'] ?? '';
2181 // make sure to not overwrite existing values with blank entries except some technical fields
2182 $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
2183 foreach ($ret as $key => $val) {
2184 if (!array_key_exists($key, $contact)) {
2186 } elseif (($contact[$key] != '') && ($val === '') && !is_bool($ret[$key]) && !in_array($key, $keep)) {
2187 $ret[$key] = $contact[$key];
2188 } elseif ($ret[$key] != $contact[$key]) {
2193 if (!empty($ret['last-item']) && ($contact['last-item'] < $ret['last-item'])) {
2196 unset($ret['last-item']);
2199 if (empty($uriid)) {
2203 if (!empty($ret['photo']) && ($ret['network'] != Protocol::FEED)) {
2204 self::updateAvatar($id, $ret['photo'], $update);
2208 self::updateContact($id, $uid, $contact['url'], $ret['url'], ['failed' => false, 'last-update' => $updated, 'success_update' => $updated]);
2210 if (Contact\Relation::isDiscoverable($ret['url'])) {
2211 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2214 // Update the public contact
2216 $contact = self::getByURL($ret['url'], false, ['id']);
2217 if (!empty($contact['id'])) {
2218 self::updateFromProbeArray($contact['id'], $ret);
2226 $ret['uri-id'] = ItemURI::getIdByURI($ret['url']);
2228 $ret['uri-id'] = ItemURI::insert(['uri' => $ret['url'], 'guid' => $guid]);
2231 $ret['nurl'] = Strings::normaliseLink($ret['url']);
2232 $ret['updated'] = $updated;
2233 $ret['failed'] = false;
2235 // Only fill the pubkey if it had been empty before. We have to prevent identity theft.
2236 if (empty($pubkey) && !empty($new_pubkey)) {
2237 $ret['pubkey'] = $new_pubkey;
2240 if ((!empty($ret['addr']) && ($ret['addr'] != $contact['addr'])) || (!empty($ret['alias']) && ($ret['alias'] != $contact['alias']))) {
2241 $ret['uri-date'] = $updated;
2244 if ((!empty($ret['name']) && ($ret['name'] != $contact['name'])) || (!empty($ret['nick']) && ($ret['nick'] != $contact['nick']))) {
2245 $ret['name-date'] = $updated;
2248 if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2249 $ret['last-update'] = $updated;
2250 $ret['success_update'] = $updated;
2253 unset($ret['photo']);
2255 self::updateContact($id, $uid, $contact['url'], $ret['url'], $ret);
2257 if (Contact\Relation::isDiscoverable($ret['url'])) {
2258 Worker::add(PRIORITY_LOW, 'ContactDiscovery', $ret['url']);
2264 private static function updateFromPublicContact(int $id, array $contact)
2266 $public = self::getByURL($contact['url'], false);
2270 foreach ($contact as $field => $value) {
2271 if ($field == 'uid') {
2274 if ($public[$field] != $value) {
2275 $fields[$field] = $public[$field];
2278 if (!empty($fields)) {
2279 self::update($fields, ['id' => $id, 'self' => false]);
2280 Logger::info('Updating local contact', ['id' => $id]);
2285 * @param integer $url contact url
2286 * @return integer Contact id
2287 * @throws HTTPException\InternalServerErrorException
2288 * @throws \ImagickException
2290 public static function updateFromProbeByURL($url)
2292 $id = self::getIdForURL($url);
2298 self::updateFromProbe($id);
2304 * Detects the communication protocol for a given contact url.
2305 * This is used to detect Friendica contacts that we can communicate via AP.
2307 * @param string $url contact url
2308 * @param string $network Network of that contact
2309 * @return string with protocol
2311 public static function getProtocol($url, $network)
2313 if ($network != Protocol::DFRN) {
2317 $apcontact = APContact::getByURL($url);
2318 if (!empty($apcontact) && !empty($apcontact['generator'])) {
2319 return Protocol::ACTIVITYPUB;
2326 * Takes a $uid and a url/handle and adds a new contact
2328 * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
2329 * dfrn_request page.
2331 * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
2334 * $return['success'] boolean true if successful
2335 * $return['message'] error text if success is false.
2337 * Takes a $uid and a url/handle and adds a new contact
2339 * @param int $uid The user id the contact should be created for
2340 * @param string $url The profile URL of the contact
2341 * @param string $network
2343 * @throws HTTPException\InternalServerErrorException
2344 * @throws HTTPException\NotFoundException
2345 * @throws \ImagickException
2347 public static function createFromProbeForUser(int $uid, $url, $network = '')
2349 $result = ['cid' => -1, 'success' => false, 'message' => ''];
2351 // remove ajax junk, e.g. Twitter
2352 $url = str_replace('/#!/', '/', $url);
2354 if (!Network::isUrlAllowed($url)) {
2355 $result['message'] = DI::l10n()->t('Disallowed profile URL.');
2359 if (Network::isUrlBlocked($url)) {
2360 $result['message'] = DI::l10n()->t('Blocked domain');
2365 $result['message'] = DI::l10n()->t('Connect URL missing.');
2369 $arr = ['url' => $url, 'contact' => []];
2371 Hook::callAll('follow', $arr);
2374 $result['message'] = DI::l10n()->t('The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page.');
2378 if (!empty($arr['contact']['name'])) {
2380 $ret = $arr['contact'];
2383 $ret = Probe::uri($url, $network, $uid);
2386 if (($network != '') && ($ret['network'] != $network)) {
2387 Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
2391 // check if we already have a contact
2392 // the poll url is more reliable than the profile url, as we may have
2393 // indirect links or webfinger links
2395 $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
2396 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2397 if (!DBA::isResult($contact)) {
2398 $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
2399 $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
2402 $protocol = self::getProtocol($ret['url'], $ret['network']);
2404 // This extra param just confuses things, remove it
2405 if ($protocol === Protocol::DIASPORA) {
2406 $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
2409 // do we have enough information?
2410 if (empty($protocol) || ($protocol == Protocol::PHANTOM) || (empty($ret['url']) && empty($ret['addr']))) {
2411 $result['message'] .= DI::l10n()->t('The profile address specified does not provide adequate information.') . EOL;
2412 if (empty($ret['poll'])) {
2413 $result['message'] .= DI::l10n()->t('No compatible communication protocols or feeds were discovered.') . EOL;
2415 if (empty($ret['name'])) {
2416 $result['message'] .= DI::l10n()->t('An author or name was not found.') . EOL;
2418 if (empty($ret['url'])) {
2419 $result['message'] .= DI::l10n()->t('No browser URL could be matched to this address.') . EOL;
2421 if (strpos($ret['url'], '@') !== false) {
2422 $result['message'] .= DI::l10n()->t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
2423 $result['message'] .= DI::l10n()->t('Use mailto: in front of address to force email check.') . EOL;
2428 if ($protocol === Protocol::OSTATUS && DI::config()->get('system', 'ostatus_disabled')) {
2429 $result['message'] .= DI::l10n()->t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
2430 $ret['notify'] = '';
2433 if (!$ret['notify']) {
2434 $result['message'] .= DI::l10n()->t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
2437 $writeable = ((($protocol === Protocol::OSTATUS) && ($ret['notify'])) ? 1 : 0);
2439 $subhub = (($protocol === Protocol::OSTATUS) ? true : false);
2441 $hidden = (($protocol === Protocol::MAIL) ? 1 : 0);
2444 if (($protocol == Protocol::ACTIVITYPUB) && isset($ret['manually-approve'])) {
2445 $pending = (bool)$ret['manually-approve'];
2448 if (in_array($protocol, [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
2452 if (DBA::isResult($contact)) {
2454 $new_relation = (($contact['rel'] == self::FOLLOWER) ? self::FRIEND : self::SHARING);
2456 $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
2457 self::update($fields, ['id' => $contact['id']]);
2459 $new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
2461 // create contact record
2464 'created' => DateTimeFormat::utcNow(),
2465 'url' => $ret['url'],
2466 'nurl' => Strings::normaliseLink($ret['url']),
2467 'addr' => $ret['addr'],
2468 'alias' => $ret['alias'],
2469 'batch' => $ret['batch'],
2470 'notify' => $ret['notify'],
2471 'poll' => $ret['poll'],
2472 'poco' => $ret['poco'],
2473 'name' => $ret['name'],
2474 'nick' => $ret['nick'],
2475 'network' => $ret['network'],
2476 'baseurl' => $ret['baseurl'],
2477 'gsid' => $ret['gsid'] ?? null,
2478 'protocol' => $protocol,
2479 'pubkey' => $ret['pubkey'],
2480 'rel' => $new_relation,
2481 'priority'=> $ret['priority'],
2482 'writable'=> $writeable,
2483 'hidden' => $hidden,
2486 'pending' => $pending,
2491 $contact = DBA::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
2492 if (!DBA::isResult($contact)) {
2493 $result['message'] .= DI::l10n()->t('Unable to retrieve contact information.') . EOL;
2497 $contact_id = $contact['id'];
2498 $result['cid'] = $contact_id;
2500 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
2502 // Update the avatar
2503 self::updateAvatar($contact_id, $ret['photo']);
2505 // pull feed and consume it, which should subscribe to the hub.
2506 if ($contact['network'] == Protocol::OSTATUS) {
2507 Worker::add(PRIORITY_HIGH, 'OnePoll', $contact_id, 'force');
2511 self::updateFromProbeArray($contact_id, $ret);
2513 Worker::add(PRIORITY_HIGH, 'UpdateContact', $contact_id);
2516 $owner = User::getOwnerDataById($uid);
2518 if (DBA::isResult($owner)) {
2519 if (in_array($protocol, [Protocol::OSTATUS, Protocol::DFRN])) {
2520 // create a follow slap
2522 $item['verb'] = Activity::FOLLOW;
2523 $item['gravity'] = GRAVITY_ACTIVITY;
2524 $item['follow'] = $contact["url"];
2526 $item['title'] = '';
2528 $item['uri-id'] = 0;
2530 $slap = OStatus::salmon($item, $owner);
2532 if (!empty($contact['notify'])) {
2533 Salmon::slapper($owner, $contact['notify'], $slap);
2535 } elseif ($protocol == Protocol::DIASPORA) {
2536 $ret = Diaspora::sendShare($owner, $contact);
2537 Logger::log('share returns: ' . $ret);
2538 } elseif ($protocol == Protocol::ACTIVITYPUB) {
2539 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
2540 if (empty($activity_id)) {
2541 // This really should never happen
2545 $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid, $activity_id);
2546 Logger::log('Follow returns: ' . $ret);
2550 $result['success'] = true;
2555 * Updated contact's SSL policy
2557 * @param array $contact Contact array
2558 * @param string $new_policy New policy, valid: self,full
2560 * @return array Contact array with updated values
2561 * @throws \Exception
2563 public static function updateSslPolicy(array $contact, $new_policy)
2565 $ssl_changed = false;
2566 if ((intval($new_policy) == BaseURL::SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
2567 $ssl_changed = true;
2568 $contact['url'] = str_replace('https:', 'http:', $contact['url']);
2569 $contact['request'] = str_replace('https:', 'http:', $contact['request']);
2570 $contact['notify'] = str_replace('https:', 'http:', $contact['notify']);
2571 $contact['poll'] = str_replace('https:', 'http:', $contact['poll']);
2572 $contact['confirm'] = str_replace('https:', 'http:', $contact['confirm']);
2573 $contact['poco'] = str_replace('https:', 'http:', $contact['poco']);
2576 if ((intval($new_policy) == BaseURL::SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
2577 $ssl_changed = true;
2578 $contact['url'] = str_replace('http:', 'https:', $contact['url']);
2579 $contact['request'] = str_replace('http:', 'https:', $contact['request']);
2580 $contact['notify'] = str_replace('http:', 'https:', $contact['notify']);
2581 $contact['poll'] = str_replace('http:', 'https:', $contact['poll']);
2582 $contact['confirm'] = str_replace('http:', 'https:', $contact['confirm']);
2583 $contact['poco'] = str_replace('http:', 'https:', $contact['poco']);
2587 $fields = ['url' => $contact['url'], 'request' => $contact['request'],
2588 'notify' => $contact['notify'], 'poll' => $contact['poll'],
2589 'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
2590 self::update($fields, ['id' => $contact['id']]);
2599 * @param int $cid Public contact id
2600 * @param int $uid User ID
2602 * @return bool "true" if following had been successful
2604 public static function follow(int $cid, int $uid)
2606 $contact = self::getById($cid, ['url']);
2608 $result = self::createFromProbeForUser($uid, $contact['url']);
2610 return $result['cid'];
2614 * Unfollow a contact
2616 * @param int $cid Public contact id
2617 * @param int $uid User ID
2619 * @return bool "true" if unfollowing had been successful
2621 public static function unfollow(int $cid, int $uid)
2623 $cdata = self::getPublicAndUserContactID($cid, $uid);
2624 if (empty($cdata['user'])) {
2628 $contact = self::getById($cdata['user']);
2630 self::removeSharer([], $contact);
2636 * @param array $importer Owner (local user) data
2637 * @param array $contact Existing owner-specific contact data we want to expand the relationship with. Optional.
2638 * @param array $datarray An item-like array with at least the 'author-id' and 'author-url' keys for the contact. Mandatory.
2639 * @param bool $sharing True: Contact is now sharing with Owner; False: Contact is now following Owner (default)
2640 * @param string $note Introduction additional message
2641 * @return bool|null True: follow request is accepted; False: relationship is rejected; Null: relationship is pending
2642 * @throws HTTPException\InternalServerErrorException
2643 * @throws \ImagickException
2645 public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '')
2647 // Should always be set
2648 if (empty($datarray['author-id'])) {
2652 $fields = ['url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked'];
2653 $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]);
2654 if (!DBA::isResult($pub_contact)) {
2655 // Should never happen
2659 // Contact is blocked at node-level
2660 if (self::isBlocked($datarray['author-id'])) {
2664 $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url'];
2665 $name = $pub_contact['name'];
2666 $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"];
2667 $nick = $pub_contact['nick'];
2668 $network = $pub_contact['network'];
2670 // Ensure that we don't create a new contact when there already is one
2671 $cid = self::getIdForURL($url, $importer['uid']);
2673 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
2676 if (!empty($contact)) {
2677 if (!empty($contact['pending'])) {
2678 Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
2682 // Contact is blocked at user-level
2683 if (!empty($contact['id']) && !empty($importer['id']) &&
2684 Contact\User::isBlocked($contact['id'], $importer['id'])) {
2688 // Make sure that the existing contact isn't archived
2689 self::unmarkForArchival($contact);
2691 if (($contact['rel'] == self::SHARING)
2692 || ($sharing && $contact['rel'] == self::FOLLOWER)) {
2693 self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
2694 ['id' => $contact['id'], 'uid' => $importer['uid']]);
2697 // Ensure to always have the correct network type, independent from the connection request method
2698 self::updateFromProbe($contact['id']);
2700 Post\UserNotification::insertNotication($contact['id'], Verb::getID(Activity::FOLLOW), $importer['uid']);
2704 // send email notification to owner?
2705 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
2706 Logger::log('ignoring duplicated connection request from pending contact ' . $url);
2710 // create contact record
2711 $contact_id = self::insert([
2712 'uid' => $importer['uid'],
2713 'created' => DateTimeFormat::utcNow(),
2715 'nurl' => Strings::normaliseLink($url),
2718 'network' => $network,
2719 'rel' => self::FOLLOWER,
2726 // Ensure to always have the correct network type, independent from the connection request method
2727 self::updateFromProbe($contact_id);
2729 self::updateAvatar($contact_id, $photo, true);
2731 Post\UserNotification::insertNotication($contact_id, Verb::getID(Activity::FOLLOW), $importer['uid']);
2733 $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
2735 /// @TODO Encapsulate this into a function/method
2736 $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
2737 $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]);
2738 if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2739 // create notification
2740 $hash = Strings::getRandomHex();
2742 if (is_array($contact_record)) {
2743 DBA::insert('intro', ['uid' => $importer['uid'], 'contact-id' => $contact_record['id'],
2744 'blocked' => false, 'knowyou' => false, 'note' => $note,
2745 'hash' => $hash, 'datetime' => DateTimeFormat::utcNow()]);
2748 Group::addMember(User::getDefaultGroup($importer['uid'], $contact_record["network"]), $contact_record['id']);
2750 if (($user['notify-flags'] & Notification\Type::INTRO) &&
2751 in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL])) {
2754 'type' => Notification\Type::INTRO,
2755 'otype' => Notification\ObjectType::INTRO,
2756 'verb' => ($sharing ? Activity::FRIEND : Activity::FOLLOW),
2757 'uid' => $user['uid'],
2758 'cid' => $contact_record['id'],
2759 'link' => DI::baseUrl() . '/notifications/intros',
2762 } elseif (DBA::isResult($user) && in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) {
2763 if (($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) && ($network != Protocol::DIASPORA)) {
2764 self::createFromProbeForUser($importer['uid'], $url, $network);
2767 $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true];
2768 $fields = ['pending' => false];
2769 if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) {
2770 $fields['rel'] = self::FRIEND;
2773 self::update($fields, $condition);
2782 public static function removeFollower($importer, $contact)
2784 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::SHARING)) {
2785 self::update(['rel' => self::SHARING], ['id' => $contact['id']]);
2787 self::remove($contact['id']);
2791 public static function removeSharer($importer, $contact)
2793 if (($contact['rel'] == self::FRIEND) || ($contact['rel'] == self::FOLLOWER)) {
2794 self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
2796 self::remove($contact['id']);
2801 * Create a birthday event.
2803 * Update the year and the birthday.
2805 public static function updateBirthdays()
2809 AND (`contact`.`rel` = ? OR `contact`.`rel` = ?)
2810 AND NOT `contact`.`pending`
2811 AND NOT `contact`.`hidden`
2812 AND NOT `contact`.`blocked`
2813 AND NOT `contact`.`archive`
2814 AND NOT `contact`.`deleted`',
2820 $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
2822 while ($contact = DBA::fetch($contacts)) {
2823 Logger::log('update_contact_birthday: ' . $contact['bd']);
2825 $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
2827 if (Event::createBirthday($contact, $nextbd)) {
2831 ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
2832 ['id' => $contact['id']]
2836 DBA::close($contacts);
2840 * Remove the unavailable contact ids from the provided list
2842 * @param array $contact_ids Contact id list
2844 * @throws \Exception
2846 public static function pruneUnavailable(array $contact_ids)
2848 if (empty($contact_ids)) {
2852 $contacts = self::selectToArray(['id'], [
2853 'id' => $contact_ids,
2859 return array_column($contacts, 'id');
2863 * Returns a magic link to authenticate remote visitors
2865 * @todo check if the return is either a fully qualified URL or a relative path to Friendica basedir
2867 * @param string $contact_url The address of the target contact profile
2868 * @param string $url An url that we will be redirected to after the authentication
2870 * @return string with "redir" link
2871 * @throws HTTPException\InternalServerErrorException
2872 * @throws \ImagickException
2874 public static function magicLink($contact_url, $url = '')
2876 if (!Session::isAuthenticated()) {
2877 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2880 $contact = self::getByURL($contact_url, false);
2881 if (empty($contact)) {
2882 return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
2885 // Prevents endless loop in case only a non-public contact exists for the contact URL
2886 unset($contact['uid']);
2888 return self::magicLinkByContact($contact, $url ?: $contact_url);
2892 * Returns a magic link to authenticate remote visitors
2894 * @param integer $cid The contact id of the target contact profile
2895 * @param string $url An url that we will be redirected to after the authentication
2897 * @return string with "redir" link
2898 * @throws HTTPException\InternalServerErrorException
2899 * @throws \ImagickException
2901 public static function magicLinkById($cid, $url = '')
2903 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
2905 return self::magicLinkByContact($contact, $url);
2909 * Returns a magic link to authenticate remote visitors
2911 * @param array $contact The contact array with "uid", "network" and "url"
2912 * @param string $url An url that we will be redirected to after the authentication
2914 * @return string with "redir" link
2915 * @throws HTTPException\InternalServerErrorException
2916 * @throws \ImagickException
2918 public static function magicLinkByContact($contact, $url = '')
2920 $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
2922 if (!Session::isAuthenticated()) {
2923 return $destination;
2926 // Only redirections to the same host do make sense
2927 if (($url != '') && (parse_url($url, PHP_URL_HOST) != parse_url($contact['url'], PHP_URL_HOST))) {
2931 if (DI::pConfig()->get(local_user(), 'system', 'stay_local') && ($url == '')) {
2932 return 'contact/' . $contact['id'] . '/conversations';
2935 if (!empty($contact['network']) && $contact['network'] != Protocol::DFRN) {
2936 return $destination;
2939 if (empty($contact['id'])) {
2940 return $destination;
2943 $redirect = 'redir/' . $contact['id'];
2945 if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
2946 $redirect .= '?url=' . $url;
2953 * Is the contact a forum?
2955 * @param integer $contactid ID of the contact
2957 * @return boolean "true" if it is a forum
2959 public static function isForum($contactid)
2961 $fields = ['forum', 'prv'];
2962 $condition = ['id' => $contactid];
2963 $contact = DBA::selectFirst('contact', $fields, $condition);
2964 if (!DBA::isResult($contact)) {
2969 return ($contact['forum'] || $contact['prv']);
2973 * Can the remote contact receive private messages?
2975 * @param array $contact
2978 public static function canReceivePrivateMessages(array $contact)
2980 $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
2981 $self = $contact['self'] ?? false;
2983 return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self;
2987 * Search contact table by nick or name
2989 * @param string $search Name or nick
2990 * @param string $mode Search mode (e.g. "community")
2991 * @param int $uid User ID
2993 * @return array with search results
2994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2996 public static function searchByName(string $search, string $mode = '', int $uid = 0)
2998 if (empty($search)) {
3002 // check supported networks
3003 if (DI::config()->get('system', 'diaspora_enabled')) {
3004 $diaspora = Protocol::DIASPORA;
3006 $diaspora = Protocol::DFRN;
3009 if (!DI::config()->get('system', 'ostatus_disabled')) {
3010 $ostatus = Protocol::OSTATUS;
3012 $ostatus = Protocol::DFRN;
3015 // check if we search only communities or every contact
3016 if ($mode === 'community') {
3017 $extra_sql = sprintf(' AND `contact-type` = %d', self::TYPE_COMMUNITY);
3024 $results = DBA::p("SELECT * FROM `contact`
3025 WHERE (NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` where `publish` OR `net-publish`))
3026 AND `network` IN (?, ?, ?, ?) AND
3027 NOT `failed` AND `uid` = ? AND
3028 (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?) $extra_sql
3029 ORDER BY `nurl` DESC LIMIT 1000",
3030 Protocol::DFRN, Protocol::ACTIVITYPUB, $ostatus, $diaspora, $uid, $search, $search, $search
3033 $contacts = DBA::toArray($results);
3038 * Add public contacts from an array
3040 * @param array $urls
3041 * @return array result "count", "added" and "updated"
3043 public static function addByUrls(array $urls)
3050 foreach ($urls as $url) {
3051 if (empty($url) || !is_string($url)) {
3054 $contact = self::getByURL($url, false, ['id', 'updated']);
3055 if (empty($contact['id'])) {
3056 Worker::add(PRIORITY_LOW, 'AddContact', 0, $url);
3058 } elseif ($contact['updated'] < DateTimeFormat::utc('now -7 days')) {
3059 Worker::add(PRIORITY_LOW, 'UpdateContact', $contact['id']);
3067 return ['count' => $count, 'added' => $added, 'updated' => $updated, 'unchanged' => $unchanged];
3071 * Returns a random, global contact array of the current node
3073 * @return array The profile array
3076 public static function getRandomContact()
3078 $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
3079 "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
3080 0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
3081 ], ['order' => ['RAND()']]);
3083 if (DBA::isResult($contact)) {