<?php
/**
- * @copyright Copyright (C) 2010-2022, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
namespace Friendica\Model;
use Friendica\Contact\Avatar;
+use Friendica\Contact\Header;
use Friendica\Contact\Introduction\Exception\IntroductionNotFoundException;
+use Friendica\Contact\LocalRelationship\Entity\LocalRelationship;
+use Friendica\Content\Conversation as ConversationContent;
use Friendica\Content\Pager;
use Friendica\Content\Text\HTML;
use Friendica\Core\Hook;
use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\DI;
+use Friendica\Network\HTTPClient\Client\HttpClientAccept;
+use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Network\HTTPException;
use Friendica\Network\Probe;
+use Friendica\Object\Image;
use Friendica\Protocol\Activity;
use Friendica\Protocol\ActivityPub;
use Friendica\Util\DateTimeFormat;
+use Friendica\Util\HTTPSignature;
use Friendica\Util\Images;
use Friendica\Util\Network;
use Friendica\Util\Proxy;
use Friendica\Util\Strings;
+use Friendica\Worker\UpdateContact;
/**
* functions for interacting with a contact
* TYPE_NEWS - the account is a news reflector
* Associated page type: PAGE_SOAPBOX
*
- * TYPE_COMMUNITY - the account is community forum
+ * TYPE_COMMUNITY - the account is community group
* Associated page types: PAGE_COMMUNITY, PAGE_PRVGROUP
*
* TYPE_RELAY - the account is a relay
* @}
*/
- const MIRROR_DEACTIVATED = 0;
- const MIRROR_FORWARDED = 1;
- const MIRROR_OWN_POST = 2;
- const MIRROR_NATIVE_RESHARE = 3;
+ /** @deprecated Use Entity\LocalRelationship::MIRROR_DEACTIVATED instead */
+ const MIRROR_DEACTIVATED = LocalRelationship::MIRROR_DEACTIVATED;
+ /** @deprecated Now does the same as MIRROR_OWN_POST */
+ const MIRROR_FORWARDED = 1;
+ /** @deprecated Use Entity\LocalRelationship::MIRROR_OWN_POST instead */
+ const MIRROR_OWN_POST = LocalRelationship::MIRROR_OWN_POST;
+ /** @deprecated Use Entity\LocalRelationship::MIRROR_NATIVE_RESHARE instead */
+ const MIRROR_NATIVE_RESHARE = LocalRelationship::MIRROR_NATIVE_RESHARE;
- /**
+ /**
* @param array $fields Array of selected fields, empty for all
* @param array $condition Array of fields for condition
* @param array $params Array of several parameters
return $contact;
}
+ /**
+ * @param array $fields Array of selected fields, empty for all
+ * @param array $condition Array of fields for condition
+ * @param array $params Array of several parameters
+ * @return array
+ * @throws \Exception
+ */
+ public static function selectAccountToArray(array $fields = [], array $condition = [], array $params = []): array
+ {
+ return DBA::selectToArray('account-user-view', $fields, $condition, $params);
+ }
+
/**
* @param array $fields Array of selected fields, empty for all
* @param array $condition Array of fields for condition
* @param array $condition condition array with the key values
* @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)
*
- * @return boolean was the update successfull?
+ * @return boolean was the update successful?
* @throws \Exception
* @todo Let's get rid of boolean type of $old_fields
*/
- public static function update(array $fields, array $condition, $old_fields = [])
+ public static function update(array $fields, array $condition, $old_fields = []): bool
{
- $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
- $ret = DBA::update('contact', $fields, $condition, $old_fields);
-
// Apply changes to the "user-contact" table on dedicated fields
Contact\User::updateByContactUpdate($fields, $condition);
- return $ret;
+ $fields = DI::dbaDefinition()->truncateFieldsForTable('contact', $fields);
+ return DBA::update('contact', $fields, $condition, $old_fields);
}
/**
// Add internal fields
$removal = [];
if (!empty($fields)) {
- foreach (['id', 'next-update', 'network'] as $internal) {
+ foreach (['id', 'next-update', 'network', 'local-data'] as $internal) {
if (!in_array($internal, $fields)) {
$fields[] = $internal;
$removal[] = $internal;
return [];
}
+ $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
+
// Update the contact in the background if needed
- if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
- Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
+ if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+ try {
+ UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['contact' => $contact]);
+ }
}
// Remove the internal fields
{
if (!parse_url($url, PHP_URL_SCHEME)) {
$addr_parts = explode('@', $url);
- return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHostname());
+ return (count($addr_parts) == 2) && ($addr_parts[1] == DI::baseUrl()->getHost());
}
return Strings::compareLink(self::getBasepath($url, true), DI::baseUrl());
public static function getPublicAndUserContactID(int $cid, int $uid): array
{
// We have to use the legacy function as long as the post update hasn't finished
- if (DI::config()->get('system', 'post_update_version') < 1427) {
+ if (DI::keyValue()->get('post_update_version') < 1427) {
return self::legacyGetPublicAndUserContactID($cid, $uid);
}
*/
public static function createSelfFromUserId(int $uid): bool
{
- $user = DBA::selectFirst('user', ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
- ['uid' => $uid, 'account_expired' => false]);
+ $user = DBA::selectFirst(
+ 'user',
+ ['uid', 'username', 'nickname', 'pubkey', 'prvkey'],
+ ['uid' => $uid, 'account_expired' => false]
+ );
if (!DBA::isResult($user)) {
return false;
}
'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
- 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
'name-date' => DateTimeFormat::utcNow(),
'uri-date' => DateTimeFormat::utcNow(),
'avatar-date' => DateTimeFormat::utcNow(),
/**
* Updates the self-contact for the provided user id
*
- * @param int $uid
- * @param bool $update_avatar Force the avatar update
+ * @param int $uid
+ * @param bool $update_avatar Force the avatar update
* @return bool "true" if updated
- * @throws HTTPException\InternalServerErrorException
+ * @throws \Exception
*/
public static function updateSelfFromUserID(int $uid, bool $update_avatar = false): bool
{
- $fields = ['id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
+ $fields = [
+ 'id', 'uri-id', 'name', 'nick', 'location', 'about', 'keywords', 'avatar', 'prvkey', 'pubkey', 'manually-approve',
'xmpp', 'matrix', 'contact-type', 'forum', 'prv', 'avatar-date', 'url', 'nurl', 'unsearchable',
- 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'];
+ 'photo', 'thumb', 'micro', 'header', 'addr', 'request', 'notify', 'poll', 'confirm', 'poco', 'network'
+ ];
$self = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
if (!DBA::isResult($self)) {
return false;
}
- $fields = ['uid', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
+ $fields = ['uid', 'username', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey'];
$user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'account_expired' => false]);
if (!DBA::isResult($user)) {
return false;
}
- $fields = ['name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
- 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'];
+ $fields = [
+ 'name', 'photo', 'thumb', 'about', 'address', 'locality', 'region',
+ 'country-name', 'pub_keywords', 'xmpp', 'matrix', 'net-publish'
+ ];
$profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
if (!DBA::isResult($profile)) {
return false;
$url = DI::baseUrl() . '/profile/' . $user['nickname'];
$fields = [
- 'name' => $profile['name'],
+ 'name' => $user['username'],
'nick' => $user['nickname'],
'avatar-date' => $self['avatar-date'],
'location' => Profile::formatLocation($profile),
'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3),
'request' => DI::baseUrl() . '/dfrn_request/' . $user['nickname'],
'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'],
- 'poll' => DI::baseUrl() . '/dfrn_poll/'. $user['nickname'],
+ 'poll' => DI::baseUrl() . '/dfrn_poll/' . $user['nickname'],
'confirm' => DI::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
- 'poco' => DI::baseUrl() . '/poco/' . $user['nickname'],
];
-
$avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]);
if (DBA::isResult($avatar)) {
if ($update_avatar) {
// We are adding a timestamp value so that other systems won't use cached content
$timestamp = strtotime($fields['avatar-date']);
- $prefix = DI::baseUrl() . '/photo/' .$avatar['resource-id'] . '-';
+ $prefix = DI::baseUrl() . '/photo/' . $avatar['resource-id'] . '-';
$suffix = '.' . $file_suffix . '?ts=' . $timestamp;
$fields['photo'] = $prefix . '4' . $suffix;
* Returns the data array for the photo menu of a given contact
*
* @param array $contact contact
- * @param int $uid optional, default 0
+ * @param int $uid Visitor user id
* @return array
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
- public static function photoMenu(array $contact, int $uid = 0): array
+ public static function photoMenu(array $contact, int $uid): array
{
- $pm_url = '';
- $status_link = '';
- $photos_link = '';
-
- if ($uid == 0) {
- $uid = DI::userSession()->getLocalUserId();
+ // Anonymous visitor
+ if (!$uid) {
+ return ['profile' => [DI::l10n()->t('View Profile'), self::magicLinkByContact($contact), true]];
}
- if (empty($contact['uid']) || ($contact['uid'] != $uid)) {
- if ($uid == 0) {
- $profile_link = self::magicLinkByContact($contact);
- $menu = ['profile' => [DI::l10n()->t('View Profile'), $profile_link, true]];
-
- return $menu;
- }
-
- // Look for our own contact if the uid doesn't match and isn't public
- $contact_own = DBA::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
- if (DBA::isResult($contact_own)) {
- return self::photoMenu($contact_own, $uid);
- }
- }
+ $pm_url = '';
+ $status_link = '';
+ $photos_link = '';
- $sparkle = false;
if (($contact['network'] === Protocol::DFRN) && !$contact['self'] && empty($contact['pending'])) {
- $sparkle = true;
- $profile_link = DI::baseUrl() . '/redir/' . $contact['id'];
+ $profile_link = 'contact/redir/' . $contact['id'];
+ $status_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/status']);
+ $photos_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/photos']);
+ $profile_link = $profile_link . '?' . http_build_query(['url' => $contact['url'] . '/profile']);
} else {
$profile_link = $contact['url'];
}
$profile_link = '';
}
- if ($sparkle) {
- $status_link = $profile_link . '/status';
- $photos_link = str_replace('/profile/', '/photos/', $profile_link);
- $profile_link = $profile_link . '/profile';
- }
-
if (self::canReceivePrivateMessages($contact) && empty($contact['pending'])) {
- $pm_url = DI::baseUrl() . '/message/new/' . $contact['id'];
+ $pm_url = 'message/new/' . $contact['id'];
}
- $contact_url = DI::baseUrl() . '/contact/' . $contact['id'];
-
- $posts_link = DI::baseUrl() . '/contact/' . $contact['id'] . '/conversations';
+ $contact_url = 'contact/' . $contact['id'];
+ $posts_link = 'contact/' . $contact['id'] . '/conversations';
- $follow_link = '';
+ $follow_link = '';
$unfollow_link = '';
if (!$contact['self'] && Protocol::supportsFollow($contact['network'])) {
if ($contact['uid'] && in_array($contact['rel'], [self::SHARING, self::FRIEND])) {
$unfollow_link = 'contact/unfollow?url=' . urlencode($contact['url']) . '&auto=1';
- } elseif(!$contact['pending']) {
+ } elseif (!$contact['pending']) {
$follow_link = 'contact/follow?url=' . urlencode($contact['url']) . '&auto=1';
}
}
*/
if (empty($contact['uid'])) {
$menu = [
- 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
- 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
- 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
- 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
- 'unfollow'=> [DI::l10n()->t('Unfollow') , $unfollow_link, true],
+ 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
+ 'network' => [DI::l10n()->t('Network Posts'), $posts_link, false],
+ 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
+ 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
+ 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
];
} else {
$menu = [
- 'status' => [DI::l10n()->t('View Status') , $status_link , true],
- 'profile' => [DI::l10n()->t('View Profile') , $profile_link , true],
- 'photos' => [DI::l10n()->t('View Photos') , $photos_link , true],
- 'network' => [DI::l10n()->t('Network Posts') , $posts_link , false],
- 'edit' => [DI::l10n()->t('View Contact') , $contact_url , false],
- 'pm' => [DI::l10n()->t('Send PM') , $pm_url , false],
- 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link , true],
- 'unfollow'=> [DI::l10n()->t('Unfollow') , $unfollow_link , true],
+ 'status' => [DI::l10n()->t('View Status'), $status_link, true],
+ 'profile' => [DI::l10n()->t('View Profile'), $profile_link, true],
+ 'photos' => [DI::l10n()->t('View Photos'), $photos_link, true],
+ 'network' => [DI::l10n()->t('Network Posts'), $posts_link, false],
+ 'edit' => [DI::l10n()->t('View Contact'), $contact_url, false],
+ 'pm' => [DI::l10n()->t('Send PM'), $pm_url, false],
+ 'follow' => [DI::l10n()->t('Connect/Follow'), $follow_link, true],
+ 'unfollow' => [DI::l10n()->t('Unfollow'), $unfollow_link, true],
];
if (!empty($contact['pending'])) {
try {
- $intro = DI::intro()->selectForContact($contact['id']);
+ $intro = DI::intro()->selectForContact($contact['id']);
$menu['follow'] = [DI::l10n()->t('Approve'), 'notifications/intros/' . $intro->id, true];
} catch (IntroductionNotFoundException $exception) {
DI::logger()->error('Pending contact doesn\'t have an introduction.', ['exception' => $exception]);
return 0;
}
- $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update'], $uid);
+ $contact = self::getByURL($url, false, ['id', 'network', 'uri-id', 'next-update', 'local-data'], $uid);
if (!empty($contact)) {
$contact_id = $contact['id'];
- if (Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
- Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
+ $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
+
+ if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+ try {
+ UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['contact' => $contact]);
+ }
}
if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
if (($uid == 0) && (empty($data['network']) || ($data['network'] == Protocol::PHANTOM))) {
// Fetch data for the public contact via the first found personal contact
/// @todo Check if this case can happen at all (possibly with mail accounts?)
- $fields = ['name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
+ $fields = [
+ 'name', 'nick', 'url', 'addr', 'alias', 'avatar', 'header', 'contact-type',
'keywords', 'location', 'about', 'unsearchable', 'batch', 'notify', 'poll',
- 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'];
+ 'request', 'confirm', 'poco', 'subscribe', 'network', 'baseurl', 'gsid'
+ ];
$personal_contact = DBA::selectFirst('contact', $fields, ["`addr` = ? AND `uid` != 0", $url]);
if (!DBA::isResult($personal_contact)) {
}
if ($data['network'] == Protocol::DIASPORA) {
- FContact::updateFromProbeArray($data);
+ try {
+ DI::dsprContact()->updateFromProbeArray($data);
+ } catch (HTTPException\NotFoundException $e) {
+ Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]);
+ }
+ } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
+ try {
+ DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
+ } catch (HTTPException\NotFoundException $e) {
+ Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
+ }
}
self::updateFromProbeArray($contact_id, $data);
if (!empty($contact['batch'])) {
$condition = ['archive' => true, 'uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY];
return DBA::exists('contact', $condition);
- }
+ }
return false;
}
$contact_field = ((($contact["contact-type"] == self::TYPE_COMMUNITY) || ($contact['network'] == Protocol::MAIL)) ? 'owner-id' : 'author-id');
if ($thread_mode) {
- $condition = ["((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
- $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), DI::userSession()->getLocalUserId()];
+ $condition = [
+ "((`$contact_field` = ? AND `gravity` = ?) OR (`author-id` = ? AND `gravity` = ? AND `vid` = ? AND `protocol` != ? AND `thr-parent-id` = `parent-uri-id`)) AND " . $sql,
+ $cid, Item::GRAVITY_PARENT, $cid, Item::GRAVITY_ACTIVITY, Verb::getID(Activity::ANNOUNCE), Conversation::PARCEL_DIASPORA, DI::userSession()->getLocalUserId()
+ ];
} else {
- $condition = ["`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
- $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()];
+ $condition = [
+ "`$contact_field` = ? AND `gravity` IN (?, ?) AND " . $sql,
+ $cid, Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT, DI::userSession()->getLocalUserId()
+ ];
}
if (!empty($parent)) {
}
if ($only_media) {
- $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
- Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]);
+ $condition = DBA::mergeConditions($condition, [
+ "`uri-id` IN (SELECT `uri-id` FROM `post-media` WHERE `type` IN (?, ?, ?))",
+ Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO
+ ]);
}
if (DI::mode()->isMobile()) {
- $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network',
- DI::config()->get('system', 'itemspage_network_mobile'));
+ $itemsPerPage = DI::pConfig()->get(
+ DI::userSession()->getLocalUserId(),
+ 'system',
+ 'itemspage_mobile_network',
+ DI::config()->get('system', 'itemspage_network_mobile')
+ );
} else {
- $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network',
- DI::config()->get('system', 'itemspage_network'));
+ $itemsPerPage = DI::pConfig()->get(
+ DI::userSession()->getLocalUserId(),
+ 'system',
+ 'itemspage_network',
+ DI::config()->get('system', 'itemspage_network')
+ );
}
$pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
}
}
- $o .= DI::conversation()->create($items, 'contacts', $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
+ $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_commented', DI::userSession()->getLocalUserId());
} else {
$fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']);
$items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
if ($pager->getStart() == 0) {
$cdata = self::getPublicAndUserContactID($cid, DI::userSession()->getLocalUserId());
if (!empty($cdata['public'])) {
- $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
- $cdata['public'], Post\Collection::FEATURED];
+ $condition = [
+ "`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
+ $cdata['public'], Post\Collection::FEATURED
+ ];
$pinned = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), $fields, $condition, $params));
$items = array_merge($pinned, $items);
}
}
- $o .= DI::conversation()->create($items, 'contact-posts', $update);
+ $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACT_POSTS, $update);
}
if (!$update) {
break;
case self::TYPE_COMMUNITY:
- $account_type = DI::l10n()->t("Forum");
+ $account_type = DI::l10n()->t("Group");
break;
default:
* Unblocks a contact
*
* @param int $cid Contact id to unblock
- * @return bool Whether it was successfull
+ * @return bool Whether it was successful
*/
public static function unblock(int $cid): bool
{
} elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
Logger::info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
self::updateAvatar($cid, $contact['avatar'], true);
- return;
+ return;
}
}
*
* @param array $contact contact array
* @param string $size Size of the avatar picture
- * @param bool $no_update Don't perfom an update if no cached avatar was found
+ * @param bool $no_update Don't perform an update if no cached avatar was found
* @return string photo path
*/
private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
* Return the photo path for a given contact array
*
* @param array $contact Contact array
- * @param bool $no_update Don't perfom an update if no cached avatar was found
+ * @param bool $no_update Don't perform an update if no cached avatar was found
* @return string photo path
*/
public static function getPhoto(array $contact, bool $no_update = false): string
* Return the photo path (thumb size) for a given contact array
*
* @param array $contact Contact array
- * @param bool $no_update Don't perfom an update if no cached avatar was found
+ * @param bool $no_update Don't perform an update if no cached avatar was found
* @return string photo path
*/
public static function getThumb(array $contact, bool $no_update = false): string
* Return the photo path (micro size) for a given contact array
*
* @param array $contact Contact array
- * @param bool $no_update Don't perfom an update if no cached avatar was found
+ * @param bool $no_update Don't perform an update if no cached avatar was found
* @return string photo path
*/
public static function getMicro(array $contact, bool $no_update = false): string
* Check the given contact array for avatar cache fields
*
* @param array $contact
- * @param bool $no_update Don't perfom an update if no cached avatar was found
+ * @param bool $no_update Don't perform an update if no cached avatar was found
* @return array contact array with avatar cache fields
*/
private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
switch ($platform) {
case 'friendica':
case 'friendika':
- /**
- * Picture credits
- * @author Lostinlight <https://mastodon.xyz/@lightone>
- * @license CC0 https://creativecommons.org/share-your-work/public-domain/cc0/
- * @link https://gitlab.com/lostinlight/per_aspera_ad_astra/-/blob/master/friendica-404/friendica-promo-bubbles.jpg
- */
- $header = DI::baseUrl() . '/images/friendica-banner.jpg';
+ $header = DI::baseUrl() . (new Header(DI::config()))->getMastodonBannerPath();
break;
case 'diaspora':
/**
* @param integer $cid contact id
* @param string $size One of the Proxy::SIZE_* constants
* @param string $updated Contact update date
+ * @param bool $static If "true" a parameter is added to convert the avatar to a static one
* @return string avatar link
*/
- public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
+ public static function getAvatarUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
{
// We have to fetch the "updated" variable when it wasn't provided
// The parameter can be provided to improve performance
$url .= Proxy::PIXEL_LARGE . '/';
break;
}
- return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
+ $query_params = [];
+ if ($updated) {
+ $query_params['ts'] = strtotime($updated);
+ }
+ if ($static) {
+ $query_params['static'] = true;
+ }
+
+ return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
}
/**
*/
public static function getAvatarUrlForUrl(string $url, int $uid, string $size = ''): string
{
- $condition = ["`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
- Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0];
+ $condition = [
+ "`nurl` = ? AND ((`uid` = ? AND `network` IN (?, ?)) OR `uid` = ?)",
+ Strings::normaliseLink($url), $uid, Protocol::FEED, Protocol::MAIL, 0
+ ];
$contact = self::selectFirst(['id', 'updated'], $condition, ['order' => ['uid' => true]]);
return self::getAvatarUrlForId($contact['id'] ?? 0, $size, $contact['updated'] ?? '');
}
* @param integer $cid contact id
* @param string $size One of the Proxy::SIZE_* constants
* @param string $updated Contact update date
+ * @param bool $static If "true" a parameter is added to convert the header to a static one
* @return string header link
*/
- public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = ''): string
+ public static function getHeaderUrlForId(int $cid, string $size = '', string $updated = '', string $guid = '', bool $static = false): string
{
// We have to fetch the "updated" variable when it wasn't provided
// The parameter can be provided to improve performance
break;
}
- return $url . ($guid ?: $cid) . ($updated ? '?ts=' . strtotime($updated) : '');
+ $query_params = [];
+ if ($updated) {
+ $query_params['ts'] = strtotime($updated);
+ }
+ if ($static) {
+ $query_params['static'] = true;
+ }
+
+ return $url . ($guid ?: $cid) . (!empty($query_params) ? '?' . http_build_query($query_params) : '');
}
/**
*/
public static function updateAvatar(int $cid, string $avatar, bool $force = false, bool $create_cache = false)
{
- $contact = DBA::selectFirst('contact', ['uid', 'avatar', 'photo', 'thumb', 'micro', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
- ['id' => $cid, 'self' => false]);
+ $contact = DBA::selectFirst(
+ 'contact',
+ ['uid', 'avatar', 'photo', 'thumb', 'micro', 'blurhash', 'xmpp', 'addr', 'nurl', 'url', 'network', 'uri-id'],
+ ['id' => $cid, 'self' => false]
+ );
if (!DBA::isResult($contact)) {
return;
}
+ if (!Network::isValidHttpUrl($avatar)) {
+ Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
+ $avatar = '';
+ }
+
$uid = $contact['uid'];
// Only update the cached photo links of public contacts when they already are cached
if (($uid == 0) && !$force && empty($contact['thumb']) && empty($contact['micro']) && !$create_cache) {
- if ($contact['avatar'] != $avatar) {
- self::update(['avatar' => $avatar], ['id' => $cid]);
+ if (($contact['avatar'] != $avatar) || empty($contact['blurhash'])) {
+ $update_fields = ['avatar' => $avatar];
+ if (!Network::isLocalLink($avatar)) {
+ try {
+ $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
+
+ $img_str = $fetchResult->getBody();
+ if (!empty($img_str)) {
+ $image = new Image($img_str, Images::getMimeTypeByData($img_str));
+ if ($image->isValid()) {
+ $update_fields['blurhash'] = $image->getBlurHash();
+ } else {
+ return;
+ }
+ }
+ } catch (\Exception $exception) {
+ Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
+ return;
+ }
+ } elseif (!empty($contact['blurhash'])) {
+ $update_fields['blurhash'] = null;
+ } else {
+ return;
+ }
+
+ self::update($update_fields, ['id' => $cid]);
Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
}
return;
}
if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || $cache_avatar) {
- Avatar::deleteCache($contact);
+ if (Avatar::deleteCache($contact)) {
+ $force = true;
+ }
if ($default_avatar && Proxy::isLocalImage($avatar)) {
- $fields = ['avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
+ $fields = [
+ 'avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(),
'photo' => $avatar,
'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB),
- 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)];
+ 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO)
+ ];
Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
}
if ($update) {
$photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
if ($photos) {
- $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => DateTimeFormat::utcNow()];
+ $fields = ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow()];
$update = !empty($fields);
Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
} else {
$uids = [];
if (($uid == 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
// Collect all user contacts of the given public contact
- $personal_contacts = DBA::select('contact', ['id', 'uid'],
- ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]);
+ $personal_contacts = DBA::select(
+ 'contact',
+ ['id', 'uid'],
+ ["`nurl` = ? AND `id` != ? AND NOT `self`", $contact['nurl'], $cid]
+ );
while ($personal_contact = DBA::fetch($personal_contacts)) {
$cids[] = $personal_contact['id'];
$uids[] = $personal_contact['uid'];
$condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
$condition['network'] = [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB];
+
+ if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT) && Protocol::supportsProbe($contact['network'])) {
+ $condition['network'][] = $contact['network'];
+ }
+
self::update($fields, $condition);
// We mustn't set the update fields for OStatus contacts since they are updated in OnePoll
return true;
}
+ /**
+ * Perform a contact update if the contact is outdated
+ *
+ * @param integer $id contact id
+ * @return bool
+ */
+ public static function updateByIdIfNeeded(int $id): bool
+ {
+ $contact = self::selectFirst(['url'], ["`id` = ? AND `next-update` < ?", $id, DateTimeFormat::utcNow()]);
+ if (empty($contact['url'])) {
+ return false;
+ }
+
+ if (self::isLocal($contact['url'])) {
+ return true;
+ }
+
+ $stamp = (float)microtime(true);
+ self::updateFromProbe($id);
+ Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url'], 'callstack' => System::callstack(20)]);
+ return true;
+ }
+
+ /**
+ * Perform a contact update if the contact is outdated
+ *
+ * @param string $url contact url
+ * @return bool
+ */
+ public static function updateByUrlIfNeeded(string $url): bool
+ {
+ $id = self::getIdForURL($url, 0, false);
+ if (!empty($id)) {
+ return self::updateByIdIfNeeded($id);
+ }
+ return (bool)self::getIdForURL($url);
+ }
+
/**
* Updates contact record by provided id and optional network
*
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
- public static function updateFromProbe(int $id, string $network = '')
+ public static function updateFromProbe(int $id, string $network = ''): bool
{
$contact = DBA::selectFirst('contact', ['uid', 'url'], ['id' => $id]);
if (!DBA::isResult($contact)) {
return false;
}
- $ret = Probe::uri($contact['url'], $network, $contact['uid']);
+ $data = Probe::uri($contact['url'], $network, $contact['uid']);
- if ($ret['network'] == Protocol::DIASPORA) {
- FContact::updateFromProbeArray($ret);
+ if ($data['network'] == Protocol::DIASPORA) {
+ try {
+ DI::dsprContact()->updateFromProbeArray($data);
+ } catch (HTTPException\NotFoundException $e) {
+ Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
+ }
+ } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
+ try {
+ DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
+ } catch (HTTPException\NotFoundException $e) {
+ Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
+ }
}
- return self::updateFromProbeArray($id, $ret);
+ return self::updateFromProbeArray($id, $data);
}
/**
// These fields aren't updated by this routine:
// 'sensitive'
- $fields = ['uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
+ $fields = [
+ 'uid', 'uri-id', 'avatar', 'header', 'name', 'nick', 'location', 'keywords', 'about', 'subscribe',
'manually-approve', 'unsearchable', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco',
'network', 'alias', 'baseurl', 'gsid', 'forum', 'prv', 'contact-type', 'pubkey', 'last-item', 'xmpp', 'matrix',
- 'created', 'last-update'];
+ 'created', 'last-update'
+ ];
$contact = DBA::selectFirst('contact', $fields, ['id' => $id]);
if (!DBA::isResult($contact)) {
return false;
return true;
}
+ $has_local_data = self::hasLocalData($id, $contact);
+
$uid = $contact['uid'];
unset($contact['uid']);
$updated = DateTimeFormat::utcNow();
- $has_local_data = self::hasLocalData($id, $contact);
-
- if (!Probe::isProbable($ret['network'])) {
+ if (!Protocol::supportsProbe($ret['network']) && !Protocol::supportsProbe($contact['network'])) {
// Periodical checks are only done on federated contacts
$failed_next_update = null;
$success_next_update = null;
} elseif ($has_local_data) {
$failed_next_update = GServer::getNextUpdateDate(false, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
$success_next_update = GServer::getNextUpdateDate(true, $created, $last_update, !in_array($contact['network'], Protocol::FEDERATED));
- } else {
+ } elseif (in_array($ret['network'], array_merge(Protocol::NATIVE_SUPPORT, [Protocol::ZOT, Protocol::PHANTOM]))) {
$failed_next_update = DateTimeFormat::utc('now +6 month');
$success_next_update = DateTimeFormat::utc('now +1 month');
+ } else {
+ // We don't check connector networks very often to not run into API rate limits
+ $failed_next_update = DateTimeFormat::utc('now +12 month');
+ $success_next_update = DateTimeFormat::utc('now +12 month');
}
if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
// We must not try to update relay contacts via probe. They are no real contacts.
// We check after the probing to be able to correct falsely detected contact types.
if (($contact['contact-type'] == self::TYPE_RELAY) &&
- (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))) {
+ (!Strings::compareLink($ret['url'], $contact['url']) || in_array($ret['network'], [Protocol::FEED, Protocol::PHANTOM]))
+ ) {
self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => false, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $success_next_update, 'success_update' => $updated]);
Logger::info('Not updating relais', ['id' => $id, 'url' => $contact['url']]);
return true;
}
$update = false;
- $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], parse_url($ret['url'], PHP_URL_HOST));
+ $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? '');
// make sure to not overwrite existing values with blank entries except some technical fields
$keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl'];
return $result;
}
- $arr = ['url' => $url, 'contact' => []];
+ $arr = ['url' => $url, 'uid' => $uid, 'contact' => []];
Hook::callAll('follow', $arr);
}
if (($network != '') && ($ret['network'] != $network)) {
- Logger::notice('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
+ $result['message'] = DI::l10n()->t('Expected network %s does not match actual network %s', $network, $ret['network']);
return $result;
}
// check if we already have a contact
- // the poll url is more reliable than the profile url, as we may have
- // indirect links or webfinger links
-
- $condition = ['uid' => $uid, 'poll' => [$ret['poll'], Strings::normaliseLink($ret['poll'])], 'network' => $ret['network'], 'pending' => false];
- $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
- if (!DBA::isResult($contact)) {
- $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'network' => $ret['network'], 'pending' => false];
- $contact = DBA::selectFirst('contact', ['id', 'rel'], $condition);
- }
+ $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false];
+ $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition);
$protocol = self::getProtocol($ret['url'], $ret['network']);
// update contact
$new_relation = (in_array($contact['rel'], [self::FOLLOWER, self::FRIEND]) ? self::FRIEND : self::SHARING);
- $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
+ $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false, 'network' => $ret['network']];
+
+ if ($contact['pending'] && !empty($contact['hub-verify'])) {
+ ActivityPub\Transmitter::sendContactAccept($contact['url'], $contact['hub-verify'], $uid);
+ $fields['pending'] = false;
+ }
+
self::update($fields, ['id' => $contact['id']]);
} else {
$new_relation = (in_array($protocol, [Protocol::MAIL]) ? self::FRIEND : self::SHARING);
// create contact record
self::insert([
- 'uid' => $uid,
- 'created' => DateTimeFormat::utcNow(),
- 'url' => $ret['url'],
- 'nurl' => Strings::normaliseLink($ret['url']),
- 'addr' => $ret['addr'],
- 'alias' => $ret['alias'],
- 'batch' => $ret['batch'],
- 'notify' => $ret['notify'],
- 'poll' => $ret['poll'],
- 'poco' => $ret['poco'],
- 'name' => $ret['name'],
- 'nick' => $ret['nick'],
- 'network' => $ret['network'],
- 'baseurl' => $ret['baseurl'],
- 'gsid' => $ret['gsid'] ?? null,
- 'protocol' => $protocol,
- 'pubkey' => $ret['pubkey'],
- 'rel' => $new_relation,
- 'priority'=> $ret['priority'],
- 'writable'=> $writeable,
- 'hidden' => $hidden,
- 'blocked' => 0,
- 'readonly'=> 0,
- 'pending' => $pending,
- 'subhub' => $subhub
+ 'uid' => $uid,
+ 'created' => DateTimeFormat::utcNow(),
+ 'url' => $ret['url'],
+ 'nurl' => Strings::normaliseLink($ret['url']),
+ 'addr' => $ret['addr'],
+ 'alias' => $ret['alias'],
+ 'batch' => $ret['batch'],
+ 'notify' => $ret['notify'],
+ 'poll' => $ret['poll'],
+ 'poco' => $ret['poco'],
+ 'name' => $ret['name'],
+ 'nick' => $ret['nick'],
+ 'network' => $ret['network'],
+ 'baseurl' => $ret['baseurl'],
+ 'gsid' => $ret['gsid'] ?? null,
+ 'contact-type' => $ret['account-type'] ?? self::TYPE_PERSON,
+ 'protocol' => $protocol,
+ 'pubkey' => $ret['pubkey'],
+ 'rel' => $new_relation,
+ 'priority' => $ret['priority'],
+ 'writable' => $writeable,
+ 'hidden' => $hidden,
+ 'blocked' => 0,
+ 'readonly' => 0,
+ 'pending' => $pending,
+ 'subhub' => $subhub
]);
}
$contact_id = $contact['id'];
$result['cid'] = $contact_id;
- Group::addMember(User::getDefaultGroup($uid), $contact_id);
+ if ($contact['contact-type'] == self::TYPE_COMMUNITY) {
+ Circle::addMember(User::getDefaultGroupCircle($uid), $contact_id);
+ } else {
+ Circle::addMember(User::getDefaultCircle($uid), $contact_id);
+ }
// Update the avatar
self::updateAvatar($contact_id, $ret['photo']);
if ($probed) {
self::updateFromProbeArray($contact_id, $ret);
} else {
- Worker::add(Worker::PRIORITY_HIGH, 'UpdateContact', $contact_id);
+ try {
+ UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['contact' => $contact]);
+ }
}
$result['success'] = Protocol::follow($uid, $contact, $protocol);
}
// Contact is blocked at user-level
- if (!empty($contact['id']) && !empty($importer['id']) &&
- Contact\User::isBlocked($contact['id'], $importer['id'])) {
+ if (
+ !empty($contact['id']) && !empty($importer['id']) &&
+ Contact\User::isBlocked($contact['id'], $importer['id'])
+ ) {
return false;
}
self::unmarkForArchival($contact);
if (($contact['rel'] == self::SHARING)
- || ($sharing && $contact['rel'] == self::FOLLOWER)) {
- self::update(['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
- ['id' => $contact['id'], 'uid' => $importer['uid']]);
+ || ($sharing && $contact['rel'] == self::FOLLOWER)
+ ) {
+ self::update(
+ ['rel' => self::FRIEND, 'writable' => true, 'pending' => false],
+ ['id' => $contact['id'], 'uid' => $importer['uid']]
+ );
}
// Ensure to always have the correct network type, independent from the connection request method
Post\UserNotification::insertNotification($pub_contact['id'], Activity::FOLLOW, $importer['uid']);
- $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo'], ['id' => $contact_id]);
+ $contact_record = DBA::selectFirst('contact', ['id', 'network', 'name', 'url', 'photo', 'contact-type'], ['id' => $contact_id]);
/// @TODO Encapsulate this into a function/method
$fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language'];
DI::intro()->save($intro);
}
- Group::addMember(User::getDefaultGroup($importer['uid']), $contact_record['id']);
+ if ($contact_record['contact-type'] == self::TYPE_COMMUNITY) {
+ Circle::addMember(User::getDefaultGroupCircle($importer['uid']), $contact_record['id']);
+ } else {
+ Circle::addMember(User::getDefaultCircle($importer['uid']), $contact_record['id']);
+ }
if (($user['notify-flags'] & Notification\Type::INTRO) && $user['page-flags'] == User::PAGE_FLAGS_NORMAL) {
DI::notify()->createFromArray([
return;
}
+ Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
+
self::clearFollowerFollowingEndpointCache($contact['uid']);
$cdata = self::getPublicAndUserContactID($contact['id'], $contact['uid']);
-
- DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
+ if (!empty($cdata['public'])) {
+ DI::notification()->deleteForUserByVerb($contact['uid'], Activity::FOLLOW, ['actor-id' => $cdata['public']]);
+ }
}
/**
if ($contact['rel'] == self::SHARING || in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
self::remove($contact['id']);
} else {
- self::update(['rel' => self::FOLLOWER], ['id' => $contact['id']]);
+ self::update(['rel' => self::FOLLOWER, 'pending' => false], ['id' => $contact['id']]);
}
+
+ Worker::add(Worker::PRIORITY_LOW, 'ContactDiscoveryForUser', $contact['uid']);
}
/**
*/
public static function magicLinkById(int $cid, string $url = ''): string
{
- $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
+ $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], ['id' => $cid]);
return self::magicLinkByContact($contact, $url);
}
*/
public static function magicLinkByContact(array $contact, string $url = ''): string
{
- $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
+ $destination = $url ?: (!Network::isValidHttpUrl($contact['url']) && !empty($contact['alias']) && Network::isValidHttpUrl($contact['alias']) ? $contact['alias'] : $contact['url']);
if (!DI::userSession()->isAuthenticated()) {
return $destination;
return $destination;
}
- $redirect = 'redir/' . $contact['id'];
+ $redirect = 'contact/redir/' . $contact['id'];
if (($url != '') && !Strings::compareLink($contact['url'], $url)) {
$redirect .= '?url=' . $url;
}
/**
- * Is the contact a forum?
+ * Is the contact a group?
*
* @param integer $contactid ID of the contact
*
- * @return boolean "true" if it is a forum
+ * @return boolean "true" if it is a group
*/
- public static function isForum(int $contactid): bool
+ public static function isGroup(int $contactid): bool
{
$fields = ['contact-type'];
$condition = ['id' => $contactid];
return false;
}
- // Is it a forum?
+ // Is it a group?
return ($contact['contact-type'] == self::TYPE_COMMUNITY);
}
/**
* Search contact table by nick or name
*
- * @param string $search Name or nick
- * @param string $mode Search mode (e.g. "community")
- * @param int $uid User ID
- * @param int $limit Maximum amount of returned values
- * @param int $offset Limit offset
+ * @param string $search Name or nick
+ * @param string $mode Search mode (e.g. "community")
+ * @param bool $show_blocked Show users from blocked servers. Default is false
+ * @param int $uid User ID
+ * @param int $limit Maximum amount of returned values
+ * @param int $offset Limit offset
*
* @return array with search results
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
- public static function searchByName(string $search, string $mode = '', int $uid = 0, int $limit = 0, int $offset = 0): array
+ public static function searchByName(string $search, string $mode = '', bool $show_blocked = false, int $uid = 0, int $limit = 0, int $offset = 0): array
{
if (empty($search)) {
return [];
$networks[] = Protocol::OSTATUS;
}
- $condition = ['network' => $networks, 'failed' => false, 'deleted' => false, 'uid' => $uid];
+ $condition = [
+ 'network' => $networks,
+ 'server-failed' => false,
+ 'failed' => false,
+ 'deleted' => false,
+ 'unsearchable' => false,
+ 'uid' => $uid
+ ];
+
+ if (!$show_blocked) {
+ $condition['server-blocked'] = true;
+ }
if ($uid == 0) {
$condition['blocked'] = false;
$params['limit'] = $limit;
}
- $condition = DBA::mergeConditions($condition,
- ["(NOT `unsearchable` OR `nurl` IN (SELECT `nurl` FROM `owner-view` WHERE `publish` OR `net-publish`))
- AND (`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]);
+ $condition = DBA::mergeConditions(
+ $condition,
+ ["(`addr` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)", $search, $search, $search]
+ );
- $contacts = self::selectToArray([], $condition, $params);
- return $contacts;
+ return DBA::selectToArray('account-user-view', [], $condition, $params);
}
/**
if (empty($contact['id']) && Network::isValidHttpUrl($url)) {
Worker::add(Worker::PRIORITY_LOW, 'AddContact', 0, $url);
++$added;
- } elseif (!empty($contact['network']) && Probe::isProbable($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
- Worker::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], 'UpdateContact', $contact['id']);
- ++$updated;
+ } elseif (!empty($contact['network']) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
+ try {
+ UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
+ ++$updated;
+ } catch (\InvalidArgumentException $e) {
+ Logger::notice($e->getMessage(), ['contact' => $contact]);
+ }
} else {
++$unchanged;
}
*/
public static function getRandomContact(): array
{
- $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
+ $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'alias', 'uid'], [
"`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",
0, Protocol::DFRN, DateTimeFormat::utc('now - 1 month'),
], ['order' => ['RAND()']]);
return [];
}
+
+ /**
+ * Checks, if contacts with the given condition exists
+ *
+ * @param array $condition
+ *
+ * @return bool
+ * @throws \Exception
+ */
+ public static function exists(array $condition): bool
+ {
+ return DBA::exists('contact', $condition);
+ }
}