Merge branch 'develop' into xundeenergy/dropzone-upload-improvement

This commit is contained in:
Hypolite Petovan 2025-01-22 21:52:52 -05:00
commit 3980de94a4
181 changed files with 5714 additions and 5383 deletions

View file

@ -52,4 +52,4 @@ $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__));
$app = \Friendica\App::fromContainer($container); $app = \Friendica\App::fromContainer($container);
$app->processEjabberd(); $app->processEjabberd($_SERVER);

View file

@ -19,4 +19,4 @@ $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__));
$app = \Friendica\App::fromContainer($container); $app = \Friendica\App::fromContainer($container);
$app->processConsole($_SERVER['argv'] ?? []); $app->processConsole($_SERVER);

View file

@ -6,7 +6,7 @@
* *
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
* *
* @deprecated 2025.02 use bin/console.php daemon instead * @deprecated 2025.02 use `bin/console.php daemon` instead
*/ */
/** /**
@ -24,11 +24,15 @@ chdir(dirname(__DIR__));
require dirname(__DIR__) . '/vendor/autoload.php'; require dirname(__DIR__) . '/vendor/autoload.php';
fwrite(STDOUT, '`bin/daemon.php` is deprecated since 2024.02 and will be removed in 5 months, please use `bin/console.php daemon` instead.' . \PHP_EOL);
// BC: Add console command as second argument
$argv = $_SERVER['argv'] ?? []; $argv = $_SERVER['argv'] ?? [];
array_splice($argv, 1, 0, "daemon"); array_splice($argv, 1, 0, "daemon");
$_SERVER['argv'] = $argv;
$container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__));
$app = \Friendica\App::fromContainer($container); $app = \Friendica\App::fromContainer($container);
$app->processConsole($argv); $app->processConsole($_SERVER);

View file

@ -6,7 +6,7 @@
* *
* SPDX-License-Identifier: AGPL-3.0-or-later * SPDX-License-Identifier: AGPL-3.0-or-later
* *
* @deprecated 2025.02 use bin/console.php jetstream instead * @deprecated 2025.02 use `bin/console.php jetstream` instead
*/ */
if (php_sapi_name() !== 'cli') { if (php_sapi_name() !== 'cli') {
@ -19,11 +19,15 @@ chdir(dirname(__DIR__));
require dirname(__DIR__) . '/vendor/autoload.php'; require dirname(__DIR__) . '/vendor/autoload.php';
fwrite(STDOUT, '`bin/jetstream.php` is deprecated since 2024.02 and will be removed in 5 months, please use `bin/console.php jetstream` instead.' . \PHP_EOL);
// BC: Add console command as second argument
$argv = $_SERVER['argv'] ?? []; $argv = $_SERVER['argv'] ?? [];
array_splice($argv, 1, 0, "jetstream"); array_splice($argv, 1, 0, "jetstream");
$_SERVER['argv'] = $argv;
$container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__));
$app = \Friendica\App::fromContainer($container); $app = \Friendica\App::fromContainer($container);
$app->processConsole($argv); $app->processConsole($_SERVER);

View file

@ -8,7 +8,7 @@
* *
* Starts the background processing * Starts the background processing
* *
* @deprecated 2025.02 use bin/console.php worker instead * @deprecated 2025.02 use `bin/console.php worker` instead
*/ */
if (php_sapi_name() !== 'cli') { if (php_sapi_name() !== 'cli') {
@ -21,11 +21,15 @@ chdir(dirname(__DIR__));
require dirname(__DIR__) . '/vendor/autoload.php'; require dirname(__DIR__) . '/vendor/autoload.php';
fwrite(STDOUT, '`bin/worker.php` is deprecated since 2024.02 and will be removed in 5 months, please use `bin/console.php worker` instead.' . \PHP_EOL);
// BC: Add console command as second argument
$argv = $_SERVER['argv'] ?? []; $argv = $_SERVER['argv'] ?? [];
array_splice($argv, 1, 0, "worker"); array_splice($argv, 1, 0, "worker");
$_SERVER['argv'] = $argv;
$container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__));
$app = \Friendica\App::fromContainer($container); $app = \Friendica\App::fromContainer($container);
$app->processConsole($argv); $app->processConsole($_SERVER);

View file

@ -171,6 +171,7 @@
"cs:fix": [ "cs:fix": [
"@cs:install", "@cs:install",
"bin/dev/php-cs-fixer/vendor/bin/php-cs-fixer fix" "bin/dev/php-cs-fixer/vendor/bin/php-cs-fixer fix"
] ],
"cs:fix-develop": "TARGET_BRANCH=develop COMMAND=fix bin/dev/fix-codestyle.sh"
} }
} }

View file

@ -156,3 +156,97 @@ If you are interested in improving those clients, please contact the developers
* iOS: *currently no client* * iOS: *currently no client*
* SailfishOS: **Friendiy** [src](https://kirgroup.com/projects/fabrixxm/harbour-friendly) - developed by [Fabio](https://kirgroup.com/profile/fabrixxm/profile) * SailfishOS: **Friendiy** [src](https://kirgroup.com/projects/fabrixxm/harbour-friendly) - developed by [Fabio](https://kirgroup.com/profile/fabrixxm/profile)
* Windows: **Friendica Mobile** for Windows versions [before 8.1](http://windowsphone.com/s?appid=e3257730-c9cf-4935-9620-5261e3505c67) and [Windows 10](https://www.microsoft.com/store/apps/9nblggh0fhmn) - developed by [Gerhard Seeber](http://mozartweg.dyndns.org/friendica/profile/gerhard/profile) * Windows: **Friendica Mobile** for Windows versions [before 8.1](http://windowsphone.com/s?appid=e3257730-c9cf-4935-9620-5261e3505c67) and [Windows 10](https://www.microsoft.com/store/apps/9nblggh0fhmn) - developed by [Gerhard Seeber](http://mozartweg.dyndns.org/friendica/profile/gerhard/profile)
## Backward compatibility
### Backward Compatibility Promise
Friendica can be extended by addons.
These addons relies on many classes and conventions from Friendica.
As developers our work on Friendica should not break things in the addons without giving the addon maintainers a chance to fix their addons.
Our goal is to build trust for the addon maintainers but also allow Friendica developers to move on.
This is called the Backward Compatibility Promise.
Inspired by the [Symonfy BC promise](https://symfony.com/doc/current/contributing/code/bc.html) we promise BC for every class, interface, trait, enum, function, constant, etc., but with the exception of:
- Classes, interfaces, traits, enums, functions, methods, properties and constants marked as `@internal` or `@private`
- Extending or modifying a `final` class or method in any way
- Calling `private` methods (via Reflection)
- Accessing `private` properties (via Reflection)
- Accessing `private` methods (via Reflection)
- Accessing `private` constants (via Reflection)
- New properties on overridden `protected` methods
- Possible name collisions with new methods in an extended class (addon developers should prefix their custom methods in the extending classes in an appropriate way)
- Dropping support for every PHP version that has reached end of life
### Deprecation and removing features
As the development goes by Friendica needs to get rid of old code and concepts.
This will be done in 3 steps to give addon maintainers a chance to adjust their addons.
**1. Label deprecation**
If we as the Friendica maintainers decide to remove some functions, classes, interface, etc. we start this by adding a `@deprecated` PHPDoc note on the code.
For instance the class `Friendica\Core\Logger` should be removed, so we add the following note with a possible replacement:
```php
/**
* Logger functions
*
* @deprecated 2025.02 Use constructor injection or `DI::logger()` instead
*/
class Logger {/* ... */}
```
This way addon developers might be notified early by their IDE or other tools that the usage of the class is deprecated.
In Friendica we can now start to replace all occurrences and usage of this class with the alternative.
The deprecation label COULD be remain over multiple releases.
As long as the code that is labeled with `@deprecated` is used inside Friendica or the official addon repository, it SHOULD NOT be hard deprecated.
**2. Hard deprecation**
If the deprecated code is no longer used inside Friendica or the official addons it MUST be hard deprecated.
The code MUST NOT be deleted.
Starting from the next release, it MUST be stay for at least 5 months.
Hard deprecated code COULD remain longer than 5 months, depending on when a release appears.
Addon developer MUST NOT consider that they have more than 5 months to adjust their code.
Hard deprecation code means that the code triggers an `E_USER_DEPRECATION` error if it is called.
For instance with the deprecated class `Friendica\Core\Logger` the call of every method should trigger an error:
```php
/**
* Logger functions
*
* @deprecated 2025.02 Use constructor injection or `DI::logger()` instead
*/
class Logger {
public static function info(string $message, array $context = [])
{
trigger_error('Class `' . __CLASS__ . '` is deprecated since 2025.05 and will be removed after 5 months, use constructor injection or `DI::logger()` instead.', E_USER_DEPRECATED);
self::getInstance()->info($message, $context);
}
/* ... */
}
```
This way the maintainer or users of addons will be notified that the addon will stop working in one of the next releases.
The addon maintainer now has at least 5 months or at least one release to fix the deprecations.
Please note that the deprecation message contains the release that will be released next.
In the example the code was hard deprecated with release `2025.05`, so it COULD be removed earliest with the `2025.11` release.
**3. Code Removing**
We promise BC for deprecated code for at least 5 months, starting from the release the deprecation was announced.
After this time the deprecated code COULD be remove within the next release.
Breaking changes MUST be happen only in a new release but MUST be hard deprecated first.
The BC promise refers only to releases, respective the `stable` branch.
Deprecated code on other branches like `develop` or RC branches could be removed earlier.
This is not a BC break as long as the release will be published 5 months after the hard deprecation.
If a release breaks BC without deprecation or earlier than 5 months, this SHOULD considered as a bug and BC SHOULD be restored in a bugfix release.

View file

@ -19,7 +19,6 @@
use Friendica\Content\Conversation; use Friendica\Content\Conversation;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -56,7 +55,7 @@ function item_post()
*/ */
if (!$preview && !empty($_REQUEST['post_id_random'])) { if (!$preview && !empty($_REQUEST['post_id_random'])) {
if (DI::session()->get('post-random') == $_REQUEST['post_id_random']) { if (DI::session()->get('post-random') == $_REQUEST['post_id_random']) {
Logger::warning('duplicate post'); DI::logger()->warning('duplicate post');
item_post_return(DI::baseUrl(), $return_path); item_post_return(DI::baseUrl(), $return_path);
} else { } else {
DI::session()->set('post-random', $_REQUEST['post_id_random']); DI::session()->set('post-random', $_REQUEST['post_id_random']);
@ -165,7 +164,7 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat
// This enables interaction like starring and saving into folders // This enables interaction like starring and saving into folders
if ($toplevel_item['uid'] == 0) { if ($toplevel_item['uid'] == 0) {
$stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]); $stored = Item::storeForUserByUriId($toplevel_item['uri-id'], $post['uid'], ['post-reason' => Item::PR_ACTIVITY]);
Logger::info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]); DI::logger()->info('Public item stored for user', ['uri-id' => $toplevel_item['uri-id'], 'uid' => $post['uid'], 'stored' => $stored]);
} }
$post['parent'] = $toplevel_item['id']; $post['parent'] = $toplevel_item['id'];
@ -197,7 +196,7 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat
$post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]); $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
if (!$post) { if (!$post) {
Logger::error('Item couldn\'t be fetched.', ['post_id' => $post_id]); DI::logger()->error('Item couldn\'t be fetched.', ['post_id' => $post_id]);
if ($return_path) { if ($return_path) {
DI::baseUrl()->redirect($return_path); DI::baseUrl()->redirect($return_path);
} }
@ -213,7 +212,7 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat
DI::contentItem()->copyPermissions($post['thr-parent-id'], $post['uri-id'], $post['parent-uri-id']); DI::contentItem()->copyPermissions($post['thr-parent-id'], $post['uri-id'], $post['parent-uri-id']);
} }
Logger::debug('post_complete'); DI::logger()->debug('post_complete');
item_post_return(DI::baseUrl(), $return_path); item_post_return(DI::baseUrl(), $return_path);
// NOTREACHED // NOTREACHED
@ -297,7 +296,7 @@ function item_process(array $post, array $request, bool $preview, string $return
} }
if (!empty($post['cancel'])) { if (!empty($post['cancel'])) {
Logger::info('mod_item: post cancelled by addon.'); DI::logger()->info('mod_item: post cancelled by addon.');
if ($return_path) { if ($return_path) {
DI::baseUrl()->redirect($return_path); DI::baseUrl()->redirect($return_path);
} }
@ -324,7 +323,7 @@ function item_post_return($baseurl, $return_path)
$json['reload'] = $baseurl . '/' . $_REQUEST['jsreload']; $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
} }
Logger::debug('post_json', ['json' => $json]); DI::logger()->debug('post_json', ['json' => $json]);
System::jsonExit($json); System::jsonExit($json);
} }
@ -444,7 +443,7 @@ function drop_item(int $id, string $return = ''): string
item_redirect_after_action($item, $return); item_redirect_after_action($item, $return);
//NOTREACHED //NOTREACHED
} else { } else {
Logger::warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]); DI::logger()->warning('Permission denied.', ['local' => DI::userSession()->getLocalUserId(), 'uid' => $item['uid'], 'cid' => $contact_id]);
DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.')); DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.'));
DI::baseUrl()->redirect('display/' . $item['guid']); DI::baseUrl()->redirect('display/' . $item['guid']);
//NOTREACHED //NOTREACHED

View file

@ -13,7 +13,6 @@ use Friendica\Content\Text\BBCode;
use Friendica\Core\ACL; use Friendica\Core\ACL;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -277,7 +276,7 @@ function photos_post()
} }
if (!empty($_POST['rotate']) && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) { if (!empty($_POST['rotate']) && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) {
Logger::debug('rotate'); DI::logger()->debug('rotate');
$photo = Photo::getPhotoForUser($page_owner_uid, $resource_id); $photo = Photo::getPhotoForUser($page_owner_uid, $resource_id);
@ -1027,7 +1026,7 @@ function photos_content()
} }
$edit = Null; $edit = null;
if ($cmd === 'edit' && $can_post) { if ($cmd === 'edit' && $can_post) {
$edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl'); $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl');

View file

@ -57,6 +57,7 @@ use Psr\Log\LoggerInterface;
* and anything else that might need to be passed around * and anything else that might need to be passed around
* before we spit the page out. * before we spit the page out.
* *
* @final
*/ */
class App class App
{ {
@ -64,6 +65,9 @@ class App
const CODENAME = 'Interrupted Fern'; const CODENAME = 'Interrupted Fern';
const VERSION = '2025.02-dev'; const VERSION = '2025.02-dev';
/**
* @internal
*/
public static function fromContainer(Container $container): self public static function fromContainer(Container $container): self
{ {
return new self($container); return new self($container);
@ -130,6 +134,9 @@ class App
$this->container = $container; $this->container = $container;
} }
/**
* @internal
*/
public function processRequest(ServerRequestInterface $request, float $start_time): void public function processRequest(ServerRequestInterface $request, float $start_time): void
{ {
$this->container->addRule(Mode::class, [ $this->container->addRule(Mode::class, [
@ -158,16 +165,18 @@ class App
$this->session = $this->container->create(IHandleUserSessions::class); $this->session = $this->container->create(IHandleUserSessions::class);
$this->appHelper = $this->container->create(AppHelper::class); $this->appHelper = $this->container->create(AppHelper::class);
$this->loadSetupForFrontend( $this->load(
$request, $request->getServerParams(),
$this->container->create(DbaDefinition::class), $this->container->create(DbaDefinition::class),
$this->container->create(ViewDefinition::class), $this->container->create(ViewDefinition::class),
$this->mode,
$this->config,
$this->profiler,
$this->appHelper,
); );
$this->registerTemplateEngine(); $this->registerTemplateEngine();
$this->mode->setExecutor(Mode::INDEX);
$this->runFrontend( $this->runFrontend(
$this->container->create(IManagePersonalConfigValues::class), $this->container->create(IManagePersonalConfigValues::class),
$this->container->create(Page::class), $this->container->create(Page::class),
@ -178,8 +187,13 @@ class App
); );
} }
public function processConsole(array $argv): void /**
* @internal
*/
public function processConsole(array $serverParams): void
{ {
$argv = $serverParams['argv'] ?? [];
$this->setupContainerForAddons(); $this->setupContainerForAddons();
$this->setupLogChannel($this->determineLogChannel($argv)); $this->setupLogChannel($this->determineLogChannel($argv));
@ -188,12 +202,25 @@ class App
$this->registerErrorHandler(); $this->registerErrorHandler();
$this->load(
$serverParams,
$this->container->create(DbaDefinition::class),
$this->container->create(ViewDefinition::class),
$this->container->create(Mode::class),
$this->container->create(IManageConfigValues::class),
$this->container->create(Profiler::class),
$this->container->create(AppHelper::class),
);
$this->registerTemplateEngine(); $this->registerTemplateEngine();
(\Friendica\Core\Console::create($this->container, $argv))->execute(); (\Friendica\Core\Console::create($this->container, $argv))->execute();
} }
public function processEjabberd(): void /**
* @internal
*/
public function processEjabberd(array $serverParams): void
{ {
$this->setupContainerForAddons(); $this->setupContainerForAddons();
@ -203,6 +230,16 @@ class App
$this->registerErrorHandler(); $this->registerErrorHandler();
$this->load(
$serverParams,
$this->container->create(DbaDefinition::class),
$this->container->create(ViewDefinition::class),
$this->container->create(Mode::class),
$this->container->create(IManageConfigValues::class),
$this->container->create(Profiler::class),
$this->container->create(AppHelper::class),
);
/** @var BasePath */ /** @var BasePath */
$basePath = $this->container->create(BasePath::class); $basePath = $this->container->create(BasePath::class);
@ -272,14 +309,21 @@ class App
/** /**
* Load the whole app instance * Load the whole app instance
*/ */
private function loadSetupForFrontend(ServerRequestInterface $request, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition) private function load(
{ array $serverParams,
if ($this->config->get('system', 'ini_max_execution_time') !== false) { DbaDefinition $dbaDefinition,
set_time_limit((int)$this->config->get('system', 'ini_max_execution_time')); ViewDefinition $viewDefinition,
Mode $mode,
IManageConfigValues $config,
Profiler $profiler,
AppHelper $appHelper
): void {
if ($config->get('system', 'ini_max_execution_time') !== false) {
set_time_limit((int) $config->get('system', 'ini_max_execution_time'));
} }
if ($this->config->get('system', 'ini_pcre_backtrack_limit') !== false) { if ($config->get('system', 'ini_pcre_backtrack_limit') !== false) {
ini_set('pcre.backtrack_limit', (int)$this->config->get('system', 'ini_pcre_backtrack_limit')); ini_set('pcre.backtrack_limit', (int) $config->get('system', 'ini_pcre_backtrack_limit'));
} }
// Normally this constant is defined - but not if "pcntl" isn't installed // Normally this constant is defined - but not if "pcntl" isn't installed
@ -290,11 +334,11 @@ class App
// Ensure that all "strtotime" operations do run timezone independent // Ensure that all "strtotime" operations do run timezone independent
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
$this->profiler->reset(); $profiler->reset();
if ($this->mode->has(Mode::DBAVAILABLE)) { if ($mode->has(Mode::DBAVAILABLE)) {
Core\Hook::loadHooks(); Core\Hook::loadHooks();
$loader = (new Config())->createConfigFileManager($this->appHelper->getBasePath(), $request->getServerParams()); $loader = (new Config())->createConfigFileManager($appHelper->getBasePath(), $serverParams);
Core\Hook::callAll('load_config', $loader); Core\Hook::callAll('load_config', $loader);
// Hooks are now working, reload the whole definitions with hook enabled // Hooks are now working, reload the whole definitions with hook enabled
@ -302,7 +346,7 @@ class App
$viewDefinition->load(true); $viewDefinition->load(true);
} }
$this->loadDefaultTimezone(); $this->loadDefaultTimezone($config, $appHelper);
} }
/** /**
@ -312,16 +356,16 @@ class App
* *
* @global string $default_timezone * @global string $default_timezone
*/ */
private function loadDefaultTimezone() private function loadDefaultTimezone(IManageConfigValues $config, AppHelper $appHelper)
{ {
if ($this->config->get('system', 'default_timezone')) { if ($config->get('system', 'default_timezone')) {
$timezone = $this->config->get('system', 'default_timezone', 'UTC'); $timezone = $config->get('system', 'default_timezone', 'UTC');
} else { } else {
global $default_timezone; global $default_timezone;
$timezone = $default_timezone ?? '' ?: 'UTC'; $timezone = $default_timezone ?? '' ?: 'UTC';
} }
$this->appHelper->setTimeZone($timezone); $appHelper->setTimeZone($timezone);
} }
/** /**
@ -348,6 +392,8 @@ class App
float $start_time, float $start_time,
ServerRequestInterface $request ServerRequestInterface $request
) { ) {
$this->mode->setExecutor(Mode::INDEX);
$httpInput = new HTTPInputData($request->getServerParams()); $httpInput = new HTTPInputData($request->getServerParams());
$serverVars = $request->getServerParams(); $serverVars = $request->getServerParams();
$queryVars = $request->getQueryParams(); $queryVars = $request->getQueryParams();

View file

@ -16,12 +16,12 @@ use Friendica\Content\Nav;
use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Session\Model\UserSession; use Friendica\Core\Session\Model\UserSession;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Theme; use Friendica\Core\Theme;
use Friendica\DI;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Util\Images; use Friendica\Util\Images;
use Friendica\Util\Network; use Friendica\Util\Network;
@ -102,7 +102,7 @@ class Page implements ArrayAccess
$load = number_format(System::currentLoad(), 2); $load = number_format(System::currentLoad(), 2);
$runtime = number_format(microtime(true) - $this->timestamp, 3); $runtime = number_format(microtime(true) - $this->timestamp, 3);
if ($runtime > $config->get('system', 'runtime_loglimit')) { if ($runtime > $config->get('system', 'runtime_loglimit')) {
Logger::debug('Runtime', ['method' => $this->method, 'module' => $this->module, 'runtime' => $runtime, 'load' => $load, 'origin' => $origin, 'signature' => $signature, 'request' => $_SERVER['REQUEST_URI'] ?? '']); DI::logger()->debug('Runtime', ['method' => $this->method, 'module' => $this->module, 'runtime' => $runtime, 'load' => $load, 'origin' => $origin, 'signature' => $signature, 'request' => $_SERVER['REQUEST_URI'] ?? '']);
} }
} }

View file

@ -32,6 +32,7 @@ use Friendica\Util\Strings;
* and anything else that might need to be passed around * and anything else that might need to be passed around
* before we spit the page out. * before we spit the page out.
* *
* @internal
*/ */
final class AppLegacy implements AppHelper final class AppLegacy implements AppHelper
{ {

View file

@ -12,7 +12,6 @@ use Friendica\Capabilities\ICanHandleRequests;
use Friendica\Capabilities\ICanCreateResponses; use Friendica\Capabilities\ICanCreateResponses;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Model\User; use Friendica\Model\User;
use Friendica\Module\Response; use Friendica\Module\Response;
@ -412,8 +411,8 @@ abstract class BaseModule implements ICanHandleRequests
public static function checkFormSecurityTokenRedirectOnError(string $err_redirect, string $typename = '', string $formname = 'form_security_token') public static function checkFormSecurityTokenRedirectOnError(string $err_redirect, string $typename = '', string $formname = 'form_security_token')
{ {
if (!self::checkFormSecurityToken($typename, $formname)) { if (!self::checkFormSecurityToken($typename, $formname)) {
Logger::notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename); DI::logger()->notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename);
Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]); DI::logger()->debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
DI::sysmsg()->addNotice(self::getFormSecurityStandardErrorMessage()); DI::sysmsg()->addNotice(self::getFormSecurityStandardErrorMessage());
DI::baseUrl()->redirect($err_redirect); DI::baseUrl()->redirect($err_redirect);
} }
@ -422,8 +421,8 @@ abstract class BaseModule implements ICanHandleRequests
public static function checkFormSecurityTokenForbiddenOnError(string $typename = '', string $formname = 'form_security_token') public static function checkFormSecurityTokenForbiddenOnError(string $typename = '', string $formname = 'form_security_token')
{ {
if (!self::checkFormSecurityToken($typename, $formname)) { if (!self::checkFormSecurityToken($typename, $formname)) {
Logger::notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename); DI::logger()->notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename);
Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]); DI::logger()->debug('checkFormSecurityToken failed', ['request' => $_REQUEST]);
throw new \Friendica\Network\HTTPException\ForbiddenException(); throw new \Friendica\Network\HTTPException\ForbiddenException();
} }

View file

@ -1,39 +0,0 @@
<?php
// Copyright (C) 2010-2024, the Friendica project
// SPDX-FileCopyrightText: 2010-2024 the Friendica project
//
// SPDX-License-Identifier: AGPL-3.0-or-later
declare(strict_types=1);
namespace Friendica\Console;
use Asika\SimpleConsole\Console;
use Friendica\Core\Console as CoreConsole;
use Friendica\Core\Logger\Capability\LogChannel;
/**
* Abstract Console class for common settings
*/
abstract class AbstractConsole extends Console
{
/**
* Overwrite this const in case you want to switch the LogChannel for this console command
*
* @var string
*/
public const LOG_CHANNEL = LogChannel::CONSOLE;
/**
* Checks, if the Console command was executed outside `bin/console.php` and prints the correct execution
*
* @param string $command the current command
*/
protected function checkDeprecated(string $command): void
{
if (substr($this->executable, -strlen(CoreConsole::getDefaultExecutable())) !== CoreConsole::getDefaultExecutable()) {
$this->out(sprintf("'%s' is deprecated and will removed. Please use 'bin/console.php %s' instead", $this->executable, $command));
}
}
}

View file

@ -10,10 +10,10 @@ declare(strict_types=1);
namespace Friendica\Console; namespace Friendica\Console;
use Asika\SimpleConsole\CommandArgsException; use Asika\SimpleConsole\CommandArgsException;
use Asika\SimpleConsole\Console;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\KeyValueStorage\Capability\IManageKeyValuePairs; use Friendica\Core\KeyValueStorage\Capability\IManageKeyValuePairs;
use Friendica\Core\Logger\Capability\LogChannel;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Update; use Friendica\Core\Update;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -27,10 +27,8 @@ use RuntimeException;
/** /**
* Console command for interacting with the daemon * Console command for interacting with the daemon
*/ */
final class Daemon extends AbstractConsole final class Daemon extends Console
{ {
public const LOG_CHANNEL = LogChannel::DAEMON;
private Mode $mode; private Mode $mode;
private IManageConfigValues $config; private IManageConfigValues $config;
private IManageKeyValuePairs $keyValue; private IManageKeyValuePairs $keyValue;
@ -93,8 +91,6 @@ HELP;
protected function doExecute() protected function doExecute()
{ {
$this->checkDeprecated('daemon');
if ($this->mode->isInstall()) { if ($this->mode->isInstall()) {
throw new RuntimeException("Friendica isn't properly installed yet"); throw new RuntimeException("Friendica isn't properly installed yet");
} }

View file

@ -9,12 +9,12 @@ declare(strict_types=1);
namespace Friendica\Console; namespace Friendica\Console;
use Asika\SimpleConsole\Console;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\KeyValueStorage\Capability\IManageKeyValuePairs; use Friendica\Core\KeyValueStorage\Capability\IManageKeyValuePairs;
use Friendica\Core\Logger\Capability\LogChannel;
use Friendica\Protocol\ATProtocol\Jetstream; use Friendica\Protocol\ATProtocol\Jetstream;
use Friendica\System\Daemon as SysDaemon; use Friendica\System\Daemon as SysDaemon;
use RuntimeException; use RuntimeException;
@ -22,10 +22,8 @@ use RuntimeException;
/** /**
* Console command for interacting with the daemon * Console command for interacting with the daemon
*/ */
final class JetstreamDaemon extends AbstractConsole final class JetstreamDaemon extends Console
{ {
public const LOG_CHANNEL = LogChannel::DAEMON;
private Mode $mode; private Mode $mode;
private IManageConfigValues $config; private IManageConfigValues $config;
private IManageKeyValuePairs $keyValue; private IManageKeyValuePairs $keyValue;
@ -79,8 +77,6 @@ HELP;
protected function doExecute() protected function doExecute()
{ {
$this->checkDeprecated('jetstream');
if ($this->mode->isInstall()) { if ($this->mode->isInstall()) {
throw new RuntimeException("Friendica isn't properly installed yet"); throw new RuntimeException("Friendica isn't properly installed yet");
} }

View file

@ -9,8 +9,8 @@ declare(strict_types=1);
namespace Friendica\Console; namespace Friendica\Console;
use Asika\SimpleConsole\Console;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\Core\Logger\Capability\LogChannel;
use Friendica\Core\Update; use Friendica\Core\Update;
use Friendica\Core\Worker as CoreWorker; use Friendica\Core\Worker as CoreWorker;
use Friendica\Core\Worker\Repository\Process as ProcessRepository; use Friendica\Core\Worker\Repository\Process as ProcessRepository;
@ -19,10 +19,8 @@ use Friendica\Util\BasePath;
/** /**
* Console command for starting worker * Console command for starting worker
*/ */
final class Worker extends AbstractConsole final class Worker extends Console
{ {
public const LOG_CHANNEL = LogChannel::WORKER;
private Mode $mode; private Mode $mode;
private BasePath $basePath; private BasePath $basePath;
private ProcessRepository $processRepo; private ProcessRepository $processRepo;
@ -69,8 +67,6 @@ HELP;
protected function doExecute() protected function doExecute()
{ {
$this->checkDeprecated('worker');
$this->mode->setExecutor(Mode::WORKER); $this->mode->setExecutor(Mode::WORKER);
// Check the database structure and possibly fixes it // Check the database structure and possibly fixes it

View file

@ -7,7 +7,6 @@
namespace Friendica\Contact; namespace Friendica\Contact;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Network\HTTPClient\Client\HttpClientAccept; use Friendica\Network\HTTPClient\Client\HttpClientAccept;
use Friendica\Network\HTTPClient\Client\HttpClientOptions; use Friendica\Network\HTTPClient\Client\HttpClientOptions;
@ -47,36 +46,36 @@ class Avatar
if (($avatar != $contact['avatar']) || $force) { if (($avatar != $contact['avatar']) || $force) {
self::deleteCache($contact); self::deleteCache($contact);
Logger::debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]); DI::logger()->debug('Avatar file name changed', ['new' => $avatar, 'old' => $contact['avatar']]);
} elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) { } elseif (self::isCacheFile($contact['photo']) && self::isCacheFile($contact['thumb']) && self::isCacheFile($contact['micro'])) {
$fields['photo'] = $contact['photo']; $fields['photo'] = $contact['photo'];
$fields['thumb'] = $contact['thumb']; $fields['thumb'] = $contact['thumb'];
$fields['micro'] = $contact['micro']; $fields['micro'] = $contact['micro'];
Logger::debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]); DI::logger()->debug('Using existing cache files', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
return $fields; return $fields;
} }
try { try {
$fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]); $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::notice('Avatar is invalid', ['avatar' => $avatar, 'exception' => $exception]); DI::logger()->notice('Avatar is invalid', ['avatar' => $avatar, 'exception' => $exception]);
return $fields; return $fields;
} }
if (!$fetchResult->isSuccess()) { if (!$fetchResult->isSuccess()) {
Logger::debug('Fetching was unsuccessful', ['avatar' => $avatar]); DI::logger()->debug('Fetching was unsuccessful', ['avatar' => $avatar]);
return $fields; return $fields;
} }
$img_str = $fetchResult->getBodyString(); $img_str = $fetchResult->getBodyString();
if (empty($img_str)) { if (empty($img_str)) {
Logger::debug('Avatar is invalid', ['avatar' => $avatar]); DI::logger()->debug('Avatar is invalid', ['avatar' => $avatar]);
return $fields; return $fields;
} }
$image = new Image($img_str, $fetchResult->getContentType(), $avatar); $image = new Image($img_str, $fetchResult->getContentType(), $avatar);
if (!$image->isValid()) { if (!$image->isValid()) {
Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]); DI::logger()->debug('Avatar picture is invalid', ['avatar' => $avatar]);
return $fields; return $fields;
} }
@ -89,7 +88,7 @@ class Avatar
$fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp); $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $timestamp);
$fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp); $fields['micro'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_MICRO, $timestamp);
Logger::debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]); DI::logger()->debug('Storing new avatar cache', ['uri-id' => $contact['uri-id'], 'fields' => $fields]);
return $fields; return $fields;
} }
@ -155,36 +154,36 @@ class Avatar
if (!file_exists($dirpath)) { if (!file_exists($dirpath)) {
if (!@mkdir($dirpath, $dir_perm) && !file_exists($dirpath)) { if (!@mkdir($dirpath, $dir_perm) && !file_exists($dirpath)) {
Logger::warning('Directory could not be created', ['directory' => $dirpath]); DI::logger()->warning('Directory could not be created', ['directory' => $dirpath]);
} }
} elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) { } elseif ((($old_perm = fileperms($dirpath) & 0777) != $dir_perm) && !chmod($dirpath, $dir_perm)) {
Logger::warning('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]); DI::logger()->warning('Directory permissions could not be changed', ['directory' => $dirpath, 'old' => $old_perm, 'new' => $dir_perm]);
} }
if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) { if ((($old_group = filegroup($dirpath)) != $group) && !chgrp($dirpath, $group)) {
Logger::warning('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]); DI::logger()->warning('Directory group could not be changed', ['directory' => $dirpath, 'old' => $old_group, 'new' => $group]);
} }
} }
if (!file_put_contents($filepath, $image->asString())) { if (!file_put_contents($filepath, $image->asString())) {
Logger::warning('File could not be created', ['file' => $filepath]); DI::logger()->warning('File could not be created', ['file' => $filepath]);
} }
$old_perm = fileperms($filepath) & 0666; $old_perm = fileperms($filepath) & 0666;
$old_group = filegroup($filepath); $old_group = filegroup($filepath);
if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) { if (($old_perm != $file_perm) && !chmod($filepath, $file_perm)) {
Logger::warning('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]); DI::logger()->warning('File permissions could not be changed', ['file' => $filepath, 'old' => $old_perm, 'new' => $file_perm]);
} }
if (($old_group != $group) && !chgrp($filepath, $group)) { if (($old_group != $group) && !chgrp($filepath, $group)) {
Logger::warning('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]); DI::logger()->warning('File group could not be changed', ['file' => $filepath, 'old' => $old_group, 'new' => $group]);
} }
DI::profiler()->stopRecording(); DI::profiler()->stopRecording();
if (!file_exists($filepath)) { if (!file_exists($filepath)) {
Logger::warning('Avatar cache file could not be stored', ['file' => $filepath]); DI::logger()->warning('Avatar cache file could not be stored', ['file' => $filepath]);
return ''; return '';
} }
@ -257,7 +256,7 @@ class Avatar
$localFile = self::getCacheFile($avatar); $localFile = self::getCacheFile($avatar);
if (!empty($localFile)) { if (!empty($localFile)) {
@unlink($localFile); @unlink($localFile);
Logger::debug('Unlink avatar', ['avatar' => $avatar, 'local' => $localFile]); DI::logger()->debug('Unlink avatar', ['avatar' => $avatar, 'local' => $localFile]);
} }
} }
@ -277,11 +276,11 @@ class Avatar
if (!file_exists($basepath)) { if (!file_exists($basepath)) {
// We only automatically create the folder when it is in the web root // We only automatically create the folder when it is in the web root
if (strpos($basepath, DI::basePath()) !== 0) { if (strpos($basepath, DI::basePath()) !== 0) {
Logger::warning('Base directory does not exist', ['directory' => $basepath]); DI::logger()->warning('Base directory does not exist', ['directory' => $basepath]);
return ''; return '';
} }
if (!mkdir($basepath, 0775)) { if (!mkdir($basepath, 0775)) {
Logger::warning('Base directory could not be created', ['directory' => $basepath]); DI::logger()->warning('Base directory could not be created', ['directory' => $basepath]);
return ''; return '';
} }
} }

View file

@ -14,7 +14,6 @@ use Friendica\Content\Text\BBCode\Video;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Session\Capability\IHandleUserSessions; use Friendica\Core\Session\Capability\IHandleUserSessions;
@ -520,18 +519,18 @@ class Item
$only_to_group = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]); $only_to_group = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
$private_id = $contact['id']; $private_id = $contact['id'];
$group_contact = $contact; $group_contact = $contact;
Logger::info('Private group or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]); DI::logger()->info('Private group or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
} elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') { } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
$private_group = false; $private_group = false;
$only_to_group = true; $only_to_group = true;
$private_id = $contact['id']; $private_id = $contact['id'];
$group_contact = $contact; $group_contact = $contact;
Logger::info('Public group', ['url' => $tag[2], 'mention' => $tag[1]]); DI::logger()->info('Public group', ['url' => $tag[2], 'mention' => $tag[1]]);
} else { } else {
Logger::info('Post with group mention will not be converted to a group post', ['url' => $tag[2], 'mention' => $tag[1]]); DI::logger()->info('Post with group mention will not be converted to a group post', ['url' => $tag[2], 'mention' => $tag[1]]);
} }
} }
Logger::info('Got inform', ['inform' => $item['inform']]); DI::logger()->info('Got inform', ['inform' => $item['inform']]);
if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($group_contact) && ($private_group || $only_to_group)) { if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($group_contact) && ($private_group || $only_to_group)) {
// we tagged a group in a top level post. Now we change the post // we tagged a group in a top level post. Now we change the post
@ -638,7 +637,7 @@ class Item
$fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id']; $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network', 'quote-uri-id'];
$shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]); $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
if (!DBA::isResult($shared_item)) { if (!DBA::isResult($shared_item)) {
Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]); DI::logger()->notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
return $body; return $body;
} }
@ -654,7 +653,7 @@ class Item
$shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]); $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
if (!DBA::isResult($shared_item)) { if (!DBA::isResult($shared_item)) {
Logger::notice('Post does not exist.', ['guid' => $guid]); DI::logger()->notice('Post does not exist.', ['guid' => $guid]);
return ''; return '';
} }
@ -1087,7 +1086,7 @@ class Item
$expire_date = time() - ($expire_interval * 86400); $expire_date = time() - ($expire_interval * 86400);
$created_date = strtotime($created); $created_date = strtotime($created);
if ($created_date < $expire_date) { if ($created_date < $expire_date) {
Logger::notice('Item created before expiration interval.', ['created' => date('c', $created_date), 'expired' => date('c', $expire_date)]); DI::logger()->notice('Item created before expiration interval.', ['created' => date('c', $created_date), 'expired' => date('c', $expire_date)]);
return true; return true;
} }
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Content; namespace Friendica\Content;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Util\ParseUrl; use Friendica\Util\ParseUrl;
@ -28,7 +27,7 @@ class PageInfo
*/ */
public static function searchAndAppendToBody(string $body, bool $searchNakedUrls = false, bool $no_photos = false) public static function searchAndAppendToBody(string $body, bool $searchNakedUrls = false, bool $no_photos = false)
{ {
Logger::debug('add_page_info_to_body: fetch page info for body', ['body' => $body]); DI::logger()->debug('add_page_info_to_body: fetch page info for body', ['body' => $body]);
$url = self::getRelevantUrlFromBody($body, $searchNakedUrls); $url = self::getRelevantUrlFromBody($body, $searchNakedUrls);
if (!$url) { if (!$url) {
@ -194,7 +193,7 @@ class PageInfo
} }
} }
Logger::debug('fetch page info for URL', ['url' => $url, 'data' => $data]); DI::logger()->debug('fetch page info for URL', ['url' => $url, 'data' => $data]);
return $data; return $data;
} }
@ -216,8 +215,11 @@ class PageInfo
$taglist = []; $taglist = [];
foreach ($data['keywords'] as $keyword) { foreach ($data['keywords'] as $keyword) {
$hashtag = str_replace([' ', '+', '/', '.', '#', "'"], $hashtag = str_replace(
['', '', '', '', '', ''], $keyword); [' ', '+', '/', '.', '#', "'"],
['', '', '', '', '', ''],
$keyword
);
$taglist[] = $hashtag; $taglist[] = $hashtag;
} }

View file

@ -16,7 +16,6 @@ use Friendica\Content\OEmbed;
use Friendica\Content\PageInfo; use Friendica\Content\PageInfo;
use Friendica\Content\Smilies; use Friendica\Content\Smilies;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\DI; use Friendica\DI;
@ -135,6 +134,7 @@ class BBCode
$value = html_entity_decode($value, ENT_QUOTES, 'UTF-8'); $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
$data['title'] = self::escapeContent($value); $data['title'] = self::escapeContent($value);
// no break
default: default:
$data[$field] = html_entity_decode($value, ENT_QUOTES, 'UTF-8'); $data[$field] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
break; break;
@ -328,7 +328,7 @@ class BBCode
// than the maximum, then don't waste time looking for the images // than the maximum, then don't waste time looking for the images
if ($maxlen && (strlen($body) > $maxlen)) { if ($maxlen && (strlen($body) > $maxlen)) {
Logger::info('the total body length exceeds the limit', ['maxlen' => $maxlen, 'body_len' => strlen($body)]); DI::logger()->info('the total body length exceeds the limit', ['maxlen' => $maxlen, 'body_len' => strlen($body)]);
$orig_body = $body; $orig_body = $body;
$new_body = ''; $new_body = '';
@ -348,7 +348,7 @@ class BBCode
if (($textlen + $img_start) > $maxlen) { if (($textlen + $img_start) > $maxlen) {
if ($textlen < $maxlen) { if ($textlen < $maxlen) {
Logger::debug('the limit happens before an embedded image'); DI::logger()->debug('the limit happens before an embedded image');
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
$textlen = $maxlen; $textlen = $maxlen;
} }
@ -362,7 +362,7 @@ class BBCode
if (($textlen + $img_end) > $maxlen) { if (($textlen + $img_end) > $maxlen) {
if ($textlen < $maxlen) { if ($textlen < $maxlen) {
Logger::debug('the limit happens before the end of a non-embedded image'); DI::logger()->debug('the limit happens before the end of a non-embedded image');
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
$textlen = $maxlen; $textlen = $maxlen;
} }
@ -385,11 +385,11 @@ class BBCode
if (($textlen + strlen($orig_body)) > $maxlen) { if (($textlen + strlen($orig_body)) > $maxlen) {
if ($textlen < $maxlen) { if ($textlen < $maxlen) {
Logger::debug('the limit happens after the end of the last image'); DI::logger()->debug('the limit happens after the end of the last image');
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
} }
} else { } else {
Logger::debug('the text size with embedded images extracted did not violate the limit'); DI::logger()->debug('the text size with embedded images extracted did not violate the limit');
$new_body = $new_body . $orig_body; $new_body = $new_body . $orig_body;
} }
@ -2107,7 +2107,7 @@ class BBCode
try { try {
return (string)Uri::fromParts($parts); return (string)Uri::fromParts($parts);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Exception on unparsing url', ['url' => $url, 'parts' => $parts, 'code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Exception on unparsing url', ['url' => $url, 'parts' => $parts, 'code' => $th->getCode(), 'message' => $th->getMessage()]);
return $url; return $url;
} }
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Content\Text; namespace Friendica\Content\Text;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -25,7 +24,8 @@ class Markdown
* @param string $baseuri Optional. Prepend anchor links with this URL * @param string $baseuri Optional. Prepend anchor links with this URL
* @return string * @return string
*/ */
public static function convert($text, $hardwrap = true, $baseuri = null) { public static function convert($text, $hardwrap = true, $baseuri = null)
{
DI::profiler()->startRecording('rendering'); DI::profiler()->startRecording('rendering');
$MarkdownParser = new MarkdownParser(); $MarkdownParser = new MarkdownParser();
@ -97,7 +97,7 @@ class Markdown
{ {
// @TODO Temporary until we find the source of the null value to finally set the correct type-hint // @TODO Temporary until we find the source of the null value to finally set the correct type-hint
if (is_null($s)) { if (is_null($s)) {
Logger::warning('Received null value'); DI::logger()->warning('Received null value');
return ''; return '';
} }

View file

@ -9,7 +9,6 @@ namespace Friendica\Content\Widget;
use Friendica\Content\ContactSelector; use Friendica\Content\ContactSelector;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\DI; use Friendica\DI;
@ -34,7 +33,7 @@ class VCard
public static function getHTML(array $contact, bool $hide_mention = false, bool $hide_follow = false): string public static function getHTML(array $contact, bool $hide_mention = false, bool $hide_follow = false): string
{ {
if (!isset($contact['network']) || !isset($contact['id'])) { if (!isset($contact['network']) || !isset($contact['id'])) {
Logger::warning('Incomplete contact', ['contact' => $contact]); DI::logger()->warning('Incomplete contact', ['contact' => $contact]);
} }
$contact_url = Contact::getProfileLink($contact); $contact_url = Contact::getProfileLink($contact);

View file

@ -117,7 +117,7 @@ class Addon
{ {
$addon = Strings::sanitizeFilePathItem($addon); $addon = Strings::sanitizeFilePathItem($addon);
Logger::debug("Addon {addon}: {action}", ['action' => 'uninstall', 'addon' => $addon]); DI::logger()->debug("Addon {addon}: {action}", ['action' => 'uninstall', 'addon' => $addon]);
DI::config()->delete('addons', $addon); DI::config()->delete('addons', $addon);
@include_once('addon/' . $addon . '/' . $addon . '.php'); @include_once('addon/' . $addon . '/' . $addon . '.php');
@ -150,7 +150,7 @@ class Addon
return false; return false;
} }
Logger::debug("Addon {addon}: {action}", ['action' => 'install', 'addon' => $addon]); DI::logger()->debug("Addon {addon}: {action}", ['action' => 'install', 'addon' => $addon]);
$t = @filemtime($addon_file_path); $t = @filemtime($addon_file_path);
@include_once($addon_file_path); @include_once($addon_file_path);
if (function_exists($addon . '_install')) { if (function_exists($addon . '_install')) {
@ -189,7 +189,7 @@ class Addon
continue; continue;
} }
Logger::debug("Addon {addon}: {action}", ['action' => 'reload', 'addon' => $name]); DI::logger()->debug("Addon {addon}: {action}", ['action' => 'reload', 'addon' => $name]);
self::uninstall($name); self::uninstall($name);
self::install($name); self::install($name);

View file

@ -11,6 +11,8 @@ namespace Friendica\Core;
/** /**
* Dependency Injection Container * Dependency Injection Container
*
* @internal
*/ */
interface Container interface Container
{ {

View file

@ -13,6 +13,8 @@ use Dice\Dice;
/** /**
* Wrapper for the Dice class to make some basic setups * Wrapper for the Dice class to make some basic setups
*
* @internal
*/ */
final class DiceContainer implements Container final class DiceContainer implements Container
{ {

View file

@ -26,6 +26,8 @@ use Psr\Log\LoggerInterface;
* *
* @see \Friendica\Core\Logger\Factory\StreamLogger * @see \Friendica\Core\Logger\Factory\StreamLogger
* @see \Friendica\Core\Logger\Factory\SyslogLogger * @see \Friendica\Core\Logger\Factory\SyslogLogger
*
* @internal
*/ */
final class LegacyLoggerFactory implements LoggerFactory final class LegacyLoggerFactory implements LoggerFactory
{ {

View file

@ -21,6 +21,8 @@ use Psr\Log\NullLogger;
/** /**
* Manager for the core logging instances * Manager for the core logging instances
*
* @internal
*/ */
final class LoggerManager final class LoggerManager
{ {

View file

@ -8,6 +8,7 @@
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\User; use Friendica\Model\User;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Protocol\ActivityPub; use Friendica\Protocol\ActivityPub;
@ -123,7 +124,7 @@ class Protocol
if ($protocol == self::DIASPORA) { if ($protocol == self::DIASPORA) {
$contact = Diaspora::sendShare($owner, $contact); $contact = Diaspora::sendShare($owner, $contact);
Logger::notice('share returns: ' . $contact); DI::logger()->notice('share returns: ' . $contact);
} elseif (in_array($protocol, [self::ACTIVITYPUB, self::DFRN])) { } elseif (in_array($protocol, [self::ACTIVITYPUB, self::DFRN])) {
$activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']); $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
if (empty($activity_id)) { if (empty($activity_id)) {
@ -132,7 +133,7 @@ class Protocol
} }
$success = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $owner['uid'], $activity_id); $success = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $owner['uid'], $activity_id);
Logger::notice('Follow returns: ' . $success); DI::logger()->notice('Follow returns: ' . $success);
} }
return true; return true;
@ -150,7 +151,7 @@ class Protocol
public static function unfollow(array $contact, array $owner): ?bool public static function unfollow(array $contact, array $owner): ?bool
{ {
if (empty($contact['network'])) { if (empty($contact['network'])) {
Logger::notice('Contact has got no network, we quit here', ['id' => $contact['id']]); DI::logger()->notice('Contact has got no network, we quit here', ['id' => $contact['id']]);
return null; return null;
} }

View file

@ -16,7 +16,6 @@ use Friendica\Network\HTTPException;
use Friendica\Object\Search\ContactResult; use Friendica\Object\Search\ContactResult;
use Friendica\Object\Search\ResultList; use Friendica\Object\Search\ResultList;
use Friendica\Util\Network; use Friendica\Util\Network;
use Friendica\Util\Strings;
use GuzzleHttp\Psr7\Uri; use GuzzleHttp\Psr7\Uri;
/** /**
@ -160,7 +159,7 @@ class Search
*/ */
public static function getContactsFromLocalDirectory(string $search, int $type = self::TYPE_ALL, int $start = 0, int $itemPage = 80): ResultList public static function getContactsFromLocalDirectory(string $search, int $type = self::TYPE_ALL, int $start = 0, int $itemPage = 80): ResultList
{ {
Logger::info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]); DI::logger()->info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]);
$contacts = Contact::searchByName($search, $type == self::TYPE_GROUP ? 'community' : '', true); $contacts = Contact::searchByName($search, $type == self::TYPE_GROUP ? 'community' : '', true);
@ -200,7 +199,7 @@ class Search
*/ */
public static function searchContact(string $search, string $mode, int $page = 1): array public static function searchContact(string $search, string $mode, int $page = 1): array
{ {
Logger::info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]); DI::logger()->info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]);
if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) { if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
return []; return [];
@ -223,7 +222,7 @@ class Search
try { try {
$curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTDISCOVER]); $curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTDISCOVER]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return []; return [];
} }
if ($curlResult->isSuccess()) { if ($curlResult->isSuccess()) {

View file

@ -322,7 +322,7 @@ class System
} }
if ($status) { if ($status) {
Logger::notice('xml_status returning non_zero: ' . $status . " message=" . $message); DI::logger()->notice('xml_status returning non_zero: ' . $status . " message=" . $message);
} }
self::httpExit(XML::fromArray(['result' => $result]), Response::TYPE_XML); self::httpExit(XML::fromArray(['result' => $result]), Response::TYPE_XML);
@ -340,7 +340,7 @@ class System
public static function httpError($httpCode, $message = '', $content = '') public static function httpError($httpCode, $message = '', $content = '')
{ {
if ($httpCode >= 400) { if ($httpCode >= 400) {
Logger::debug('Exit with error', ['code' => $httpCode, 'message' => $message, 'method' => DI::args()->getMethod(), 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); DI::logger()->debug('Exit with error', ['code' => $httpCode, 'message' => $message, 'method' => DI::args()->getMethod(), 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
} }
DI::apiResponse()->setStatus($httpCode, $message); DI::apiResponse()->setStatus($httpCode, $message);
@ -373,7 +373,7 @@ class System
public static function jsonError($httpCode, $content, $content_type = 'application/json') public static function jsonError($httpCode, $content, $content_type = 'application/json')
{ {
if ($httpCode >= 400) { if ($httpCode >= 400) {
Logger::debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'method' => DI::args()->getMethod(), 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); DI::logger()->debug('Exit with error', ['code' => $httpCode, 'content_type' => $content_type, 'method' => DI::args()->getMethod(), 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']);
} }
DI::apiResponse()->setStatus($httpCode); DI::apiResponse()->setStatus($httpCode);
self::jsonExit($content, $content_type); self::jsonExit($content, $content_type);
@ -520,7 +520,7 @@ class System
public static function externalRedirect($url, $code = 302) public static function externalRedirect($url, $code = 302)
{ {
if (empty(parse_url($url, PHP_URL_SCHEME))) { if (empty(parse_url($url, PHP_URL_SCHEME))) {
Logger::warning('No fully qualified URL provided', ['url' => $url]); DI::logger()->warning('No fully qualified URL provided', ['url' => $url]);
DI::baseUrl()->redirect($url); DI::baseUrl()->redirect($url);
} }
@ -564,27 +564,27 @@ class System
private static function isDirectoryUsable(string $directory): bool private static function isDirectoryUsable(string $directory): bool
{ {
if (empty($directory)) { if (empty($directory)) {
Logger::warning('Directory is empty. This shouldn\'t happen.'); DI::logger()->warning('Directory is empty. This shouldn\'t happen.');
return false; return false;
} }
if (!file_exists($directory)) { if (!file_exists($directory)) {
Logger::info('Path does not exist', ['directory' => $directory, 'user' => static::getUser()]); DI::logger()->info('Path does not exist', ['directory' => $directory, 'user' => static::getUser()]);
return false; return false;
} }
if (is_file($directory)) { if (is_file($directory)) {
Logger::warning('Path is a file', ['directory' => $directory, 'user' => static::getUser()]); DI::logger()->warning('Path is a file', ['directory' => $directory, 'user' => static::getUser()]);
return false; return false;
} }
if (!is_dir($directory)) { if (!is_dir($directory)) {
Logger::warning('Path is not a directory', ['directory' => $directory, 'user' => static::getUser()]); DI::logger()->warning('Path is not a directory', ['directory' => $directory, 'user' => static::getUser()]);
return false; return false;
} }
if (!is_writable($directory)) { if (!is_writable($directory)) {
Logger::warning('Path is not writable', ['directory' => $directory, 'user' => static::getUser()]); DI::logger()->warning('Path is not writable', ['directory' => $directory, 'user' => static::getUser()]);
return false; return false;
} }

View file

@ -191,7 +191,7 @@ class Theme
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
Logger::error('Theme installation failed', ['theme' => $theme, 'error' => $e->getMessage()]); DI::logger()->error('Theme installation failed', ['theme' => $theme, 'error' => $e->getMessage()]);
return false; return false;
} }
} }

View file

@ -178,7 +178,7 @@ class Update
// If the Lock is acquired, never release it automatically to avoid double updates // If the Lock is acquired, never release it automatically to avoid double updates
if (DI::lock()->acquire('dbupdate', 0, Cache\Enum\Duration::INFINITE)) { if (DI::lock()->acquire('dbupdate', 0, Cache\Enum\Duration::INFINITE)) {
Logger::notice('Update starting.', ['from' => $stored, 'to' => $current]); DI::logger()->notice('Update starting.', ['from' => $stored, 'to' => $current]);
// Checks if the build changed during Lock acquiring (so no double update occurs) // Checks if the build changed during Lock acquiring (so no double update occurs)
$retryBuild = DI::config()->get('system', 'build'); $retryBuild = DI::config()->get('system', 'build');
@ -192,7 +192,7 @@ class Update
} }
if ($retryBuild != $build) { if ($retryBuild != $build) {
Logger::notice('Update already done.', ['from' => $build, 'retry' => $retryBuild, 'to' => $current]); DI::logger()->notice('Update already done.', ['from' => $build, 'retry' => $retryBuild, 'to' => $current]);
DI::lock()->release('dbupdate'); DI::lock()->release('dbupdate');
return ''; return '';
} }
@ -202,12 +202,15 @@ class Update
// run the pre_update_nnnn functions in update.php // run the pre_update_nnnn functions in update.php
for ($version = $stored + 1; $version <= $current; $version++) { for ($version = $stored + 1; $version <= $current; $version++) {
Logger::notice('Execute pre update.', ['version' => $version]); DI::logger()->notice('Execute pre update.', ['version' => $version]);
DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing pre update %d', DI::config()->set('system', 'maintenance_reason', DI::l10n()->t(
DateTimeFormat::utcNow() . ' ' . date('e'), $version)); '%s: executing pre update %d',
DateTimeFormat::utcNow() . ' ' . date('e'),
$version
));
$r = self::runUpdateFunction($version, 'pre_update', $sendMail); $r = self::runUpdateFunction($version, 'pre_update', $sendMail);
if (!$r) { if (!$r) {
Logger::warning('Pre update failed', ['version' => $version]); DI::logger()->warning('Pre update failed', ['version' => $version]);
DI::config()->set('system', 'update', Update::FAILED); DI::config()->set('system', 'update', Update::FAILED);
DI::lock()->release('dbupdate'); DI::lock()->release('dbupdate');
DI::config()->beginTransaction() DI::config()->beginTransaction()
@ -216,12 +219,12 @@ class Update
->commit(); ->commit();
return $r; return $r;
} else { } else {
Logger::notice('Pre update executed.', ['version' => $version]); DI::logger()->notice('Pre update executed.', ['version' => $version]);
} }
} }
// update the structure in one call // update the structure in one call
Logger::notice('Execute structure update'); DI::logger()->notice('Execute structure update');
$retval = DBStructure::performUpdate(false, $verbose); $retval = DBStructure::performUpdate(false, $verbose);
if (!empty($retval)) { if (!empty($retval)) {
if ($sendMail) { if ($sendMail) {
@ -230,7 +233,7 @@ class Update
$retval $retval
); );
} }
Logger::error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]); DI::logger()->error('Update ERROR.', ['from' => $stored, 'to' => $current, 'retval' => $retval]);
DI::config()->set('system', 'update', Update::FAILED); DI::config()->set('system', 'update', Update::FAILED);
DI::lock()->release('dbupdate'); DI::lock()->release('dbupdate');
DI::config()->beginTransaction() DI::config()->beginTransaction()
@ -239,17 +242,20 @@ class Update
->commit(); ->commit();
return $retval; return $retval;
} else { } else {
Logger::notice('Database structure update finished.', ['from' => $stored, 'to' => $current]); DI::logger()->notice('Database structure update finished.', ['from' => $stored, 'to' => $current]);
} }
// run the update_nnnn functions in update.php // run the update_nnnn functions in update.php
for ($version = $stored + 1; $version <= $current; $version++) { for ($version = $stored + 1; $version <= $current; $version++) {
Logger::notice('Execute post update.', ['version' => $version]); DI::logger()->notice('Execute post update.', ['version' => $version]);
DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing post update %d', DI::config()->set('system', 'maintenance_reason', DI::l10n()->t(
DateTimeFormat::utcNow() . ' ' . date('e'), $version)); '%s: executing post update %d',
DateTimeFormat::utcNow() . ' ' . date('e'),
$version
));
$r = self::runUpdateFunction($version, 'update', $sendMail); $r = self::runUpdateFunction($version, 'update', $sendMail);
if (!$r) { if (!$r) {
Logger::warning('Post update failed', ['version' => $version]); DI::logger()->warning('Post update failed', ['version' => $version]);
DI::config()->set('system', 'update', Update::FAILED); DI::config()->set('system', 'update', Update::FAILED);
DI::lock()->release('dbupdate'); DI::lock()->release('dbupdate');
DI::config()->beginTransaction() DI::config()->beginTransaction()
@ -259,7 +265,7 @@ class Update
return $r; return $r;
} else { } else {
DI::config()->set('system', 'build', $version); DI::config()->set('system', 'build', $version);
Logger::notice('Post update executed.', ['version' => $version]); DI::logger()->notice('Post update executed.', ['version' => $version]);
} }
} }
@ -271,12 +277,12 @@ class Update
->delete('system', 'maintenance_reason') ->delete('system', 'maintenance_reason')
->commit(); ->commit();
Logger::notice('Update success.', ['from' => $stored, 'to' => $current]); DI::logger()->notice('Update success.', ['from' => $stored, 'to' => $current]);
if ($sendMail) { if ($sendMail) {
self::updateSuccessful($stored, $current); self::updateSuccessful($stored, $current);
} }
} else { } else {
Logger::warning('Update lock could not be acquired'); DI::logger()->warning('Update lock could not be acquired');
} }
} }
} }
@ -297,7 +303,7 @@ class Update
{ {
$funcname = $prefix . '_' . $version; $funcname = $prefix . '_' . $version;
Logger::notice('Update function start.', ['function' => $funcname]); DI::logger()->notice('Update function start.', ['function' => $funcname]);
if (function_exists($funcname)) { if (function_exists($funcname)) {
// There could be a lot of processes running or about to run. // There could be a lot of processes running or about to run.
@ -310,9 +316,9 @@ class Update
if (DI::lock()->acquire('dbupdate_function', 120, Cache\Enum\Duration::INFINITE)) { if (DI::lock()->acquire('dbupdate_function', 120, Cache\Enum\Duration::INFINITE)) {
// call the specific update // call the specific update
Logger::notice('Pre update function start.', ['function' => $funcname]); DI::logger()->notice('Pre update function start.', ['function' => $funcname]);
$retval = $funcname(); $retval = $funcname();
Logger::notice('Update function done.', ['function' => $funcname]); DI::logger()->notice('Update function done.', ['function' => $funcname]);
if ($retval) { if ($retval) {
if ($sendMail) { if ($sendMail) {
@ -322,20 +328,20 @@ class Update
DI::l10n()->t('Update %s failed. See error logs.', $version) DI::l10n()->t('Update %s failed. See error logs.', $version)
); );
} }
Logger::error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]); DI::logger()->error('Update function ERROR.', ['function' => $funcname, 'retval' => $retval]);
DI::lock()->release('dbupdate_function'); DI::lock()->release('dbupdate_function');
return false; return false;
} else { } else {
DI::lock()->release('dbupdate_function'); DI::lock()->release('dbupdate_function');
Logger::notice('Update function finished.', ['function' => $funcname]); DI::logger()->notice('Update function finished.', ['function' => $funcname]);
return true; return true;
} }
} else { } else {
Logger::error('Locking failed.', ['function' => $funcname]); DI::logger()->error('Locking failed.', ['function' => $funcname]);
return false; return false;
} }
} else { } else {
Logger::notice('Update function skipped.', ['function' => $funcname]); DI::logger()->notice('Update function skipped.', ['function' => $funcname]);
return true; return true;
} }
} }
@ -352,19 +358,21 @@ class Update
{ {
$adminEmails = User::getAdminListForEmailing(['uid', 'language', 'email']); $adminEmails = User::getAdminListForEmailing(['uid', 'language', 'email']);
if (!$adminEmails) { if (!$adminEmails) {
Logger::warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]); DI::logger()->warning('Cannot notify administrators .', ['update' => $update_id, 'message' => $error_message]);
return; return;
} }
foreach($adminEmails as $admin) { foreach($adminEmails as $admin) {
$l10n = DI::l10n()->withLang($admin['language'] ?: 'en'); $l10n = DI::l10n()->withLang($admin['language'] ?: 'en');
$preamble = Strings::deindent($l10n->t(" $preamble = Strings::deindent($l10n->t(
"
The friendica developers released update %s recently, The friendica developers released update %s recently,
but when I tried to install it, something went terribly wrong. but when I tried to install it, something went terribly wrong.
This needs to be fixed soon and I can't do it alone. Please contact a This needs to be fixed soon and I can't do it alone. Please contact a
friendica developer if you can not help me on your own. My database might be invalid.", friendica developer if you can not help me on your own. My database might be invalid.",
$update_id)); $update_id
));
$body = $l10n->t('The error message is\n[pre]%s[/pre]', $error_message); $body = $l10n->t('The error message is\n[pre]%s[/pre]', $error_message);
$email = DI::emailer() $email = DI::emailer()
@ -376,7 +384,7 @@ class Update
DI::emailer()->send($email); DI::emailer()->send($email);
} }
Logger::alert('Database structure update failed.', ['error' => $error_message]); DI::logger()->alert('Database structure update failed.', ['error' => $error_message]);
} }
/** /**
@ -391,9 +399,12 @@ class Update
foreach(User::getAdminListForEmailing(['uid', 'language', 'email']) as $admin) { foreach(User::getAdminListForEmailing(['uid', 'language', 'email']) as $admin) {
$l10n = DI::l10n()->withLang($admin['language'] ?: 'en'); $l10n = DI::l10n()->withLang($admin['language'] ?: 'en');
$preamble = Strings::deindent($l10n->t(' $preamble = Strings::deindent($l10n->t(
'
The friendica database was successfully updated from %s to %s.', The friendica database was successfully updated from %s to %s.',
$from_build, $to_build)); $from_build,
$to_build
));
$email = DI::emailer() $email = DI::emailer()
->newSystemMail() ->newSystemMail()
@ -404,6 +415,6 @@ class Update
DI::emailer()->send($email); DI::emailer()->send($email);
} }
Logger::debug('Database structure update successful.'); DI::logger()->debug('Database structure update successful.');
} }
} }

View file

@ -71,7 +71,7 @@ class Worker
// At first check the maximum load. We shouldn't continue with a high load // At first check the maximum load. We shouldn't continue with a high load
if (DI::system()->isMaxLoadReached()) { if (DI::system()->isMaxLoadReached()) {
Logger::notice('Pre check: maximum load reached, quitting.'); DI::logger()->notice('Pre check: maximum load reached, quitting.');
return; return;
} }
@ -109,7 +109,7 @@ class Worker
foreach ($r as $entry) { foreach ($r as $entry) {
// The work will be done // The work will be done
if (!self::execute($entry)) { if (!self::execute($entry)) {
Logger::warning('Process execution failed, quitting.', ['entry' => $entry]); DI::logger()->warning('Process execution failed, quitting.', ['entry' => $entry]);
return; return;
} }
@ -131,14 +131,14 @@ class Worker
if (DI::lock()->acquire(self::LOCK_WORKER, 0)) { if (DI::lock()->acquire(self::LOCK_WORKER, 0)) {
// Count active workers and compare them with a maximum value that depends on the load // Count active workers and compare them with a maximum value that depends on the load
if (self::tooMuchWorkers()) { if (self::tooMuchWorkers()) {
Logger::info('Active worker limit reached, quitting.'); DI::logger()->info('Active worker limit reached, quitting.');
DI::lock()->release(self::LOCK_WORKER); DI::lock()->release(self::LOCK_WORKER);
return; return;
} }
// Check free memory // Check free memory
if (DI::system()->isMinMemoryReached()) { if (DI::system()->isMinMemoryReached()) {
Logger::warning('Memory limit reached, quitting.'); DI::logger()->warning('Memory limit reached, quitting.');
DI::lock()->release(self::LOCK_WORKER); DI::lock()->release(self::LOCK_WORKER);
return; return;
} }
@ -149,7 +149,7 @@ class Worker
// Quit the worker once every cron interval // Quit the worker once every cron interval
if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60)) && !self::systemLimitReached()) { if (time() > ($starttime + (DI::config()->get('system', 'cron_interval') * 60)) && !self::systemLimitReached()) {
Logger::info('Process lifetime reached, respawning.'); DI::logger()->info('Process lifetime reached, respawning.');
self::unclaimProcess($process); self::unclaimProcess($process);
if (Worker\Daemon::isMode()) { if (Worker\Daemon::isMode()) {
Worker\IPC::SetJobState(true); Worker\IPC::SetJobState(true);
@ -164,7 +164,7 @@ class Worker
if (Worker\Daemon::isMode()) { if (Worker\Daemon::isMode()) {
Worker\IPC::SetJobState(false); Worker\IPC::SetJobState(false);
} }
Logger::info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]); DI::logger()->info("Couldn't select a workerqueue entry, quitting process", ['pid' => getmypid()]);
} }
/** /**
@ -178,25 +178,25 @@ class Worker
{ {
// Count active workers and compare them with a maximum value that depends on the load // Count active workers and compare them with a maximum value that depends on the load
if (self::tooMuchWorkers()) { if (self::tooMuchWorkers()) {
Logger::info('Active worker limit reached, quitting.'); DI::logger()->info('Active worker limit reached, quitting.');
return false; return false;
} }
// Do we have too few memory? // Do we have too few memory?
if (DI::system()->isMinMemoryReached()) { if (DI::system()->isMinMemoryReached()) {
Logger::warning('Memory limit reached, quitting.'); DI::logger()->warning('Memory limit reached, quitting.');
return false; return false;
} }
// Possibly there are too much database connections // Possibly there are too much database connections
if (self::maxConnectionsReached()) { if (self::maxConnectionsReached()) {
Logger::warning('Maximum connections reached, quitting.'); DI::logger()->warning('Maximum connections reached, quitting.');
return false; return false;
} }
// Possibly there are too much database processes that block the system // Possibly there are too much database processes that block the system
if (DI::system()->isMaxProcessesReached()) { if (DI::system()->isMaxProcessesReached()) {
Logger::warning('Maximum processes reached, quitting.'); DI::logger()->warning('Maximum processes reached, quitting.');
return false; return false;
} }
@ -322,19 +322,19 @@ class Worker
// Quit when in maintenance // Quit when in maintenance
if (DI::config()->get('system', 'maintenance', false)) { if (DI::config()->get('system', 'maintenance', false)) {
Logger::notice('Maintenance mode - quit process', ['pid' => $mypid]); DI::logger()->notice('Maintenance mode - quit process', ['pid' => $mypid]);
return false; return false;
} }
// Constantly check the number of parallel database processes // Constantly check the number of parallel database processes
if (DI::system()->isMaxProcessesReached()) { if (DI::system()->isMaxProcessesReached()) {
Logger::warning('Max processes reached for process', ['pid' => $mypid]); DI::logger()->warning('Max processes reached for process', ['pid' => $mypid]);
return false; return false;
} }
// Constantly check the number of available database connections to let the frontend be accessible at any time // Constantly check the number of available database connections to let the frontend be accessible at any time
if (self::maxConnectionsReached()) { if (self::maxConnectionsReached()) {
Logger::warning('Max connection reached for process', ['pid' => $mypid]); DI::logger()->warning('Max connection reached for process', ['pid' => $mypid]);
return false; return false;
} }
@ -348,7 +348,7 @@ class Worker
} }
if (empty($argv)) { if (empty($argv)) {
Logger::warning('Parameter is empty', ['queue' => $queue]); DI::logger()->warning('Parameter is empty', ['queue' => $queue]);
return false; return false;
} }
@ -387,7 +387,7 @@ class Worker
} }
if (!self::validateInclude($include)) { if (!self::validateInclude($include)) {
Logger::warning('Include file is not valid', ['file' => $argv[0]]); DI::logger()->warning('Include file is not valid', ['file' => $argv[0]]);
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
DBA::delete('workerqueue', ['id' => $queue['id']]); DBA::delete('workerqueue', ['id' => $queue['id']]);
self::$db_duration = (microtime(true) - $stamp); self::$db_duration = (microtime(true) - $stamp);
@ -424,7 +424,7 @@ class Worker
self::$db_duration = (microtime(true) - $stamp); self::$db_duration = (microtime(true) - $stamp);
self::$db_duration_write += (microtime(true) - $stamp); self::$db_duration_write += (microtime(true) - $stamp);
} else { } else {
Logger::warning('Function does not exist', ['function' => $funcname]); DI::logger()->warning('Function does not exist', ['function' => $funcname]);
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
DBA::delete('workerqueue', ['id' => $queue['id']]); DBA::delete('workerqueue', ['id' => $queue['id']]);
self::$db_duration = (microtime(true) - $stamp); self::$db_duration = (microtime(true) - $stamp);
@ -477,7 +477,7 @@ class Worker
{ {
$cooldown = DI::config()->get('system', 'worker_cooldown', 0); $cooldown = DI::config()->get('system', 'worker_cooldown', 0);
if ($cooldown > 0) { if ($cooldown > 0) {
Logger::debug('Wait for cooldown.', ['cooldown' => $cooldown]); DI::logger()->debug('Wait for cooldown.', ['cooldown' => $cooldown]);
if ($cooldown < 1) { if ($cooldown < 1) {
usleep($cooldown * 1000000); usleep($cooldown * 1000000);
} else { } else {
@ -501,7 +501,7 @@ class Worker
while ($load = System::getLoadAvg($processes_cooldown != 0)) { while ($load = System::getLoadAvg($processes_cooldown != 0)) {
if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) { if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) {
if (!$sleeping) { if (!$sleeping) {
Logger::info('Load induced pre execution cooldown.', ['max' => $load_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]); DI::logger()->info('Load induced pre execution cooldown.', ['max' => $load_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
$sleeping = true; $sleeping = true;
} }
sleep(1); sleep(1);
@ -509,7 +509,7 @@ class Worker
} }
if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) { if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) {
if (!$sleeping) { if (!$sleeping) {
Logger::info('Process induced pre execution cooldown.', ['max' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]); DI::logger()->info('Process induced pre execution cooldown.', ['max' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
$sleeping = true; $sleeping = true;
} }
sleep(1); sleep(1);
@ -519,7 +519,7 @@ class Worker
} }
if ($sleeping) { if ($sleeping) {
Logger::info('Cooldown ended.', ['max-load' => $load_cooldown, 'max-processes' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]); DI::logger()->info('Cooldown ended.', ['max-load' => $load_cooldown, 'max-processes' => $processes_cooldown, 'load' => $load, 'called-by' => System::callstack(1)]);
} }
} }
@ -677,12 +677,12 @@ class Worker
// If $max is set we will use the processlist to determine the current number of connections // If $max is set we will use the processlist to determine the current number of connections
// The processlist only shows entries of the current user // The processlist only shows entries of the current user
if ($max != 0) { if ($max != 0) {
Logger::info('Connection usage (user values)', ['working' => $used, 'sleeping' => $sleep, 'max' => $max]); DI::logger()->info('Connection usage (user values)', ['working' => $used, 'sleeping' => $sleep, 'max' => $max]);
$level = ($used / $max) * 100; $level = ($used / $max) * 100;
if ($level >= $maxlevel) { if ($level >= $maxlevel) {
Logger::warning('Maximum level (' . $maxlevel . '%) of user connections reached: ' . $used .'/' . $max); DI::logger()->warning('Maximum level (' . $maxlevel . '%) of user connections reached: ' . $used .'/' . $max);
return true; return true;
} }
} }
@ -705,14 +705,14 @@ class Worker
if ($used == 0) { if ($used == 0) {
return false; return false;
} }
Logger::info('Connection usage (system values)', ['working' => $used, 'sleeping' => $sleep, 'max' => $max]); DI::logger()->info('Connection usage (system values)', ['working' => $used, 'sleeping' => $sleep, 'max' => $max]);
$level = $used / $max * 100; $level = $used / $max * 100;
if ($level < $maxlevel) { if ($level < $maxlevel) {
return false; return false;
} }
Logger::warning('Maximum level (' . $level . '%) of system connections reached: ' . $used . '/' . $max); DI::logger()->warning('Maximum level (' . $level . '%) of system connections reached: ' . $used . '/' . $max);
return true; return true;
} }
@ -815,16 +815,16 @@ class Worker
$high_running = self::processWithPriorityActive($top_priority); $high_running = self::processWithPriorityActive($top_priority);
if (!$high_running && ($top_priority > self::PRIORITY_UNDEFINED) && ($top_priority < self::PRIORITY_NEGLIGIBLE)) { if (!$high_running && ($top_priority > self::PRIORITY_UNDEFINED) && ($top_priority < self::PRIORITY_NEGLIGIBLE)) {
Logger::info('Jobs with a higher priority are waiting but none is executed. Open a fastlane.', ['priority' => $top_priority]); DI::logger()->info('Jobs with a higher priority are waiting but none is executed. Open a fastlane.', ['priority' => $top_priority]);
$queues = $active + 1; $queues = $active + 1;
} }
} }
Logger::info('Load: ' . $load . '/' . $maxsysload . ' - processes: ' . $deferred . '/' . $active . '/' . $waiting_processes . $processlist . ' - maximum: ' . $queues . '/' . $maxqueues); DI::logger()->info('Load: ' . $load . '/' . $maxsysload . ' - processes: ' . $deferred . '/' . $active . '/' . $waiting_processes . $processlist . ' - maximum: ' . $queues . '/' . $maxqueues);
// Are there fewer workers running as possible? Then fork a new one. // Are there fewer workers running as possible? Then fork a new one.
if (!DI::config()->get('system', 'worker_dont_fork', false) && ($queues > ($active + 1)) && self::entriesExists() && !self::systemLimitReached()) { if (!DI::config()->get('system', 'worker_dont_fork', false) && ($queues > ($active + 1)) && self::entriesExists() && !self::systemLimitReached()) {
Logger::info('There are fewer workers as possible, fork a new worker.', ['active' => $active, 'queues' => $queues]); DI::logger()->info('There are fewer workers as possible, fork a new worker.', ['active' => $active, 'queues' => $queues]);
if (Worker\Daemon::isMode()) { if (Worker\Daemon::isMode()) {
Worker\IPC::SetJobState(true); Worker\IPC::SetJobState(true);
} else { } else {
@ -840,10 +840,10 @@ class Worker
&& !DBA::exists('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $max_idletime . ' second')]) && !DBA::exists('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $max_idletime . ' second')])
) { ) {
DI::cache()->set(self::LAST_CHECK, time(), Duration::HOUR); DI::cache()->set(self::LAST_CHECK, time(), Duration::HOUR);
Logger::info('The last worker execution had been too long ago.', ['last' => $last_check, 'last-check' => $last_date, 'seconds' => $max_idletime, 'load' => $load, 'max_load' => $maxsysload, 'active_worker' => $active, 'max_worker' => $maxqueues]); DI::logger()->info('The last worker execution had been too long ago.', ['last' => $last_check, 'last-check' => $last_date, 'seconds' => $max_idletime, 'load' => $load, 'max_load' => $maxsysload, 'active_worker' => $active, 'max_worker' => $maxqueues]);
return false; return false;
} elseif ($max_idletime > 0) { } elseif ($max_idletime > 0) {
Logger::debug('Maximum idletime not reached.', ['last' => $last_check, 'last-check' => $last_date, 'seconds' => $max_idletime, 'load' => $load, 'max_load' => $maxsysload, 'active_worker' => $active, 'max_worker' => $maxqueues]); DI::logger()->debug('Maximum idletime not reached.', ['last' => $last_check, 'last-check' => $last_date, 'seconds' => $max_idletime, 'load' => $load, 'max_load' => $maxsysload, 'active_worker' => $active, 'max_worker' => $maxqueues]);
} }
} }
} }
@ -924,7 +924,7 @@ class Worker
{ {
$priority = self::nextPriority(); $priority = self::nextPriority();
if (empty($priority)) { if (empty($priority)) {
Logger::info('No tasks found'); DI::logger()->info('No tasks found');
return []; return [];
} }
@ -948,7 +948,7 @@ class Worker
} }
DBA::close($tasks); DBA::close($tasks);
Logger::info('Found:', ['priority' => $priority, 'id' => $ids]); DI::logger()->info('Found:', ['priority' => $priority, 'id' => $ids]);
return $ids; return $ids;
} }
@ -987,7 +987,7 @@ class Worker
foreach ($priorities as $priority) { foreach ($priorities as $priority) {
if (!empty($waiting[$priority]) && empty($running[$priority])) { if (!empty($waiting[$priority]) && empty($running[$priority])) {
Logger::info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]); DI::logger()->info('No running worker found with priority {priority} - assigning it.', ['priority' => $priority]);
return $priority; return $priority;
} }
} }
@ -1009,14 +1009,14 @@ class Worker
$i = 0; $i = 0;
foreach ($running as $priority => $workers) { foreach ($running as $priority => $workers) {
if ($workers < $limit[$i++]) { if ($workers < $limit[$i++]) {
Logger::info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]); DI::logger()->info('Priority {priority} has got {workers} workers out of a limit of {limit}', ['priority' => $priority, 'workers' => $workers, 'limit' => $limit[$i - 1]]);
return $priority; return $priority;
} }
} }
if (!empty($waiting)) { if (!empty($waiting)) {
$priority = array_keys($waiting)[0]; $priority = array_keys($waiting)[0];
Logger::info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]); DI::logger()->info('No underassigned priority found, now taking the highest priority.', ['priority' => $priority]);
return $priority; return $priority;
} }
@ -1090,7 +1090,7 @@ class Worker
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
foreach ($worker as $worker_pid => $worker_ids) { foreach ($worker as $worker_pid => $worker_ids) {
Logger::info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]); DI::logger()->info('Set queue entry', ['pid' => $worker_pid, 'ids' => $worker_ids]);
DBA::update( DBA::update(
'workerqueue', 'workerqueue',
['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid], ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid],
@ -1155,7 +1155,7 @@ class Worker
private static function forkProcess(bool $do_cron) private static function forkProcess(bool $do_cron)
{ {
if (DI::system()->isMinMemoryReached()) { if (DI::system()->isMinMemoryReached()) {
Logger::warning('Memory limit reached - quitting'); DI::logger()->warning('Memory limit reached - quitting');
return; return;
} }
@ -1165,21 +1165,21 @@ class Worker
$pid = pcntl_fork(); $pid = pcntl_fork();
if ($pid == -1) { if ($pid == -1) {
DBA::connect(); DBA::connect();
Logger::warning('Could not spawn worker'); DI::logger()->warning('Could not spawn worker');
return; return;
} elseif ($pid) { } elseif ($pid) {
// The parent process continues here // The parent process continues here
DBA::connect(); DBA::connect();
Worker\IPC::SetJobState(true, $pid); Worker\IPC::SetJobState(true, $pid);
Logger::info('Spawned new worker', ['pid' => $pid]); DI::logger()->info('Spawned new worker', ['pid' => $pid]);
$cycles = 0; $cycles = 0;
while (Worker\IPC::JobsExists($pid) && (++$cycles < 100)) { while (Worker\IPC::JobsExists($pid) && (++$cycles < 100)) {
usleep(10000); usleep(10000);
} }
Logger::info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]); DI::logger()->info('Spawned worker is ready', ['pid' => $pid, 'wait_cycles' => $cycles]);
return; return;
} }
@ -1194,7 +1194,7 @@ class Worker
usleep(10000); usleep(10000);
} }
Logger::info('Worker spawned', ['pid' => $process->pid, 'wait_cycles' => $cycles]); DI::logger()->info('Worker spawned', ['pid' => $process->pid, 'wait_cycles' => $cycles]);
self::processQueue($do_cron, $process); self::processQueue($do_cron, $process);
@ -1202,7 +1202,7 @@ class Worker
Worker\IPC::SetJobState(false, $process->pid); Worker\IPC::SetJobState(false, $process->pid);
DI::process()->delete($process); DI::process()->delete($process);
Logger::info('Worker ended', ['pid' => $process->pid]); DI::logger()->info('Worker ended', ['pid' => $process->pid]);
exit(); exit();
} }
@ -1292,7 +1292,7 @@ class Worker
$added = 0; $added = 0;
if (!is_int($priority) || !in_array($priority, self::PRIORITIES)) { if (!is_int($priority) || !in_array($priority, self::PRIORITIES)) {
Logger::warning('Invalid priority', ['priority' => $priority, 'command' => $command]); DI::logger()->warning('Invalid priority', ['priority' => $priority, 'command' => $command]);
$priority = self::PRIORITY_MEDIUM; $priority = self::PRIORITY_MEDIUM;
} }
@ -1377,7 +1377,7 @@ class Worker
$new_retrial = $retrial; $new_retrial = $retrial;
} }
} }
Logger::notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]); DI::logger()->notice('New retrial for task', ['id' => $queue['id'], 'created' => $queue['created'], 'old' => $queue['retrial'], 'new' => $new_retrial]);
return $new_retrial; return $new_retrial;
} }
@ -1419,7 +1419,7 @@ class Worker
$new_retrial = self::getNextRetrial($queue, $max_level); $new_retrial = self::getNextRetrial($queue, $max_level);
if ($new_retrial > $max_level) { if ($new_retrial > $max_level) {
Logger::notice('The task exceeded the maximum retry count', ['id' => $id, 'created' => $queue['created'], 'old_prio' => $queue['priority'], 'old_retrial' => $queue['retrial'], 'max_level' => $max_level, 'retrial' => $new_retrial]); DI::logger()->notice('The task exceeded the maximum retry count', ['id' => $id, 'created' => $queue['created'], 'old_prio' => $queue['priority'], 'old_retrial' => $queue['retrial'], 'max_level' => $max_level, 'retrial' => $new_retrial]);
return false; return false;
} }
@ -1435,7 +1435,7 @@ class Worker
$priority = self::PRIORITY_NEGLIGIBLE; $priority = self::PRIORITY_NEGLIGIBLE;
} }
Logger::info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]); DI::logger()->info('Deferred task', ['id' => $id, 'retrial' => $new_retrial, 'created' => $queue['created'], 'next_execution' => $next, 'old_prio' => $queue['priority'], 'new_prio' => $priority]);
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
$fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority]; $fields = ['retrial' => $new_retrial, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0, 'priority' => $priority];
@ -1458,7 +1458,7 @@ class Worker
$start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400; $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;
$end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400; $end = strtotime(DI::config()->get('system', 'maintenance_end')) % 86400;
Logger::info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]); DI::logger()->info('Maintenance window', ['start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
if ($check_last_execution) { if ($check_last_execution) {
// Calculate the window duration // Calculate the window duration
@ -1467,7 +1467,7 @@ class Worker
// Quit when the last cron execution had been after the previous window // Quit when the last cron execution had been after the previous window
$last_cron = DI::keyValue()->get('last_cron_daily'); $last_cron = DI::keyValue()->get('last_cron_daily');
if ($last_cron + $duration > time()) { if ($last_cron + $duration > time()) {
Logger::info('The Daily cron had been executed recently', ['last' => date(DateTimeFormat::MYSQL, $last_cron), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]); DI::logger()->info('The Daily cron had been executed recently', ['last' => date(DateTimeFormat::MYSQL, $last_cron), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
return false; return false;
} }
} }
@ -1483,9 +1483,9 @@ class Worker
} }
if ($execute) { if ($execute) {
Logger::info('We are inside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]); DI::logger()->info('We are inside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
} else { } else {
Logger::info('We are outside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]); DI::logger()->info('We are outside the maintenance window', ['current' => date('H:i:s', $current), 'start' => date('H:i:s', $start), 'end' => date('H:i:s', $end)]);
} }
return $execute; return $execute;

View file

@ -7,7 +7,6 @@
namespace Friendica\Core\Worker; namespace Friendica\Core\Worker;
use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -32,7 +31,7 @@ class Cron
*/ */
public static function run() public static function run()
{ {
Logger::info('Add cron entries'); DI::logger()->info('Add cron entries');
// Check for spooled items // Check for spooled items
Worker::add(['priority' => Worker::PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost'); Worker::add(['priority' => Worker::PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost');
@ -99,7 +98,7 @@ class Cron
// How long is the process already running? // How long is the process already running?
$duration = (time() - strtotime($entry["executed"])) / 60; $duration = (time() - strtotime($entry["executed"])) / 60;
if ($duration > $max_duration) { if ($duration > $max_duration) {
Logger::warning('Worker process took too much time - killed', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]); DI::logger()->warning('Worker process took too much time - killed', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
posix_kill($entry["pid"], SIGTERM); posix_kill($entry["pid"], SIGTERM);
// We killed the stale process. // We killed the stale process.
@ -113,10 +112,13 @@ class Cron
} elseif ($entry['priority'] != Worker::PRIORITY_CRITICAL) { } elseif ($entry['priority'] != Worker::PRIORITY_CRITICAL) {
$new_priority = Worker::PRIORITY_NEGLIGIBLE; $new_priority = Worker::PRIORITY_NEGLIGIBLE;
} }
DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0], ['id' => $entry["id"]] DBA::update(
'workerqueue',
['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0],
['id' => $entry["id"]]
); );
} else { } else {
Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]); DI::logger()->info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
} }
} }
} }
@ -156,12 +158,12 @@ class Cron
$deliveries = DBA::p("SELECT `item-uri`.`uri` AS `inbox`, MAX(`gsid`) AS `gsid`, MAX(`shared`) AS `shared`, MAX(`failed`) AS `failed` FROM `post-delivery` INNER JOIN `item-uri` ON `item-uri`.`id` = `post-delivery`.`inbox-id` LEFT JOIN `inbox-status` ON `inbox-status`.`url` = `item-uri`.`uri` GROUP BY `inbox` ORDER BY RAND()"); $deliveries = DBA::p("SELECT `item-uri`.`uri` AS `inbox`, MAX(`gsid`) AS `gsid`, MAX(`shared`) AS `shared`, MAX(`failed`) AS `failed` FROM `post-delivery` INNER JOIN `item-uri` ON `item-uri`.`id` = `post-delivery`.`inbox-id` LEFT JOIN `inbox-status` ON `inbox-status`.`url` = `item-uri`.`uri` GROUP BY `inbox` ORDER BY RAND()");
while ($delivery = DBA::fetch($deliveries)) { while ($delivery = DBA::fetch($deliveries)) {
if ($delivery['failed'] > 0) { if ($delivery['failed'] > 0) {
Logger::info('Removing failed deliveries', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed']]); DI::logger()->info('Removing failed deliveries', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed']]);
Post\Delivery::removeFailed($delivery['inbox']); Post\Delivery::removeFailed($delivery['inbox']);
} }
if (($delivery['failed'] == 0) && $delivery['shared'] && !empty($delivery['gsid']) && GServer::isReachableById($delivery['gsid'])) { if (($delivery['failed'] == 0) && $delivery['shared'] && !empty($delivery['gsid']) && GServer::isReachableById($delivery['gsid'])) {
$result = ActivityPub\Delivery::deliver($delivery['inbox']); $result = ActivityPub\Delivery::deliver($delivery['inbox']);
Logger::info('Directly deliver inbox', ['inbox' => $delivery['inbox'], 'result' => $result['success']]); DI::logger()->info('Directly deliver inbox', ['inbox' => $delivery['inbox'], 'result' => $result['success']]);
continue; continue;
} elseif ($delivery['failed'] < 3) { } elseif ($delivery['failed'] < 3) {
$priority = Worker::PRIORITY_HIGH; $priority = Worker::PRIORITY_HIGH;
@ -174,7 +176,7 @@ class Cron
} }
if (Worker::add(['priority' => $priority, 'force_priority' => true], 'APDelivery', '', 0, $delivery['inbox'], 0)) { if (Worker::add(['priority' => $priority, 'force_priority' => true], 'APDelivery', '', 0, $delivery['inbox'], 0)) {
Logger::info('Priority for APDelivery worker adjusted', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed'], 'priority' => $priority]); DI::logger()->info('Priority for APDelivery worker adjusted', ['inbox' => $delivery['inbox'], 'failed' => $delivery['failed'], 'priority' => $priority]);
} }
} }
@ -182,9 +184,9 @@ class Cron
// Optimizing this table only last seconds // Optimizing this table only last seconds
if (DI::config()->get('system', 'optimize_tables')) { if (DI::config()->get('system', 'optimize_tables')) {
Logger::info('Optimize start'); DI::logger()->info('Optimize start');
DBA::optimizeTable('post-delivery'); DBA::optimizeTable('post-delivery');
Logger::info('Optimize end'); DI::logger()->info('Optimize end');
} }
} }
@ -195,7 +197,7 @@ class Cron
{ {
foreach(DI::deliveryQueueItemRepo()->selectAggregateByServerId() as $delivery) { foreach(DI::deliveryQueueItemRepo()->selectAggregateByServerId() as $delivery) {
if ($delivery->failed > 0) { if ($delivery->failed > 0) {
Logger::info('Removing failed deliveries', ['gsid' => $delivery->targetServerId, 'failed' => $delivery->failed]); DI::logger()->info('Removing failed deliveries', ['gsid' => $delivery->targetServerId, 'failed' => $delivery->failed]);
DI::deliveryQueueItemRepo()->removeFailedByServerId($delivery->targetServerId, DI::config()->get('system', 'worker_defer_limit')); DI::deliveryQueueItemRepo()->removeFailedByServerId($delivery->targetServerId, DI::config()->get('system', 'worker_defer_limit'));
} }
@ -210,15 +212,15 @@ class Cron
} }
if (Worker::add(['priority' => $priority, 'force_priority' => true], 'BulkDelivery', $delivery->targetServerId)) { if (Worker::add(['priority' => $priority, 'force_priority' => true], 'BulkDelivery', $delivery->targetServerId)) {
Logger::info('Priority for BulkDelivery worker adjusted', ['gsid' => $delivery->targetServerId, 'failed' => $delivery->failed, 'priority' => $priority]); DI::logger()->info('Priority for BulkDelivery worker adjusted', ['gsid' => $delivery->targetServerId, 'failed' => $delivery->failed, 'priority' => $priority]);
} }
} }
// Optimizing this table only last seconds // Optimizing this table only last seconds
if (DI::config()->get('system', 'optimize_tables')) { if (DI::config()->get('system', 'optimize_tables')) {
Logger::info('Optimize start'); DI::logger()->info('Optimize start');
DI::deliveryQueueItemRepo()->optimizeStorage(); DI::deliveryQueueItemRepo()->optimizeStorage();
Logger::info('Optimize end'); DI::logger()->info('Optimize end');
} }
} }
@ -237,7 +239,7 @@ class Cron
'datetime' => $contact['created'], 'datetime' => $contact['created'],
'hash' => Strings::getRandomHex() 'hash' => Strings::getRandomHex()
]; ];
Logger::notice('Adding missing intro', ['fields' => $fields]); DI::logger()->notice('Adding missing intro', ['fields' => $fields]);
DBA::insert('intro', $fields); DBA::insert('intro', $fields);
} }
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Core\Worker; namespace Friendica\Core\Worker;
use Friendica\App\Mode; use Friendica\App\Mode;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
/** /**
@ -98,11 +97,11 @@ class Daemon
$pid = intval(file_get_contents($pidfile)); $pid = intval(file_get_contents($pidfile));
if (posix_kill($pid, 0)) { if (posix_kill($pid, 0)) {
Logger::info('Daemon process is running', ['pid' => $pid]); DI::logger()->info('Daemon process is running', ['pid' => $pid]);
return; return;
} }
Logger::warning('Daemon process is not running', ['pid' => $pid]); DI::logger()->warning('Daemon process is not running', ['pid' => $pid]);
self::spawn(); self::spawn();
} }
@ -114,8 +113,8 @@ class Daemon
*/ */
private static function spawn() private static function spawn()
{ {
Logger::notice('Starting new daemon process'); DI::logger()->notice('Starting new daemon process');
DI::system()->run('bin/console.php', ['start']); DI::system()->run('bin/console.php', ['start']);
Logger::notice('New daemon process started'); DI::logger()->notice('New daemon process started');
} }
} }

View file

@ -60,7 +60,8 @@ abstract class DI
/** /**
* Returns a clone of the current dice instance * Returns a clone of the current dice instance
* This useful for overloading the current instance with mocked methods during tests *
* @internal This useful for overloading the current instance with mocked methods during tests
* *
* @return Dice * @return Dice
*/ */

View file

@ -8,7 +8,6 @@
namespace Friendica\Database; namespace Friendica\Database;
use Exception; use Exception;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Item; use Friendica\Model\Item;
use Friendica\Model\User; use Friendica\Model\User;
@ -74,8 +73,11 @@ class DBStructure
'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge', 'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge',
'auth_codes', 'tokens', 'clients', 'profile_check', 'host', 'conversation', 'fcontact', 'addon', 'push_subscriber']; 'auth_codes', 'tokens', 'clients', 'profile_check', 'host', 'conversation', 'fcontact', 'addon', 'push_subscriber'];
$tables = DBA::selectToArray('INFORMATION_SCHEMA.TABLES', ['TABLE_NAME'], $tables = DBA::selectToArray(
['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']); 'INFORMATION_SCHEMA.TABLES',
['TABLE_NAME'],
['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']
);
if (empty($tables)) { if (empty($tables)) {
echo DI::l10n()->t('No unused tables found.'); echo DI::l10n()->t('No unused tables found.');
@ -144,8 +146,11 @@ class DBStructure
*/ */
private static function printUpdateError(string $message): string private static function printUpdateError(string $message): string
{ {
echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n", echo DI::l10n()->t(
DBA::errorNo(), DBA::errorMessage()); "\nError %d occurred during database update:\n%s\n",
DBA::errorNo(),
DBA::errorMessage()
);
return DI::l10n()->t('Errors encountered performing database changes: ') . $message . '<br />'; return DI::l10n()->t('Errors encountered performing database changes: ') . $message . '<br />';
} }
@ -238,7 +243,7 @@ class DBStructure
$errors = ''; $errors = '';
Logger::info('updating structure'); DI::logger()->info('updating structure');
// Get the current structure // Get the current structure
$database = []; $database = [];
@ -251,7 +256,7 @@ class DBStructure
foreach ($tables as $table) { foreach ($tables as $table) {
$table = current($table); $table = current($table);
Logger::info('updating structure', ['table' => $table]); DI::logger()->info('updating structure', ['table' => $table]);
$database[$table] = self::tableStructure($table); $database[$table] = self::tableStructure($table);
} }
} }
@ -523,21 +528,27 @@ class DBStructure
// This query doesn't seem to be executable as a prepared statement // This query doesn't seem to be executable as a prepared statement
$indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table))); $indexes = DBA::toArray(DBA::p("SHOW INDEX FROM " . DBA::quoteIdentifier($table)));
$fields = DBA::selectToArray('INFORMATION_SCHEMA.COLUMNS', $fields = DBA::selectToArray(
'INFORMATION_SCHEMA.COLUMNS',
['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA', ['COLUMN_NAME', 'COLUMN_TYPE', 'IS_NULLABLE', 'COLUMN_DEFAULT', 'EXTRA',
'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'], 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'],
["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?", ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
DBA::databaseName(), $table]); DBA::databaseName(), $table]
);
$foreign_keys = DBA::selectToArray('INFORMATION_SCHEMA.KEY_COLUMN_USAGE', $foreign_keys = DBA::selectToArray(
'INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'], ['COLUMN_NAME', 'CONSTRAINT_NAME', 'REFERENCED_TABLE_NAME', 'REFERENCED_COLUMN_NAME'],
["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL", ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
DBA::databaseName(), $table]); DBA::databaseName(), $table]
);
$table_status = DBA::selectFirst('INFORMATION_SCHEMA.TABLES', $table_status = DBA::selectFirst(
'INFORMATION_SCHEMA.TABLES',
['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'], ['ENGINE', 'TABLE_COLLATION', 'TABLE_COMMENT'],
["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?", ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?",
DBA::databaseName(), $table]); DBA::databaseName(), $table]
);
$fielddata = []; $fielddata = [];
$indexdata = []; $indexdata = [];
@ -732,9 +743,11 @@ class DBStructure
*/ */
public static function existsForeignKeyForField(string $table, string $field): bool public static function existsForeignKeyForField(string $table, string $field): bool
{ {
return DBA::exists('INFORMATION_SCHEMA.KEY_COLUMN_USAGE', return DBA::exists(
'INFORMATION_SCHEMA.KEY_COLUMN_USAGE',
["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL", ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ? AND `COLUMN_NAME` = ? AND `REFERENCED_TABLE_SCHEMA` IS NOT NULL",
DBA::databaseName(), $table, $field]); DBA::databaseName(), $table, $field]
);
} }
/** /**

View file

@ -7,7 +7,6 @@
namespace Friendica\Database; namespace Friendica\Database;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -141,22 +140,22 @@ class PostUpdate
$max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]); $max_item_delivery_data = DBA::selectFirst('item-delivery-data', ['iid'], ['queue_count > 0 OR queue_done > 0'], ['order' => ['iid']]);
$max_iid = $max_item_delivery_data['iid'] ?? 0; $max_iid = $max_item_delivery_data['iid'] ?? 0;
Logger::info('Start update1297 with max iid: ' . $max_iid); DI::logger()->info('Start update1297 with max iid: ' . $max_iid);
$condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid]; $condition = ['`queue_count` = 0 AND `iid` < ?', $max_iid];
DBA::update('item-delivery-data', ['queue_count' => -1], $condition); DBA::update('item-delivery-data', ['queue_count' => -1], $condition);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage()); DI::logger()->error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
return false; return false;
} }
Logger::info('Processed rows: ' . DBA::affectedRows()); DI::logger()->info('Processed rows: ' . DBA::affectedRows());
DI::keyValue()->set('post_update_version', 1297); DI::keyValue()->set('post_update_version', 1297);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -173,24 +172,31 @@ class PostUpdate
return true; return true;
} }
Logger::info('Start'); DI::logger()->info('Start');
$contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact` $contacts = DBA::p(
"SELECT `nurl`, `uid` FROM `contact`
WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2` WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`) WHERE `c2`.`nurl` = `contact`.`nurl` AND `c2`.`id` != `contact`.`id` AND `c2`.`uid` = `contact`.`uid` AND `c2`.`network` IN (?, ?, ?) AND NOT `deleted`)
AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`", AND (`network` IN (?, ?, ?) OR (`uid` = ?)) AND NOT `deleted` GROUP BY `nurl`, `uid`",
Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, Protocol::DIASPORA,
Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0); Protocol::OSTATUS,
Protocol::ACTIVITYPUB,
Protocol::DIASPORA,
Protocol::OSTATUS,
Protocol::ACTIVITYPUB,
0
);
while ($contact = DBA::fetch($contacts)) { while ($contact = DBA::fetch($contacts)) {
Logger::info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]); DI::logger()->info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]);
Contact::removeDuplicates($contact['nurl'], $contact['uid']); Contact::removeDuplicates($contact['nurl'], $contact['uid']);
} }
DBA::close($contact); DBA::close($contact);
DI::keyValue()->set('post_update_version', 1322); DI::keyValue()->set('post_update_version', 1322);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -215,7 +221,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1329_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1329_id') ?? 0;
Logger::info('Start', ['item' => $id]); DI::logger()->info('Start', ['item' => $id]);
$start_id = $id; $start_id = $id;
$rows = 0; $rows = 0;
@ -224,7 +230,7 @@ class PostUpdate
$items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params); $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -239,11 +245,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1329_id', $id); DI::keyValue()->set('post_update_version_1329_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($start_id == $id) { if ($start_id == $id) {
DI::keyValue()->set('post_update_version', 1329); DI::keyValue()->set('post_update_version', 1329);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -270,7 +276,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1341_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1341_id') ?? 0;
Logger::info('Start', ['item' => $id]); DI::logger()->info('Start', ['item' => $id]);
$rows = 0; $rows = 0;
@ -279,7 +285,7 @@ class PostUpdate
ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id); ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -295,13 +301,13 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1341_id', $id); DI::keyValue()->set('post_update_version_1341_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
// When there are less than 1,000 items processed this means that we reached the end // When there are less than 1,000 items processed this means that we reached the end
// The other entries will then be processed with the regular functionality // The other entries will then be processed with the regular functionality
if ($rows < 1000) { if ($rows < 1000) {
DI::keyValue()->set('post_update_version', 1341); DI::keyValue()->set('post_update_version', 1341);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -328,19 +334,25 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1342_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1342_id') ?? 0;
Logger::info('Start', ['item' => $id]); DI::logger()->info('Start', ['item' => $id]);
$rows = 0; $rows = 0;
$terms = DBA::p("SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body` $terms = DBA::p(
"SELECT `term`.`tid`, `item`.`uri-id`, `term`.`type`, `term`.`term`, `term`.`url`, `item-content`.`body`
FROM `term` FROM `term`
INNER JOIN `item` ON `item`.`id` = `term`.`oid` INNER JOIN `item` ON `item`.`id` = `term`.`oid`
INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id` INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id`
WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000", WHERE term.type IN (?, ?, ?, ?) AND `tid` >= ? ORDER BY `tid` LIMIT 100000",
Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id); Tag::HASHTAG,
Tag::MENTION,
Tag::EXCLUSIVE_MENTION,
Tag::IMPLICIT_MENTION,
$id
);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -371,13 +383,13 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1342_id', $id); DI::keyValue()->set('post_update_version_1342_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
// When there are less than 1,000 items processed this means that we reached the end // When there are less than 1,000 items processed this means that we reached the end
// The other entries will then be processed with the regular functionality // The other entries will then be processed with the regular functionality
if ($rows < 1000) { if ($rows < 1000) {
DI::keyValue()->set('post_update_version', 1342); DI::keyValue()->set('post_update_version', 1342);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -404,7 +416,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1345_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1345_id') ?? 0;
Logger::info('Start', ['item' => $id]); DI::logger()->info('Start', ['item' => $id]);
$rows = 0; $rows = 0;
@ -415,7 +427,7 @@ class PostUpdate
WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id); WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -429,13 +441,13 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1345_id', $id); DI::keyValue()->set('post_update_version_1345_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
// When there are less than 100 items processed this means that we reached the end // When there are less than 100 items processed this means that we reached the end
// The other entries will then be processed with the regular functionality // The other entries will then be processed with the regular functionality
if ($rows < 100) { if ($rows < 100) {
DI::keyValue()->set('post_update_version', 1345); DI::keyValue()->set('post_update_version', 1345);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -487,16 +499,19 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1346_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1346_id') ?? 0;
Logger::info('Start', ['item' => $id]); DI::logger()->info('Start', ['item' => $id]);
$rows = 0; $rows = 0;
$terms = DBA::select('term', ['oid'], $terms = DBA::select(
'term',
['oid'],
["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id], ["`type` IN (?, ?) AND `oid` >= ?", Category::CATEGORY, Category::FILE, $id],
['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]); ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]
);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -521,13 +536,13 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1346_id', $id); DI::keyValue()->set('post_update_version_1346_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
// When there are less than 10 items processed this means that we reached the end // When there are less than 10 items processed this means that we reached the end
// The other entries will then be processed with the regular functionality // The other entries will then be processed with the regular functionality
if ($rows < 10) { if ($rows < 10) {
DI::keyValue()->set('post_update_version', 1346); DI::keyValue()->set('post_update_version', 1346);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -555,7 +570,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1347_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1347_id') ?? 0;
Logger::info('Start', ['item' => $id]); DI::logger()->info('Start', ['item' => $id]);
$start_id = $id; $start_id = $id;
$rows = 0; $rows = 0;
@ -566,7 +581,7 @@ class PostUpdate
WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", Item::GRAVITY_ACTIVITY, $id); WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", Item::GRAVITY_ACTIVITY, $id);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -590,11 +605,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1347_id', $id); DI::keyValue()->set('post_update_version_1347_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($start_id == $id) { if ($start_id == $id) {
DI::keyValue()->set('post_update_version', 1347); DI::keyValue()->set('post_update_version', 1347);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -617,7 +632,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1348_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1348_id') ?? 0;
Logger::info('Start', ['contact' => $id]); DI::logger()->info('Start', ['contact' => $id]);
$start_id = $id; $start_id = $id;
$rows = 0; $rows = 0;
@ -626,16 +641,18 @@ class PostUpdate
$contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params); $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
while ($contact = DBA::fetch($contacts)) { while ($contact = DBA::fetch($contacts)) {
$id = $contact['id']; $id = $contact['id'];
DBA::update('contact', DBA::update(
'contact',
['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])], ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])],
['id' => $contact['id']]); ['id' => $contact['id']]
);
++$rows; ++$rows;
} }
@ -643,11 +660,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1348_id', $id); DI::keyValue()->set('post_update_version_1348_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($start_id == $id) { if ($start_id == $id) {
DI::keyValue()->set('post_update_version', 1348); DI::keyValue()->set('post_update_version', 1348);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -670,7 +687,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1349_id') ?? ''; $id = DI::keyValue()->get('post_update_version_1349_id') ?? '';
Logger::info('Start', ['apcontact' => $id]); DI::logger()->info('Start', ['apcontact' => $id]);
$start_id = $id; $start_id = $id;
$rows = 0; $rows = 0;
@ -679,16 +696,18 @@ class PostUpdate
$apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params); $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
while ($apcontact = DBA::fetch($apcontacts)) { while ($apcontact = DBA::fetch($apcontacts)) {
$id = $apcontact['url']; $id = $apcontact['url'];
DBA::update('apcontact', DBA::update(
'apcontact',
['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])], ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])],
['url' => $apcontact['url']]); ['url' => $apcontact['url']]
);
++$rows; ++$rows;
} }
@ -696,11 +715,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1349_id', $id); DI::keyValue()->set('post_update_version_1349_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($start_id == $id) { if ($start_id == $id) {
DI::keyValue()->set('post_update_version', 1349); DI::keyValue()->set('post_update_version', 1349);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -721,7 +740,7 @@ class PostUpdate
return true; return true;
} }
Logger::info('Start'); DI::logger()->info('Start');
$deleted = 0; $deleted = 0;
$avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro']; $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro'];
@ -744,7 +763,7 @@ class PostUpdate
DBA::close($photos); DBA::close($photos);
DI::keyValue()->set('post_update_version', 1383); DI::keyValue()->set('post_update_version', 1383);
Logger::info('Done', ['deleted' => $deleted]); DI::logger()->info('Done', ['deleted' => $deleted]);
return true; return true;
} }
@ -763,13 +782,13 @@ class PostUpdate
} }
$condition = ["`hash` IS NULL"]; $condition = ["`hash` IS NULL"];
Logger::info('Start', ['rest' => DBA::count('photo', $condition)]); DI::logger()->info('Start', ['rest' => DBA::count('photo', $condition)]);
$rows = 0; $rows = 0;
$photos = DBA::select('photo', [], $condition, ['limit' => 100]); $photos = DBA::select('photo', [], $condition, ['limit' => 100]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -782,11 +801,11 @@ class PostUpdate
} }
DBA::close($photos); DBA::close($photos);
Logger::info('Processed', ['rows' => $rows]); DI::logger()->info('Processed', ['rows' => $rows]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1384); DI::keyValue()->set('post_update_version', 1384);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -813,13 +832,13 @@ class PostUpdate
} }
$condition = ["`extid` != ? AND EXISTS(SELECT `id` FROM `post-user` WHERE `uri-id` = `item`.`uri-id` AND `uid` = `item`.`uid` AND `external-id` IS NULL)", '']; $condition = ["`extid` != ? AND EXISTS(SELECT `id` FROM `post-user` WHERE `uri-id` = `item`.`uri-id` AND `uid` = `item`.`uid` AND `external-id` IS NULL)", ''];
Logger::info('Start', ['rest' => DBA::count('item', $condition)]); DI::logger()->info('Start', ['rest' => DBA::count('item', $condition)]);
$rows = 0; $rows = 0;
$items = DBA::select('item', ['uri-id', 'uid', 'extid'], $condition, ['order' => ['id'], 'limit' => 10000]); $items = DBA::select('item', ['uri-id', 'uid', 'extid'], $condition, ['order' => ['id'], 'limit' => 10000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -829,11 +848,11 @@ class PostUpdate
} }
DBA::close($items); DBA::close($items);
Logger::info('Processed', ['rows' => $rows]); DI::logger()->info('Processed', ['rows' => $rows]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1400); DI::keyValue()->set('post_update_version', 1400);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -855,13 +874,13 @@ class PostUpdate
} }
$condition = ["`uri-id` IS NULL"]; $condition = ["`uri-id` IS NULL"];
Logger::info('Start', ['rest' => DBA::count('contact', $condition)]); DI::logger()->info('Start', ['rest' => DBA::count('contact', $condition)]);
$rows = 0; $rows = 0;
$contacts = DBA::select('contact', ['id', 'url'], $condition, ['limit' => 1000]); $contacts = DBA::select('contact', ['id', 'url'], $condition, ['limit' => 1000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -871,11 +890,11 @@ class PostUpdate
} }
DBA::close($contacts); DBA::close($contacts);
Logger::info('Processed', ['rows' => $rows]); DI::logger()->info('Processed', ['rows' => $rows]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1424); DI::keyValue()->set('post_update_version', 1424);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -902,13 +921,13 @@ class PostUpdate
} }
$condition = ["`uri-id` IS NULL"]; $condition = ["`uri-id` IS NULL"];
Logger::info('Start', ['rest' => DBA::count('fcontact', $condition)]); DI::logger()->info('Start', ['rest' => DBA::count('fcontact', $condition)]);
$rows = 0; $rows = 0;
$fcontacts = DBA::select('fcontact', ['id', 'url', 'guid'], $condition, ['limit' => 1000]); $fcontacts = DBA::select('fcontact', ['id', 'url', 'guid'], $condition, ['limit' => 1000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -923,11 +942,11 @@ class PostUpdate
} }
DBA::close($fcontacts); DBA::close($fcontacts);
Logger::info('Processed', ['rows' => $rows]); DI::logger()->info('Processed', ['rows' => $rows]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1425); DI::keyValue()->set('post_update_version', 1425);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -949,13 +968,13 @@ class PostUpdate
} }
$condition = ["`uri-id` IS NULL"]; $condition = ["`uri-id` IS NULL"];
Logger::info('Start', ['rest' => DBA::count('apcontact', $condition)]); DI::logger()->info('Start', ['rest' => DBA::count('apcontact', $condition)]);
$rows = 0; $rows = 0;
$apcontacts = DBA::select('apcontact', ['url', 'uuid'], $condition, ['limit' => 1000]); $apcontacts = DBA::select('apcontact', ['url', 'uuid'], $condition, ['limit' => 1000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -970,11 +989,11 @@ class PostUpdate
} }
DBA::close($apcontacts); DBA::close($apcontacts);
Logger::info('Processed', ['rows' => $rows]); DI::logger()->info('Processed', ['rows' => $rows]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1426); DI::keyValue()->set('post_update_version', 1426);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -996,13 +1015,13 @@ class PostUpdate
} }
$condition = ["`uri-id` IS NULL"]; $condition = ["`uri-id` IS NULL"];
Logger::info('Start', ['rest' => DBA::count('event', $condition)]); DI::logger()->info('Start', ['rest' => DBA::count('event', $condition)]);
$rows = 0; $rows = 0;
$events = DBA::select('event', ['id', 'uri', 'guid'], $condition, ['limit' => 1000]); $events = DBA::select('event', ['id', 'uri', 'guid'], $condition, ['limit' => 1000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -1017,11 +1036,11 @@ class PostUpdate
} }
DBA::close($events); DBA::close($events);
Logger::info('Processed', ['rows' => $rows]); DI::logger()->info('Processed', ['rows' => $rows]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1427); DI::keyValue()->set('post_update_version', 1427);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -1049,18 +1068,22 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1452_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1452_id') ?? 0;
Logger::info('Start', ['uri-id' => $id]); DI::logger()->info('Start', ['uri-id' => $id]);
$rows = 0; $rows = 0;
$received = ''; $received = '';
$conversations = DBA::p("SELECT `post-view`.`uri-id`, `conversation`.`source`, `conversation`.`received` FROM `conversation` $conversations = DBA::p(
"SELECT `post-view`.`uri-id`, `conversation`.`source`, `conversation`.`received` FROM `conversation`
INNER JOIN `post-view` ON `post-view`.`uri` = `conversation`.`item-uri` INNER JOIN `post-view` ON `post-view`.`uri` = `conversation`.`item-uri`
WHERE NOT `source` IS NULL AND `conversation`.`protocol` = ? AND `uri-id` > ? LIMIT ?", WHERE NOT `source` IS NULL AND `conversation`.`protocol` = ? AND `uri-id` > ? LIMIT ?",
Conversation::PARCEL_ACTIVITYPUB, $id, 1000); Conversation::PARCEL_ACTIVITYPUB,
$id,
1000
);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -1088,11 +1111,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1452_id', $id); DI::keyValue()->set('post_update_version_1452_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id, 'last-received' => $received]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id, 'last-received' => $received]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1452); DI::keyValue()->set('post_update_version', 1452);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -1114,7 +1137,7 @@ class PostUpdate
return true; return true;
} }
Logger::info('Start'); DI::logger()->info('Start');
$posts = DBA::select('post-view', ['uri-id'], ['conversation' => './']); $posts = DBA::select('post-view', ['uri-id'], ['conversation' => './']);
while ($post = DBA::fetch($posts)) { while ($post = DBA::fetch($posts)) {
@ -1127,7 +1150,7 @@ class PostUpdate
DBA::close($posts); DBA::close($posts);
DI::keyValue()->set('post_update_version', 1483); DI::keyValue()->set('post_update_version', 1483);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -1147,14 +1170,14 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1484_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1484_id') ?? 0;
Logger::info('Start', ['id' => $id]); DI::logger()->info('Start', ['id' => $id]);
$rows = 0; $rows = 0;
$contacts = DBA::select('contact', ['id', 'uid', 'uri-id', 'url'], ["`id` > ?", $id], ['order' => ['id'], 'limit' => 1000]); $contacts = DBA::select('contact', ['id', 'uid', 'uri-id', 'url'], ["`id` > ?", $id], ['order' => ['id'], 'limit' => 1000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -1171,11 +1194,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1484_id', $id); DI::keyValue()->set('post_update_version_1484_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1484); DI::keyValue()->set('post_update_version', 1484);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -1198,7 +1221,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1506_id') ?? 0; $id = DI::keyValue()->get('post_update_version_1506_id') ?? 0;
Logger::info('Start', ['contact' => $id]); DI::logger()->info('Start', ['contact' => $id]);
$start_id = $id; $start_id = $id;
$rows = 0; $rows = 0;
@ -1207,7 +1230,7 @@ class PostUpdate
$contacts = DBA::select('contact', ['id', 'url'], $condition, $params); $contacts = DBA::select('contact', ['id', 'url'], $condition, $params);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -1218,9 +1241,11 @@ class PostUpdate
unset($parts['path']); unset($parts['path']);
$server = (string)Uri::fromParts($parts); $server = (string)Uri::fromParts($parts);
DBA::update('contact', DBA::update(
'contact',
['gsid' => GServer::getID($server, true), 'baseurl' => GServer::cleanURL($server)], ['gsid' => GServer::getID($server, true), 'baseurl' => GServer::cleanURL($server)],
['id' => $contact['id']]); ['id' => $contact['id']]
);
++$rows; ++$rows;
} }
@ -1228,11 +1253,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1506_id', $id); DI::keyValue()->set('post_update_version_1506_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($start_id == $id) { if ($start_id == $id) {
DI::keyValue()->set('post_update_version', 1506); DI::keyValue()->set('post_update_version', 1506);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -1255,7 +1280,7 @@ class PostUpdate
$id = DI::keyValue()->get('post_update_version_1507_id') ?? ''; $id = DI::keyValue()->get('post_update_version_1507_id') ?? '';
Logger::info('Start', ['apcontact' => $id]); DI::logger()->info('Start', ['apcontact' => $id]);
$start_id = $id; $start_id = $id;
$rows = 0; $rows = 0;
@ -1264,7 +1289,7 @@ class PostUpdate
$apcontacts = DBA::select('apcontact', ['url', 'gsid', 'sharedinbox', 'inbox'], $condition, $params); $apcontacts = DBA::select('apcontact', ['url', 'gsid', 'sharedinbox', 'inbox'], $condition, $params);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -1283,11 +1308,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1507_id', $id); DI::keyValue()->set('post_update_version_1507_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($start_id == $id) { if ($start_id == $id) {
DI::keyValue()->set('post_update_version', 1507); DI::keyValue()->set('post_update_version', 1507);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -1314,14 +1339,14 @@ class PostUpdate
$id = (int)($post['uri-id'] ?? 0); $id = (int)($post['uri-id'] ?? 0);
} }
Logger::info('Start', ['uri-id' => $id]); DI::logger()->info('Start', ['uri-id' => $id]);
$rows = 0; $rows = 0;
$posts = Post::selectPosts(['uri-id', 'parent-uri-id'], ["`uri-id` < ? AND `gravity` IN (?, ?)", $id, Item::GRAVITY_COMMENT, Item::GRAVITY_PARENT], ['order' => ['uri-id' => true], 'limit' => 1000]); $posts = Post::selectPosts(['uri-id', 'parent-uri-id'], ["`uri-id` < ? AND `gravity` IN (?, ?)", $id, Item::GRAVITY_COMMENT, Item::GRAVITY_PARENT], ['order' => ['uri-id' => true], 'limit' => 1000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -1334,11 +1359,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1544_id', $id); DI::keyValue()->set('post_update_version_1544_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1544); DI::keyValue()->set('post_update_version', 1544);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }
@ -1368,7 +1393,7 @@ class PostUpdate
try { try {
Post\Engagement::storeFromItem($item); Post\Engagement::storeFromItem($item);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Exception on storing engagement', ['uri-id' => $engagement['uri-id'], 'code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Exception on storing engagement', ['uri-id' => $engagement['uri-id'], 'code' => $th->getCode(), 'message' => $th->getMessage()]);
} }
} }
DBA::close($engagements); DBA::close($engagements);
@ -1379,7 +1404,7 @@ class PostUpdate
$id = (int)($post['uri-id'] ?? 0); $id = (int)($post['uri-id'] ?? 0);
} }
Logger::info('Start', ['uri-id' => $id]); DI::logger()->info('Start', ['uri-id' => $id]);
$rows = 0; $rows = 0;
@ -1393,7 +1418,7 @@ class PostUpdate
$posts = Post::selectPosts(['uri-id', 'created'], $condition, ['order' => ['uri-id' => true], 'limit' => 1000]); $posts = Post::selectPosts(['uri-id', 'created'], $condition, ['order' => ['uri-id' => true], 'limit' => 1000]);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false; return false;
} }
@ -1406,11 +1431,11 @@ class PostUpdate
DI::keyValue()->set('post_update_version_1550_id', $id); DI::keyValue()->set('post_update_version_1550_id', $id);
Logger::info('Processed', ['rows' => $rows, 'last' => $id]); DI::logger()->info('Processed', ['rows' => $rows, 'last' => $id]);
if ($rows <= 100) { if ($rows <= 100) {
DI::keyValue()->set('post_update_version', 1550); DI::keyValue()->set('post_update_version', 1550);
Logger::info('Done'); DI::logger()->info('Done');
return true; return true;
} }

View file

@ -12,7 +12,6 @@ use Friendica\Content\ContactSelector;
use Friendica\Content\Item as ContentItem; use Friendica\Content\Item as ContentItem;
use Friendica\Content\Smilies; use Friendica\Content\Smilies;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -309,7 +308,7 @@ class Status extends BaseFactory
try { try {
$reshare = $this->createFromUriId($uriId, $uid, $display_quote, false, false)->toArray(); $reshare = $this->createFromUriId($uriId, $uid, $display_quote, false, false)->toArray();
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Reshare not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]); DI::logger()->info('Reshare not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
$reshare = []; $reshare = [];
} }
} else { } else {
@ -320,7 +319,7 @@ class Status extends BaseFactory
try { try {
$in_reply = $this->createFromUriId($item['thr-parent-id'], $uid, $display_quote, false, false)->toArray(); $in_reply = $this->createFromUriId($item['thr-parent-id'], $uid, $display_quote, false, false)->toArray();
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Reply post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]); DI::logger()->info('Reply post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
$in_reply = []; $in_reply = [];
} }
} else { } else {
@ -361,7 +360,7 @@ class Status extends BaseFactory
try { try {
$quote = $this->createFromUriId($quote_id, $uid, false, false, false)->toArray(); $quote = $this->createFromUriId($quote_id, $uid, false, false, false)->toArray();
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Quote not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]); DI::logger()->info('Quote not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
$quote = []; $quote = [];
} }
} else { } else {

View file

@ -9,12 +9,10 @@ namespace Friendica\Model;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Item;
use Friendica\Network\HTTPException; use Friendica\Network\HTTPException;
use Friendica\Network\Probe; use Friendica\Network\Probe;
use Friendica\Protocol\ActivityNamespace; use Friendica\Protocol\ActivityNamespace;
@ -95,12 +93,12 @@ class APContact
public static function getByURL(string $url, bool $update = null): array public static function getByURL(string $url, bool $update = null): array
{ {
if (empty($url) || Network::isUrlBlocked($url)) { if (empty($url) || Network::isUrlBlocked($url)) {
Logger::info('Domain is blocked', ['url' => $url]); DI::logger()->info('Domain is blocked', ['url' => $url]);
return []; return [];
} }
if (!Network::isValidHttpUrl($url) && !filter_var($url, FILTER_VALIDATE_EMAIL)) { if (!Network::isValidHttpUrl($url) && !filter_var($url, FILTER_VALIDATE_EMAIL)) {
Logger::info('Invalid URL', ['url' => $url]); DI::logger()->info('Invalid URL', ['url' => $url]);
return []; return [];
} }
@ -156,7 +154,7 @@ class APContact
$cachekey = 'apcontact:' . ItemURI::getIdByURI($url); $cachekey = 'apcontact:' . ItemURI::getIdByURI($url);
$result = DI::cache()->get($cachekey); $result = DI::cache()->get($cachekey);
if (!is_null($result)) { if (!is_null($result)) {
Logger::info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'result' => $result]); DI::logger()->info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'result' => $result]);
if (!empty($fetched_contact)) { if (!empty($fetched_contact)) {
return $fetched_contact; return $fetched_contact;
} }
@ -192,7 +190,7 @@ class APContact
$failed = true; $failed = true;
} }
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]); DI::logger()->notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
$failed = true; $failed = true;
} }
@ -291,7 +289,7 @@ class APContact
try { try {
$apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority(); $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority();
} catch (\Throwable $e) { } catch (\Throwable $e) {
Logger::warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]); DI::logger()->warning('Unable to coerce APContact URL into a UriInterface object', ['url' => $apcontact['url'], 'error' => $e->getMessage()]);
$apcontact['addr'] = ''; $apcontact['addr'] = '';
} }
} }
@ -371,7 +369,7 @@ class APContact
$apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']); $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']);
if (!Network::isValidHttpUrl($apcontact['photo'])) { if (!Network::isValidHttpUrl($apcontact['photo'])) {
Logger::warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]); DI::logger()->warning('Invalid URL for photo', ['url' => $apcontact['url'], 'photo' => $apcontact['photo']]);
$apcontact['photo'] = ''; $apcontact['photo'] = '';
} }
} }
@ -457,9 +455,9 @@ class APContact
if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) { if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) {
$key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES); $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES);
APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']); APContact\Endpoint::update($apcontact['uri-id'], $key, $endpoint['@id']);
Logger::debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]); DI::logger()->debug('Store endpoint', ['key' => $key, 'name' => $name, 'endpoint' => $endpoint['@id']]);
} elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) { } elseif (!in_array($name, ['as:sharedInbox', 'as:uploadMedia', 'as:oauthTokenEndpoint', 'as:oauthAuthorizationEndpoint', 'litepub:oauthRegistrationEndpoint'])) {
Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]); DI::logger()->debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]);
} }
} }
} }
@ -468,7 +466,7 @@ class APContact
// We delete the old entry when the URL is changed // We delete the old entry when the URL is changed
if ($url != $apcontact['url']) { if ($url != $apcontact['url']) {
Logger::info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]); DI::logger()->info('Delete changed profile url', ['old' => $url, 'new' => $apcontact['url']]);
DBA::delete('apcontact', ['url' => $url]); DBA::delete('apcontact', ['url' => $url]);
} }
@ -481,7 +479,7 @@ class APContact
DBA::replace('apcontact', $apcontact); DBA::replace('apcontact', $apcontact);
} }
Logger::info('Updated profile', ['url' => $url]); DI::logger()->info('Updated profile', ['url' => $url]);
return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: []; return DBA::selectFirst('apcontact', [], ['url' => $apcontact['url']]) ?: [];
} }
@ -532,7 +530,7 @@ class APContact
public static function markForArchival(array $apcontact) public static function markForArchival(array $apcontact)
{ {
if (!empty($apcontact['inbox'])) { if (!empty($apcontact['inbox'])) {
Logger::info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]); DI::logger()->info('Set inbox status to failure', ['inbox' => $apcontact['inbox']]);
HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']); HTTPSignature::setInboxStatus($apcontact['inbox'], false, false, $apcontact['gsid']);
} }
@ -542,7 +540,7 @@ class APContact
$apcontact['sharedinbox']]); $apcontact['sharedinbox']]);
if (!$available) { if (!$available) {
// If all known personal inboxes are failing then set their shared inbox to failure as well // If all known personal inboxes are failing then set their shared inbox to failure as well
Logger::info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]); DI::logger()->info('Set shared inbox status to failure', ['sharedinbox' => $apcontact['sharedinbox']]);
HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']); HTTPSignature::setInboxStatus($apcontact['sharedinbox'], false, true, $apcontact['gsid']);
} }
} }
@ -557,11 +555,11 @@ class APContact
public static function unmarkForArchival(array $apcontact) public static function unmarkForArchival(array $apcontact)
{ {
if (!empty($apcontact['inbox'])) { if (!empty($apcontact['inbox'])) {
Logger::info('Set inbox status to success', ['inbox' => $apcontact['inbox']]); DI::logger()->info('Set inbox status to success', ['inbox' => $apcontact['inbox']]);
HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']); HTTPSignature::setInboxStatus($apcontact['inbox'], true, false, $apcontact['gsid']);
} }
if (!empty($apcontact['sharedinbox'])) { if (!empty($apcontact['sharedinbox'])) {
Logger::info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]); DI::logger()->info('Set shared inbox status to success', ['sharedinbox' => $apcontact['sharedinbox']]);
HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']); HTTPSignature::setInboxStatus($apcontact['sharedinbox'], true, true, $apcontact['gsid']);
} }
} }

View file

@ -9,7 +9,6 @@ namespace Friendica\Model;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Content\Widget; use Friendica\Content\Widget;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Database\Database; use Friendica\Database\Database;
@ -164,7 +163,8 @@ class Circle
*/ */
public static function countUnseen(int $uid) public static function countUnseen(int $uid)
{ {
$stmt = DBA::p("SELECT `circle`.`id`, `circle`.`name`, $stmt = DBA::p(
"SELECT `circle`.`id`, `circle`.`name`,
(SELECT COUNT(*) FROM `post-user` (SELECT COUNT(*) FROM `post-user`
WHERE `uid` = ? WHERE `uid` = ?
AND `unseen` AND `unseen`
@ -495,7 +495,7 @@ class Circle
} }
DBA::close($stmt); DBA::close($stmt);
Logger::info('Got circles', $display_circles); DI::logger()->info('Got circles', $display_circles);
$o = Renderer::replaceMacros(Renderer::getMarkupTemplate('circle_selection.tpl'), [ $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('circle_selection.tpl'), [
'$id' => $id, '$id' => $id,
@ -608,7 +608,7 @@ class Circle
*/ */
public static function getIdForGroup(int $id): int public static function getIdForGroup(int $id): int
{ {
Logger::info('Get id for group id', ['id' => $id]); DI::logger()->info('Get id for group id', ['id' => $id]);
$contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']); $contact = Contact::getById($id, ['uid', 'name', 'contact-type', 'manually-approve']);
if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) { if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) {
return 0; return 0;
@ -638,7 +638,7 @@ class Circle
*/ */
public static function updateMembersForGroup(int $id) public static function updateMembersForGroup(int $id)
{ {
Logger::info('Update group members', ['id' => $id]); DI::logger()->info('Update group members', ['id' => $id]);
$contact = Contact::getById($id, ['uid', 'url']); $contact = Contact::getById($id, ['uid', 'url']);
if (empty($contact)) { if (empty($contact)) {
@ -673,6 +673,6 @@ class Circle
} }
DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]); DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $current]);
Logger::info('Updated group members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]); DI::logger()->info('Updated group members', ['id' => $id, 'count' => DBA::count('group_member', ['gid' => $gid])]);
} }
} }

View file

@ -15,7 +15,6 @@ use Friendica\Content\Conversation as ConversationContent;
use Friendica\Content\Pager; use Friendica\Content\Pager;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\System; use Friendica\Core\System;
@ -182,7 +181,7 @@ class Contact
$contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]); $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
// Shouldn't happen // Shouldn't happen
Logger::warning('Created contact could not be found', ['fields' => $fields]); DI::logger()->warning('Created contact could not be found', ['fields' => $fields]);
return 0; return 0;
} }
@ -190,23 +189,23 @@ class Contact
DBA::insert('account-user', $fields, Database::INSERT_IGNORE); DBA::insert('account-user', $fields, Database::INSERT_IGNORE);
$account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]); $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
if (empty($account_user['id'])) { if (empty($account_user['id'])) {
Logger::warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]); DI::logger()->warning('Account-user entry not found', ['cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
} elseif ($account_user['id'] != $contact['id']) { } elseif ($account_user['id'] != $contact['id']) {
$duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]); $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]);
if (!empty($duplicate['id'])) { if (!empty($duplicate['id'])) {
$ret = Contact::deleteById($contact['id']); $ret = Contact::deleteById($contact['id']);
Logger::notice('Deleted duplicated contact', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $duplicate['id'], 'uid' => $duplicate['uid'], 'uri-id' => $duplicate['uri-id'], 'url' => $duplicate['url']]); DI::logger()->notice('Deleted duplicated contact', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $duplicate['id'], 'uid' => $duplicate['uid'], 'uri-id' => $duplicate['uri-id'], 'url' => $duplicate['url']]);
$contact = $duplicate; $contact = $duplicate;
} else { } else {
$ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]); $ret = DBA::update('account-user', ['id' => $contact['id']], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-id']]);
Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]); DI::logger()->notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $contact['id'], 'uid' => $contact['uid'], 'uri-id' => $contact['uri-id'], 'url' => $contact['url']]);
} }
} }
Contact\User::insertForContactArray($contact); Contact\User::insertForContactArray($contact);
if ((empty($contact['baseurl']) || empty($contact['gsid'])) && Probe::isProbable($contact['network'])) { if ((empty($contact['baseurl']) || empty($contact['gsid'])) && Probe::isProbable($contact['network'])) {
Logger::debug('Update missing baseurl', ['id' => $contact['id'], 'url' => $contact['url'], 'callstack' => System::callstack(4, 0, true)]); DI::logger()->debug('Update missing baseurl', ['id' => $contact['id'], 'url' => $contact['url'], 'callstack' => System::callstack(4, 0, true)]);
UpdateContact::add(['priority' => Worker::PRIORITY_MEDIUM, 'dont_fork' => true], $contact['id']); UpdateContact::add(['priority' => Worker::PRIORITY_MEDIUM, 'dont_fork' => true], $contact['id']);
} }
@ -221,7 +220,7 @@ class Contact
*/ */
public static function deleteById(int $id): bool public static function deleteById(int $id): bool
{ {
Logger::debug('Delete contact', ['id' => $id]); DI::logger()->debug('Delete contact', ['id' => $id]);
DBA::delete('account-user', ['id' => $id]); DBA::delete('account-user', ['id' => $id]);
return DBA::delete('contact', ['id' => $id]); return DBA::delete('contact', ['id' => $id]);
} }
@ -363,14 +362,12 @@ class Contact
return []; return [];
} }
$background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true;
// Update the contact in the background if needed // Update the contact in the background if needed
if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) { if (UpdateContact::isUpdatable($contact['id'])) {
try { try {
UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['contact' => $contact]); DI::logger()->notice($e->getMessage(), ['contact' => $contact]);
} }
} }
@ -538,6 +535,17 @@ class Contact
return DBA::exists('account-user-view', ["`pid` = ? AND `uid` != ? AND `rel` IN (?, ?)", $cid, 0, self::SHARING, self::FRIEND]); return DBA::exists('account-user-view', ["`pid` = ? AND `uid` != ? AND `rel` IN (?, ?)", $cid, 0, self::SHARING, self::FRIEND]);
} }
/**
* Checks if the provided public contact id has got relations with someone on this system
*
* @param integer $cid Public Contact Id
* @return boolean Contact has followers or sharers on this system
*/
public static function hasRelations(int $cid): bool
{
return DBA::exists('account-user-view', ["`pid` = ? AND `uid` != ? AND `rel` IN (?, ?, ?)", $cid, 0, self::FOLLOWER, self::SHARING, self::FRIEND]);
}
/** /**
* Get the basepath for a given contact link * Get the basepath for a given contact link
* *
@ -567,11 +575,11 @@ class Contact
// And fetch the result // And fetch the result
$contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]); $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]);
if (empty($contact['baseurl'])) { if (empty($contact['baseurl'])) {
Logger::info('No baseurl for contact', ['url' => $url]); DI::logger()->info('No baseurl for contact', ['url' => $url]);
return ''; return '';
} }
Logger::info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]); DI::logger()->info('Found baseurl for contact', ['url' => $url, 'baseurl' => $contact['baseurl']]);
return $contact['baseurl']; return $contact['baseurl'];
} }
@ -1090,10 +1098,10 @@ class Contact
return; return;
} }
} elseif (!isset($contact['url']) || !isset($contact['uri-id'])) { } elseif (!isset($contact['url']) || !isset($contact['uri-id'])) {
Logger::info('Empty contact', ['contact' => $contact]); DI::logger()->info('Empty contact', ['contact' => $contact]);
} }
Logger::info('Contact is marked for archival', ['id' => $contact['id'], 'archive' => $contact['archive'], 'term-date' => $contact['term-date'], 'url' => $contact['url']]); DI::logger()->info('Contact is marked for archival', ['id' => $contact['id'], 'archive' => $contact['archive'], 'term-date' => $contact['term-date'], 'url' => $contact['url']]);
// Contact already archived or "self" contact? => nothing to do // Contact already archived or "self" contact? => nothing to do
if ($contact['archive'] || $contact['self']) { if ($contact['archive'] || $contact['self']) {
@ -1157,7 +1165,7 @@ class Contact
} }
} }
Logger::info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date'], 'url' => $contact['url']]); DI::logger()->info('Contact is marked as vital again', ['id' => $contact['id'], 'term-date' => $contact['term-date'], 'url' => $contact['url']]);
// It's a miracle. Our dead contact has inexplicably come back to life. // It's a miracle. Our dead contact has inexplicably come back to life.
$fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false]; $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false];
@ -1310,7 +1318,7 @@ class Contact
$contact_id = 0; $contact_id = 0;
if (empty($url)) { if (empty($url)) {
Logger::notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]); DI::logger()->notice('Empty url, quitting', ['url' => $url, 'user' => $uid, 'default' => $default]);
return 0; return 0;
} }
@ -1319,25 +1327,23 @@ class Contact
if (!empty($contact)) { if (!empty($contact)) {
$contact_id = $contact['id']; $contact_id = $contact['id'];
$background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true; if (UpdateContact::isUpdatable($contact['id'])) {
if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) {
try { try {
UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['contact' => $contact]); DI::logger()->notice($e->getMessage(), ['contact' => $contact]);
} }
} }
if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) { if (empty($update) && (!empty($contact['uri-id']) || is_bool($update))) {
Logger::debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]); DI::logger()->debug('Contact found', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
return $contact_id; return $contact_id;
} }
} elseif ($uid != 0) { } elseif ($uid != 0) {
Logger::debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]); DI::logger()->debug('Contact does not exist for the user', ['url' => $url, 'uid' => $uid, 'update' => $update]);
return 0; return 0;
} elseif (empty($default) && !is_null($update) && !$update) { } elseif (empty($default) && !is_null($update) && !$update) {
Logger::info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]); DI::logger()->info('Contact not found, update not desired', ['url' => $url, 'uid' => $uid, 'update' => $update]);
return 0; return 0;
} }
@ -1369,7 +1375,7 @@ class Contact
} }
if (DBA::isResult($personal_contact) && !Probe::isProbable($personal_contact['network'])) { if (DBA::isResult($personal_contact) && !Probe::isProbable($personal_contact['network'])) {
Logger::info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact]); DI::logger()->info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact]);
$data = $personal_contact; $data = $personal_contact;
$data['photo'] = $personal_contact['avatar']; $data['photo'] = $personal_contact['avatar'];
$data['account-type'] = $personal_contact['contact-type']; $data['account-type'] = $personal_contact['contact-type'];
@ -1381,12 +1387,12 @@ class Contact
} }
if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) { if (empty($data['network']) || ($data['network'] == Protocol::PHANTOM)) {
Logger::notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update]); DI::logger()->notice('No valid network found', ['url' => $url, 'uid' => $uid, 'default' => $default, 'update' => $update]);
return 0; return 0;
} }
if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) { if (!$contact_id && !empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
Logger::info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]); DI::logger()->info('Contact is a tombstone. It will not be inserted', ['url' => $url, 'uid' => $uid]);
return 0; return 0;
} }
@ -1398,7 +1404,7 @@ class Contact
$contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]); $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]);
if (!empty($contact['id'])) { if (!empty($contact['id'])) {
$contact_id = $contact['id']; $contact_id = $contact['id'];
Logger::info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]); DI::logger()->info('Fetched id by url', ['cid' => $contact_id, 'uid' => $uid, 'url' => $url, 'data' => $data]);
} }
} }
@ -1424,37 +1430,37 @@ class Contact
$contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]); $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]);
if (DBA::isResult($contact)) { if (DBA::isResult($contact)) {
$contact_id = $contact['id']; $contact_id = $contact['id'];
Logger::notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]); DI::logger()->notice('Contact had been created (shortly) before', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
} else { } else {
$contact_id = self::insert($fields); $contact_id = self::insert($fields);
if ($contact_id) { if ($contact_id) {
Logger::info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]); DI::logger()->info('Contact inserted', ['id' => $contact_id, 'url' => $url, 'uid' => $uid]);
} }
} }
if (!$contact_id) { if (!$contact_id) {
Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]); DI::logger()->warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]);
return 0; return 0;
} }
} else { } else {
Logger::info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]); DI::logger()->info('Contact will be updated', ['url' => $url, 'uid' => $uid, 'update' => $update, 'cid' => $contact_id]);
} }
if ($data['network'] == Protocol::DIASPORA) { if ($data['network'] == Protocol::DIASPORA) {
try { try {
DI::dsprContact()->updateFromProbeArray($data); DI::dsprContact()->updateFromProbeArray($data);
} catch (NotFoundException $e) { } catch (NotFoundException $e) {
Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]); DI::logger()->notice($e->getMessage(), ['url' => $url, 'data' => $data]);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]); DI::logger()->notice($e->getMessage(), ['url' => $url, 'data' => $data]);
} }
} elseif (!empty($data['networks'][Protocol::DIASPORA])) { } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
try { try {
DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]); DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
} catch (NotFoundException $e) { } catch (NotFoundException $e) {
Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]); DI::logger()->notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]); DI::logger()->notice($e->getMessage(), ['url' => $url, 'data' => $data['networks'][Protocol::DIASPORA]]);
} }
} }
@ -1463,7 +1469,7 @@ class Contact
// Don't return a number for a deleted account // Don't return a number for a deleted account
if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) { if (!empty($data['account-type']) && $data['account-type'] == User::ACCOUNT_TYPE_DELETED) {
Logger::info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]); DI::logger()->info('Contact is a tombstone', ['url' => $url, 'uid' => $uid]);
return 0; return 0;
} }
@ -1812,16 +1818,16 @@ class Contact
if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) { if (in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) || DI::config()->get('system', 'cache_contact_avatar')) {
if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) { if (!empty($contact['avatar']) && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) {
Logger::info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]); DI::logger()->info('Adding avatar cache', ['id' => $cid, 'contact' => $contact]);
self::updateAvatar($cid, $contact['avatar'], true); self::updateAvatar($cid, $contact['avatar'], true);
return; return;
} }
} elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) { } elseif (Photo::isPhotoURI($contact['photo']) || Photo::isPhotoURI($contact['thumb']) || Photo::isPhotoURI($contact['micro'])) {
Logger::info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]); DI::logger()->info('Replacing legacy avatar cache', ['id' => $cid, 'contact' => $contact]);
self::updateAvatar($cid, $contact['avatar'], true); self::updateAvatar($cid, $contact['avatar'], true);
return; return;
} elseif (DI::config()->get('system', 'avatar_cache') && (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']))) { } 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]); DI::logger()->info('Adding avatar cache file', ['id' => $cid, 'contact' => $contact]);
self::updateAvatar($cid, $contact['avatar'], true); self::updateAvatar($cid, $contact['avatar'], true);
return; return;
} }
@ -2303,7 +2309,7 @@ class Contact
} }
if (!empty($avatar) && !Network::isValidHttpUrl($avatar)) { if (!empty($avatar) && !Network::isValidHttpUrl($avatar)) {
Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]); DI::logger()->warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]);
$avatar = ''; $avatar = '';
} }
@ -2327,7 +2333,7 @@ class Contact
} }
} }
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]); DI::logger()->notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]);
return; return;
} }
} elseif (!empty($contact['blurhash'])) { } elseif (!empty($contact['blurhash'])) {
@ -2337,7 +2343,7 @@ class Contact
} }
self::update($update_fields, ['id' => $cid]); self::update($update_fields, ['id' => $cid]);
Logger::info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]); DI::logger()->info('Only update the avatar', ['id' => $cid, 'avatar' => $avatar, 'contact' => $contact]);
} }
return; return;
} }
@ -2346,7 +2352,7 @@ class Contact
if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) { if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) {
$pcid = self::getIdForURL($contact['url'], 0, false); $pcid = self::getIdForURL($contact['url'], 0, false);
if (!empty($pcid)) { if (!empty($pcid)) {
Logger::debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]); DI::logger()->debug('Update the private contact via the public contact', ['id' => $cid, 'uid' => $uid, 'public' => $pcid]);
self::updateAvatar($pcid, $avatar, $force, true); self::updateAvatar($pcid, $avatar, $force, true);
return; return;
} }
@ -2380,7 +2386,7 @@ class Contact
'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB), '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]); DI::logger()->debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
} }
$local_uid = 0; $local_uid = 0;
@ -2390,7 +2396,7 @@ class Contact
$local_uid = User::getIdForURL($contact['url']); $local_uid = User::getIdForURL($contact['url']);
if (!empty($local_uid)) { if (!empty($local_uid)) {
$fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]); $fields = self::selectFirst(['avatar', 'avatar-date', 'photo', 'thumb', 'micro'], ['self' => true, 'uid' => $local_uid]);
Logger::debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]); DI::logger()->debug('Use owner data', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
} }
} }
@ -2407,7 +2413,7 @@ class Contact
foreach ($data as $image_uri) { foreach ($data as $image_uri) {
$image_rid = Photo::ridFromURI($image_uri); $image_rid = Photo::ridFromURI($image_uri);
if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) { if ($image_rid && !Photo::exists(['resource-id' => $image_rid, 'uid' => $uid])) {
Logger::debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]); DI::logger()->debug('Regenerating avatar', ['contact uid' => $uid, 'cid' => $cid, 'missing photo' => $image_rid, 'avatar' => $contact['avatar']]);
$update = true; $update = true;
} }
} }
@ -2425,7 +2431,7 @@ class Contact
'avatar-date' => DateTimeFormat::utcNow(), 'avatar-date' => DateTimeFormat::utcNow(),
]; ];
$update = true; $update = true;
Logger::debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]); DI::logger()->debug('Created new cached avatars', ['id' => $cid, 'uid' => $uid, 'owner-uid' => $local_uid]);
} else { } else {
$update = false; $update = false;
} }
@ -2466,7 +2472,7 @@ class Contact
$cids[] = $cid; $cids[] = $cid;
$uids[] = $uid; $uids[] = $uid;
Logger::info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]); DI::logger()->info('Updating cached contact avatars', ['cid' => $cids, 'uid' => $uids, 'fields' => $fields]);
self::update($fields, ['id' => $cids]); self::update($fields, ['id' => $cids]);
} }
@ -2476,7 +2482,7 @@ class Contact
$condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)]; $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)];
$contacts = DBA::select('contact', ['id', 'uid'], $condition); $contacts = DBA::select('contact', ['id', 'uid'], $condition);
while ($contact = DBA::fetch($contacts)) { while ($contact = DBA::fetch($contacts)) {
Logger::info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]); DI::logger()->info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]);
self::remove($contact['id']); self::remove($contact['id']);
} }
} }
@ -2508,7 +2514,7 @@ class Contact
private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields) private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields)
{ {
if (!self::update($fields, ['id' => $id])) { if (!self::update($fields, ['id' => $id])) {
Logger::info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]); DI::logger()->info('Couldn\'t update contact.', ['id' => $id, 'fields' => $fields]);
return; return;
} }
@ -2517,7 +2523,7 @@ class Contact
// Archive or unarchive the contact. // Archive or unarchive the contact.
$contact = DBA::selectFirst('contact', [], ['id' => $id]); $contact = DBA::selectFirst('contact', [], ['id' => $id]);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
Logger::info('Couldn\'t select contact for archival.', ['id' => $id]); DI::logger()->info('Couldn\'t select contact for archival.', ['id' => $id]);
return; return;
} }
@ -2564,29 +2570,29 @@ class Contact
if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) { if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) {
if ($account_user['uid'] == $uid) { if ($account_user['uid'] == $uid) {
$ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]); $ret = DBA::update('account-user', ['uri-id' => $uri_id], ['id' => $id]);
Logger::notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]); DI::logger()->notice('Updated account-user uri-id', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
} else { } else {
// This should never happen // This should never happen
Logger::warning('account-user exists for a different uri-id and uid', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]); DI::logger()->warning('account-user exists for a different uri-id and uid', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
} }
} }
$account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]); $account_user = DBA::selectFirst('account-user', ['id', 'uid', 'uri-id'], ['uid' => $uid, 'uri-id' => $uri_id]);
if (!empty($account_user['id'])) { if (!empty($account_user['id'])) {
if ($account_user['id'] == $id) { if ($account_user['id'] == $id) {
Logger::debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]); DI::logger()->debug('account-user already exists', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
return; return;
} elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) { } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) {
$ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]); $ret = DBA::update('account-user', ['id' => $id], ['uid' => $uid, 'uri-id' => $uri_id]);
Logger::notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]); DI::logger()->notice('Updated account-user', ['ret' => $ret, 'account-user' => $account_user, 'cid' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
return; return;
} }
Logger::warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]); DI::logger()->warning('account-user exists for a different contact id', ['account_user' => $account_user, 'id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid); Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $account_user['id'], $id, $uid);
} elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) { } elseif (DBA::insert('account-user', ['id' => $id, 'uri-id' => $uri_id, 'uid' => $uid], Database::INSERT_IGNORE)) {
Logger::notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]); DI::logger()->notice('account-user was added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
} else { } else {
Logger::warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]); DI::logger()->warning('account-user was not added', ['id' => $id, 'uid' => $uid, 'uri-id' => $uri_id, 'url' => $url]);
} }
} }
@ -2613,7 +2619,7 @@ class Contact
} }
$first = $first_contact['id']; $first = $first_contact['id'];
Logger::info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]); DI::logger()->info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]);
// Find all duplicates // Find all duplicates
$condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first]; $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first];
@ -2626,7 +2632,7 @@ class Contact
Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid); Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid);
} }
DBA::close($duplicates); DBA::close($duplicates);
Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]); DI::logger()->info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]);
return true; return true;
} }
@ -2649,7 +2655,7 @@ class Contact
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
self::updateFromProbe($id); self::updateFromProbe($id);
Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url']]); DI::logger()->debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url']]);
return true; return true;
} }
@ -2698,17 +2704,17 @@ class Contact
try { try {
DI::dsprContact()->updateFromProbeArray($data); DI::dsprContact()->updateFromProbeArray($data);
} catch (NotFoundException $e) { } catch (NotFoundException $e) {
Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]); DI::logger()->notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]); DI::logger()->notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
} }
} elseif (!empty($data['networks'][Protocol::DIASPORA])) { } elseif (!empty($data['networks'][Protocol::DIASPORA])) {
try { try {
DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]); DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]);
} catch (NotFoundException $e) { } catch (NotFoundException $e) {
Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]); DI::logger()->notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]); DI::logger()->notice($e->getMessage(), ['id' => $id, 'network' => $network, 'contact' => $contact, 'data' => $data]);
} }
} }
@ -2789,7 +2795,7 @@ class Contact
if (self::isLocal($ret['url'])) { if (self::isLocal($ret['url'])) {
if ($contact['uid'] == 0) { if ($contact['uid'] == 0) {
Logger::info('Local contacts are not updated here.'); DI::logger()->info('Local contacts are not updated here.');
} else { } else {
self::updateFromPublicContact($id, $contact); self::updateFromPublicContact($id, $contact);
} }
@ -2797,7 +2803,7 @@ class Contact
} }
if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) { if (!empty($ret['account-type']) && $ret['account-type'] == User::ACCOUNT_TYPE_DELETED) {
Logger::info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]); DI::logger()->info('Deleted account', ['id' => $id, 'url' => $ret['url'], 'ret' => $ret]);
self::remove($id); self::remove($id);
// Delete all contacts with the same URL // Delete all contacts with the same URL
@ -2844,7 +2850,7 @@ class Contact
} }
if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) { if (Strings::normaliseLink($contact['url']) != Strings::normaliseLink($ret['url'])) {
Logger::notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]); DI::logger()->notice('New URL differs from old URL', ['id' => $id, 'uid' => $uid, 'old' => $contact['url'], 'new' => $ret['url']]);
self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]); self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated]);
return false; return false;
} }
@ -2857,10 +2863,10 @@ class Contact
) { ) {
if (GServer::reachable($contact)) { if (GServer::reachable($contact)) {
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, 'unsearchable' => true]); 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, 'unsearchable' => true]);
Logger::info('Not updating relay', ['id' => $id, 'url' => $contact['url']]); DI::logger()->info('Not updating relay', ['id' => $id, 'url' => $contact['url']]);
return true; return true;
} }
Logger::info('Relay server is not reachable', ['id' => $id, 'url' => $contact['url']]); DI::logger()->info('Relay server is not reachable', ['id' => $id, 'url' => $contact['url']]);
self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated, 'unsearchable' => true]); self::updateContact($id, $uid, $uriid, $contact['url'], ['failed' => true, 'local-data' => $has_local_data, 'last-update' => $updated, 'next-update' => $failed_next_update, 'failure_update' => $updated, 'unsearchable' => true]);
return false; return false;
} }
@ -2874,7 +2880,7 @@ class Contact
if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) { if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) {
$cid = self::getIdForURL($ret['url'], 0, false); $cid = self::getIdForURL($ret['url'], 0, false);
if (!empty($cid) && ($cid != $id)) { if (!empty($cid) && ($cid != $id)) {
Logger::notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]); DI::logger()->notice('URL of contact changed.', ['id' => $id, 'new_id' => $cid, 'old' => $contact['url'], 'new' => $ret['url']]);
return self::updateFromProbeArray($cid, $ret); return self::updateFromProbeArray($cid, $ret);
} }
} }
@ -2904,7 +2910,7 @@ class Contact
} }
$ret['last-item'] = Probe::getLastUpdate($ret); $ret['last-item'] = Probe::getLastUpdate($ret);
Logger::info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item']]); DI::logger()->info('Fetched last item', ['id' => $id, 'probed_url' => $ret['url'], 'last-item' => $ret['last-item']]);
} }
$update = false; $update = false;
@ -3006,7 +3012,7 @@ class Contact
} }
if (!empty($fields)) { if (!empty($fields)) {
self::update($fields, ['id' => $id, 'self' => false]); self::update($fields, ['id' => $id, 'self' => false]);
Logger::info('Updating local contact', ['id' => $id]); DI::logger()->info('Updating local contact', ['id' => $id]);
} }
} }
@ -3243,7 +3249,7 @@ class Contact
try { try {
UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']); UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['contact' => $contact]); DI::logger()->notice($e->getMessage(), ['contact' => $contact]);
} }
} }
@ -3297,7 +3303,7 @@ class Contact
if (!empty($contact)) { if (!empty($contact)) {
if (!empty($contact['pending'])) { if (!empty($contact['pending'])) {
Logger::info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]); DI::logger()->info('Pending contact request already exists.', ['url' => $url, 'uid' => $importer['uid']]);
return null; return null;
} }
@ -3330,7 +3336,7 @@ class Contact
} else { } else {
// send email notification to owner? // send email notification to owner?
if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) { if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($url), 'uid' => $importer['uid'], 'pending' => true])) {
Logger::notice('ignoring duplicated connection request from pending contact ' . $url); DI::logger()->notice('ignoring duplicated connection request from pending contact ' . $url);
return null; return null;
} }
@ -3492,7 +3498,7 @@ class Contact
$contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition); $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition);
while ($contact = DBA::fetch($contacts)) { while ($contact = DBA::fetch($contacts)) {
Logger::notice('update_contact_birthday: ' . $contact['bd']); DI::logger()->notice('update_contact_birthday: ' . $contact['bd']);
$nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4); $nextbd = DateTimeFormat::utcNow('Y') . substr($contact['bd'], 4);
@ -3774,7 +3780,7 @@ class Contact
UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']);
++$updated; ++$updated;
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['contact' => $contact]); DI::logger()->notice($e->getMessage(), ['contact' => $contact]);
} }
} else { } else {
++$unchanged; ++$unchanged;

View file

@ -9,7 +9,6 @@ namespace Friendica\Model\Contact;
use Exception; use Exception;
use Friendica\Content\Widget; use Friendica\Content\Widget;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -67,7 +66,7 @@ class Relation
{ {
$contact = Contact::selectFirst(['id', 'url', 'network'], ['id' => Contact::getPublicIdByUserId($uid)]); $contact = Contact::selectFirst(['id', 'url', 'network'], ['id' => Contact::getPublicIdByUserId($uid)]);
if (empty($contact)) { if (empty($contact)) {
Logger::warning('Self contact for user not found', ['uid' => $uid]); DI::logger()->warning('Self contact for user not found', ['uid' => $uid]);
return; return;
} }
@ -87,22 +86,22 @@ class Relation
{ {
$contact = Contact::getByURL($url); $contact = Contact::getByURL($url);
if (empty($contact)) { if (empty($contact)) {
Logger::info('Contact not found', ['url' => $url]); DI::logger()->info('Contact not found', ['url' => $url]);
return; return;
} }
if (!self::isDiscoverable($url, $contact)) { if (!self::isDiscoverable($url, $contact)) {
Logger::info('Contact is not discoverable', ['url' => $url]); DI::logger()->info('Contact is not discoverable', ['url' => $url]);
return; return;
} }
$uid = User::getIdForURL($url); $uid = User::getIdForURL($url);
if (!empty($uid)) { if (!empty($uid)) {
Logger::info('Fetch the followers/followings locally', ['url' => $url]); DI::logger()->info('Fetch the followers/followings locally', ['url' => $url]);
$followers = self::getContacts($uid, [Contact::FOLLOWER, Contact::FRIEND]); $followers = self::getContacts($uid, [Contact::FOLLOWER, Contact::FRIEND]);
$followings = self::getContacts($uid, [Contact::SHARING, Contact::FRIEND]); $followings = self::getContacts($uid, [Contact::SHARING, Contact::FRIEND]);
} elseif (!Contact::isLocal($url)) { } elseif (!Contact::isLocal($url)) {
Logger::info('Fetch the followers/followings by polling the endpoints', ['url' => $url]); DI::logger()->info('Fetch the followers/followings by polling the endpoints', ['url' => $url]);
$apcontact = APContact::getByURL($url, false); $apcontact = APContact::getByURL($url, false);
if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) { if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) {
@ -117,7 +116,7 @@ class Relation
$followings = []; $followings = [];
} }
} else { } else {
Logger::warning('Contact seems to be local but could not be found here', ['url' => $url]); DI::logger()->warning('Contact seems to be local but could not be found here', ['url' => $url]);
$followers = []; $followers = [];
$followings = []; $followings = [];
} }
@ -137,7 +136,7 @@ class Relation
{ {
if (empty($followers) && empty($followings)) { if (empty($followers) && empty($followings)) {
Contact::update(['last-discovery' => DateTimeFormat::utcNow()], ['id' => $contact['id']]); Contact::update(['last-discovery' => DateTimeFormat::utcNow()], ['id' => $contact['id']]);
Logger::info('The contact does not offer discoverable data', ['id' => $contact['id'], 'url' => $contact['url'], 'network' => $contact['network']]); DI::logger()->info('The contact does not offer discoverable data', ['id' => $contact['id'], 'url' => $contact['url'], 'network' => $contact['network']]);
return; return;
} }
@ -162,7 +161,7 @@ class Relation
$follower_counter = 0; $follower_counter = 0;
$following_counter = 0; $following_counter = 0;
Logger::info('Discover contacts', ['id' => $target, 'url' => $url, 'contacts' => count($contacts)]); DI::logger()->info('Discover contacts', ['id' => $target, 'url' => $url, 'contacts' => count($contacts)]);
foreach ($contacts as $contact) { foreach ($contacts as $contact) {
$actor = Contact::getIdForURL($contact); $actor = Contact::getIdForURL($contact);
if (!empty($actor)) { if (!empty($actor)) {
@ -186,7 +185,7 @@ class Relation
} }
Contact::update(['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]); Contact::update(['last-discovery' => DateTimeFormat::utcNow()], ['id' => $target]);
Logger::info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]); DI::logger()->info('Contacts discovery finished', ['id' => $target, 'url' => $url, 'follower' => $follower_counter, 'following' => $following_counter]);
return; return;
} }
@ -260,34 +259,34 @@ class Relation
} }
if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) { if ($contact['last-discovery'] > DateTimeFormat::utc('now - 1 month')) {
Logger::info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]); DI::logger()->info('No discovery - Last was less than a month ago.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['last-discovery']]);
return false; return false;
} }
if ($contact_discovery != self::DISCOVERY_ALL) { if ($contact_discovery != self::DISCOVERY_ALL) {
$local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]); $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]);
if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) { if (($contact_discovery == self::DISCOVERY_LOCAL) && !$local) {
Logger::info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]); DI::logger()->info('No discovery - This contact is not followed/following locally.', ['id' => $contact['id'], 'url' => $url]);
return false; return false;
} }
if ($contact_discovery == self::DISCOVERY_INTERACTOR) { if ($contact_discovery == self::DISCOVERY_INTERACTOR) {
$interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]); $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]);
if (!$local && !$interactor) { if (!$local && !$interactor) {
Logger::info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]); DI::logger()->info('No discovery - This contact is not interacting locally.', ['id' => $contact['id'], 'url' => $url]);
return false; return false;
} }
} }
} elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) { } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) {
// Newly created contacts are not discovered to avoid DDoS attacks // Newly created contacts are not discovered to avoid DDoS attacks
Logger::info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]); DI::logger()->info('No discovery - Contact record is less than a day old.', ['id' => $contact['id'], 'url' => $url, 'discovery' => $contact['created']]);
return false; return false;
} }
if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) { if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
$apcontact = APContact::getByURL($url, false); $apcontact = APContact::getByURL($url, false);
if (empty($apcontact)) { if (empty($apcontact)) {
Logger::info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]); DI::logger()->info('No discovery - The contact does not seem to speak ActivityPub.', ['id' => $contact['id'], 'url' => $url, 'network' => $contact['network']]);
return false; return false;
} }
} }
@ -301,7 +300,7 @@ class Relation
* @param integer $uid * @param integer $uid
* @return boolean * @return boolean
*/ */
static public function areSuggestionsOutdated(int $uid): bool public static function areSuggestionsOutdated(int $uid): bool
{ {
return DI::pConfig()->get($uid, 'suggestion', 'last_update') + 3600 < time(); return DI::pConfig()->get($uid, 'suggestion', 'last_update') + 3600 < time();
} }
@ -312,7 +311,7 @@ class Relation
* @param integer $uid * @param integer $uid
* @return void * @return void
*/ */
static public function updateCachedSuggestions(int $uid) public static function updateCachedSuggestions(int $uid)
{ {
if (!self::areSuggestionsOutdated($uid)) { if (!self::areSuggestionsOutdated($uid)) {
return; return;
@ -335,7 +334,7 @@ class Relation
* @param int $limit optional, default 80 * @param int $limit optional, default 80
* @return array * @return array
*/ */
static public function getCachedSuggestions(int $uid, int $start = 0, int $limit = 80): array public static function getCachedSuggestions(int $uid, int $start = 0, int $limit = 80): array
{ {
$condition = ["`uid` = ? AND `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE NOT `ignore` AND `uid` = ?)", 0, $uid]; $condition = ["`uid` = ? AND `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE NOT `ignore` AND `uid` = ?)", 0, $uid];
$params = ['limit' => [$start, $limit]]; $params = ['limit' => [$start, $limit]];
@ -356,7 +355,7 @@ class Relation
* @param int $limit optional, default 80 * @param int $limit optional, default 80
* @return array * @return array
*/ */
static public function getSuggestions(int $uid, int $start = 0, int $limit = 80): array public static function getSuggestions(int $uid, int $start = 0, int $limit = 80): array
{ {
if ($uid == 0) { if ($uid == 0) {
return []; return [];
@ -366,13 +365,16 @@ class Relation
$totallimit = $start + $limit; $totallimit = $start + $limit;
$contacts = []; $contacts = [];
Logger::info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]); DI::logger()->info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]);
$diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB; $diaspora = DI::config()->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::ACTIVITYPUB;
// The query returns contacts where contacts interacted with whom the given user follows. // The query returns contacts where contacts interacted with whom the given user follows.
// Contacts who already are in the user's contact table are ignored. // Contacts who already are in the user's contact table are ignored.
$results = DBA::select('contact', [], ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN $results = DBA::select(
'contact',
[],
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
(SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?) (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
(SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))) AND `id` = `cid`) (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))) AND `id` = `cid`)
@ -382,7 +384,8 @@ class Relation
0, 0,
$uid, Contact::FRIEND, Contact::SHARING, $uid, Contact::FRIEND, Contact::SHARING,
Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid
], [ ],
[
'order' => ['last-item' => true], 'order' => ['last-item' => true],
'limit' => $totallimit, 'limit' => $totallimit,
] ]
@ -394,7 +397,7 @@ class Relation
DBA::close($results); DBA::close($results);
Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]); DI::logger()->info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
if (count($contacts) >= $totallimit) { if (count($contacts) >= $totallimit) {
return array_slice($contacts, $start, $limit); return array_slice($contacts, $start, $limit);
@ -402,7 +405,9 @@ class Relation
// The query returns contacts where contacts interacted with whom also interacted with the given user. // The query returns contacts where contacts interacted with whom also interacted with the given user.
// Contacts who already are in the user's contact table are ignored. // Contacts who already are in the user's contact table are ignored.
$results = DBA::select('contact', [], $results = DBA::select(
'contact',
[],
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
(SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?)
AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
@ -419,14 +424,16 @@ class Relation
} }
DBA::close($results); DBA::close($results);
Logger::info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]); DI::logger()->info('Contacts of contacts who are following the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
if (count($contacts) >= $totallimit) { if (count($contacts) >= $totallimit) {
return array_slice($contacts, $start, $limit); return array_slice($contacts, $start, $limit);
} }
// The query returns contacts that follow the given user but aren't followed by that user. // The query returns contacts that follow the given user but aren't followed by that user.
$results = DBA::select('contact', [], $results = DBA::select(
'contact',
[],
["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?) ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` = ?)
AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?) AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?)
AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)", AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
@ -440,14 +447,16 @@ class Relation
} }
DBA::close($results); DBA::close($results);
Logger::info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]); DI::logger()->info('Followers that are not followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
if (count($contacts) >= $totallimit) { if (count($contacts) >= $totallimit) {
return array_slice($contacts, $start, $limit); return array_slice($contacts, $start, $limit);
} }
// The query returns any contact that isn't followed by that user. // The query returns any contact that isn't followed by that user.
$results = DBA::select('contact', [], $results = DBA::select(
'contact',
[],
["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?) AND `nurl` = `nurl`) ["NOT `nurl` IN (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?) AND `nurl` = `nurl`)
AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?) AND NOT `hidden` AND `uid` = ? AND `network` IN (?, ?, ?)
AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)", AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)",
@ -461,7 +470,7 @@ class Relation
} }
DBA::close($results); DBA::close($results);
Logger::info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]); DI::logger()->info('Any contact', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
return array_slice($contacts, $start, $limit); return array_slice($contacts, $start, $limit);
} }
@ -713,7 +722,8 @@ class Relation
*/ */
public static function countCommonFollows(int $sourceId, int $targetId, array $condition = []): int public static function countCommonFollows(int $sourceId, int $targetId, array $condition = []): int
{ {
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions(
$condition,
['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
$sourceId, $targetId] $sourceId, $targetId]
@ -736,13 +746,17 @@ class Relation
*/ */
public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false) public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
{ {
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions(
$condition,
["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)", AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)",
$sourceId, $targetId] $sourceId, $targetId]
); );
return DI::dba()->selectToArray('contact', [], $condition, return DI::dba()->selectToArray(
'contact',
[],
$condition,
['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']] ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
); );
} }
@ -758,7 +772,8 @@ class Relation
*/ */
public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = []): int public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = []): int
{ {
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions(
$condition,
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)", AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
$sourceId, $targetId] $sourceId, $targetId]
@ -781,13 +796,17 @@ class Relation
*/ */
public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false) public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
{ {
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions(
$condition,
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)", AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)",
$sourceId, $targetId] $sourceId, $targetId]
); );
return DI::dba()->selectToArray('contact', [], $condition, return DI::dba()->selectToArray(
'contact',
[],
$condition,
['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']] ['limit' => [$offset, $count], 'order' => [$shuffle ? 'RAND()' : 'name']]
); );
} }
@ -803,7 +822,7 @@ class Relation
$days = DI::config()->get('channel', 'interaction_score_days'); $days = DI::config()->get('channel', 'interaction_score_days');
$contact_id = Contact::getPublicIdByUserId($uid); $contact_id = Contact::getPublicIdByUserId($uid);
Logger::debug('Calculation - start', ['uid' => $uid, 'cid' => $contact_id, 'days' => $days]); DI::logger()->debug('Calculation - start', ['uid' => $uid, 'cid' => $contact_id, 'days' => $days]);
$follow = Verb::getID(Activity::FOLLOW); $follow = Verb::getID(Activity::FOLLOW);
$view = Verb::getID(Activity::VIEW); $view = Verb::getID(Activity::VIEW);
@ -811,73 +830,151 @@ class Relation
DBA::update('contact-relation', ['score' => 0, 'relation-score' => 0, 'thread-score' => 0, 'relation-thread-score' => 0], ['relation-cid' => $contact_id]); DBA::update('contact-relation', ['score' => 0, 'relation-score' => 0, 'thread-score' => 0, 'relation-thread-score' => 0], ['relation-cid' => $contact_id]);
$total = DBA::fetchFirst("SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)", $total = DBA::fetchFirst(
$contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); "SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)",
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
Logger::debug('Calculate relation-score', ['uid' => $uid, 'total' => $total['activity']]); DI::logger()->debug('Calculate relation-score', ['uid' => $uid, 'total' => $total['activity']]);
$interactions = DBA::p("SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows` $interactions = DBA::p(
"SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows`
FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`", FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`",
$uid, Contact::SHARING, Contact::FRIEND, $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); $uid,
Contact::SHARING,
Contact::FRIEND,
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
while ($interaction = DBA::fetch($interactions)) { while ($interaction = DBA::fetch($interactions)) {
$score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535); $score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535);
DBA::update('contact-relation', ['relation-score' => $score, 'follows' => $interaction['follows']], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]); DBA::update('contact-relation', ['relation-score' => $score, 'follows' => $interaction['follows']], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]);
} }
DBA::close($interactions); DBA::close($interactions);
$total = DBA::fetchFirst("SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)", $total = DBA::fetchFirst(
$contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); "SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)",
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
Logger::debug('Calculate relation-thread-score', ['uid' => $uid, 'total' => $total['activity']]); DI::logger()->debug('Calculate relation-thread-score', ['uid' => $uid, 'total' => $total['activity']]);
$interactions = DBA::p("SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows` $interactions = DBA::p(
"SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows`
FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`", FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`",
$uid, Contact::SHARING, Contact::FRIEND, $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); $uid,
Contact::SHARING,
Contact::FRIEND,
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
while ($interaction = DBA::fetch($interactions)) { while ($interaction = DBA::fetch($interactions)) {
$score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535); $score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535);
DBA::update('contact-relation', ['relation-thread-score' => $score, 'follows' => !empty($interaction['follows'])], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]); DBA::update('contact-relation', ['relation-thread-score' => $score, 'follows' => !empty($interaction['follows'])], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]);
} }
DBA::close($interactions); DBA::close($interactions);
$total = DBA::fetchFirst("SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)", $total = DBA::fetchFirst(
$contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); "SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)",
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
Logger::debug('Calculate score', ['uid' => $uid, 'total' => $total['activity']]); DI::logger()->debug('Calculate score', ['uid' => $uid, 'total' => $total['activity']]);
$interactions = DBA::p("SELECT `post`.`author-id`, count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`", $interactions = DBA::p(
$contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); "SELECT `post`.`author-id`, count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`",
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
while ($interaction = DBA::fetch($interactions)) { while ($interaction = DBA::fetch($interactions)) {
$score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535); $score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535);
DBA::update('contact-relation', ['score' => $score], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]); DBA::update('contact-relation', ['score' => $score], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]);
} }
DBA::close($interactions); DBA::close($interactions);
$total = DBA::fetchFirst("SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)", $total = DBA::fetchFirst(
$contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); "SELECT count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?)",
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
Logger::debug('Calculate thread-score', ['uid' => $uid, 'total' => $total['activity']]); DI::logger()->debug('Calculate thread-score', ['uid' => $uid, 'total' => $total['activity']]);
$interactions = DBA::p("SELECT `post`.`author-id`, count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`", $interactions = DBA::p(
$contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); "SELECT `post`.`author-id`, count(*) AS `activity` FROM `post-user` INNER JOIN `post` ON `post-user`.`uri-id` = `post`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`",
$contact_id,
DateTimeFormat::utc('now - ' . $days . ' day'),
$uid,
$contact_id,
$follow,
$view,
$read
);
while ($interaction = DBA::fetch($interactions)) { while ($interaction = DBA::fetch($interactions)) {
$score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535); $score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535);
DBA::update('contact-relation', ['thread-score' => $score], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]); DBA::update('contact-relation', ['thread-score' => $score], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]);
} }
DBA::close($interactions); DBA::close($interactions);
$total = DBA::fetchFirst("SELECT count(*) AS `posts` FROM `post-thread-user` WHERE EXISTS(SELECT `cid` FROM `contact-relation` WHERE `cid` = `post-thread-user`.`author-id` AND `relation-cid` = ? AND `follows`) AND `uid` = ? AND `created` > ?", $total = DBA::fetchFirst(
$contact_id, $uid, DateTimeFormat::utc('now - ' . $days . ' day')); "SELECT count(*) AS `posts` FROM `post-thread-user` WHERE EXISTS(SELECT `cid` FROM `contact-relation` WHERE `cid` = `post-thread-user`.`author-id` AND `relation-cid` = ? AND `follows`) AND `uid` = ? AND `created` > ?",
$contact_id,
$uid,
DateTimeFormat::utc('now - ' . $days . ' day')
);
Logger::debug('Calculate post-score', ['uid' => $uid, 'total' => $total['posts']]); DI::logger()->debug('Calculate post-score', ['uid' => $uid, 'total' => $total['posts']]);
$posts = DBA::p("SELECT `author-id`, count(*) AS `posts` FROM `post-thread-user` WHERE EXISTS(SELECT `cid` FROM `contact-relation` WHERE `cid` = `post-thread-user`.`author-id` AND `relation-cid` = ? AND `follows`) AND `uid` = ? AND `created` > ? GROUP BY `author-id`", $posts = DBA::p(
$contact_id, $uid, DateTimeFormat::utc('now - ' . $days . ' day')); "SELECT `author-id`, count(*) AS `posts` FROM `post-thread-user` WHERE EXISTS(SELECT `cid` FROM `contact-relation` WHERE `cid` = `post-thread-user`.`author-id` AND `relation-cid` = ? AND `follows`) AND `uid` = ? AND `created` > ? GROUP BY `author-id`",
$contact_id,
$uid,
DateTimeFormat::utc('now - ' . $days . ' day')
);
while ($post = DBA::fetch($posts)) { while ($post = DBA::fetch($posts)) {
$score = min((int)(($post['posts'] / $total['posts']) * 65535), 65535); $score = min((int)(($post['posts'] / $total['posts']) * 65535), 65535);
DBA::update('contact-relation', ['post-score' => $score], ['relation-cid' => $contact_id, 'cid' => $post['author-id']]); DBA::update('contact-relation', ['post-score' => $score], ['relation-cid' => $contact_id, 'cid' => $post['author-id']]);
} }
DBA::close($posts); DBA::close($posts);
Logger::debug('Calculation - end', ['uid' => $uid]); DI::logger()->debug('Calculation - end', ['uid' => $uid]);
} }
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Model\Contact; namespace Friendica\Model\Contact;
use Exception; use Exception;
use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -41,7 +40,7 @@ class User
} }
if (empty($contact['uri-id']) && empty($contact['url'])) { if (empty($contact['uri-id']) && empty($contact['url'])) {
Logger::info('Missing contact details', ['contact' => $contact]); DI::logger()->info('Missing contact details', ['contact' => $contact]);
return false; return false;
} }
@ -53,7 +52,7 @@ class User
if (!empty($contact['uri-id']) && DBA::isResult($pcontact)) { if (!empty($contact['uri-id']) && DBA::isResult($pcontact)) {
$pcid = $pcontact['id']; $pcid = $pcontact['id'];
} elseif (empty($contact['url']) || !($pcid = Contact::getIdForURL($contact['url'], 0, false))) { } elseif (empty($contact['url']) || !($pcid = Contact::getIdForURL($contact['url'], 0, false))) {
Logger::info('Public contact for user not found', ['uri-id' => $contact['uri-id'], 'uid' => $contact['uid']]); DI::logger()->info('Public contact for user not found', ['uri-id' => $contact['uri-id'], 'uid' => $contact['uid']]);
return false; return false;
} }
@ -64,7 +63,7 @@ class User
$ret = DBA::insert('user-contact', $fields, Database::INSERT_UPDATE); $ret = DBA::insert('user-contact', $fields, Database::INSERT_UPDATE);
Logger::info('Inserted user contact', ['uid' => $contact['uid'], 'cid' => $pcid, 'uri-id' => $contact['uri-id'], 'ret' => $ret]); DI::logger()->info('Inserted user contact', ['uid' => $contact['uid'], 'cid' => $pcid, 'uri-id' => $contact['uri-id'], 'ret' => $ret]);
return $ret; return $ret;
} }
@ -91,7 +90,7 @@ class User
} }
$update_fields['cid'] = $contact['pid']; $update_fields['cid'] = $contact['pid'];
$ret = DBA::update('user-contact', $update_fields, ['uri-id' => $contact['uri-id'], 'uid' => $contact['uid']], true); $ret = DBA::update('user-contact', $update_fields, ['uri-id' => $contact['uri-id'], 'uid' => $contact['uid']], true);
Logger::info('Updated user contact', ['uid' => $contact['uid'], 'id' => $contact['pid'], 'uri-id' => $contact['uri-id'], 'ret' => $ret]); DI::logger()->info('Updated user contact', ['uid' => $contact['uid'], 'id' => $contact['pid'], 'uri-id' => $contact['uri-id'], 'ret' => $ret]);
} }
DBA::close($contacts); DBA::close($contacts);

View file

@ -10,7 +10,6 @@ namespace Friendica\Model;
use Friendica\Content\Feature; use Friendica\Content\Feature;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -30,7 +29,6 @@ use Friendica\Util\XML;
*/ */
class Event class Event
{ {
public static function getHTML(array $event, bool $simple = false, int $uriid = 0): string public static function getHTML(array $event, bool $simple = false, int $uriid = 0): string
{ {
if (empty($event)) { if (empty($event)) {
@ -219,7 +217,7 @@ class Event
} }
DBA::delete('event', ['id' => $event_id]); DBA::delete('event', ['id' => $event_id]);
Logger::info("Deleted event", ['id' => $event_id]); DI::logger()->info("Deleted event", ['id' => $event_id]);
} }
/** /**
@ -655,7 +653,7 @@ class Event
$title = strip_tags(BBCode::convertForUriId($event['uri-id'], $event['summary'])); $title = strip_tags(BBCode::convertForUriId($event['uri-id'], $event['summary']));
if (!$title) { if (!$title) {
[$title, $_trash] = explode("<br", BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc'])), BBCode::TWITTER_API); list($title, $_trash) = explode("<br", BBCode::convertForUriId($event['uri-id'], Strings::escapeHtml($event['desc'])), BBCode::TWITTER_API);
} }
$event['author-link'] = Contact::magicLink($event['author-link']); $event['author-link'] = Contact::magicLink($event['author-link']);

View file

@ -10,7 +10,6 @@ namespace Friendica\Model;
use DOMDocument; use DOMDocument;
use DOMXPath; use DOMXPath;
use Exception; use Exception;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\Database; use Friendica\Database\Database;
@ -114,7 +113,7 @@ class GServer
$gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]); $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]);
if (DBA::isResult($gserver)) { if (DBA::isResult($gserver)) {
Logger::debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url]); DI::logger()->debug('Got ID for URL', ['id' => $gserver['id'], 'url' => $url]);
if (Network::isUrlBlocked($url)) { if (Network::isUrlBlocked($url)) {
self::setBlockedById($gserver['id']); self::setBlockedById($gserver['id']);
@ -336,7 +335,7 @@ class GServer
} }
if (Network::isUrlBlocked($server_url)) { if (Network::isUrlBlocked($server_url)) {
Logger::info('Server is blocked', ['url' => $server_url]); DI::logger()->info('Server is blocked', ['url' => $server_url]);
self::setBlockedByUrl($server_url); self::setBlockedByUrl($server_url);
return false; return false;
} }
@ -350,12 +349,12 @@ class GServer
} }
if (!$force && (strtotime($gserver['next_contact']) > time())) { if (!$force && (strtotime($gserver['next_contact']) > time())) {
Logger::info('No update needed', ['server' => $server_url]); DI::logger()->info('No update needed', ['server' => $server_url]);
return (!$gserver['failed']); return (!$gserver['failed']);
} }
Logger::info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]); DI::logger()->info('Server is outdated. Start discovery.', ['Server' => $server_url, 'Force' => $force]);
} else { } else {
Logger::info('Server is unknown. Start discovery.', ['Server' => $server_url]); DI::logger()->info('Server is unknown. Start discovery.', ['Server' => $server_url]);
} }
return self::detect($server_url, $network, $only_nodeinfo); return self::detect($server_url, $network, $only_nodeinfo);
@ -381,7 +380,7 @@ class GServer
$fields['network'] = $network; $fields['network'] = $network;
} }
self::update($fields, ['id' => $gsid]); self::update($fields, ['id' => $gsid]);
Logger::info('Reset failed status for server', ['url' => $gserver['url']]); DI::logger()->info('Reset failed status for server', ['url' => $gserver['url']]);
if (strtotime($gserver['next_contact']) < time()) { if (strtotime($gserver['next_contact']) < time()) {
UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']); UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
@ -403,7 +402,7 @@ class GServer
$gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]); $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]);
if (DBA::isResult($gserver) && !$gserver['failed']) { if (DBA::isResult($gserver) && !$gserver['failed']) {
self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]); self::update(['failed' => true, 'blocked' => Network::isUrlBlocked($gserver['url']), 'last_failure' => DateTimeFormat::utcNow()], ['id' => $gsid]);
Logger::info('Set failed status for server', ['url' => $gserver['url']]); DI::logger()->info('Set failed status for server', ['url' => $gserver['url']]);
if (strtotime($gserver['next_contact']) < time()) { if (strtotime($gserver['next_contact']) < time()) {
UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']); UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']);
@ -416,7 +415,7 @@ class GServer
$gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]); $gserver = DBA::selectFirst('gserver', ['url'], ["(`blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
if (DBA::isResult($gserver)) { if (DBA::isResult($gserver)) {
self::update(['blocked' => false], ['id' => $gsid]); self::update(['blocked' => false], ['id' => $gsid]);
Logger::info('Set unblocked status for server', ['url' => $gserver['url']]); DI::logger()->info('Set unblocked status for server', ['url' => $gserver['url']]);
} }
} }
@ -425,7 +424,7 @@ class GServer
$gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]); $gserver = DBA::selectFirst('gserver', ['url'], ["(NOT `blocked` OR `blocked` IS NULL) AND `id` = ?", $gsid]);
if (DBA::isResult($gserver)) { if (DBA::isResult($gserver)) {
self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]); self::update(['blocked' => true, 'failed' => true], ['id' => $gsid]);
Logger::info('Set blocked status for server', ['url' => $gserver['url']]); DI::logger()->info('Set blocked status for server', ['url' => $gserver['url']]);
} }
} }
@ -434,7 +433,7 @@ class GServer
$gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]); $gserver = DBA::selectFirst('gserver', ['url', 'id'], ["(NOT `blocked` OR `blocked` IS NULL) AND `nurl` = ?", Strings::normaliseLink($url)]);
if (DBA::isResult($gserver)) { if (DBA::isResult($gserver)) {
self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]); self::update(['blocked' => true, 'failed' => true], ['id' => $gserver['id']]);
Logger::info('Set blocked status for server', ['url' => $gserver['url']]); DI::logger()->info('Set blocked status for server', ['url' => $gserver['url']]);
} }
} }
@ -451,10 +450,12 @@ class GServer
$gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]); $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]);
if (DBA::isResult($gserver)) { if (DBA::isResult($gserver)) {
$next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']); $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']);
self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(), self::update(
['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(),
'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null], 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null],
['nurl' => $nurl]); ['nurl' => $nurl]
Logger::info('Set failed status for existing server', ['url' => $url]); );
DI::logger()->info('Set failed status for existing server', ['url' => $url]);
if (self::isDefunct($gserver)) { if (self::isDefunct($gserver)) {
self::archiveContacts($gserver['id']); self::archiveContacts($gserver['id']);
} }
@ -464,7 +465,7 @@ class GServer
self::insert(['url' => $url, 'nurl' => $nurl, self::insert(['url' => $url, 'nurl' => $nurl,
'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(), 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(),
'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]); 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]);
Logger::info('Set failed status for new server', ['url' => $url]); DI::logger()->info('Set failed status for new server', ['url' => $url]);
} }
/** /**
@ -493,7 +494,7 @@ class GServer
try { try {
return (string)self::cleanUri(new Uri($dirtyUrl)); return (string)self::cleanUri(new Uri($dirtyUrl));
} catch (\Throwable $e) { } catch (\Throwable $e) {
Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]); DI::logger()->warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]);
return ''; return '';
} }
} }
@ -533,14 +534,14 @@ class GServer
*/ */
private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool private static function detect(string $url, string $network = '', bool $only_nodeinfo = false): bool
{ {
Logger::info('Detect server type', ['server' => $url]); DI::logger()->info('Detect server type', ['server' => $url]);
$original_url = $url; $original_url = $url;
// Remove URL content that is not supposed to exist for a server url // Remove URL content that is not supposed to exist for a server url
$url = rtrim(self::cleanURL($url), '/'); $url = rtrim(self::cleanURL($url), '/');
if (empty($url)) { if (empty($url)) {
Logger::notice('Empty URL.'); DI::logger()->notice('Empty URL.');
return false; return false;
} }
@ -566,7 +567,7 @@ class GServer
// Some systems have got redirects on their landing page to a single account page. This check handles it. // Some systems have got redirects on their landing page to a single account page. This check handles it.
if (((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH))) || if (((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) == parse_url($valid_url, PHP_URL_PATH))) ||
(((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) || (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH))) && empty(parse_url($valid_url, PHP_URL_PATH)))) { (((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) || (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH))) && empty(parse_url($valid_url, PHP_URL_PATH)))) {
Logger::debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]); DI::logger()->debug('Found redirect. Mark old entry as failure', ['old' => $url, 'new' => $valid_url]);
self::setFailureByUrl($url); self::setFailureByUrl($url);
if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) { if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) {
self::detect($valid_url, $network, $only_nodeinfo); self::detect($valid_url, $network, $only_nodeinfo);
@ -576,7 +577,7 @@ class GServer
if ((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH)) && if ((parse_url($url, PHP_URL_HOST) != parse_url($valid_url, PHP_URL_HOST)) && (parse_url($url, PHP_URL_PATH) != parse_url($valid_url, PHP_URL_PATH)) &&
(parse_url($url, PHP_URL_PATH) == '')) { (parse_url($url, PHP_URL_PATH) == '')) {
Logger::debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]); DI::logger()->debug('Found redirect. Mark old entry as failure and redirect to the basepath.', ['old' => $url, 'new' => $valid_url]);
$parts = (array)parse_url($valid_url); $parts = (array)parse_url($valid_url);
unset($parts['path']); unset($parts['path']);
$valid_url = (string)Uri::fromParts($parts); $valid_url = (string)Uri::fromParts($parts);
@ -587,7 +588,7 @@ class GServer
} }
return false; return false;
} }
Logger::debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]); DI::logger()->debug('Found redirect, but ignore it.', ['old' => $url, 'new' => $valid_url]);
} }
if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) && if ((parse_url($url, PHP_URL_HOST) == parse_url($valid_url, PHP_URL_HOST)) &&
@ -617,7 +618,7 @@ class GServer
} }
if ($only_nodeinfo && empty($serverdata)) { if ($only_nodeinfo && empty($serverdata)) {
Logger::info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]); DI::logger()->info('Invalid nodeinfo in nodeinfo-mode, server is marked as failure', ['url' => $url]);
self::setFailureByUrl($url); self::setFailureByUrl($url);
return false; return false;
} elseif (empty($serverdata)) { } elseif (empty($serverdata)) {
@ -804,6 +805,7 @@ class GServer
$gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]); $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]);
if (!DBA::isResult($gserver)) { if (!DBA::isResult($gserver)) {
$serverdata['created'] = DateTimeFormat::utcNow(); $serverdata['created'] = DateTimeFormat::utcNow();
$ret = self::insert($serverdata); $ret = self::insert($serverdata);
$id = DBA::lastInsertId(); $id = DBA::lastInsertId();
} else { } else {
@ -820,14 +822,14 @@ class GServer
$contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]); $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]);
$max_users = max($apcontacts, $contacts); $max_users = max($apcontacts, $contacts);
if ($max_users > $serverdata['registered-users']) { if ($max_users > $serverdata['registered-users']) {
Logger::info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]); DI::logger()->info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]);
self::update(['registered-users' => $max_users], ['id' => $id]); self::update(['registered-users' => $max_users], ['id' => $id]);
} }
if (empty($serverdata['active-month-users'])) { if (empty($serverdata['active-month-users'])) {
$contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]); $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 30 days')]);
if ($contacts > 0) { if ($contacts > 0) {
Logger::info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]); DI::logger()->info('Update monthly users', ['id' => $id, 'url' => $serverdata['nurl'], 'monthly-users' => $contacts]);
self::update(['active-month-users' => $contacts], ['id' => $id]); self::update(['active-month-users' => $contacts], ['id' => $id]);
} }
} }
@ -835,7 +837,7 @@ class GServer
if (empty($serverdata['active-halfyear-users'])) { if (empty($serverdata['active-halfyear-users'])) {
$contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]); $contacts = DBA::count('contact', ["`uid` = ? AND `gsid` = ? AND NOT `failed` AND `last-item` > ?", 0, $id, DateTimeFormat::utc('now - 180 days')]);
if ($contacts > 0) { if ($contacts > 0) {
Logger::info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]); DI::logger()->info('Update halfyear users', ['id' => $id, 'url' => $serverdata['nurl'], 'halfyear-users' => $contacts]);
self::update(['active-halfyear-users' => $contacts], ['id' => $id]); self::update(['active-halfyear-users' => $contacts], ['id' => $id]);
} }
} }
@ -847,7 +849,7 @@ class GServer
if (!empty($systemactor)) { if (!empty($systemactor)) {
$contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']); $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']);
Logger::debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]); DI::logger()->debug('Fetched system actor', ['url' => $url, 'gsid' => $id, 'contact' => $contact]);
} }
return $ret; return $ret;
@ -864,7 +866,7 @@ class GServer
*/ */
private static function discoverRelay(string $server_url) private static function discoverRelay(string $server_url)
{ {
Logger::info('Discover relay data', ['server' => $server_url]); DI::logger()->info('Discover relay data', ['server' => $server_url]);
$curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); $curlResult = DI::httpClient()->get($server_url . '/.well-known/x-social-relay', HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]);
if (!$curlResult->isSuccess()) { if (!$curlResult->isSuccess()) {
@ -947,7 +949,7 @@ class GServer
} }
} }
Logger::info('Discovery ended', ['server' => $server_url, 'data' => $fields]); DI::logger()->info('Discovery ended', ['server' => $server_url, 'data' => $fields]);
Relay::updateContact($gserver, $fields); Relay::updateContact($gserver, $fields);
} }
@ -983,6 +985,7 @@ class GServer
if (!empty($data['version'])) { if (!empty($data['version'])) {
$valid = true; $valid = true;
$serverdata['version'] = $data['version']; $serverdata['version'] = $data['version'];
// Version numbers on statistics.json are presented with additional info, e.g.: // Version numbers on statistics.json are presented with additional info, e.g.:
// 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191. // 0.6.3.0-p1702cc1c, 0.6.99.0-p1b9ab160 or 3.4.3-2-1191.
@ -991,11 +994,13 @@ class GServer
if (!empty($data['name'])) { if (!empty($data['name'])) {
$valid = true; $valid = true;
$serverdata['site_name'] = $data['name']; $serverdata['site_name'] = $data['name'];
} }
if (!empty($data['network'])) { if (!empty($data['network'])) {
$valid = true; $valid = true;
$serverdata['platform'] = strtolower($data['network']); $serverdata['platform'] = strtolower($data['network']);
if ($serverdata['platform'] == 'diaspora') { if ($serverdata['platform'] == 'diaspora') {
@ -1011,21 +1016,25 @@ class GServer
if (!empty($data['total_users'])) { if (!empty($data['total_users'])) {
$valid = true; $valid = true;
$serverdata['registered-users'] = max($data['total_users'], 1); $serverdata['registered-users'] = max($data['total_users'], 1);
} }
if (!empty($data['active_users_monthly'])) { if (!empty($data['active_users_monthly'])) {
$valid = true; $valid = true;
$serverdata['active-month-users'] = max($data['active_users_monthly'], 0); $serverdata['active-month-users'] = max($data['active_users_monthly'], 0);
} }
if (!empty($data['active_users_halfyear'])) { if (!empty($data['active_users_halfyear'])) {
$valid = true; $valid = true;
$serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0); $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0);
} }
if (!empty($data['local_posts'])) { if (!empty($data['local_posts'])) {
$valid = true; $valid = true;
$serverdata['local-posts'] = max($data['local_posts'], 0); $serverdata['local-posts'] = max($data['local_posts'], 0);
} }
@ -1072,7 +1081,7 @@ class GServer
foreach ($nodeinfo['links'] as $link) { foreach ($nodeinfo['links'] as $link) {
if (!is_array($link) || empty($link['rel']) || empty($link['href'])) { if (!is_array($link) || empty($link['rel']) || empty($link['href'])) {
Logger::info('Invalid nodeinfo format', ['url' => $url]); DI::logger()->info('Invalid nodeinfo format', ['url' => $url]);
continue; continue;
} }
@ -1829,8 +1838,7 @@ class GServer
} }
if (!empty($data['totalResults'])) { if (!empty($data['totalResults'])) {
$registeredUsers = $serverdata['registered-users'] ?? 0; $serverdata['registered-users'] = max($data['totalResults'], $serverdata['registered-users'] ?? 0, 1);
$serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1);
$serverdata['directory-type'] = self::DT_POCO; $serverdata['directory-type'] = self::DT_POCO;
$serverdata['poco'] = $url . '/poco'; $serverdata['poco'] = $url . '/poco';
} }
@ -2015,6 +2023,7 @@ class GServer
$serverdata['platform'] = 'mastodon'; $serverdata['platform'] = 'mastodon';
$serverdata['version'] = $data['version'] ?? ''; $serverdata['version'] = $data['version'] ?? '';
$serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['network'] = Protocol::ACTIVITYPUB;
$valid = true; $valid = true;
} }
@ -2025,6 +2034,7 @@ class GServer
if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) { if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) {
$serverdata['platform'] = 'mastodon'; $serverdata['platform'] = 'mastodon';
$serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['network'] = Protocol::ACTIVITYPUB;
$valid = true; $valid = true;
} }
@ -2039,18 +2049,21 @@ class GServer
if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) { if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) {
$serverdata['platform'] = strtolower($matches[1]); $serverdata['platform'] = strtolower($matches[1]);
$serverdata['version'] = $matches[2]; $serverdata['version'] = $matches[2];
$valid = true; $valid = true;
} }
if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) { if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) {
$serverdata['platform'] = 'pleroma'; $serverdata['platform'] = 'pleroma';
$serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version']));
$valid = true; $valid = true;
} }
if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) { if (!empty($serverdata['platform']) && strstr($serverdata['platform'], 'pleroma')) {
$serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform'])); $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['platform']));
$serverdata['platform'] = 'pleroma'; $serverdata['platform'] = 'pleroma';
$valid = true; $valid = true;
} }
@ -2277,7 +2290,7 @@ class GServer
$serverdata['register_policy'] = Register::CLOSED; $serverdata['register_policy'] = Register::CLOSED;
break; break;
default: default:
Logger::info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]); DI::logger()->info('Register policy is invalid', ['policy' => $register_policy, 'server' => $url]);
$serverdata['register_policy'] = Register::CLOSED; $serverdata['register_policy'] = Register::CLOSED;
break; break;
} }
@ -2318,12 +2331,14 @@ class GServer
$doc = new DOMDocument(); $doc = new DOMDocument();
@$doc->loadHTML($curlResult->getBodyString()); @$doc->loadHTML($curlResult->getBodyString());
$xpath = new DOMXPath($doc); $xpath = new DOMXPath($doc);
$assigned = false; $assigned = false;
// We can only detect honk via some HTML element on their page // We can only detect honk via some HTML element on their page
if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) { if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) {
$serverdata['platform'] = 'honk'; $serverdata['platform'] = 'honk';
$serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['network'] = Protocol::ACTIVITYPUB;
$assigned = true; $assigned = true;
} }
@ -2359,9 +2374,11 @@ class GServer
'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) { 'twitter:app:name:googleplay', 'twitter:app:name:iphone', 'twitter:app:name:ipad', 'generator'])) {
$platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']); $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']);
$platform = str_replace('/', ' ', $platform); $platform = str_replace('/', ' ', $platform);
$platform_parts = explode(' ', $platform); $platform_parts = explode(' ', $platform);
if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) { if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) {
$platform = $platform_parts[0]; $platform = $platform_parts[0];
$serverdata['version'] = $platform_parts[1]; $serverdata['version'] = $platform_parts[1];
} }
if (in_array($platform, array_values($grouped_platforms['dfrn_platforms']))) { if (in_array($platform, array_values($grouped_platforms['dfrn_platforms']))) {
@ -2373,6 +2390,7 @@ class GServer
} }
if (in_array($platform, array_values($platforms))) { if (in_array($platform, array_values($platforms))) {
$serverdata['platform'] = $platform; $serverdata['platform'] = $platform;
$assigned = true; $assigned = true;
} }
} }
@ -2408,6 +2426,7 @@ class GServer
if (in_array($attr['property'], ['og:platform', 'generator'])) { if (in_array($attr['property'], ['og:platform', 'generator'])) {
if (in_array($attr['content'], array_keys($platforms))) { if (in_array($attr['content'], array_keys($platforms))) {
$serverdata['platform'] = $platforms[$attr['content']]; $serverdata['platform'] = $platforms[$attr['content']];
$assigned = true; $assigned = true;
} }
@ -2426,6 +2445,7 @@ class GServer
$serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
$serverdata['platform'] = 'microblog'; $serverdata['platform'] = 'microblog';
$serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['network'] = Protocol::ACTIVITYPUB;
$assigned = true; $assigned = true;
} }
} }
@ -2439,6 +2459,7 @@ class GServer
$serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']);
$serverdata['platform'] = 'microblog'; $serverdata['platform'] = 'microblog';
$serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['network'] = Protocol::ACTIVITYPUB;
$assigned = true; $assigned = true;
} }
} }
@ -2489,10 +2510,6 @@ class GServer
*/ */
public static function discover() public static function discover()
{ {
if (!DI::config()->get('system', 'discover_servers')) {
return;
}
// Update the server list // Update the server list
self::discoverFederation(); self::discoverFederation();
@ -2502,15 +2519,18 @@ class GServer
$last_update = date('c', time() - (60 * 60 * 24 * $requery_days)); $last_update = date('c', time() - (60 * 60 * 24 * $requery_days));
$gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'network', 'poco', 'directory-type'], $gservers = DBA::select(
'gserver',
['id', 'url', 'nurl', 'network', 'poco', 'directory-type'],
["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update], ["NOT `blocked` AND NOT `failed` AND `directory-type` != ? AND `last_poco_query` < ?", GServer::DT_NONE, $last_update],
['order' => ['RAND()']]); ['order' => ['RAND()']]
);
while ($gserver = DBA::fetch($gservers)) { while ($gserver = DBA::fetch($gservers)) {
Logger::info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]); DI::logger()->info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]);
Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']); Worker::add(Worker::PRIORITY_LOW, 'UpdateServerPeers', $gserver['url']);
Logger::info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]); DI::logger()->info('Update directory', ['server' => $gserver['url'], 'id' => $gserver['id']]);
Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver); Worker::add(Worker::PRIORITY_LOW, 'UpdateServerDirectory', $gserver);
$fields = ['last_poco_query' => DateTimeFormat::utcNow()]; $fields = ['last_poco_query' => DateTimeFormat::utcNow()];
@ -2651,7 +2671,7 @@ class GServer
} }
} }
Logger::info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url']]); DI::logger()->info('Protocol for server', ['protocol' => $protocol, 'old' => $old, 'id' => $gsid, 'url' => $gserver['url']]);
self::update(['protocol' => $protocol], ['id' => $gsid]); self::update(['protocol' => $protocol], ['id' => $gsid]);
} }

View file

@ -16,7 +16,6 @@ use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\System; use Friendica\Core\System;
@ -215,7 +214,7 @@ class Item
return $rows; return $rows;
} }
Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]); DI::logger()->info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
$items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition); $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network', 'quote-uri-id'], $condition);
@ -236,7 +235,7 @@ class Item
if ($item['origin'] && empty($item['quote-uri-id'])) { if ($item['origin'] && empty($item['quote-uri-id'])) {
$quote_id = Post\Media::getActivityUriId($item['uri-id']); $quote_id = Post\Media::getActivityUriId($item['uri-id']);
if (!empty($quote_id)) { if (!empty($quote_id)) {
Logger::notice('Found attached post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]); DI::logger()->notice('Found attached post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
$content_fields['quote-uri-id'] = $quote_id; $content_fields['quote-uri-id'] = $quote_id;
} }
} }
@ -332,7 +331,7 @@ class Item
if ($item['uid'] == $uid) { if ($item['uid'] == $uid) {
self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH); self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH);
} elseif ($item['uid'] != 0) { } elseif ($item['uid'] != 0) {
Logger::warning('Wrong ownership. Not deleting item', ['id' => $item['id']]); DI::logger()->warning('Wrong ownership. Not deleting item', ['id' => $item['id']]);
} }
} }
DBA::close($items); DBA::close($items);
@ -348,7 +347,7 @@ class Item
*/ */
public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool public static function markForDeletionById(int $item_id, int $priority = Worker::PRIORITY_HIGH): bool
{ {
Logger::info('Mark item for deletion by id', ['id' => $item_id]); DI::logger()->info('Mark item for deletion by id', ['id' => $item_id]);
// locate item to be deleted // locate item to be deleted
$fields = [ $fields = [
'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin', 'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
@ -357,12 +356,12 @@ class Item
]; ];
$item = Post::selectFirst($fields, ['id' => $item_id]); $item = Post::selectFirst($fields, ['id' => $item_id]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
Logger::info('Item not found.', ['id' => $item_id]); DI::logger()->info('Item not found.', ['id' => $item_id]);
return false; return false;
} }
if ($item['deleted']) { if ($item['deleted']) {
Logger::info('Item has already been marked for deletion.', ['id' => $item_id]); DI::logger()->info('Item has already been marked for deletion.', ['id' => $item_id]);
return false; return false;
} }
@ -444,7 +443,7 @@ class Item
Post\Counts::update($item['thr-parent-id'], $item['parent-uri-id'], $item['vid'], $item['verb'], $item['body']); Post\Counts::update($item['thr-parent-id'], $item['parent-uri-id'], $item['vid'], $item['verb'], $item['body']);
} }
Logger::info('Item has been marked for deletion.', ['id' => $item_id]); DI::logger()->info('Item has been marked for deletion.', ['id' => $item_id]);
return true; return true;
} }
@ -554,7 +553,7 @@ class Item
return $contact_id; return $contact_id;
} }
Logger::warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]); DI::logger()->warning('contact-id could not be fetched, using self contact instead.', ['uid' => $item['uid'], 'item' => $item]);
$self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]); $self = Contact::selectFirst(['id'], ['self' => true, 'uid' => $item['uid']]);
return $self['id']; return $self['id'];
} }
@ -577,7 +576,7 @@ class Item
$spool = $spoolpath . '/' . $file; $spool = $spoolpath . '/' . $file;
file_put_contents($spool, json_encode($item)); file_put_contents($spool, json_encode($item));
Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]); DI::logger()->warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
} }
} }
@ -592,7 +591,7 @@ class Item
// Checking if there is already an item with the same guid // Checking if there is already an item with the same guid
$condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']]; $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
if (Post::exists($condition)) { if (Post::exists($condition)) {
Logger::notice('Found already existing item', $condition); DI::logger()->notice('Found already existing item', $condition);
return true; return true;
} }
@ -601,7 +600,7 @@ class Item
'network' => [$item['network'], Protocol::DFRN] 'network' => [$item['network'], Protocol::DFRN]
]; ];
if (Post::exists($condition)) { if (Post::exists($condition)) {
Logger::notice('duplicated item with the same uri found.', $condition); DI::logger()->notice('duplicated item with the same uri found.', $condition);
return true; return true;
} }
@ -609,7 +608,7 @@ class Item
if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) { if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
$condition = ['guid' => $item['guid'], 'uid' => $item['uid']]; $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
if (Post::exists($condition)) { if (Post::exists($condition)) {
Logger::notice('duplicated item with the same guid found.', $condition); DI::logger()->notice('duplicated item with the same guid found.', $condition);
return true; return true;
} }
} }
@ -620,7 +619,7 @@ class Item
* An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this. * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
*/ */
if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) { if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]); DI::logger()->notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
return true; return true;
} }
@ -637,47 +636,47 @@ class Item
{ {
// When there is no content then we don't post it // When there is no content then we don't post it
if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) { if (($item['body'] . $item['title'] == '') && empty($item['quote-uri-id']) && empty($item['attachments']) && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
Logger::notice('No body, no title.'); DI::logger()->notice('No body, no title.');
return false; return false;
} }
if (!empty($item['uid'])) { if (!empty($item['uid'])) {
$owner = User::getOwnerDataById($item['uid'], false); $owner = User::getOwnerDataById($item['uid'], false);
if (!$owner) { if (!$owner) {
Logger::warning('Missing item user owner data', ['uid' => $item['uid']]); DI::logger()->warning('Missing item user owner data', ['uid' => $item['uid']]);
return false; return false;
} }
if ($owner['account_expired'] || $owner['account_removed']) { if ($owner['account_expired'] || $owner['account_removed']) {
Logger::notice('Item user has been deleted/expired/removed', ['uid' => $item['uid'], 'deleted' => $owner['deleted'], 'account_expired' => $owner['account_expired'], 'account_removed' => $owner['account_removed']]); DI::logger()->notice('Item user has been deleted/expired/removed', ['uid' => $item['uid'], 'deleted' => $owner['deleted'], 'account_expired' => $owner['account_expired'], 'account_removed' => $owner['account_removed']]);
return false; return false;
} }
} }
if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) { if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]); DI::logger()->notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
return false; return false;
} }
if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) { if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]); DI::logger()->notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
return false; return false;
} }
if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) { if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]); DI::logger()->notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
return false; return false;
} }
if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) { if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]); DI::logger()->notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
return false; return false;
} }
if ($item['verb'] == Activity::FOLLOW) { if ($item['verb'] == Activity::FOLLOW) {
if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) { if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
// Our own follow request can be relayed to us. We don't store it to avoid notification chaos. // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]); DI::logger()->info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
return false; return false;
} }
@ -687,7 +686,7 @@ class Item
]; ];
if (Post::exists($condition)) { if (Post::exists($condition)) {
// It happens that we receive multiple follow requests by the same author - we only store one. // It happens that we receive multiple follow requests by the same author - we only store one.
Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]); DI::logger()->info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
return false; return false;
} }
} }
@ -716,7 +715,7 @@ class Item
if (DBA::isResult($existing)) { if (DBA::isResult($existing)) {
// We only log the entries with a different user id than 0. Otherwise we would have too many false positives // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
if ($item['uid'] != 0) { if ($item['uid'] != 0) {
Logger::notice('Item already existed for user', [ DI::logger()->notice('Item already existed for user', [
'uri-id' => $item['uri-id'], 'uri-id' => $item['uri-id'],
'uid' => $item['uid'], 'uid' => $item['uid'],
'network' => $item['network'], 'network' => $item['network'],
@ -776,18 +775,18 @@ class Item
$stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]); $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
} }
if ($stored) { if ($stored) {
Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]); DI::logger()->info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
$parent = Post::selectFirst($fields, $condition, $params); $parent = Post::selectFirst($fields, $condition, $params);
} }
} }
if (!DBA::isResult($parent)) { if (!DBA::isResult($parent)) {
Logger::notice('item parent was not found - ignoring item', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]); DI::logger()->notice('item parent was not found - ignoring item', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
return []; return [];
} }
if (self::hasRestrictions($item, $parent['author-id'], $parent['restrictions'])) { if (self::hasRestrictions($item, $parent['author-id'], $parent['restrictions'])) {
Logger::notice('Restrictions apply - ignoring item', ['restrictions' => $parent['restrictions'], 'verb' => $parent['verb'], 'uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]); DI::logger()->notice('Restrictions apply - ignoring item', ['restrictions' => $parent['restrictions'], 'verb' => $parent['verb'], 'uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
return []; return [];
} }
@ -805,12 +804,12 @@ class Item
if (!DBA::isResult($toplevel_parent) && $item['origin']) { if (!DBA::isResult($toplevel_parent) && $item['origin']) {
$stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]); $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]); DI::logger()->info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
$toplevel_parent = Post::selectFirst($fields, $condition, $params); $toplevel_parent = Post::selectFirst($fields, $condition, $params);
} }
if (!DBA::isResult($toplevel_parent)) { if (!DBA::isResult($toplevel_parent)) {
Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]); DI::logger()->notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
return []; return [];
} }
@ -839,7 +838,7 @@ class Item
return self::GRAVITY_ACTIVITY; return self::GRAVITY_ACTIVITY;
} }
Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]); DI::logger()->info('Unknown gravity for verb', ['verb' => $item['verb']]);
return self::GRAVITY_UNKNOWN; // Should not happen return self::GRAVITY_UNKNOWN; // Should not happen
} }
@ -971,7 +970,7 @@ class Item
if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) { if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
$user = User::getById($uid, ['account-type']); $user = User::getById($uid, ['account-type']);
if ($user['account-type'] == Contact::TYPE_COMMUNITY) { if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
Logger::info('Community posts are not supported via Diaspora'); DI::logger()->info('Community posts are not supported via Diaspora');
return 0; return 0;
} }
} }
@ -1014,7 +1013,7 @@ class Item
!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) && !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
empty($item['origin']) && DI::contentItem()->isTooOld($item['created'], $item['uid']) empty($item['origin']) && DI::contentItem()->isTooOld($item['created'], $item['uid'])
) { ) {
Logger::info('Item is too old', ['item' => $item]); DI::logger()->info('Item is too old', ['item' => $item]);
return 0; return 0;
} }
@ -1067,7 +1066,7 @@ class Item
// If its a post that originated here then tag the thread as "mention" // If its a post that originated here then tag the thread as "mention"
if ($item['origin'] && $item['uid']) { if ($item['origin'] && $item['uid']) {
DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]); DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]); DI::logger()->info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
} }
// Update the contact relations // Update the contact relations
@ -1149,7 +1148,7 @@ class Item
} }
if (!empty($item['cancel'])) { if (!empty($item['cancel'])) {
Logger::notice('post cancelled by addon.'); DI::logger()->notice('post cancelled by addon.');
return 0; return 0;
} }
@ -1193,13 +1192,13 @@ class Item
if (!empty($quote_id)) { if (!empty($quote_id)) {
// This is one of these "should not happen" situations. // This is one of these "should not happen" situations.
// The protocol implementations should already have done this job. // The protocol implementations should already have done this job.
Logger::notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]); DI::logger()->notice('Quote-uri-id detected in post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
$item['quote-uri-id'] = $quote_id; $item['quote-uri-id'] = $quote_id;
} }
} }
if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] == $item['uri-id'])) { if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] == $item['uri-id'])) {
Logger::info('Quote-Uri-Id is identical to Uri-Id', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->info('Quote-Uri-Id is identical to Uri-Id', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
unset($item['quote-uri-id']); unset($item['quote-uri-id']);
} }
@ -1232,7 +1231,7 @@ class Item
if ($item['origin'] && empty($item['quote-uri-id'])) { if ($item['origin'] && empty($item['quote-uri-id'])) {
$quote_id = Post\Media::getActivityUriId($item['uri-id']); $quote_id = Post\Media::getActivityUriId($item['uri-id']);
if (!empty($quote_id)) { if (!empty($quote_id)) {
Logger::notice('Found attached post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]); DI::logger()->notice('Found attached post', ['id' => $quote_id, 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
$item['quote-uri-id'] = $quote_id; $item['quote-uri-id'] = $quote_id;
} }
} }
@ -1242,7 +1241,7 @@ class Item
$ev = Event::fromBBCode($item['body']); $ev = Event::fromBBCode($item['body']);
if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) { if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
Logger::info('Event found.'); DI::logger()->info('Event found.');
$ev['cid'] = $item['contact-id']; $ev['cid'] = $item['contact-id'];
$ev['uid'] = $item['uid']; $ev['uid'] = $item['uid'];
$ev['uri'] = $item['uri']; $ev['uri'] = $item['uri'];
@ -1263,7 +1262,7 @@ class Item
$event_id = Event::store($ev); $event_id = Event::store($ev);
$item = Event::getItemArrayForImportedId($event_id, $item); $item = Event::getItemArrayForImportedId($event_id, $item);
Logger::info('Event was stored', ['id' => $event_id]); DI::logger()->info('Event was stored', ['id' => $event_id]);
} }
} }
@ -1328,13 +1327,13 @@ class Item
$condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']]; $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
if (Post::exists($condition)) { if (Post::exists($condition)) {
Logger::notice('Item is already inserted - aborting', $condition); DI::logger()->notice('Item is already inserted - aborting', $condition);
return 0; return 0;
} }
$post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item); $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
if (!$post_user_id) { if (!$post_user_id) {
Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]); DI::logger()->notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
return 0; return 0;
} }
@ -1343,12 +1342,12 @@ class Item
Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item); Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
} }
Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
$posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]); $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
if (!DBA::isResult($posted_item)) { if (!DBA::isResult($posted_item)) {
// On failure store the data into a spool file so that the "SpoolPost" worker can try again later. // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]); DI::logger()->warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
self::spool($orig_item); self::spool($orig_item);
return 0; return 0;
} }
@ -1385,7 +1384,7 @@ class Item
// Get the user information for the logging // Get the user information for the logging
$user = User::getById($uid); $user = User::getById($uid);
Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]); DI::logger()->notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
return 0; return 0;
} }
@ -1418,15 +1417,15 @@ class Item
if ($transmit) { if ($transmit) {
if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) { if ($posted_item['uid'] && Contact\User::isBlocked($posted_item['author-id'], $posted_item['uid'])) {
Logger::info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]); DI::logger()->info('Message from blocked author will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['author-id']]);
$transmit = false; $transmit = false;
} }
if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) { if ($transmit && $posted_item['uid'] && Contact\User::isBlocked($posted_item['owner-id'], $posted_item['uid'])) {
Logger::info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]); DI::logger()->info('Message from blocked owner will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['owner-id']]);
$transmit = false; $transmit = false;
} }
if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) { if ($transmit && !empty($posted_item['causer-id']) && $posted_item['uid'] && Contact\User::isBlocked($posted_item['causer-id'], $posted_item['uid'])) {
Logger::info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]); DI::logger()->info('Message from blocked causer will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'cid' => $posted_item['causer-id']]);
$transmit = false; $transmit = false;
} }
@ -1434,7 +1433,7 @@ class Item
if (($posted_item['verb'] == Activity::FOLLOW) && if (($posted_item['verb'] == Activity::FOLLOW) &&
(!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid))) (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))
) { ) {
Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]); DI::logger()->info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
$transmit = false; $transmit = false;
} }
} }
@ -1520,25 +1519,25 @@ class Item
$item = Post::selectFirst(['id', 'private', 'network', 'language', 'owner-id'], ['uri-id' => $uri_id, 'uid' => 0]); $item = Post::selectFirst(['id', 'private', 'network', 'language', 'owner-id'], ['uri-id' => $uri_id, 'uid' => 0]);
if (empty($item['id'])) { if (empty($item['id'])) {
Logger::debug('Post not found', ['uri-id' => $uri_id]); DI::logger()->debug('Post not found', ['uri-id' => $uri_id]);
return; return;
} }
if (($item['private'] != self::PUBLIC) || !in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) { if (($item['private'] != self::PUBLIC) || !in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
Logger::debug('Not a public post or no AP or DFRN post', ['uri-id' => $uri_id]); DI::logger()->debug('Not a public post or no AP or DFRN post', ['uri-id' => $uri_id]);
return; return;
} }
$engagement = DBA::selectFirst('post-engagement', ['searchtext', 'media-type'], ['uri-id' => $uri_id]); $engagement = DBA::selectFirst('post-engagement', ['searchtext', 'media-type'], ['uri-id' => $uri_id]);
if (empty($engagement['searchtext'])) { if (empty($engagement['searchtext'])) {
Logger::debug('No engagement found', ['uri-id' => $uri_id]); DI::logger()->debug('No engagement found', ['uri-id' => $uri_id]);
return; return;
} }
$language = !empty($item['language']) ? array_key_first(json_decode($item['language'], true)) : ''; $language = !empty($item['language']) ? array_key_first(json_decode($item['language'], true)) : '';
$tags = array_column(Tag::getByURIId($uri_id, [Tag::HASHTAG]), 'name'); $tags = array_column(Tag::getByURIId($uri_id, [Tag::HASHTAG]), 'name');
Logger::debug('Prepare check', ['uri-id' => $uri_id, 'language' => $language, 'tags' => $tags, 'searchtext' => $engagement['searchtext'], 'media_type' => $engagement['media-type'], 'owner' => $item['owner-id'], 'reshare' => $reshare_id]); DI::logger()->debug('Prepare check', ['uri-id' => $uri_id, 'language' => $language, 'tags' => $tags, 'searchtext' => $engagement['searchtext'], 'media_type' => $engagement['media-type'], 'owner' => $item['owner-id'], 'reshare' => $reshare_id]);
$count = 0; $count = 0;
foreach (DI::userDefinedChannel()->getMatchingChannelUsers($engagement['searchtext'], $language, $tags, $engagement['media-type'], $item['owner-id'], $reshare_id) as $uid) { foreach (DI::userDefinedChannel()->getMatchingChannelUsers($engagement['searchtext'], $language, $tags, $engagement['media-type'], $item['owner-id'], $reshare_id) as $uid) {
@ -1547,19 +1546,19 @@ class Item
'author-id' => Contact::getPublicIdByUserId($uid), 'uid' => $uid, 'thr-parent-id' => $uri_id 'author-id' => Contact::getPublicIdByUserId($uid), 'uid' => $uid, 'thr-parent-id' => $uri_id
]; ];
if (!Post::exists($condition)) { if (!Post::exists($condition)) {
Logger::debug('Reshare post', ['uid' => $uid, 'uri-id' => $uri_id]); DI::logger()->debug('Reshare post', ['uid' => $uid, 'uri-id' => $uri_id]);
$allow_cid = ''; $allow_cid = '';
$allow_gid = '<' . Circle::FOLLOWERS . '>'; $allow_gid = '<' . Circle::FOLLOWERS . '>';
$deny_cid = ''; $deny_cid = '';
$deny_gid = ''; $deny_gid = '';
self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid); self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
} else { } else {
Logger::debug('Reshare already exists', ['uid' => $uid, 'uri-id' => $uri_id]); DI::logger()->debug('Reshare already exists', ['uid' => $uid, 'uri-id' => $uri_id]);
} }
$count++; $count++;
} }
Logger::debug('Check done', ['uri-id' => $uri_id, 'count' => $count]); DI::logger()->debug('Check done', ['uri-id' => $uri_id, 'count' => $count]);
} }
/** /**
@ -1622,13 +1621,13 @@ class Item
['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']] ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]
); );
if (!DBA::isResult($parent)) { if (!DBA::isResult($parent)) {
Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]); DI::logger()->error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
return; return;
} }
$author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]); $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
if (!DBA::isResult($author)) { if (!DBA::isResult($author)) {
Logger::error('Author not found', ['id' => $item['author-id']]); DI::logger()->error('Author not found', ['id' => $item['author-id']]);
return; return;
} }
@ -1637,24 +1636,24 @@ class Item
$cid = Contact::getIdForURL($author['url'], $item['uid']); $cid = Contact::getIdForURL($author['url'], $item['uid']);
if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) { if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]); DI::logger()->info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
return; return;
} }
if ($author['contact-type'] != Contact::TYPE_COMMUNITY) { if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) { if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
Logger::info('The parent is already marked as announced: quit', ['causer' => $parent['causer-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]); DI::logger()->info('The parent is already marked as announced: quit', ['causer' => $parent['causer-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
return; return;
} }
if (Contact::isSharing($parent['owner-id'], $item['uid'])) { if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
Logger::info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]); DI::logger()->info('The resharer is no group: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
return; return;
} }
} }
self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]); self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]); DI::logger()->info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
} }
/** /**
@ -1680,18 +1679,18 @@ class Item
} }
} }
if ($keep) { if ($keep) {
Logger::debug('Wanted languages found', ['uid' => $uid, 'user-languages' => $user_languages, 'item-languages' => $languages]); DI::logger()->debug('Wanted languages found', ['uid' => $uid, 'user-languages' => $user_languages, 'item-languages' => $languages]);
} else { } else {
Logger::debug('No wanted languages found', ['uid' => $uid, 'user-languages' => $user_languages, 'item-languages' => $languages]); DI::logger()->debug('No wanted languages found', ['uid' => $uid, 'user-languages' => $user_languages, 'item-languages' => $languages]);
continue; continue;
} }
} }
$stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]); $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]); DI::logger()->info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
foreach ($tags as $tag) { foreach ($tags as $tag) {
$stored = Category::storeFileByURIId($item['uri-id'], $uid, Category::SUBCRIPTION, $tag); $stored = Category::storeFileByURIId($item['uri-id'], $uid, Category::SUBCRIPTION, $tag);
Logger::debug('Stored tag subscription for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, $tag, 'stored' => $stored]); DI::logger()->debug('Stored tag subscription for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, $tag, 'stored' => $stored]);
} }
} }
} }
@ -1708,7 +1707,7 @@ class Item
$condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid]; $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
$parent = Post::selectFirst(['owner-id'], $condition); $parent = Post::selectFirst(['owner-id'], $condition);
if (!DBA::isResult($parent)) { if (!DBA::isResult($parent)) {
Logger::warning('Item not found', ['condition' => $condition]); DI::logger()->warning('Item not found', ['condition' => $condition]);
return; return;
} }
@ -1720,7 +1719,7 @@ class Item
]; ];
$item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition); $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
Logger::warning('Item not found', ['condition' => $condition]); DI::logger()->warning('Item not found', ['condition' => $condition]);
return; return;
} }
@ -1803,26 +1802,26 @@ class Item
public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
{ {
if ($uid == $source_uid) { if ($uid == $source_uid) {
Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]); DI::logger()->warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
return 0; return 0;
} }
$item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]); $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]); DI::logger()->warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
return 0; return 0;
} }
if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) { if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) {
$owner = User::getOwnerDataById($uid); $owner = User::getOwnerDataById($uid);
if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) { if (($owner['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && !Tag::isMentioned($uri_id, $owner['url'])) {
Logger::info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]); DI::logger()->info('Target user is a group but is not mentioned here, thread will not be stored', ['uid' => $uid, 'uri-id' => $uri_id]);
return 0; return 0;
} }
} }
if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], array_merge(Protocol::FEDERATED, [Protocol::BLUESKY])))) { if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], array_merge(Protocol::FEDERATED, [Protocol::BLUESKY])))) {
Logger::notice('Item is private or not from a federated network. It will not be stored for the user.', ['uri-id' => $uri_id, 'uid' => $uid, 'private' => $item['private'], 'network' => $item['network']]); DI::logger()->notice('Item is private or not from a federated network. It will not be stored for the user.', ['uri-id' => $uri_id, 'uid' => $uid, 'private' => $item['private'], 'network' => $item['network']]);
return 0; return 0;
} }
@ -1840,7 +1839,7 @@ class Item
DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE && DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
!in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE]) !in_array($item['post-reason'], [self::PR_FOLLOWER, self::PR_TAG, self::PR_TO, self::PR_CC, self::PR_ACTIVITY, self::PR_AUDIENCE])
) { ) {
Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid, 'uri-id' => $uri_id, 'post-reason' => $item['post-reason']]); DI::logger()->info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid, 'uri-id' => $uri_id, 'post-reason' => $item['post-reason']]);
return 0; return 0;
} }
@ -1848,20 +1847,20 @@ class Item
if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) { if (($uri_id != $item['parent-uri-id']) && ($item['gravity'] == self::GRAVITY_COMMENT) && !Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) { if (!self::fetchParent($item['parent-uri-id'], $uid, $causer)) {
Logger::info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]); DI::logger()->info('Parent post had not been added', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
return 0; return 0;
} }
Logger::info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]); DI::logger()->info('Fetched parent post', ['uri-id' => $item['parent-uri-id'], 'uid' => $uid, 'causer' => $causer]);
} elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) { } elseif (($uri_id != $item['thr-parent-id']) && $is_reshare && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) { if (!self::fetchParent($item['thr-parent-id'], $uid, $causer)) {
Logger::info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]); DI::logger()->info('Thread parent had not been added', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
return 0; return 0;
} }
Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]); DI::logger()->info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer]);
} }
$stored = self::storeForUser($item, $uid); $stored = self::storeForUser($item, $uid);
Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]); DI::logger()->info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'causer' => $causer, 'source-uid' => $source_uid, 'stored' => $stored]);
return $stored; return $stored;
} }
@ -1879,7 +1878,7 @@ class Item
// Fetch the origin user for the post // Fetch the origin user for the post
$origin_uid = self::GetOriginUidForUriId($uri_id, $uid); $origin_uid = self::GetOriginUidForUriId($uri_id, $uid);
if (is_null($origin_uid)) { if (is_null($origin_uid)) {
Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]); DI::logger()->info('Origin item was not found', ['uid' => $uid, 'uri-id' => $uri_id]);
return 0; return 0;
} }
@ -1955,11 +1954,11 @@ class Item
if (!empty($event)) { if (!empty($event)) {
// We aren't using "Event::store" here, since we don't want to trigger any further action // We aren't using "Event::store" here, since we don't want to trigger any further action
$ret = DBA::update('event', $event, ['id' => $event_post['event-id']]); $ret = DBA::update('event', $event, ['id' => $event_post['event-id']]);
Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]); DI::logger()->info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $event_post['event-id'], 'ret' => $ret]);
} }
} }
} }
Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]); DI::logger()->info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'id' => $post['id']]);
return $post['id']; return $post['id'];
} }
@ -1997,9 +1996,9 @@ class Item
$distributed = self::insert($item, $notify); $distributed = self::insert($item, $notify);
if (!$distributed) { if (!$distributed) {
Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]); DI::logger()->info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
} else { } else {
Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]); DI::logger()->info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
} }
return $distributed; return $distributed;
} }
@ -2065,7 +2064,7 @@ class Item
$public_shadow = self::insert($item); $public_shadow = self::insert($item);
Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]); DI::logger()->info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
} }
} }
@ -2124,7 +2123,7 @@ class Item
$public_shadow = self::insert($item); $public_shadow = self::insert($item);
Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]); DI::logger()->info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
// If this was a comment to a Diaspora post we don't get our comment back. // If this was a comment to a Diaspora post we don't get our comment back.
// This means that we have to distribute the comment by ourselves. // This means that we have to distribute the comment by ourselves.
@ -2194,7 +2193,7 @@ class Item
$author = Contact::selectFirst(['about'], ['id' => $author_id]); $author = Contact::selectFirst(['about'], ['id' => $author_id]);
if (!empty($author['about'])) { if (!empty($author['about'])) {
$about = BBCode::toSearchText($author['about'], 0); $about = BBCode::toSearchText($author['about'], 0);
Logger::debug('About field added', ['author' => $author_id, 'body' => $searchtext, 'about' => $about]); DI::logger()->debug('About field added', ['author' => $author_id, 'body' => $searchtext, 'about' => $about]);
$searchtext .= ' ' . $about; $searchtext .= ' ' . $about;
} }
} }
@ -2330,7 +2329,7 @@ class Item
public static function getLanguageMessage(array $item): string public static function getLanguageMessage(array $item): string
{ {
$iso639 = new \Matriphe\ISO639\ISO639; $iso639 = new \Matriphe\ISO639\ISO639();
$used_languages = ''; $used_languages = '';
foreach (json_decode($item['language'], true) as $language => $reliability) { foreach (json_decode($item['language'], true) as $language => $reliability) {
@ -2375,7 +2374,7 @@ class Item
$hostPart = $host ?: $parsed['host'] ?? ''; $hostPart = $host ?: $parsed['host'] ?? '';
if (!$hostPart) { if (!$hostPart) {
Logger::warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed]); DI::logger()->warning('Empty host GUID part', ['uri' => $uri, 'host' => $host, 'parsed' => $parsed]);
} }
// Glue it together to be able to make a hash from it // Glue it together to be able to make a hash from it
@ -2560,26 +2559,26 @@ class Item
{ {
$owner = User::getOwnerDataById($uid); $owner = User::getOwnerDataById($uid);
if (!DBA::isResult($owner)) { if (!DBA::isResult($owner)) {
Logger::warning('User not found, quitting here.', ['uid' => $uid]); DI::logger()->warning('User not found, quitting here.', ['uid' => $uid]);
return false; return false;
} }
if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) { if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]); DI::logger()->debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
return false; return false;
} }
$item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]); $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]); DI::logger()->debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
return false; return false;
} }
if ($item['gravity'] == self::GRAVITY_PARENT) { if ($item['gravity'] == self::GRAVITY_PARENT) {
if (Tag::isMentioned($item['uri-id'], $owner['url'])) { if (Tag::isMentioned($item['uri-id'], $owner['url'])) {
Logger::info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->info('Mention found in tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
} else { } else {
Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]); Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
return true; return true;
} }
@ -2589,14 +2588,14 @@ class Item
Hook::callAll('tagged', $arr); Hook::callAll('tagged', $arr);
} else { } else {
if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) { if (Tag::isMentioned($item['parent-uri-id'], $owner['url'])) {
Logger::info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->info('Mention found in parent tag.', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
} else { } else {
Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
return false; return false;
} }
} }
Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) { if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
$allow_cid = ''; $allow_cid = '';
@ -2608,7 +2607,7 @@ class Item
self::performActivity($item['id'], 'announce', $uid); self::performActivity($item['id'], 'announce', $uid);
} }
Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]); DI::logger()->info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
return false; return false;
} }
@ -2641,7 +2640,7 @@ class Item
return; return;
} }
Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]); DI::logger()->info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
self::performActivity($item['id'], 'announce', $item['uid']); self::performActivity($item['id'], 'announce', $item['uid']);
} }
@ -2654,34 +2653,34 @@ class Item
// Prevent the forwarding of posts that are forwarded // Prevent the forwarding of posts that are forwarded
if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) { if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) {
Logger::info('Already forwarded'); DI::logger()->info('Already forwarded');
return false; return false;
} }
// Prevent to forward already forwarded posts // Prevent to forward already forwarded posts
if ($datarray['app'] == DI::baseUrl()->getHost()) { if ($datarray['app'] == DI::baseUrl()->getHost()) {
Logger::info('Already forwarded (second test)'); DI::logger()->info('Already forwarded (second test)');
return false; return false;
} }
// Only forward posts // Only forward posts
if ($datarray['verb'] != Activity::POST) { if ($datarray['verb'] != Activity::POST) {
Logger::info('No post'); DI::logger()->info('No post');
return false; return false;
} }
if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) { if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
Logger::info('Not public'); DI::logger()->info('Not public');
return false; return false;
} }
if (User::getById($contact['uid'], ['blocked'])['blocked'] ?? false) { if (User::getById($contact['uid'], ['blocked'])['blocked'] ?? false) {
Logger::info('User is blocked', ['contact' => $contact]); DI::logger()->info('User is blocked', ['contact' => $contact]);
return false; return false;
} }
$datarray2 = $datarray; $datarray2 = $datarray;
Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]); DI::logger()->info('remote-self start', ['contact' => $contact['url'], 'remote_self' => $contact['remote_self'], 'item' => $datarray]);
$self = DBA::selectFirst( $self = DBA::selectFirst(
'contact', 'contact',
@ -2689,7 +2688,7 @@ class Item
['uid' => $contact['uid'], 'self' => true] ['uid' => $contact['uid'], 'self' => true]
); );
if (!DBA::isResult($self)) { if (!DBA::isResult($self)) {
Logger::error('Self contact not found', ['uid' => $contact['uid']]); DI::logger()->error('Self contact not found', ['uid' => $contact['uid']]);
return false; return false;
} }
@ -2723,7 +2722,7 @@ class Item
// Store the original post // Store the original post
$result = self::insert($datarray2); $result = self::insert($datarray2);
Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]); DI::logger()->info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]);
} else { } else {
$datarray['app'] = 'Feed'; $datarray['app'] = 'Feed';
$result = true; $result = true;
@ -2752,7 +2751,7 @@ class Item
return $s; return $s;
} }
Logger::info('check for photos'); DI::logger()->info('check for photos');
$site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://')); $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
$orig_body = $s; $orig_body = $s;
@ -2766,7 +2765,7 @@ class Item
$img_st_close++; // make it point to AFTER the closing bracket $img_st_close++; // make it point to AFTER the closing bracket
$image = substr($orig_body, $img_start + $img_st_close, $img_len); $image = substr($orig_body, $img_start + $img_st_close, $img_len);
Logger::info('found photo', ['image' => $image]); DI::logger()->info('found photo', ['image' => $image]);
if (stristr($image, $site . '/photo/')) { if (stristr($image, $site . '/photo/')) {
// Only embed locally hosted photos // Only embed locally hosted photos
@ -2805,7 +2804,7 @@ class Item
$photo_img = Photo::getImageForPhoto($photo); $photo_img = Photo::getImageForPhoto($photo);
// If a custom width and height were specified, apply before embedding // If a custom width and height were specified, apply before embedding
if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) { if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
Logger::info('scaling photo'); DI::logger()->info('scaling photo');
$width = intval($match[1]); $width = intval($match[1]);
$height = intval($match[2]); $height = intval($match[2]);
@ -2816,9 +2815,9 @@ class Item
$data = $photo_img->asString(); $data = $photo_img->asString();
$type = $photo_img->getType(); $type = $photo_img->getType();
Logger::info('replacing photo'); DI::logger()->info('replacing photo');
$image = 'data:' . $type . ';base64,' . base64_encode($data); $image = 'data:' . $type . ';base64,' . base64_encode($data);
Logger::debug('replaced', ['image' => $image]); DI::logger()->debug('replaced', ['image' => $image]);
} }
} }
} }
@ -2968,7 +2967,7 @@ class Item
++$expired; ++$expired;
} }
DBA::close($items); DBA::close($items);
Logger::notice('Expired', ['user' => $uid, 'days' => $days, 'network' => $network, 'force' => $force, 'expired' => $expired, 'expire items' => $expire_items, 'expire notes' => $expire_notes, 'expire starred' => $expire_starred, 'expire photos' => $expire_photos, 'condition' => $condition]); DI::logger()->notice('Expired', ['user' => $uid, 'days' => $days, 'network' => $network, 'force' => $force, 'expired' => $expired, 'expire items' => $expire_items, 'expire notes' => $expire_notes, 'expire starred' => $expire_starred, 'expire photos' => $expire_photos, 'condition' => $condition]);
return $expired; return $expired;
} }
@ -3021,11 +3020,11 @@ class Item
return false; return false;
} }
Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]); DI::logger()->notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
$item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]); $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
Logger::warning('Post had not been fetched', ['id' => $item_id]); DI::logger()->warning('Post had not been fetched', ['id' => $item_id]);
return false; return false;
} }
@ -3040,7 +3039,7 @@ class Item
if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) { if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
$item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]); $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]); DI::logger()->info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
return false; return false;
} }
} }
@ -3049,14 +3048,14 @@ class Item
// Retrieves the local post owner // Retrieves the local post owner
$owner = User::getOwnerDataById($uid); $owner = User::getOwnerDataById($uid);
if (empty($owner)) { if (empty($owner)) {
Logger::info('Empty owner for user', ['uid' => $uid]); DI::logger()->info('Empty owner for user', ['uid' => $uid]);
return false; return false;
} }
// Retrieve the current logged in user's public contact // Retrieve the current logged in user's public contact
$author_id = Contact::getPublicIdByUserId($uid); $author_id = Contact::getPublicIdByUserId($uid);
if (empty($author_id)) { if (empty($author_id)) {
Logger::info('Empty public contact'); DI::logger()->info('Empty public contact');
return false; return false;
} }
@ -3091,7 +3090,7 @@ class Item
$activity = Activity::ANNOUNCE; $activity = Activity::ANNOUNCE;
break; break;
default: default:
Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]); DI::logger()->warning('unknown verb', ['verb' => $verb, 'item' => $item_id]);
return false; return false;
} }
@ -4196,10 +4195,10 @@ class Item
*/ */
public static function fetchByLink(string $uri, int $uid = 0, int $completion = ActivityPub\Receiver::COMPLETION_MANUAL, string $mimetype = ''): int public static function fetchByLink(string $uri, int $uid = 0, int $completion = ActivityPub\Receiver::COMPLETION_MANUAL, string $mimetype = ''): int
{ {
Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]); DI::logger()->info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
$item_id = self::searchByLink($uri, $uid); $item_id = self::searchByLink($uri, $uid);
if (!empty($item_id)) { if (!empty($item_id)) {
Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]); DI::logger()->info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
return $item_id; return $item_id;
} }
@ -4216,7 +4215,7 @@ class Item
Hook::callAll('item_by_link', $hookData); Hook::callAll('item_by_link', $hookData);
if (isset($hookData['item_id'])) { if (isset($hookData['item_id'])) {
Logger::info('Hook link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $hookData['item_id']]); DI::logger()->info('Hook link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $hookData['item_id']]);
return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0; return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
} }
@ -4225,7 +4224,7 @@ class Item
$curlResult = DI::httpClient()->head($uri, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::JSON_AS, HttpClientOptions::REQUEST => HttpClientRequest::ACTIVITYPUB]); $curlResult = DI::httpClient()->head($uri, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::JSON_AS, HttpClientOptions::REQUEST => HttpClientRequest::ACTIVITYPUB]);
$mimetype = $curlResult->getContentType(); $mimetype = $curlResult->getContentType();
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::info('Error while fetching HTTP link via HEAD', ['uid' => $uid, 'uri' => $uri, 'code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->info('Error while fetching HTTP link via HEAD', ['uid' => $uid, 'uri' => $uri, 'code' => $th->getCode(), 'message' => $th->getMessage()]);
return 0; return 0;
} }
} }
@ -4236,7 +4235,7 @@ class Item
$curlResult = HTTPSignature::fetchRaw($uri, $uid); $curlResult = HTTPSignature::fetchRaw($uri, $uid);
$mimetype = $curlResult->getContentType(); $mimetype = $curlResult->getContentType();
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::info('Error while fetching HTTP link via signed GET', ['uid' => $uid, 'uri' => $uri, 'code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->info('Error while fetching HTTP link via signed GET', ['uid' => $uid, 'uri' => $uri, 'code' => $th->getCode(), 'message' => $th->getMessage()]);
return 0; return 0;
} }
} }
@ -4246,7 +4245,7 @@ class Item
if (!empty($fetched_uri)) { if (!empty($fetched_uri)) {
$item_id = self::searchByLink($fetched_uri, $uid); $item_id = self::searchByLink($fetched_uri, $uid);
if ($item_id) { if ($item_id) {
Logger::info('ActivityPub link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]); DI::logger()->info('ActivityPub link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
return $item_id; return $item_id;
} }
} }
@ -4254,11 +4253,11 @@ class Item
$item_id = Diaspora::fetchByURL($uri); $item_id = Diaspora::fetchByURL($uri);
if ($item_id) { if ($item_id) {
Logger::info('Diaspora link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]); DI::logger()->info('Diaspora link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
return $item_id; return $item_id;
} }
Logger::info('This is not an item link', ['uid' => $uid, 'uri' => $uri]); DI::logger()->info('This is not an item link', ['uid' => $uid, 'uri' => $uri]);
return 0; return 0;
} }
@ -4277,14 +4276,14 @@ class Item
} }
if (empty($shared['link']) && empty($shared['message_id'])) { if (empty($shared['link']) && empty($shared['message_id'])) {
Logger::notice('Invalid share block.', ['share' => $shared]); DI::logger()->notice('Invalid share block.', ['share' => $shared]);
return 0; return 0;
} }
if (!empty($shared['guid'])) { if (!empty($shared['guid'])) {
$shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]); $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
if (!empty($shared_item['uri-id'])) { if (!empty($shared_item['uri-id'])) {
Logger::debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]); DI::logger()->debug('Found post by guid', ['guid' => $shared['guid'], 'uid' => $uid]);
return $shared_item['uri-id']; return $shared_item['uri-id'];
} }
} }
@ -4292,7 +4291,7 @@ class Item
if (!empty($shared['message_id'])) { if (!empty($shared['message_id'])) {
$shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]); $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]);
if (!empty($shared_item['uri-id'])) { if (!empty($shared_item['uri-id'])) {
Logger::debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]); DI::logger()->debug('Found post by message_id', ['message_id' => $shared['message_id'], 'uid' => $uid]);
return $shared_item['uri-id']; return $shared_item['uri-id'];
} }
} }
@ -4300,7 +4299,7 @@ class Item
if (!empty($shared['link'])) { if (!empty($shared['link'])) {
$shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]); $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]);
if (!empty($shared_item['uri-id'])) { if (!empty($shared_item['uri-id'])) {
Logger::debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]); DI::logger()->debug('Found post by link', ['link' => $shared['link'], 'uid' => $uid]);
return $shared_item['uri-id']; return $shared_item['uri-id'];
} }
} }
@ -4308,17 +4307,17 @@ class Item
$url = $shared['message_id'] ?: $shared['link']; $url = $shared['message_id'] ?: $shared['link'];
$id = self::fetchByLink($url, 0, ActivityPub\Receiver::COMPLETION_ASYNC); $id = self::fetchByLink($url, 0, ActivityPub\Receiver::COMPLETION_ASYNC);
if (!$id) { if (!$id) {
Logger::notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]); DI::logger()->notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]);
return 0; return 0;
} }
$shared_item = Post::selectFirst(['uri-id'], ['id' => $id]); $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]);
if (!empty($shared_item['uri-id'])) { if (!empty($shared_item['uri-id'])) {
Logger::debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]); DI::logger()->debug('Fetched shared post', ['id' => $id, 'url' => $url, 'uid' => $uid]);
return $shared_item['uri-id']; return $shared_item['uri-id'];
} }
Logger::warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]); DI::logger()->warning('Post does not exist although it was supposed to had been fetched.', ['id' => $id, 'url' => $url, 'uid' => $uid]);
return 0; return 0;
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\Logger;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -32,7 +31,7 @@ class ItemURI
$itemuri = DBA::selectFirst('item-uri', ['id', 'guid'], ['uri' => $fields['uri']]); $itemuri = DBA::selectFirst('item-uri', ['id', 'guid'], ['uri' => $fields['uri']]);
if (!DBA::isResult($itemuri)) { if (!DBA::isResult($itemuri)) {
// This shouldn't happen // This shouldn't happen
Logger::warning('Item-uri not found', $fields); DI::logger()->warning('Item-uri not found', $fields);
return null; return null;
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\ACL; use Friendica\Core\ACL;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -58,7 +57,7 @@ class Mail
if (DBA::exists('mail', ['uri' => $msg['uri'], 'uid' => $msg['uid']])) { if (DBA::exists('mail', ['uri' => $msg['uri'], 'uid' => $msg['uid']])) {
DBA::unlock(); DBA::unlock();
Logger::info('duplicate message already delivered.'); DI::logger()->info('duplicate message already delivered.');
return false; return false;
} }
@ -94,7 +93,7 @@ class Mail
DI::notify()->createFromArray($notif_params); DI::notify()->createFromArray($notif_params);
Logger::info('Mail is processed, notification was sent.', ['id' => $msg['id'], 'uri' => $msg['uri']]); DI::logger()->info('Mail is processed, notification was sent.', ['id' => $msg['id'], 'uri' => $msg['uri']]);
} }
return $msg['id']; return $msg['id'];
@ -170,7 +169,7 @@ class Mail
} }
if (!$convid) { if (!$convid) {
Logger::warning('conversation not found.'); DI::logger()->warning('conversation not found.');
return -4; return -4;
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -583,7 +582,7 @@ class Photo
$photo_failure = false; $photo_failure = false;
if (!Network::isValidHttpUrl($image_url)) { if (!Network::isValidHttpUrl($image_url)) {
Logger::warning('Invalid image url', ['image_url' => $image_url, 'uid' => $uid, 'cid' => $cid]); DI::logger()->warning('Invalid image url', ['image_url' => $image_url, 'uid' => $uid, 'cid' => $cid]);
return false; return false;
} }
@ -592,10 +591,10 @@ class Photo
try { try {
$ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::MEDIAPROXY]); $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::MEDIAPROXY]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return false; return false;
} }
Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]); DI::logger()->debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
$img_str = $ret->getBodyString(); $img_str = $ret->getBodyString();
$type = $ret->getContentType(); $type = $ret->getContentType();
} else { } else {
@ -615,24 +614,24 @@ class Photo
$maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize')); $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'));
if ($maximagesize && ($filesize > $maximagesize)) { if ($maximagesize && ($filesize > $maximagesize)) {
Logger::info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]); DI::logger()->info('Avatar exceeds image limit', ['uid' => $uid, 'cid' => $cid, 'maximagesize' => $maximagesize, 'size' => $filesize, 'type' => $image->getType()]);
if ($image->getImageType() == IMAGETYPE_GIF) { if ($image->getImageType() == IMAGETYPE_GIF) {
$image->toStatic(); $image->toStatic();
$image = new Image($image->asString(), image_type_to_mime_type(IMAGETYPE_PNG)); $image = new Image($image->asString(), image_type_to_mime_type(IMAGETYPE_PNG));
$filesize = strlen($image->asString()); $filesize = strlen($image->asString());
Logger::info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]); DI::logger()->info('Converted gif to a static png', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
} }
if ($filesize > $maximagesize) { if ($filesize > $maximagesize) {
foreach ([160, 80] as $pixels) { foreach ([160, 80] as $pixels) {
if ($filesize > $maximagesize) { if ($filesize > $maximagesize) {
Logger::info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]); DI::logger()->info('Resize', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'max' => $maximagesize, 'pixels' => $pixels, 'type' => $image->getType()]);
$image->scaleDown($pixels); $image->scaleDown($pixels);
$filesize = strlen($image->asString()); $filesize = strlen($image->asString());
} }
} }
} }
Logger::info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]); DI::logger()->info('Avatar is resized', ['uid' => $uid, 'cid' => $cid, 'size' => $filesize, 'type' => $image->getType()]);
} }
$r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR); $r = self::store($image, $uid, $cid, $resource_id, $filename, self::CONTACT_PHOTOS, 4, self::CONTACT_AVATAR);
@ -869,9 +868,9 @@ class Photo
if (!self::exists($condition)) { if (!self::exists($condition)) {
$photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]); $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]);
if (!DBA::isResult($photo)) { if (!DBA::isResult($photo)) {
Logger::info('Image not found', ['resource-id' => $image_rid]); DI::logger()->info('Image not found', ['resource-id' => $image_rid]);
} else { } else {
Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]); DI::logger()->info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]);
} }
continue; continue;
} }
@ -910,7 +909,7 @@ class Photo
]; ];
$condition = ['resource-id' => $image_rid, 'uid' => $uid]; $condition = ['resource-id' => $image_rid, 'uid' => $uid];
Logger::info('Set permissions', ['condition' => $condition, 'permissions' => $fields]); DI::logger()->info('Set permissions', ['condition' => $condition, 'permissions' => $fields]);
self::update($fields, $condition); self::update($fields, $condition);
} }
@ -1010,7 +1009,7 @@ class Photo
// Scale down to multiples of 640 until the maximum size isn't exceeded anymore // Scale down to multiples of 640 until the maximum size isn't exceeded anymore
foreach ([5120, 2560, 1280, 640, 320] as $pixels) { foreach ([5120, 2560, 1280, 640, 320] as $pixels) {
if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) { if (($filesize > $maximagesize) && (max($width, $height) > $pixels)) {
Logger::info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]); DI::logger()->info('Resize', ['size' => $filesize, 'width' => $width, 'height' => $height, 'max' => $maximagesize, 'pixels' => $pixels]);
$image->scaleDown($pixels); $image->scaleDown($pixels);
$filesize = strlen($image->asString()); $filesize = strlen($image->asString());
$width = $image->getWidth(); $width = $image->getWidth();
@ -1033,7 +1032,7 @@ class Photo
$max_length = DI::config()->get('system', 'max_image_length'); $max_length = DI::config()->get('system', 'max_image_length');
if ($max_length > 0) { if ($max_length > 0) {
$image->scaleDown($max_length); $image->scaleDown($max_length);
Logger::info('File upload: Scaling picture to new size', ['max-length' => $max_length]); DI::logger()->info('File upload: Scaling picture to new size', ['max-length' => $max_length]);
} }
return self::resizeToFileSize($image, Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize'))); return self::resizeToFileSize($image, Strings::getBytesFromShorthand(DI::config()->get('system', 'maximagesize')));
@ -1052,10 +1051,10 @@ class Photo
try { try {
$ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::MEDIAPROXY]); $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::MEDIAPROXY]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return []; return [];
} }
Logger::debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]); DI::logger()->debug('Got picture', ['Content-Type' => $ret->getHeader('Content-Type'), 'url' => $image_url]);
$img_str = $ret->getBodyString(); $img_str = $ret->getBodyString();
$type = $ret->getContentType(); $type = $ret->getContentType();
} else { } else {
@ -1064,7 +1063,7 @@ class Photo
} }
if (empty($img_str)) { if (empty($img_str)) {
Logger::notice('Empty content'); DI::logger()->notice('Empty content');
return []; return [];
} }
@ -1086,10 +1085,10 @@ class Photo
*/ */
private static function uploadImage(array $files): array private static function uploadImage(array $files): array
{ {
Logger::info('starting new upload'); DI::logger()->info('starting new upload');
if (empty($files)) { if (empty($files)) {
Logger::notice('Empty upload file'); DI::logger()->notice('Empty upload file');
return []; return [];
} }
@ -1134,16 +1133,16 @@ class Photo
} }
if (empty($src)) { if (empty($src)) {
Logger::notice('No source file name', ['files' => $files]); DI::logger()->notice('No source file name', ['files' => $files]);
return []; return [];
} }
Logger::info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]); DI::logger()->info('File upload', ['src' => $src, 'filename' => $filename, 'size' => $filesize, 'type' => $filetype]);
$imagedata = @file_get_contents($src); $imagedata = @file_get_contents($src);
$image = new Image($imagedata, $filetype, $filename); $image = new Image($imagedata, $filetype, $filename);
if (!$image->isValid()) { if (!$image->isValid()) {
Logger::notice('Image is unvalid', ['files' => $files]); DI::logger()->notice('Image is unvalid', ['files' => $files]);
return []; return [];
} }
@ -1177,13 +1176,13 @@ class Photo
{ {
$user = User::getOwnerDataById($uid); $user = User::getOwnerDataById($uid);
if (empty($user)) { if (empty($user)) {
Logger::notice('User not found', ['uid' => $uid]); DI::logger()->notice('User not found', ['uid' => $uid]);
return []; return [];
} }
$data = self::uploadImage($files); $data = self::uploadImage($files);
if (empty($data)) { if (empty($data)) {
Logger::info('upload failed'); DI::logger()->info('upload failed');
return []; return [];
} }
@ -1201,14 +1200,14 @@ class Photo
$preview = self::storeWithPreview($image, $user['uid'], $resource_id, $filename, $filesize, $album, $desc, $allow_cid, $allow_gid, $deny_cid, $deny_gid); $preview = self::storeWithPreview($image, $user['uid'], $resource_id, $filename, $filesize, $album, $desc, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
if ($preview < 0) { if ($preview < 0) {
Logger::warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]); DI::logger()->warning('Photo could not be stored', ['uid' => $user['uid'], 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
return []; return [];
} }
$condition = ['resource-id' => $resource_id]; $condition = ['resource-id' => $resource_id];
$photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]); $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]);
if (empty($photo)) { if (empty($photo)) {
Logger::notice('Photo not found', ['condition' => $condition]); DI::logger()->notice('Photo not found', ['condition' => $condition]);
return []; return [];
} }
@ -1224,7 +1223,7 @@ class Photo
$picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt(); $picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $image->getExt();
$picture['preview'] = DI::baseUrl() . '/photo/' . $resource_id . '-' . $preview . '.' . $image->getExt(); $picture['preview'] = DI::baseUrl() . '/photo/' . $resource_id . '-' . $preview . '.' . $image->getExt();
Logger::info('upload done', ['picture' => $picture]); DI::logger()->info('upload done', ['picture' => $picture]);
return $picture; return $picture;
} }
@ -1256,7 +1255,7 @@ class Photo
$result = self::store($image, $uid, 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description); $result = self::store($image, $uid, 0, $resource_id, $filename, $album, 0, self::DEFAULT, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $description);
if (!$result) { if (!$result) {
Logger::warning('Photo could not be stored', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]); DI::logger()->warning('Photo could not be stored', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
return -1; return -1;
} }
@ -1291,17 +1290,17 @@ class Photo
if (!empty($files)) { if (!empty($files)) {
$data = self::uploadImage($files); $data = self::uploadImage($files);
if (empty($data)) { if (empty($data)) {
Logger::info('upload failed'); DI::logger()->info('upload failed');
return ''; return '';
} }
} elseif (!empty($url)) { } elseif (!empty($url)) {
$data = self::loadImageFromURL($url); $data = self::loadImageFromURL($url);
if (empty($data)) { if (empty($data)) {
Logger::info('loading from external url failed'); DI::logger()->info('loading from external url failed');
return ''; return '';
} }
} else { } else {
Logger::info('Neither files nor url provided'); DI::logger()->info('Neither files nor url provided');
return ''; return '';
} }
@ -1314,7 +1313,7 @@ class Photo
$album = DI::l10n()->t(self::PROFILE_PHOTOS); $album = DI::l10n()->t(self::PROFILE_PHOTOS);
// upload profile image (scales 4, 5, 6) // upload profile image (scales 4, 5, 6)
logger::info('starting new profile image upload'); DI::logger()->info('starting new profile image upload');
if ($width > 300 || $height > 300) { if ($width > 300 || $height > 300) {
$image->scaleDown(300); $image->scaleDown(300);
@ -1322,7 +1321,7 @@ class Photo
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR); $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR);
if (!$r) { if (!$r) {
logger::warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]); DI::logger()->warning('profile image upload with scale 4 (300) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
} }
if ($width > 80 || $height > 80) { if ($width > 80 || $height > 80) {
@ -1331,7 +1330,7 @@ class Photo
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR); $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR);
if (!$r) { if (!$r) {
logger::warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]); DI::logger()->warning('profile image upload with scale 5 (80) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
} }
if ($width > 48 || $height > 48) { if ($width > 48 || $height > 48) {
@ -1340,10 +1339,10 @@ class Photo
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR); $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR);
if (!$r) { if (!$r) {
logger::warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]); DI::logger()->warning('profile image upload with scale 6 (48) failed', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename, 'album' => $album]);
} }
logger::info('new profile image upload ended'); DI::logger()->info('new profile image upload ended');
$condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid]; $condition = ["`profile` AND `resource-id` != ? AND `uid` = ?", $resource_id, $uid];
self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition); self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition);
@ -1369,17 +1368,17 @@ class Photo
if (!empty($files)) { if (!empty($files)) {
$data = self::uploadImage($files); $data = self::uploadImage($files);
if (empty($data)) { if (empty($data)) {
Logger::info('upload failed'); DI::logger()->info('upload failed');
return ''; return '';
} }
} elseif (!empty($url)) { } elseif (!empty($url)) {
$data = self::loadImageFromURL($url); $data = self::loadImageFromURL($url);
if (empty($data)) { if (empty($data)) {
Logger::info('loading from external url failed'); DI::logger()->info('loading from external url failed');
return ''; return '';
} }
} else { } else {
Logger::info('Neither files nor url provided'); DI::logger()->info('Neither files nor url provided');
return ''; return '';
} }
@ -1397,10 +1396,10 @@ class Photo
$r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER); $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER);
if (!$r) { if (!$r) {
logger::warning('profile banner upload with scale 3 (960) failed'); DI::logger()->warning('profile banner upload with scale 3 (960) failed');
} }
logger::info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]); DI::logger()->info('new profile banner upload ended', ['uid' => $uid, 'resource_id' => $resource_id, 'filename' => $filename]);
$condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid]; $condition = ["`photo-type` = ? AND `resource-id` != ? AND `uid` = ?", self::USER_BANNER, $resource_id, $uid];
self::update(['photo-type' => self::DEFAULT], $condition); self::update(['photo-type' => self::DEFAULT], $condition);

View file

@ -8,7 +8,6 @@
namespace Friendica\Model; namespace Friendica\Model;
use BadMethodCallException; use BadMethodCallException;
use Friendica\Core\Logger;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -448,7 +447,8 @@ class Post
$selected = Item::DISPLAY_FIELDLIST; $selected = Item::DISPLAY_FIELDLIST;
} }
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions(
$condition,
["`visible` AND NOT `deleted` ["`visible` AND NOT `deleted`
AND NOT `author-blocked` AND NOT `owner-blocked` AND NOT `author-blocked` AND NOT `owner-blocked`
AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked` AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked`
@ -457,7 +457,8 @@ class Post
AND NOT EXISTS(SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = " . DBA::quoteIdentifier($view) . ".`uri-id` AND `hidden`) AND NOT EXISTS(SELECT `uri-id` FROM `post-user` WHERE `uid` = ? AND `uri-id` = " . DBA::quoteIdentifier($view) . ".`uri-id` AND `hidden`)
AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` IN (`author-id`, `owner-id`) AND (`blocked` OR `ignored` OR `is-blocked`)) AND NOT EXISTS(SELECT `cid` FROM `user-contact` WHERE `uid` = ? AND `cid` IN (`author-id`, `owner-id`) AND (`blocked` OR `ignored` OR `is-blocked`))
AND NOT EXISTS(SELECT `gsid` FROM `user-gserver` WHERE `uid` = ? AND `gsid` IN (`author-gsid`, `owner-gsid`, `causer-gsid`) AND `ignored`)", AND NOT EXISTS(SELECT `gsid` FROM `user-gserver` WHERE `uid` = ? AND `gsid` IN (`author-gsid`, `owner-gsid`, `causer-gsid`) AND `ignored`)",
0, Contact::SHARING, Contact::FRIEND, 0, $uid, $uid, $uid]); 0, Contact::SHARING, Contact::FRIEND, 0, $uid, $uid, $uid]
);
$select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected)); $select_string = implode(', ', array_map([DBA::class, 'quoteIdentifier'], $selected));
@ -621,7 +622,7 @@ class Post
{ {
$affected = 0; $affected = 0;
Logger::info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => DI::userSession()->getLocalUserId()]); DI::logger()->info('Start Update', ['fields' => $fields, 'condition' => $condition, 'uid' => DI::userSession()->getLocalUserId()]);
// Don't allow changes to fields that are responsible for the relation between the records // Don't allow changes to fields that are responsible for the relation between the records
unset($fields['id']); unset($fields['id']);
@ -647,7 +648,7 @@ class Post
$puids = array_column($rows, 'post-user-id'); $puids = array_column($rows, 'post-user-id');
if (!DBA::update('post-user', $update_fields, ['id' => $puids])) { if (!DBA::update('post-user', $update_fields, ['id' => $puids])) {
DBA::rollback(); DBA::rollback();
Logger::warning('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]); DI::logger()->warning('Updating post-user failed', ['fields' => $update_fields, 'condition' => $condition]);
return false; return false;
} }
$affected_count += DBA::affectedRows(); $affected_count += DBA::affectedRows();
@ -664,7 +665,7 @@ class Post
$uriids = array_column($rows, 'uri-id'); $uriids = array_column($rows, 'uri-id');
if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) { if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) {
DBA::rollback(); DBA::rollback();
Logger::warning('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]); DI::logger()->warning('Updating post-content failed', ['fields' => $update_fields, 'condition' => $condition]);
return false; return false;
} }
$affected_count += DBA::affectedRows(); $affected_count += DBA::affectedRows();
@ -687,7 +688,7 @@ class Post
if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) { if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) {
DBA::rollback(); DBA::rollback();
Logger::warning('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]); DI::logger()->warning('Updating post failed', ['fields' => $update_fields, 'condition' => $condition]);
return false; return false;
} }
$affected_count += DBA::affectedRows(); $affected_count += DBA::affectedRows();
@ -704,7 +705,7 @@ class Post
$uriids = array_column($rows, 'uri-id'); $uriids = array_column($rows, 'uri-id');
if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) { if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) {
DBA::rollback(); DBA::rollback();
Logger::warning('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]); DI::logger()->warning('Updating post-delivery-data failed', ['fields' => $update_fields, 'condition' => $condition]);
return false; return false;
} }
$affected_count += DBA::affectedRows(); $affected_count += DBA::affectedRows();
@ -721,7 +722,7 @@ class Post
$uriids = array_column($rows, 'uri-id'); $uriids = array_column($rows, 'uri-id');
if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) { if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) {
DBA::rollback(); DBA::rollback();
Logger::warning('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]); DI::logger()->warning('Updating post-thread failed', ['fields' => $update_fields, 'condition' => $condition]);
return false; return false;
} }
$affected_count += DBA::affectedRows(); $affected_count += DBA::affectedRows();
@ -738,7 +739,7 @@ class Post
$thread_puids = array_column($rows, 'post-user-id'); $thread_puids = array_column($rows, 'post-user-id');
if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) { if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) {
DBA::rollback(); DBA::rollback();
Logger::warning('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]); DI::logger()->warning('Updating post-thread-user failed', ['fields' => $update_fields, 'condition' => $condition]);
return false; return false;
} }
$affected_count += DBA::affectedRows(); $affected_count += DBA::affectedRows();
@ -749,7 +750,7 @@ class Post
DBA::commit(); DBA::commit();
Logger::info('Updated posts', ['rows' => $affected]); DI::logger()->info('Updated posts', ['rows' => $affected]);
return $affected; return $affected;
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Model\Post; namespace Friendica\Model\Post;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\Database; use Friendica\Database\Database;
@ -45,7 +44,7 @@ class Delayed
public static function add(string $uri, array $item, int $notify = 0, int $preparation_mode = self::PREPARED, string $delayed = '', array $taglist = [], array $attachments = []) public static function add(string $uri, array $item, int $notify = 0, int $preparation_mode = self::PREPARED, string $delayed = '', array $taglist = [], array $attachments = [])
{ {
if (empty($item['uid']) || self::exists($uri, $item['uid'])) { if (empty($item['uid']) || self::exists($uri, $item['uid'])) {
Logger::notice('No uid or already found'); DI::logger()->notice('No uid or already found');
return 0; return 0;
} }
@ -58,7 +57,7 @@ class Delayed
DI::pConfig()->set($item['uid'], 'system', 'last_publish', $next_publish); DI::pConfig()->set($item['uid'], 'system', 'last_publish', $next_publish);
} }
Logger::notice('Adding post for delayed publishing', ['uid' => $item['uid'], 'delayed' => $delayed, 'uri' => $uri]); DI::logger()->notice('Adding post for delayed publishing', ['uid' => $item['uid'], 'delayed' => $delayed, 'uri' => $uri]);
$wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'DelayedPublish', $item, $notify, $taglist, $attachments, $preparation_mode, $uri); $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'DelayedPublish', $item, $notify, $taglist, $attachments, $preparation_mode, $uri);
if (!$wid) { if (!$wid) {
@ -181,7 +180,7 @@ class Delayed
$id = Item::insert($item, $notify, $preparation_mode == self::PREPARED); $id = Item::insert($item, $notify, $preparation_mode == self::PREPARED);
Logger::notice('Post stored', ['id' => $id, 'uid' => $item['uid'], 'cid' => $item['contact-id'] ?? 'N/A']); DI::logger()->notice('Post stored', ['id' => $id, 'uid' => $item['uid'], 'cid' => $item['contact-id'] ?? 'N/A']);
if (empty($uri) && !empty($item['uri'])) { if (empty($uri) && !empty($item['uri'])) {
$uri = $item['uri']; $uri = $item['uri'];

View file

@ -9,7 +9,6 @@ namespace Friendica\Model\Post;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -48,18 +47,20 @@ class Engagement
public static function storeFromItem(array $item): int public static function storeFromItem(array $item): int
{ {
if (in_array($item['verb'], [Activity::FOLLOW, Activity::VIEW, Activity::READ])) { if (in_array($item['verb'], [Activity::FOLLOW, Activity::VIEW, Activity::READ])) {
Logger::debug('Technical activities are not stored', ['uri-id' => $item['uri-id'], 'parent-uri-id' => $item['parent-uri-id'], 'verb' => $item['verb']]); DI::logger()->debug('Technical activities are not stored', ['uri-id' => $item['uri-id'], 'parent-uri-id' => $item['parent-uri-id'], 'verb' => $item['verb']]);
return 0; return 0;
} }
$parent = Post::selectFirst(['uri-id', 'created', 'uid', 'private', 'quote-uri-id', $parent = Post::selectFirst(
['uri-id', 'created', 'uid', 'private', 'quote-uri-id',
'contact-contact-type', 'network', 'title', 'content-warning', 'body', 'language', 'contact-contact-type', 'network', 'title', 'content-warning', 'body', 'language',
'author-id', 'author-contact-type', 'author-nick', 'author-addr', 'author-gsid', 'author-id', 'author-contact-type', 'author-nick', 'author-addr', 'author-gsid',
'owner-id', 'owner-contact-type', 'owner-nick', 'owner-addr', 'owner-gsid'], 'owner-id', 'owner-contact-type', 'owner-nick', 'owner-addr', 'owner-gsid'],
['uri-id' => $item['parent-uri-id']]); ['uri-id' => $item['parent-uri-id']]
);
if ($parent['created'] < self::getCreationDateLimit(false)) { if ($parent['created'] < self::getCreationDateLimit(false)) {
Logger::debug('Post is too old', ['uri-id' => $item['uri-id'], 'parent-uri-id' => $item['parent-uri-id'], 'created' => $parent['created']]); DI::logger()->debug('Post is too old', ['uri-id' => $item['uri-id'], 'parent-uri-id' => $item['parent-uri-id'], 'created' => $parent['created']]);
return 0; return 0;
} }
@ -114,16 +115,16 @@ class Engagement
]) ])
]; ];
if (!$store && ($engagement['comments'] == 0) && ($engagement['activities'] == 0)) { if (!$store && ($engagement['comments'] == 0) && ($engagement['activities'] == 0)) {
Logger::debug('No media, follower, subscribed tags, comments or activities. Engagement not stored', ['fields' => $engagement]); DI::logger()->debug('No media, follower, subscribed tags, comments or activities. Engagement not stored', ['fields' => $engagement]);
return 0; return 0;
} }
$exists = DBA::exists('post-engagement', ['uri-id' => $engagement['uri-id']]); $exists = DBA::exists('post-engagement', ['uri-id' => $engagement['uri-id']]);
if ($exists) { if ($exists) {
$ret = DBA::update('post-engagement', $engagement, ['uri-id' => $engagement['uri-id']]); $ret = DBA::update('post-engagement', $engagement, ['uri-id' => $engagement['uri-id']]);
Logger::debug('Engagement updated', ['uri-id' => $engagement['uri-id'], 'ret' => $ret]); DI::logger()->debug('Engagement updated', ['uri-id' => $engagement['uri-id'], 'ret' => $ret]);
} else { } else {
$ret = DBA::insert('post-engagement', $engagement); $ret = DBA::insert('post-engagement', $engagement);
Logger::debug('Engagement inserted', ['uri-id' => $engagement['uri-id'], 'ret' => $ret]); DI::logger()->debug('Engagement inserted', ['uri-id' => $engagement['uri-id'], 'ret' => $ret]);
} }
return ($ret && !$exists) ? $engagement['uri-id'] : 0; return ($ret && !$exists) ? $engagement['uri-id'] : 0;
} }
@ -315,8 +316,10 @@ class Engagement
private static function addResharers(string $text, int $uri_id): string private static function addResharers(string $text, int $uri_id): string
{ {
$result = Post::selectPosts(['author-addr', 'author-nick', 'author-contact-type'], $result = Post::selectPosts(
['thr-parent-id' => $uri_id, 'gravity' => Item::GRAVITY_ACTIVITY, 'verb' => Activity::ANNOUNCE, 'author-contact-type' => [Contact::TYPE_RELAY, Contact::TYPE_COMMUNITY]]); ['author-addr', 'author-nick', 'author-contact-type'],
['thr-parent-id' => $uri_id, 'gravity' => Item::GRAVITY_ACTIVITY, 'verb' => Activity::ANNOUNCE, 'author-contact-type' => [Contact::TYPE_RELAY, Contact::TYPE_COMMUNITY]]
);
while ($reshare = Post::fetch($result)) { while ($reshare = Post::fetch($result)) {
$prefix = ''; $prefix = '';
@ -369,11 +372,11 @@ class Engagement
{ {
$limit = self::getCreationDateLimit(true); $limit = self::getCreationDateLimit(true);
if (empty($limit)) { if (empty($limit)) {
Logger::notice('Expiration limit not reached'); DI::logger()->notice('Expiration limit not reached');
return; return;
} }
DBA::delete('post-engagement', ["`created` < ?", $limit]); DBA::delete('post-engagement', ["`created` < ?", $limit]);
Logger::notice('Cleared expired engagements', ['limit' => $limit, 'rows' => DBA::affectedRows()]); DI::logger()->notice('Cleared expired engagements', ['limit' => $limit, 'rows' => DBA::affectedRows()]);
} }
private static function getCreationDateLimit(bool $forDeletion): string private static function getCreationDateLimit(bool $forDeletion): string
@ -393,11 +396,11 @@ class Engagement
public static function escapeKeywords(string $fullTextSearch): string public static function escapeKeywords(string $fullTextSearch): string
{ {
foreach (SELF::SHORTCUTS as $search => $replace) { foreach (self::SHORTCUTS as $search => $replace) {
$fullTextSearch = preg_replace('~' . $search . ':(.[\w\*@\.-]+)~', $replace . ':$1', $fullTextSearch); $fullTextSearch = preg_replace('~' . $search . ':(.[\w\*@\.-]+)~', $replace . ':$1', $fullTextSearch);
} }
foreach (SELF::ALTERNATIVES as $search => $replace) { foreach (self::ALTERNATIVES as $search => $replace) {
$fullTextSearch = str_replace($search, $replace, $fullTextSearch); $fullTextSearch = str_replace($search, $replace, $fullTextSearch);
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Model\Post; namespace Friendica\Model\Post;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\DI; use Friendica\DI;
@ -28,12 +27,12 @@ class History
$post = Post::selectFirstPost($fields, ['uri-id' => $uri_id]); $post = Post::selectFirstPost($fields, ['uri-id' => $uri_id]);
if (empty($post)) { if (empty($post)) {
Logger::warning('Post not found', ['uri-id' => $uri_id]); DI::logger()->warning('Post not found', ['uri-id' => $uri_id]);
return; return;
} }
if ($item['edited'] <= $post['edited']) { if ($item['edited'] <= $post['edited']) {
Logger::info('New edit date is not newer than the old one', ['uri-id' => $uri_id, 'old' => $post['edited'], 'new' => $item['edited']]); DI::logger()->info('New edit date is not newer than the old one', ['uri-id' => $uri_id, 'old' => $post['edited'], 'new' => $item['edited']]);
return; return;
} }
@ -49,9 +48,9 @@ class History
if ($update) { if ($update) {
DBA::insert('post-history', $post, Database::INSERT_IGNORE); DBA::insert('post-history', $post, Database::INSERT_IGNORE);
Logger::info('Added history', ['uri-id' => $uri_id, 'edited' => $post['edited']]); DI::logger()->info('Added history', ['uri-id' => $uri_id, 'edited' => $post['edited']]);
} else { } else {
Logger::info('No content fields had been changed', ['uri-id' => $uri_id, 'edited' => $post['edited']]); DI::logger()->info('No content fields had been changed', ['uri-id' => $uri_id, 'edited' => $post['edited']]);
} }
} }
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Model\Post; namespace Friendica\Model\Post;
use Friendica\Core\Logger;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -53,14 +52,14 @@ class Link
} }
if (!in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'])) { if (!in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'])) {
Logger::info('Bad URL, quitting', ['uri-id' => $uriId, 'url' => $url]); DI::logger()->info('Bad URL, quitting', ['uri-id' => $uriId, 'url' => $url]);
return $url; return $url;
} }
$link = DBA::selectFirst('post-link', ['id'], ['uri-id' => $uriId, 'url' => $url]); $link = DBA::selectFirst('post-link', ['id'], ['uri-id' => $uriId, 'url' => $url]);
if (!empty($link['id'])) { if (!empty($link['id'])) {
$id = $link['id']; $id = $link['id'];
Logger::info('Found', ['id' => $id, 'uri-id' => $uriId, 'url' => $url]); DI::logger()->info('Found', ['id' => $id, 'uri-id' => $uriId, 'url' => $url]);
} else { } else {
$fields = self::fetchMimeType($url); $fields = self::fetchMimeType($url);
$fields['uri-id'] = $uriId; $fields['uri-id'] = $uriId;
@ -68,7 +67,7 @@ class Link
DBA::insert('post-link', $fields, Database::INSERT_IGNORE); DBA::insert('post-link', $fields, Database::INSERT_IGNORE);
$id = DBA::lastInsertId(); $id = DBA::lastInsertId();
Logger::info('Inserted', $fields); DI::logger()->info('Inserted', $fields);
} }
if (empty($id)) { if (empty($id)) {
@ -114,12 +113,12 @@ class Link
try { try {
$curlResult = HTTPSignature::fetchRaw($url, 0, [HttpClientOptions::TIMEOUT => $timeout, HttpClientOptions::ACCEPT_CONTENT => $accept]); $curlResult = HTTPSignature::fetchRaw($url, 0, [HttpClientOptions::TIMEOUT => $timeout, HttpClientOptions::ACCEPT_CONTENT => $accept]);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]); DI::logger()->notice('Error fetching url', ['url' => $url, 'exception' => $exception]);
return []; return [];
} }
if (!$curlResult->isSuccess()) { if (!$curlResult->isSuccess()) {
Logger::notice('Fetching unsuccessful', ['url' => $url]); DI::logger()->notice('Fetching unsuccessful', ['url' => $url]);
return []; return [];
} }

View file

@ -9,7 +9,6 @@ namespace Friendica\Model\Post;
use Friendica\Content\PageInfo; use Friendica\Content\PageInfo;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -67,12 +66,12 @@ class Media
public static function insert(array $media, bool $force = false): bool public static function insert(array $media, bool $force = false): bool
{ {
if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) { if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
Logger::warning('Incomplete media data', ['media' => $media]); DI::logger()->warning('Incomplete media data', ['media' => $media]);
return false; return false;
} }
if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) { if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url']]); DI::logger()->info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
return false; return false;
} }
@ -80,12 +79,12 @@ class Media
// and embedded as picture then we only store the picture or replace the document // and embedded as picture then we only store the picture or replace the document
$found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]); $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
if (!$force && !empty($found) && (!in_array($found['type'], [self::UNKNOWN, self::DOCUMENT]) || ($media['type'] == self::DOCUMENT))) { if (!$force && !empty($found) && (!in_array($found['type'], [self::UNKNOWN, self::DOCUMENT]) || ($media['type'] == self::DOCUMENT))) {
Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'found' => $found['type'], 'new' => $media['type']]); DI::logger()->info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'found' => $found['type'], 'new' => $media['type']]);
return false; return false;
} }
if (!ItemURI::exists($media['uri-id'])) { if (!ItemURI::exists($media['uri-id'])) {
Logger::info('Media referenced URI ID not found', ['uri-id' => $media['uri-id'], 'url' => $media['url']]); DI::logger()->info('Media referenced URI ID not found', ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
return false; return false;
} }
@ -97,7 +96,7 @@ class Media
// We are storing as fast as possible to avoid duplicated network requests // We are storing as fast as possible to avoid duplicated network requests
// when fetching additional information for pictures and other content. // when fetching additional information for pictures and other content.
$result = DBA::insert('post-media', $media, Database::INSERT_UPDATE); $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
Logger::info('Stored media', ['result' => $result, 'media' => $media]); DI::logger()->info('Stored media', ['result' => $result, 'media' => $media]);
$stored = $media; $stored = $media;
$media = self::fetchAdditionalData($media); $media = self::fetchAdditionalData($media);
@ -106,9 +105,9 @@ class Media
if (array_diff_assoc($media, $stored)) { if (array_diff_assoc($media, $stored)) {
$result = DBA::insert('post-media', $media, Database::INSERT_UPDATE); $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
Logger::info('Updated media', ['result' => $result, 'media' => $media]); DI::logger()->info('Updated media', ['result' => $result, 'media' => $media]);
} else { } else {
Logger::info('Nothing to update', ['media' => $media]); DI::logger()->info('Nothing to update', ['media' => $media]);
} }
return $result; return $result;
} }
@ -183,7 +182,7 @@ class Media
return $media; return $media;
} }
if (empty($media['mimetype']) || empty($media['size'])) { if (empty($media['mimetype']) || empty($media['size'])) {
Logger::debug('Unknown local link', ['url' => $media['url']]); DI::logger()->debug('Unknown local link', ['url' => $media['url']]);
} }
} }
@ -205,10 +204,10 @@ class Media
$media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? strlen($curlResult->getBodyString() ?? '')); $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? strlen($curlResult->getBodyString() ?? ''));
} }
} else { } else {
Logger::notice('Could not fetch head', ['media' => $media, 'code' => $curlResult->getReturnCode()]); DI::logger()->notice('Could not fetch head', ['media' => $media, 'code' => $curlResult->getReturnCode()]);
} }
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
} }
} }
@ -216,7 +215,7 @@ class Media
$media = self::addType($media); $media = self::addType($media);
} }
Logger::debug('Got type for url', ['type' => $media['type'], 'mimetype' => $media['mimetype'] ?? '', 'url' => $media['url']]); DI::logger()->debug('Got type for url', ['type' => $media['type'], 'mimetype' => $media['mimetype'] ?? '', 'url' => $media['url']]);
if ($media['type'] == self::IMAGE) { if ($media['type'] == self::IMAGE) {
$imagedata = Images::getInfoFromURLCached($media['url'], empty($media['description'])); $imagedata = Images::getInfoFromURLCached($media['url'], empty($media['description']));
@ -228,10 +227,10 @@ class Media
$media['blurhash'] = $imagedata['blurhash'] ?? null; $media['blurhash'] = $imagedata['blurhash'] ?? null;
if (!empty($imagedata['description']) && empty($media['description'])) { if (!empty($imagedata['description']) && empty($media['description'])) {
$media['description'] = $imagedata['description']; $media['description'] = $imagedata['description'];
Logger::debug('Detected text for image', $media); DI::logger()->debug('Detected text for image', $media);
} }
} else { } else {
Logger::notice('No image data', ['media' => $media]); DI::logger()->notice('No image data', ['media' => $media]);
} }
} }
@ -309,13 +308,13 @@ class Media
$item = Post::selectFirst([], ['id' => $id, 'network' => Protocol::FEDERATED]); $item = Post::selectFirst([], ['id' => $id, 'network' => Protocol::FEDERATED]);
if (empty($item['id'])) { if (empty($item['id'])) {
Logger::debug('Not a federated activity', ['id' => $id, 'uri-id' => $media['uri-id'], 'url' => $media['url']]); DI::logger()->debug('Not a federated activity', ['id' => $id, 'uri-id' => $media['uri-id'], 'url' => $media['url']]);
$media['type'] = $media['type'] == self::ACTIVITY ? self::JSON : $media['type']; $media['type'] = $media['type'] == self::ACTIVITY ? self::JSON : $media['type'];
return $media; return $media;
} }
if ($item['uri-id'] == $media['uri-id']) { if ($item['uri-id'] == $media['uri-id']) {
Logger::info('Media-Uri-Id is identical to Uri-Id', ['uri-id' => $media['uri-id']]); DI::logger()->info('Media-Uri-Id is identical to Uri-Id', ['uri-id' => $media['uri-id']]);
$media['type'] = $media['type'] == self::ACTIVITY ? self::JSON : $media['type']; $media['type'] = $media['type'] == self::ACTIVITY ? self::JSON : $media['type'];
return $media; return $media;
} }
@ -324,7 +323,7 @@ class Media
!empty($item['plink']) && Strings::compareLink($item['plink'], $media['url']) && !empty($item['plink']) && Strings::compareLink($item['plink'], $media['url']) &&
parse_url($item['plink'], PHP_URL_HOST) != parse_url($item['uri'], PHP_URL_HOST) parse_url($item['plink'], PHP_URL_HOST) != parse_url($item['uri'], PHP_URL_HOST)
) { ) {
Logger::debug('Not a link to an activity', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]); DI::logger()->debug('Not a link to an activity', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
$media['type'] = $media['type'] == self::ACTIVITY ? self::JSON : $media['type']; $media['type'] = $media['type'] == self::ACTIVITY ? self::JSON : $media['type'];
return $media; return $media;
} }
@ -357,7 +356,7 @@ class Media
$media['publisher-name'] = $gserver['site_name'] ?? null; $media['publisher-name'] = $gserver['site_name'] ?? null;
$media['publisher-image'] = null; $media['publisher-image'] = null;
Logger::debug('Activity detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]); DI::logger()->debug('Activity detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
return $media; return $media;
} }
@ -399,7 +398,7 @@ class Media
$media['publisher-name'] = $gserver['site_name'] ?? null; $media['publisher-name'] = $gserver['site_name'] ?? null;
$media['publisher-image'] = null; $media['publisher-image'] = null;
Logger::debug('Account detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'uri' => $contact['url']]); DI::logger()->debug('Account detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'uri' => $contact['url']]);
return $media; return $media;
} }
@ -415,7 +414,7 @@ class Media
if (empty($data['images'][0]['src']) && empty($data['text']) && empty($data['title'])) { if (empty($data['images'][0]['src']) && empty($data['text']) && empty($data['title'])) {
if (!empty($media['preview'])) { if (!empty($media['preview'])) {
$media = self::addPreviewData($media); $media = self::addPreviewData($media);
Logger::debug('Detected site data is empty, use suggested media data instead', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'type' => $data['type']]); DI::logger()->debug('Detected site data is empty, use suggested media data instead', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'type' => $data['type']]);
} }
} else { } else {
$media['preview'] = $data['images'][0]['src'] ?? null; $media['preview'] = $data['images'][0]['src'] ?? null;
@ -489,7 +488,7 @@ class Media
public static function addType(array $data): array public static function addType(array $data): array
{ {
if (empty($data['mimetype'])) { if (empty($data['mimetype'])) {
Logger::info('No MimeType provided', ['media' => $data]); DI::logger()->info('No MimeType provided', ['media' => $data]);
return $data; return $data;
} }
@ -501,7 +500,7 @@ class Media
{ {
$type = explode('/', current(explode(';', $mimeType))); $type = explode('/', current(explode(';', $mimeType)));
if (count($type) < 2) { if (count($type) < 2) {
Logger::info('Unknown MimeType', ['type' => $type, 'media' => $mimeType]); DI::logger()->info('Unknown MimeType', ['type' => $type, 'media' => $mimeType]);
return self::UNKNOWN; return self::UNKNOWN;
} }
@ -536,10 +535,10 @@ class Media
$type = self::APPLICATION; $type = self::APPLICATION;
} else { } else {
$type = self::UNKNOWN; $type = self::UNKNOWN;
Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $mimeType]); DI::logger()->info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $mimeType]);
} }
Logger::debug('Detected type', ['type' => $type, 'filetype' => $filetype, 'subtype' => $subtype, 'media' => $mimeType]); DI::logger()->debug('Detected type', ['type' => $type, 'filetype' => $filetype, 'subtype' => $subtype, 'media' => $mimeType]);
return $type; return $type;
} }
@ -777,15 +776,15 @@ class Media
// Search for pure links // Search for pure links
if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) { if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
foreach ($matches[1] as $url) { foreach ($matches[1] as $url) {
Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
$result = self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false); $result = self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false);
if ($result && !in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA])) { if ($result && !in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA])) {
self::revertHTMLType($uriid, $url, $fullbody); self::revertHTMLType($uriid, $url, $fullbody);
Logger::debug('Revert HTML type', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->debug('Revert HTML type', ['uri-id' => $uriid, 'url' => $url]);
} elseif ($result) { } elseif ($result) {
Logger::debug('Media had been added', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->debug('Media had been added', ['uri-id' => $uriid, 'url' => $url]);
} else { } else {
Logger::debug('Media had not been added', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->debug('Media had not been added', ['uri-id' => $uriid, 'url' => $url]);
} }
} }
} }
@ -793,15 +792,15 @@ class Media
// Search for links with descriptions // Search for links with descriptions
if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) { if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
foreach ($matches[1] as $url) { foreach ($matches[1] as $url) {
Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
$result = self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false); $result = self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false);
if ($result && !in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA])) { if ($result && !in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA])) {
self::revertHTMLType($uriid, $url, $fullbody); self::revertHTMLType($uriid, $url, $fullbody);
Logger::debug('Revert HTML type', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->debug('Revert HTML type', ['uri-id' => $uriid, 'url' => $url]);
} elseif ($result) { } elseif ($result) {
Logger::debug('Media has been added', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->debug('Media has been added', ['uri-id' => $uriid, 'url' => $url]);
} else { } else {
Logger::debug('Media has not been added', ['uri-id' => $uriid, 'url' => $url]); DI::logger()->debug('Media has not been added', ['uri-id' => $uriid, 'url' => $url]);
} }
} }
} }
@ -838,7 +837,7 @@ class Media
return; return;
} }
Logger::info('Adding attachment data', ['data' => $data]); DI::logger()->info('Adding attachment data', ['data' => $data]);
$attachment = [ $attachment = [
'uri-id' => $uriid, 'uri-id' => $uriid,
'type' => self::HTML, 'type' => self::HTML,

View file

@ -8,7 +8,6 @@
namespace Friendica\Model\Post; namespace Friendica\Model\Post;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -74,7 +73,7 @@ class SearchIndex
return; return;
} }
DBA::delete('post-searchindex', ["`created` < ?", $limit]); DBA::delete('post-searchindex', ["`created` < ?", $limit]);
Logger::notice('Cleared expired searchindex entries', ['limit' => $limit, 'rows' => DBA::affectedRows()]); DI::logger()->notice('Cleared expired searchindex entries', ['limit' => $limit, 'rows' => DBA::affectedRows()]);
} }
public static function searchAgeDateLimit(): string public static function searchAgeDateLimit(): string

View file

@ -10,7 +10,6 @@ namespace Friendica\Model\Post;
use BadMethodCallException; use BadMethodCallException;
use Exception; use Exception;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -174,14 +173,14 @@ class UserNotification
continue; continue;
} }
if (Contact\User::isBlocked($author_id, $uid) || Contact\User::isIgnored($author_id, $uid) || Contact\User::isCollapsed($author_id, $uid)) { if (Contact\User::isBlocked($author_id, $uid) || Contact\User::isIgnored($author_id, $uid) || Contact\User::isCollapsed($author_id, $uid)) {
Logger::debug('Author is blocked/ignored/collapsed by user', ['uid' => $uid, 'author' => $author_id, 'uri-id' => $item['uri-id']]); DI::logger()->debug('Author is blocked/ignored/collapsed by user', ['uid' => $uid, 'author' => $author_id, 'uri-id' => $item['uri-id']]);
return; return;
} }
} }
foreach (array_unique([$parent['author-gsid'], $parent['owner-gsid'], $parent['causer-gsid'], $item['author-gsid'], $item['owner-gsid'], $item['causer-gsid']]) as $gsid) { foreach (array_unique([$parent['author-gsid'], $parent['owner-gsid'], $parent['causer-gsid'], $item['author-gsid'], $item['owner-gsid'], $item['causer-gsid']]) as $gsid) {
if ($gsid && DI::userGServer()->isIgnoredByUser($uid, $gsid)) { if ($gsid && DI::userGServer()->isIgnoredByUser($uid, $gsid)) {
Logger::debug('Server is ignored by user', ['uid' => $uid, 'gsid' => $gsid, 'uri-id' => $item['uri-id']]); DI::logger()->debug('Server is ignored by user', ['uid' => $uid, 'gsid' => $gsid, 'uri-id' => $item['uri-id']]);
return; return;
} }
} }
@ -313,7 +312,7 @@ class UserNotification
return; return;
} }
Logger::info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]); DI::logger()->info('Set notification', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'notification-type' => $notification_type]);
$fields = ['notification-type' => $notification_type]; $fields = ['notification-type' => $notification_type];
Post\User::update($item['uri-id'], $uid, $fields); Post\User::update($item['uri-id'], $uid, $fields);

View file

@ -13,7 +13,6 @@ use Friendica\Content\Text\BBCode;
use Friendica\Content\Widget\ContactBlock; use Friendica\Content\Widget\ContactBlock;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Search; use Friendica\Core\Search;
@ -202,7 +201,7 @@ class Profile
{ {
$profile = User::getOwnerDataByNick($nickname); $profile = User::getOwnerDataByNick($nickname);
if (!isset($profile['account_removed']) || $profile['account_removed']) { if (!isset($profile['account_removed']) || $profile['account_removed']) {
Logger::info('profile error: ' . DI::args()->getQueryString()); DI::logger()->info('profile error: ' . DI::args()->getQueryString());
return []; return [];
} }
@ -306,11 +305,9 @@ class Profile
$local_user_is_self = DI::userSession()->getMyUrl() && ($profile['url'] == DI::userSession()->getMyUrl()); $local_user_is_self = DI::userSession()->getMyUrl() && ($profile['url'] == DI::userSession()->getMyUrl());
$visitor_is_authenticated = (bool)DI::userSession()->getMyUrl(); $visitor_is_authenticated = (bool)DI::userSession()->getMyUrl();
$visitor_is_following = $visitor_is_following = in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND])
|| in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]); || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]);
$visitor_is_followed = $visitor_is_followed = in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND])
|| in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]); || in_array($profile_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]);
$visitor_base_path = DI::userSession()->getMyUrl() ? preg_replace('=/profile/(.*)=ism', '', DI::userSession()->getMyUrl()) : ''; $visitor_base_path = DI::userSession()->getMyUrl() ? preg_replace('=/profile/(.*)=ism', '', DI::userSession()->getMyUrl()) : '';
@ -433,7 +430,7 @@ class Profile
$p['url'] = Contact::magicLinkById($cid, $profile['url']); $p['url'] = Contact::magicLinkById($cid, $profile['url']);
if (!isset($profile['hidewall'])) { if (!isset($profile['hidewall'])) {
Logger::warning('Missing hidewall key in profile array', ['profile' => $profile]); DI::logger()->warning('Missing hidewall key in profile array', ['profile' => $profile]);
} }
if ($profile['account-type'] == Contact::TYPE_COMMUNITY) { if ($profile['account-type'] == Contact::TYPE_COMMUNITY) {

View file

@ -7,13 +7,11 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory; use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory;
use Friendica\Navigation\Notifications\Entity\Notification as NotificationEntity; use Friendica\Navigation\Notifications\Entity\Notification as NotificationEntity;
use Friendica\Object\Api\Mastodon\Notification;
use Minishlink\WebPush\VAPID; use Minishlink\WebPush\VAPID;
class Subscription class Subscription
@ -133,7 +131,7 @@ class Subscription
$subscriptions = DBA::select('subscription', [], ['uid' => $notification->uid, $type => true]); $subscriptions = DBA::select('subscription', [], ['uid' => $notification->uid, $type => true]);
while ($subscription = DBA::fetch($subscriptions)) { while ($subscription = DBA::fetch($subscriptions)) {
Logger::info('Push notification', ['id' => $subscription['id'], 'uid' => $subscription['uid'], 'type' => $type]); DI::logger()->info('Push notification', ['id' => $subscription['id'], 'uid' => $subscription['uid'], 'type' => $type]);
Worker::add(Worker::PRIORITY_HIGH, 'PushSubscription', $subscription['id'], $notification->id); Worker::add(Worker::PRIORITY_HIGH, 'PushSubscription', $subscription['id'], $notification->id);
} }
DBA::close($subscriptions); DBA::close($subscriptions);

View file

@ -9,7 +9,6 @@ namespace Friendica\Model;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -101,11 +100,11 @@ class Tag
} }
if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) { if ((substr($url, 0, 7) == 'https//') || (substr($url, 0, 6) == 'http//')) {
Logger::notice('Wrong scheme in url', ['url' => $url]); DI::logger()->notice('Wrong scheme in url', ['url' => $url]);
} }
$cid = Contact::getIdForURL($url, 0, false); $cid = Contact::getIdForURL($url, 0, false);
Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]); DI::logger()->debug('Got id for contact', ['cid' => $cid, 'url' => $url]);
if (empty($cid)) { if (empty($cid)) {
$tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]); $tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]);
@ -141,14 +140,14 @@ class Tag
$condition = $fields; $condition = $fields;
$condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]; $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION];
if (DBA::exists('post-tag', $condition)) { if (DBA::exists('post-tag', $condition)) {
Logger::info('Tag already exists', $fields); DI::logger()->info('Tag already exists', $fields);
return; return;
} }
} }
DBA::insert('post-tag', $fields, Database::INSERT_IGNORE); DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
Logger::debug('Stored tag/mention', ['uri-id' => $uriId, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type]); DI::logger()->debug('Stored tag/mention', ['uri-id' => $uriId, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type]);
} }
/** /**
@ -170,26 +169,26 @@ class Tag
if (!empty($tag['type'])) { if (!empty($tag['type'])) {
$target = $tag['type']; $target = $tag['type'];
if ($target != self::GENERAL_COLLECTION) { if ($target != self::GENERAL_COLLECTION) {
Logger::debug('Found existing type', ['type' => $tag['type'], 'url' => $url]); DI::logger()->debug('Found existing type', ['type' => $tag['type'], 'url' => $url]);
return $target; return $target;
} }
} }
if ($url == ActivityPub::PUBLIC_COLLECTION) { if ($url == ActivityPub::PUBLIC_COLLECTION) {
$target = self::PUBLIC_COLLECTION; $target = self::PUBLIC_COLLECTION;
Logger::debug('Public collection', ['url' => $url]); DI::logger()->debug('Public collection', ['url' => $url]);
} else { } else {
if (DBA::exists('apcontact', ['followers' => $url])) { if (DBA::exists('apcontact', ['followers' => $url])) {
$target = self::FOLLOWER_COLLECTION; $target = self::FOLLOWER_COLLECTION;
Logger::debug('Found collection via existing apcontact', ['url' => $url]); DI::logger()->debug('Found collection via existing apcontact', ['url' => $url]);
} elseif (Contact::getIdForURL($url, 0, $fetch ? null : false)) { } elseif (Contact::getIdForURL($url, 0, $fetch ? null : false)) {
$target = self::ACCOUNT; $target = self::ACCOUNT;
Logger::debug('URL is an account', ['url' => $url]); DI::logger()->debug('URL is an account', ['url' => $url]);
} elseif ($fetch && ($target != self::GENERAL_COLLECTION)) { } elseif ($fetch && ($target != self::GENERAL_COLLECTION)) {
$content = HTTPSignature::fetch($url); $content = HTTPSignature::fetch($url);
if (!empty($content['type']) && ($content['type'] == 'OrderedCollection')) { if (!empty($content['type']) && ($content['type'] == 'OrderedCollection')) {
$target = self::GENERAL_COLLECTION; $target = self::GENERAL_COLLECTION;
Logger::debug('URL is an ordered collection', ['url' => $url]); DI::logger()->debug('URL is an ordered collection', ['url' => $url]);
} }
} }
} }
@ -199,7 +198,7 @@ class Tag
} }
if (empty($target)) { if (empty($target)) {
Logger::debug('No type could be detected', ['url' => $url]); DI::logger()->debug('No type could be detected', ['url' => $url]);
} }
return $target; return $target;
@ -238,7 +237,7 @@ class Tag
// Also log type // Also log type
$fields['type'] = $type; $fields['type'] = $type;
Logger::error('No tag id created', $fields); DI::logger()->error('No tag id created', $fields);
return 0; return 0;
} }
@ -305,7 +304,7 @@ class Tag
*/ */
public static function storeFromArray(array $item, string $tags = null) public static function storeFromArray(array $item, string $tags = null)
{ {
Logger::info('Check for tags', ['uri-id' => $item['uri-id'], 'hash' => $tags]); DI::logger()->info('Check for tags', ['uri-id' => $item['uri-id'], 'hash' => $tags]);
if (is_null($tags)) { if (is_null($tags)) {
$tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]; $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
@ -336,14 +335,14 @@ class Tag
*/ */
public static function storeRawTagsFromBody(int $uriId, string $body) public static function storeRawTagsFromBody(int $uriId, string $body)
{ {
Logger::info('Check for tags', ['uri-id' => $uriId]); DI::logger()->info('Check for tags', ['uri-id' => $uriId]);
$result = BBCode::getTags($body); $result = BBCode::getTags($body);
if (empty($result)) { if (empty($result)) {
return; return;
} }
Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]); DI::logger()->info('Found tags', ['uri-id' => $uriId, 'result' => $result]);
foreach ($result as $tag) { foreach ($result as $tag) {
if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) { if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
@ -397,7 +396,7 @@ class Tag
return; return;
} }
Logger::debug('Removing tag/mention', ['uri-id' => $uriId, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url]); DI::logger()->debug('Removing tag/mention', ['uri-id' => $uriId, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url]);
DBA::delete('post-tag', ['uri-id' => $uriId, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]); DBA::delete('post-tag', ['uri-id' => $uriId, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
} }
@ -576,7 +575,7 @@ class Tag
break; break;
default: default:
Logger::warning('Unknown tag type found', $tag); DI::logger()->warning('Unknown tag type found', $tag);
} }
} }
DBA::close($taglist); DBA::close($taglist);

View file

@ -15,7 +15,6 @@ use Friendica\App;
use Friendica\Content\Pager; use Friendica\Content\Pager;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Search; use Friendica\Core\Search;
use Friendica\Core\System; use Friendica\Core\System;
@ -857,7 +856,7 @@ class User
$fields['login_date'] = DateTimeFormat::utcNow(); $fields['login_date'] = DateTimeFormat::utcNow();
} }
Logger::debug('Set last activity for user', ['uid' => $user['uid'], 'fields' => $fields]); DI::logger()->debug('Set last activity for user', ['uid' => $user['uid'], 'fields' => $fields]);
self::update($fields, $user['uid']); self::update($fields, $user['uid']);
// Set the last activity for all identities of the user // Set the last activity for all identities of the user
DBA::update('user', $fields, ['parent-uid' => $user['uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]); DBA::update('user', $fields, ['parent-uid' => $user['uid'], 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]);
@ -898,7 +897,7 @@ class User
return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\Enums\PasswordStatus::EXPOSED; return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\Enums\PasswordStatus::EXPOSED;
} catch (Exception $e) { } catch (Exception $e) {
Logger::error('Password Exposed Exception: ' . $e->getMessage(), [ DI::logger()->error('Password Exposed Exception: ' . $e->getMessage(), [
'code' => $e->getCode(), 'code' => $e->getCode(),
'file' => $e->getFile(), 'file' => $e->getFile(),
'line' => $e->getLine(), 'line' => $e->getLine(),
@ -1246,7 +1245,7 @@ class User
$username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48)))); $username_max_length = max(1, min(64, intval(DI::config()->get('system', 'username_max_length', 48))));
if ($username_min_length > $username_max_length) { if ($username_min_length > $username_max_length) {
Logger::error(DI::l10n()->t('system.username_min_length (%s) and system.username_max_length (%s) are excluding each other, swapping values.', $username_min_length, $username_max_length)); DI::logger()->error(DI::l10n()->t('system.username_min_length (%s) and system.username_max_length (%s) are excluding each other, swapping values.', $username_min_length, $username_max_length));
$tmp = $username_min_length; $tmp = $username_min_length;
$username_min_length = $username_max_length; $username_min_length = $username_max_length;
$username_max_length = $tmp; $username_max_length = $tmp;
@ -1409,7 +1408,7 @@ class User
try { try {
$curlResult = DI::httpClient()->get($photo, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]); $curlResult = DI::httpClient()->get($photo, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]);
if ($curlResult->isSuccess()) { if ($curlResult->isSuccess()) {
Logger::debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $photo]); DI::logger()->debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $photo]);
$img_str = $curlResult->getBodyString(); $img_str = $curlResult->getBodyString();
$type = $curlResult->getContentType(); $type = $curlResult->getContentType();
} else { } else {
@ -1417,7 +1416,7 @@ class User
$type = ''; $type = '';
} }
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
$img_str = ''; $img_str = '';
$type = ''; $type = '';
} }
@ -1497,7 +1496,7 @@ class User
* @param bool $block Block state (default is true) * @param bool $block Block state (default is true)
* *
* @return bool True, if successfully blocked * @return bool True, if successfully blocked
*
* @throws Exception * @throws Exception
*/ */
public static function block(int $uid, bool $block = true): bool public static function block(int $uid, bool $block = true): bool
@ -1777,7 +1776,7 @@ class User
throw new \InvalidArgumentException('uid needs to be greater than 0'); throw new \InvalidArgumentException('uid needs to be greater than 0');
} }
Logger::notice('Removing user', ['user' => $uid]); DI::logger()->notice('Removing user', ['user' => $uid]);
$user = self::getById($uid); $user = self::getById($uid);
if (!$user) { if (!$user) {
@ -1947,10 +1946,13 @@ class User
'active_users_weekly' => 0, 'active_users_weekly' => 0,
]; ];
$userStmt = DBA::select('owner-view', ['uid', 'last-activity', 'last-item'], $userStmt = DBA::select(
'owner-view',
['uid', 'last-activity', 'last-item'],
["`verified` AND `last-activity` > ? AND NOT `blocked` ["`verified` AND `last-activity` > ? AND NOT `blocked`
AND NOT `account_removed` AND NOT `account_expired`", AND NOT `account_removed` AND NOT `account_expired`",
DBA::NULL_DATETIME]); DBA::NULL_DATETIME]
);
if (!DBA::isResult($userStmt)) { if (!DBA::isResult($userStmt)) {
return $statistics; return $statistics;
} }
@ -2086,19 +2088,19 @@ class User
$register_policy = DI::config()->get('config', 'register_policy'); $register_policy = DI::config()->get('config', 'register_policy');
if (!in_array($register_policy, [Module\Register::OPEN, Module\Register::CLOSED])) { if (!in_array($register_policy, [Module\Register::OPEN, Module\Register::CLOSED])) {
Logger::debug('Unsupported register policy.', ['policy' => $register_policy]); DI::logger()->debug('Unsupported register policy.', ['policy' => $register_policy]);
return; return;
} }
$users = DBA::count('user', ['blocked' => false, 'account_removed' => false, 'account_expired' => false]); $users = DBA::count('user', ['blocked' => false, 'account_removed' => false, 'account_expired' => false]);
if (($users >= $max_registered_users) && ($register_policy == Module\Register::OPEN)) { if (($users >= $max_registered_users) && ($register_policy == Module\Register::OPEN)) {
DI::config()->set('config', 'register_policy', Module\Register::CLOSED); DI::config()->set('config', 'register_policy', Module\Register::CLOSED);
Logger::notice('Max users reached, registration is closed.', ['users' => $users, 'max' => $max_registered_users]); DI::logger()->notice('Max users reached, registration is closed.', ['users' => $users, 'max' => $max_registered_users]);
} elseif (($users < $max_registered_users) && ($register_policy == Module\Register::CLOSED)) { } elseif (($users < $max_registered_users) && ($register_policy == Module\Register::CLOSED)) {
DI::config()->set('config', 'register_policy', Module\Register::OPEN); DI::config()->set('config', 'register_policy', Module\Register::OPEN);
Logger::notice('Below maximum users, registration is opened.', ['users' => $users, 'max' => $max_registered_users]); DI::logger()->notice('Below maximum users, registration is opened.', ['users' => $users, 'max' => $max_registered_users]);
} else { } else {
Logger::debug('Unchanged register policy', ['policy' => $register_policy, 'users' => $users, 'max' => $max_registered_users]); DI::logger()->debug('Unchanged register policy', ['policy' => $register_policy, 'users' => $users, 'max' => $max_registered_users]);
} }
} }
} }

View file

@ -8,8 +8,8 @@
namespace Friendica\Moderation\Repository; namespace Friendica\Moderation\Repository;
use Friendica\BaseEntity; use Friendica\BaseEntity;
use Friendica\Core\Logger;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\DI;
use Friendica\Model\Post; use Friendica\Model\Post;
use Friendica\Moderation\Factory; use Friendica\Moderation\Factory;
use Friendica\Moderation\Collection; use Friendica\Moderation\Collection;
@ -73,7 +73,7 @@ final class Report extends \Friendica\BaseRepository
if (Post::exists(['uri-id' => $post->uriId])) { if (Post::exists(['uri-id' => $post->uriId])) {
$this->db->insert('report-post', ['rid' => $newReportId, 'uri-id' => $post->uriId, 'status' => $post->status]); $this->db->insert('report-post', ['rid' => $newReportId, 'uri-id' => $post->uriId, 'status' => $post->status]);
} else { } else {
Logger::notice('Post does not exist', ['uri-id' => $post->uriId, 'report' => $Report]); DI::logger()->notice('Post does not exist', ['uri-id' => $post->uriId, 'report' => $Report]);
} }
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\ActivityPub; namespace Friendica\Module\ActivityPub;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -66,7 +65,7 @@ class Inbox extends BaseApi
} }
if (!HTTPSignature::isValidContentType($this->server['CONTENT_TYPE'] ?? '')) { if (!HTTPSignature::isValidContentType($this->server['CONTENT_TYPE'] ?? '')) {
Logger::notice('Unexpected content type', ['content-type' => $this->server['CONTENT_TYPE'] ?? '', 'agent' => $this->server['HTTP_USER_AGENT'] ?? '']); $this->logger->notice('Unexpected content type', ['content-type' => $this->server['CONTENT_TYPE'] ?? '', 'agent' => $this->server['HTTP_USER_AGENT'] ?? '']);
throw new \Friendica\Network\HTTPException\UnsupportedMediaTypeException(); throw new \Friendica\Network\HTTPException\UnsupportedMediaTypeException();
} }
@ -78,7 +77,7 @@ class Inbox extends BaseApi
} }
$tempfile = tempnam(System::getTempPath(), $filename); $tempfile = tempnam(System::getTempPath(), $filename);
file_put_contents($tempfile, json_encode(['parameters' => $this->parameters, 'header' => $_SERVER, 'body' => $postdata], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); file_put_contents($tempfile, json_encode(['parameters' => $this->parameters, 'header' => $_SERVER, 'body' => $postdata], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
Logger::notice('Incoming message stored', ['file' => $tempfile]); $this->logger->notice('Incoming message stored', ['file' => $tempfile]);
} }
if (!empty($this->parameters['nickname'])) { if (!empty($this->parameters['nickname'])) {

View file

@ -8,8 +8,6 @@
namespace Friendica\Module\ActivityPub; namespace Friendica\Module\ActivityPub;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -39,7 +37,7 @@ class Objects extends BaseModule
$itemuri = DBA::selectFirst('item-uri', ['id'], ['guid' => $this->parameters['guid']]); $itemuri = DBA::selectFirst('item-uri', ['id'], ['guid' => $this->parameters['guid']]);
if (DBA::isResult($itemuri)) { if (DBA::isResult($itemuri)) {
Logger::info('Provided GUID found.', ['guid' => $this->parameters['guid'], 'uri-id' => $itemuri['id']]); $this->logger->info('Provided GUID found.', ['guid' => $this->parameters['guid'], 'uri-id' => $itemuri['id']]);
} else { } else {
// The item URI does not always contain the GUID. This means that we have to search the URL instead // The item URI does not always contain the GUID. This means that we have to search the URL instead
$url = DI::baseUrl() . '/' . DI::args()->getQueryString(); $url = DI::baseUrl() . '/' . DI::args()->getQueryString();
@ -48,9 +46,9 @@ class Objects extends BaseModule
$itemuri = DBA::selectFirst('item-uri', ['guid', 'id'], ['uri' => [$url, $nurl, $ssl_url]]); $itemuri = DBA::selectFirst('item-uri', ['guid', 'id'], ['uri' => [$url, $nurl, $ssl_url]]);
if (DBA::isResult($itemuri)) { if (DBA::isResult($itemuri)) {
Logger::info('URL found.', ['url' => $url, 'guid' => $itemuri['guid'], 'uri-id' => $itemuri['id']]); $this->logger->info('URL found.', ['url' => $url, 'guid' => $itemuri['guid'], 'uri-id' => $itemuri['id']]);
} else { } else {
Logger::info('URL not found.', ['url' => $url]); $this->logger->info('URL not found.', ['url' => $url]);
throw new HTTPException\NotFoundException(); throw new HTTPException\NotFoundException();
} }
} }
@ -98,9 +96,11 @@ class Objects extends BaseModule
$data = ['@context' => ActivityPub::CONTEXT]; $data = ['@context' => ActivityPub::CONTEXT];
$data = array_merge($data, $activity['object']); $data = array_merge($data, $activity['object']);
} elseif (empty($this->parameters['activity']) || in_array($this->parameters['activity'], } elseif (empty($this->parameters['activity']) || in_array(
$this->parameters['activity'],
['Create', 'Announce', 'Update', 'Like', 'Dislike', 'Accept', 'Reject', ['Create', 'Announce', 'Update', 'Like', 'Dislike', 'Accept', 'Reject',
'TentativeAccept', 'Follow', 'Add'])) { 'TentativeAccept', 'Follow', 'Add']
)) {
$data = ActivityPub\Transmitter::createCachedActivityFromItem($item['id']); $data = ActivityPub\Transmitter::createCachedActivityFromItem($item['id']);
if (empty($data)) { if (empty($data)) {
throw new HTTPException\NotFoundException(); throw new HTTPException\NotFoundException();

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Admin; namespace Friendica\Module\Admin;
use Friendica\App;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Search; use Friendica\Core\Search;
use Friendica\Core\System; use Friendica\Core\System;
@ -20,7 +19,6 @@ use Friendica\Model\User;
use Friendica\Module\BaseAdmin; use Friendica\Module\BaseAdmin;
use Friendica\Module\Conversation\Community; use Friendica\Module\Conversation\Community;
use Friendica\Module\Register; use Friendica\Module\Register;
use Friendica\Navigation\SystemMessages;
use Friendica\Protocol\Relay; use Friendica\Protocol\Relay;
use Friendica\Util\BasePath; use Friendica\Util\BasePath;
use Friendica\Util\EMailer\MailBuilder; use Friendica\Util\EMailer\MailBuilder;
@ -105,6 +103,7 @@ class Site extends BaseAdmin
$optimize_tables = (!empty($_POST['optimize_tables']) ? intval(trim($_POST['optimize_tables'])) : false); $optimize_tables = (!empty($_POST['optimize_tables']) ? intval(trim($_POST['optimize_tables'])) : false);
$contact_discovery = (!empty($_POST['contact_discovery']) ? intval(trim($_POST['contact_discovery'])) : Contact\Relation::DISCOVERY_NONE); $contact_discovery = (!empty($_POST['contact_discovery']) ? intval(trim($_POST['contact_discovery'])) : Contact\Relation::DISCOVERY_NONE);
$update_active_contacts = (!empty($_POST['update_active_contacts']) ? intval(trim($_POST['update_active_contacts'])) : false); $update_active_contacts = (!empty($_POST['update_active_contacts']) ? intval(trim($_POST['update_active_contacts'])) : false);
$update_known_contacts = (!empty($_POST['update_known_contacts']) ? intval(trim($_POST['update_known_contacts'])) : false);
$synchronize_directory = (!empty($_POST['synchronize_directory']) ? intval(trim($_POST['synchronize_directory'])) : false); $synchronize_directory = (!empty($_POST['synchronize_directory']) ? intval(trim($_POST['synchronize_directory'])) : false);
$poco_requery_days = (!empty($_POST['poco_requery_days']) ? intval(trim($_POST['poco_requery_days'])) : 7); $poco_requery_days = (!empty($_POST['poco_requery_days']) ? intval(trim($_POST['poco_requery_days'])) : 7);
$poco_discovery = (!empty($_POST['poco_discovery']) ? intval(trim($_POST['poco_discovery'])) : false); $poco_discovery = (!empty($_POST['poco_discovery']) ? intval(trim($_POST['poco_discovery'])) : false);
@ -141,7 +140,6 @@ class Site extends BaseAdmin
$worker_defer_limit = (!empty($_POST['worker_defer_limit']) ? intval($_POST['worker_defer_limit']) : 15); $worker_defer_limit = (!empty($_POST['worker_defer_limit']) ? intval($_POST['worker_defer_limit']) : 15);
$worker_fetch_limit = (!empty($_POST['worker_fetch_limit']) ? intval($_POST['worker_fetch_limit']) : 1); $worker_fetch_limit = (!empty($_POST['worker_fetch_limit']) ? intval($_POST['worker_fetch_limit']) : 1);
$relay_directly = !empty($_POST['relay_directly']); $relay_directly = !empty($_POST['relay_directly']);
$relay_scope = (!empty($_POST['relay_scope']) ? trim($_POST['relay_scope']) : ''); $relay_scope = (!empty($_POST['relay_scope']) ? trim($_POST['relay_scope']) : '');
$relay_server_tags = (!empty($_POST['relay_server_tags']) ? trim($_POST['relay_server_tags']) : ''); $relay_server_tags = (!empty($_POST['relay_server_tags']) ? trim($_POST['relay_server_tags']) : '');
@ -178,6 +176,7 @@ class Site extends BaseAdmin
$transactionConfig->set('system', 'optimize_tables', $optimize_tables); $transactionConfig->set('system', 'optimize_tables', $optimize_tables);
$transactionConfig->set('system', 'contact_discovery', $contact_discovery); $transactionConfig->set('system', 'contact_discovery', $contact_discovery);
$transactionConfig->set('system', 'update_active_contacts', $update_active_contacts); $transactionConfig->set('system', 'update_active_contacts', $update_active_contacts);
$transactionConfig->set('system', 'update_known_contacts', $update_known_contacts);
$transactionConfig->set('system', 'synchronize_directory', $synchronize_directory); $transactionConfig->set('system', 'synchronize_directory', $synchronize_directory);
$transactionConfig->set('system', 'poco_requery_days', $poco_requery_days); $transactionConfig->set('system', 'poco_requery_days', $poco_requery_days);
$transactionConfig->set('system', 'poco_discovery', $poco_discovery); $transactionConfig->set('system', 'poco_discovery', $poco_discovery);
@ -546,6 +545,7 @@ class Site extends BaseAdmin
'<li>' . DI::l10n()->t('Interactors - contacts of our local contacts and contacts who interacted on locally visible postings are discovered for their followers/followings.') . '</li></ul>', '<li>' . DI::l10n()->t('Interactors - contacts of our local contacts and contacts who interacted on locally visible postings are discovered for their followers/followings.') . '</li></ul>',
$discovery_choices], $discovery_choices],
'$update_active_contacts' => ['update_active_contacts', DI::l10n()->t('Only update contacts/servers with local data'), DI::config()->get('system', 'update_active_contacts'), DI::l10n()->t('If enabled, the system will only look for changes in contacts and servers that engaged on this system by either being in a contact list of a user or when posts or comments exists from the contact on this system.')], '$update_active_contacts' => ['update_active_contacts', DI::l10n()->t('Only update contacts/servers with local data'), DI::config()->get('system', 'update_active_contacts'), DI::l10n()->t('If enabled, the system will only look for changes in contacts and servers that engaged on this system by either being in a contact list of a user or when posts or comments exists from the contact on this system.')],
'$update_known_contacts' => ['update_known_contacts', DI::l10n()->t('Only update contacts with relations'), DI::config()->get('system', 'update_known_contacts'), DI::l10n()->t('If enabled, the system will only look for changes in contacts that are in a contact list of a user on this system.')],
'$synchronize_directory' => ['synchronize_directory', DI::l10n()->t('Synchronize the contacts with the directory server'), DI::config()->get('system', 'synchronize_directory'), DI::l10n()->t('if enabled, the system will check periodically for new contacts on the defined directory server.')], '$synchronize_directory' => ['synchronize_directory', DI::l10n()->t('Synchronize the contacts with the directory server'), DI::config()->get('system', 'synchronize_directory'), DI::l10n()->t('if enabled, the system will check periodically for new contacts on the defined directory server.')],
'$poco_discovery' => ['poco_discovery', DI::l10n()->t('Discover contacts from other servers'), DI::config()->get('system', 'poco_discovery'), DI::l10n()->t('Periodically query other servers for contacts and servers that they know of. The system queries Friendica, Mastodon and Hubzilla servers. Keep it deactivated on small machines to decrease the database size and load.')], '$poco_discovery' => ['poco_discovery', DI::l10n()->t('Discover contacts from other servers'), DI::config()->get('system', 'poco_discovery'), DI::l10n()->t('Periodically query other servers for contacts and servers that they know of. The system queries Friendica, Mastodon and Hubzilla servers. Keep it deactivated on small machines to decrease the database size and load.')],

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\GNUSocial\Statusnet; namespace Friendica\Module\Api\GNUSocial\Statusnet;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\DI; use Friendica\DI;
@ -40,7 +39,7 @@ class Conversation extends BaseApi
$id = $this->getRequestValue($request, 'id', 0); $id = $this->getRequestValue($request, 'id', 0);
} }
Logger::info(BaseApi::LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]); $this->logger->info(BaseApi::LOG_PREFIX . '{subaction}', ['module' => 'api', 'action' => 'conversation', 'subaction' => 'show', 'id' => $id]);
// try to fetch the item for the local user - or the public item, if there is no local one // try to fetch the item for the local user - or the public item, if there is no local one
$item = Post::selectFirst(['parent-uri-id'], ['uri-id' => $id]); $item = Post::selectFirst(['parent-uri-id'], ['uri-id' => $id]);

View file

@ -7,8 +7,6 @@
namespace Friendica\Module\Api\Mastodon\Accounts; namespace Friendica\Module\Api\Mastodon\Accounts;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;

View file

@ -7,9 +7,7 @@
namespace Friendica\Module\Api\Mastodon\Accounts; namespace Friendica\Module\Api\Mastodon\Accounts;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Conversation; use Friendica\Model\Conversation;
@ -104,7 +102,7 @@ class Statuses extends BaseApi
$this->updateBoundaries($status, $item, $request['friendica_order']); $this->updateBoundaries($status, $item, $request['friendica_order']);
$statuses[] = $status; $statuses[] = $status;
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]); $this->logger->info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
} }
} }
DBA::close($items); DBA::close($items);

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Mastodon\Accounts; namespace Friendica\Module\Api\Mastodon\Accounts;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\Photo; use Friendica\Model\Photo;
@ -71,9 +70,9 @@ class UpdateCredentials extends BaseApi
$profile['about'] = $request['note']; $profile['about'] = $request['note'];
} }
Logger::debug('Patch data', ['data' => $request, 'files' => $_FILES]); $this->logger->debug('Patch data', ['data' => $request, 'files' => $_FILES]);
Logger::info('Update profile and user', ['uid' => $uid, 'user' => $user, 'profile' => $profile]); $this->logger->info('Update profile and user', ['uid' => $uid, 'user' => $user, 'profile' => $profile]);
if (!empty($request['avatar'])) { if (!empty($request['avatar'])) {
Photo::uploadAvatar($uid, $request['avatar']); Photo::uploadAvatar($uid, $request['avatar']);

View file

@ -7,8 +7,6 @@
namespace Friendica\Module\Api\Mastodon; namespace Friendica\Module\Api\Mastodon;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Post; use Friendica\Model\Post;
@ -64,7 +62,7 @@ class Bookmarks extends BaseApi
try { try {
$statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]); $this->logger->info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
} }
} }
DBA::close($items); DBA::close($items);

View file

@ -7,9 +7,7 @@
namespace Friendica\Module\Api\Mastodon; namespace Friendica\Module\Api\Mastodon;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
@ -34,7 +32,7 @@ class Directory extends BaseApi
'local' => false, // Only return local accounts. 'local' => false, // Only return local accounts.
], $request); ], $request);
Logger::info('directory', ['offset' => $request['offset'], 'limit' => $request['limit'], 'order' => $request['order'], 'local' => $request['local']]); $this->logger->info('directory', ['offset' => $request['offset'], 'limit' => $request['limit'], 'order' => $request['order'], 'local' => $request['local']]);
if ($request['local']) { if ($request['local']) {
$table = 'owner-view'; $table = 'owner-view';

View file

@ -7,8 +7,6 @@
namespace Friendica\Module\Api\Mastodon; namespace Friendica\Module\Api\Mastodon;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Item; use Friendica\Model\Item;
@ -66,7 +64,7 @@ class Favourited extends BaseApi
try { try {
$statuses[] = DI::mstdnStatus()->createFromUriId($item['thr-parent-id'], $uid, $display_quotes); $statuses[] = DI::mstdnStatus()->createFromUriId($item['thr-parent-id'], $uid, $display_quotes);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Post not fetchable', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'exception' => $exception]); $this->logger->info('Post not fetchable', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'exception' => $exception]);
} }
} }
DBA::close($items); DBA::close($items);

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Mastodon; namespace Friendica\Module\Api\Mastodon;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Attach; use Friendica\Model\Attach;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -33,10 +32,10 @@ class Media extends BaseApi
'focus' => '', // Two floating points (x,y), comma-delimited ranging from -1.0 to 1.0 'focus' => '', // Two floating points (x,y), comma-delimited ranging from -1.0 to 1.0
], $request); ], $request);
Logger::info('Photo post', ['request' => $request, 'files' => $_FILES]); $this->logger->info('Photo post', ['request' => $request, 'files' => $_FILES]);
if (empty($request['file'])) { if (empty($request['file'])) {
Logger::notice('Upload is invalid', ['request' => $request]); $this->logger->notice('Upload is invalid', ['request' => $request]);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity()); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity());
} }
@ -45,7 +44,7 @@ class Media extends BaseApi
if (in_array($type, [Post\Media::IMAGE, Post\Media::UNKNOWN, Post\Media::APPLICATION])) { if (in_array($type, [Post\Media::IMAGE, Post\Media::UNKNOWN, Post\Media::APPLICATION])) {
$media = Photo::upload($uid, $request['file'], '', null, null, '', '', $request['description']); $media = Photo::upload($uid, $request['file'], '', null, null, '', '', $request['description']);
if (!empty($media)) { if (!empty($media)) {
Logger::info('Uploaded photo', ['media' => $media]); $this->logger->info('Uploaded photo', ['media' => $media]);
$this->jsonExit(DI::mstdnAttachment()->createFromPhoto($media['id'])); $this->jsonExit(DI::mstdnAttachment()->createFromPhoto($media['id']));
} elseif ($type == Post\Media::IMAGE) { } elseif ($type == Post\Media::IMAGE) {
$this->jsonExit(DI::mstdnAttachment()->createFromPhoto($media['id'])); $this->jsonExit(DI::mstdnAttachment()->createFromPhoto($media['id']));
@ -58,20 +57,20 @@ class Media extends BaseApi
$maxFileSize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maxfilesize')); $maxFileSize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maxfilesize'));
if ($fileSize <= 0) { if ($fileSize <= 0) {
Logger::notice('Filesize is invalid', ['size' => $fileSize, 'request' => $request]); $this->logger->notice('Filesize is invalid', ['size' => $fileSize, 'request' => $request]);
@unlink($tempFileName); @unlink($tempFileName);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity()); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity());
} }
if ($maxFileSize && $fileSize > $maxFileSize) { if ($maxFileSize && $fileSize > $maxFileSize) {
Logger::notice('Filesize is too large', ['size' => $fileSize, 'max' => $maxFileSize, 'request' => $request]); $this->logger->notice('Filesize is too large', ['size' => $fileSize, 'max' => $maxFileSize, 'request' => $request]);
@unlink($tempFileName); @unlink($tempFileName);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity()); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity());
} }
$id = Attach::storeFile($tempFileName, self::getCurrentUserID(), $fileName, $request['file']['type'], '<' . Contact::getPublicIdByUserId(self::getCurrentUserID()) . '>'); $id = Attach::storeFile($tempFileName, self::getCurrentUserID(), $fileName, $request['file']['type'], '<' . Contact::getPublicIdByUserId(self::getCurrentUserID()) . '>');
@unlink($tempFileName); @unlink($tempFileName);
Logger::info('Uploaded media', ['id' => $id]); $this->logger->info('Uploaded media', ['id' => $id]);
$this->jsonExit(DI::mstdnAttachment()->createFromAttach($id)); $this->jsonExit(DI::mstdnAttachment()->createFromAttach($id));
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Mastodon; namespace Friendica\Module\Api\Mastodon;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -54,7 +53,7 @@ class Search extends BaseApi
$result = ['accounts' => [], 'statuses' => [], 'hashtags' => []]; $result = ['accounts' => [], 'statuses' => [], 'hashtags' => []];
if (empty($request['type']) || ($request['type'] == 'accounts')) { if (empty($request['type']) || ($request['type'] == 'accounts')) {
$result['accounts'] = self::searchAccounts($uid, $request['q'], $request['resolve'], $limit, $request['offset'], $request['following']); $result['accounts'] = $this->searchAccounts($uid, $request['q'], $request['resolve'], $limit, $request['offset'], $request['following']);
if (!is_array($result['accounts'])) { if (!is_array($result['accounts'])) {
// Curbing the search if we got an exact result // Curbing the search if we got an exact result
@ -64,7 +63,7 @@ class Search extends BaseApi
} }
if (empty($request['type']) || ($request['type'] == 'statuses')) { if (empty($request['type']) || ($request['type'] == 'statuses')) {
$result['statuses'] = self::searchStatuses($uid, $request['q'], $request['account_id'], $request['max_id'], $request['min_id'], $limit, $request['offset']); $result['statuses'] = $this->searchStatuses($uid, $request['q'], $request['account_id'], $request['max_id'], $request['min_id'], $limit, $request['offset']);
if (!is_array($result['statuses'])) { if (!is_array($result['statuses'])) {
// Curbing the search if we got an exact result // Curbing the search if we got an exact result
@ -74,7 +73,7 @@ class Search extends BaseApi
} }
if ((empty($request['type']) || ($request['type'] == 'hashtags')) && (strpos($request['q'], '@') == false)) { if ((empty($request['type']) || ($request['type'] == 'hashtags')) && (strpos($request['q'], '@') == false)) {
$result['hashtags'] = self::searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $this->parameters['version']); $result['hashtags'] = $this->searchHashtags($request['q'], $request['exclude_unreviewed'], $limit, $request['offset'], $this->parameters['version']);
} }
$this->jsonExit($result); $this->jsonExit($result);
@ -92,7 +91,7 @@ class Search extends BaseApi
* @throws \Friendica\Network\HTTPException\NotFoundException * @throws \Friendica\Network\HTTPException\NotFoundException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function searchAccounts(int $uid, string $q, bool $resolve, int $limit, int $offset, bool $following) private function searchAccounts(int $uid, string $q, bool $resolve, int $limit, int $offset, bool $following)
{ {
if (($offset == 0) && (strrpos($q, '@') > 0 || Network::isValidHttpUrl($q)) if (($offset == 0) && (strrpos($q, '@') > 0 || Network::isValidHttpUrl($q))
&& $id = Contact::getIdForURL($q, 0, $resolve ? null : false) && $id = Contact::getIdForURL($q, 0, $resolve ? null : false)
@ -121,7 +120,7 @@ class Search extends BaseApi
* @throws \Friendica\Network\HTTPException\NotFoundException * @throws \Friendica\Network\HTTPException\NotFoundException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function searchStatuses(int $uid, string $q, string $account_id, int $max_id, int $min_id, int $limit, int $offset) private function searchStatuses(int $uid, string $q, string $account_id, int $max_id, int $min_id, int $limit, int $offset)
{ {
if (Network::isValidHttpUrl($q)) { if (Network::isValidHttpUrl($q)) {
// Unique post search, any offset greater than 0 should return empty result // Unique post search, any offset greater than 0 should return empty result
@ -173,7 +172,7 @@ class Search extends BaseApi
try { try {
$statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]); $this->logger->info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
} }
} }
DBA::close($items); DBA::close($items);
@ -186,7 +185,7 @@ class Search extends BaseApi
return $statuses; return $statuses;
} }
private static function searchHashtags(string $q, bool $exclude_unreviewed, int $limit, int $offset, int $version): array private function searchHashtags(string $q, bool $exclude_unreviewed, int $limit, int $offset, int $version): array
{ {
$q = ltrim($q, '#'); $q = ltrim($q, '#');

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Mastodon\Timelines; namespace Friendica\Module\Api\Mastodon\Timelines;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Item; use Friendica\Model\Item;
@ -79,7 +78,7 @@ class Home extends BaseApi
$this->updateBoundaries($status, $item, $request['friendica_order']); $this->updateBoundaries($status, $item, $request['friendica_order']);
$statuses[] = $status; $statuses[] = $status;
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]); $this->logger->info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
} }
} }
DBA::close($items); DBA::close($items);

View file

@ -11,7 +11,6 @@ use Friendica\App\Arguments;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\AppHelper; use Friendica\AppHelper;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -84,7 +83,7 @@ class ListTimeline extends BaseApi
$this->updateBoundaries($status, $item, $request['friendica_order']); $this->updateBoundaries($status, $item, $request['friendica_order']);
$statuses[] = $status; $statuses[] = $status;
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]); $this->logger->info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
} }
} }

View file

@ -12,7 +12,6 @@ use Friendica\App\BaseURL;
use Friendica\AppHelper; use Friendica\AppHelper;
use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -113,7 +112,7 @@ class PublicTimeline extends BaseApi
$this->updateBoundaries($status, $item, $request['friendica_order']); $this->updateBoundaries($status, $item, $request['friendica_order']);
$statuses[] = $status; $statuses[] = $status;
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]); $this->logger->info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'error' => $th]);
} }
} }

View file

@ -7,9 +7,7 @@
namespace Friendica\Module\Api\Mastodon\Timelines; namespace Friendica\Module\Api\Mastodon\Timelines;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Item; use Friendica\Model\Item;
@ -107,7 +105,7 @@ class Tag extends BaseApi
try { try {
$statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]); $this->logger->info('Post not fetchable', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'exception' => $exception]);
} }
} }
DBA::close($items); DBA::close($items);

View file

@ -12,7 +12,6 @@ use Friendica\App\BaseURL;
use Friendica\AppHelper; use Friendica\AppHelper;
use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -67,7 +66,7 @@ class Statuses extends BaseApi
try { try {
$trending[] = DI::mstdnStatus()->createFromUriId($status['uri-id'], $uid, $display_quotes); $trending[] = DI::mstdnStatus()->createFromUriId($status['uri-id'], $uid, $display_quotes);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::info('Post not fetchable', ['uri-id' => $status['uri-id'], 'uid' => $uid, 'exception' => $exception]); $this->logger->info('Post not fetchable', ['uri-id' => $status['uri-id'], 'uid' => $uid, 'exception' => $exception]);
} }
} }
DBA::close($statuses); DBA::close($statuses);

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Twitter; namespace Friendica\Module\Api\Twitter;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Item; use Friendica\Model\Item;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
@ -29,7 +28,7 @@ class Favorites extends BaseApi
// in friendica starred item are private // in friendica starred item are private
// return favorites only for self // return favorites only for self
Logger::info(BaseApi::LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']); $this->logger->info(BaseApi::LOG_PREFIX . 'for {self}', ['module' => 'api', 'action' => 'favorites']);
// params // params
$count = $this->getRequestValue($request, 'count', 20, 1, 100); $count = $this->getRequestValue($request, 'count', 20, 1, 100);

View file

@ -12,7 +12,6 @@ use Friendica\App\Arguments;
use Friendica\App\BaseURL; use Friendica\App\BaseURL;
use Friendica\AppHelper; use Friendica\AppHelper;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Factory\Api\Twitter\User as TwitterUser; use Friendica\Factory\Api\Twitter\User as TwitterUser;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\User; use Friendica\Model\User;
@ -47,21 +46,21 @@ class Destroy extends ContactEndpoint
$owner = User::getOwnerDataById($uid); $owner = User::getOwnerDataById($uid);
if (!$owner) { if (!$owner) {
Logger::notice(BaseApi::LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]); $this->logger->notice(BaseApi::LOG_PREFIX . 'No owner {uid} found', ['module' => 'api', 'action' => 'friendships_destroy', 'uid' => $uid]);
throw new HTTPException\NotFoundException('Error Processing Request'); throw new HTTPException\NotFoundException('Error Processing Request');
} }
$contact_id = BaseApi::getContactIDForSearchterm($this->getRequestValue($request, 'screen_name', ''), $this->getRequestValue($request, 'profileurl', ''), $this->getRequestValue($request, 'user_id', 0), 0); $contact_id = BaseApi::getContactIDForSearchterm($this->getRequestValue($request, 'screen_name', ''), $this->getRequestValue($request, 'profileurl', ''), $this->getRequestValue($request, 'user_id', 0), 0);
if (empty($contact_id)) { if (empty($contact_id)) {
Logger::notice(BaseApi::LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']); $this->logger->notice(BaseApi::LOG_PREFIX . 'No user_id specified', ['module' => 'api', 'action' => 'friendships_destroy']);
throw new HTTPException\BadRequestException('no user_id specified'); throw new HTTPException\BadRequestException('no user_id specified');
} }
// Get Contact by given id // Get Contact by given id
$ucid = Contact::getUserContactId($contact_id, $uid); $ucid = Contact::getUserContactId($contact_id, $uid);
if (!$ucid) { if (!$ucid) {
Logger::notice(BaseApi::LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']); $this->logger->notice(BaseApi::LOG_PREFIX . 'Not following contact', ['module' => 'api', 'action' => 'friendships_destroy']);
throw new HTTPException\NotFoundException('Not following Contact'); throw new HTTPException\NotFoundException('Not following Contact');
} }
@ -71,7 +70,7 @@ class Destroy extends ContactEndpoint
try { try {
Contact::unfollow($contact); Contact::unfollow($contact);
} catch (Exception $e) { } catch (Exception $e) {
Logger::error(BaseApi::LOG_PREFIX . $e->getMessage(), ['contact' => $contact]); $this->logger->error(BaseApi::LOG_PREFIX . $e->getMessage(), ['contact' => $contact]);
throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator'); throw new HTTPException\InternalServerErrorException('Unable to unfollow this contact, please contact your administrator');
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Twitter\Media\Metadata; namespace Friendica\Module\Api\Twitter\Media\Metadata;
use Friendica\Core\Logger;
use Friendica\Model\Photo; use Friendica\Model\Photo;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException\BadRequestException; use Friendica\Network\HTTPException\BadRequestException;
@ -44,7 +43,7 @@ class Create extends BaseApi
throw new BadRequestException('No alt text.'); throw new BadRequestException('No alt text.');
} }
Logger::info('Updating metadata', ['media_id' => $data['media_id']]); $this->logger->info('Updating metadata', ['media_id' => $data['media_id']]);
$condition = ['id' => $data['media_id'], 'uid' => $uid]; $condition = ['id' => $data['media_id'], 'uid' => $uid];

View file

@ -7,8 +7,6 @@
namespace Friendica\Module\Api\Twitter\Media; namespace Friendica\Module\Api\Twitter\Media;
use Friendica\Core\Logger;
use Friendica\DI;
use Friendica\Model\Photo; use Friendica\Model\Photo;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\Network\HTTPException\BadRequestException; use Friendica\Network\HTTPException\BadRequestException;
@ -49,7 +47,7 @@ class Upload extends BaseApi
"friendica_preview_url" => $media["preview"] "friendica_preview_url" => $media["preview"]
]; ];
Logger::info('Media uploaded', ['return' => $returndata]); $this->logger->info('Media uploaded', ['return' => $returndata]);
$this->response->addFormattedContent('media', ['media' => $returndata], $this->parameters['extension'] ?? null); $this->response->addFormattedContent('media', ['media' => $returndata], $this->parameters['extension'] ?? null);
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Twitter\Statuses; namespace Friendica\Module\Api\Twitter\Statuses;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\DI; use Friendica\DI;
@ -34,7 +33,7 @@ class Show extends BaseApi
throw new BadRequestException('An id is missing.'); throw new BadRequestException('An id is missing.');
} }
Logger::notice('API: api_statuses_show: ' . $id); $this->logger->notice('API: api_statuses_show: ' . $id);
$conversation = !empty($request['conversation']); $conversation = !empty($request['conversation']);

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\Api\Twitter\Statuses; namespace Friendica\Module\Api\Twitter\Statuses;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -27,7 +26,7 @@ class UserTimeline extends BaseApi
$this->checkAllowedScope(BaseApi::SCOPE_READ); $this->checkAllowedScope(BaseApi::SCOPE_READ);
$uid = BaseApi::getCurrentUserID(); $uid = BaseApi::getCurrentUserID();
Logger::info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $request]); $this->logger->info('api_statuses_user_timeline', ['api_user' => $uid, '_REQUEST' => $request]);
$cid = BaseApi::getContactIDForSearchterm($this->getRequestValue($request, 'screen_name', ''), $this->getRequestValue($request, 'profileurl', ''), $this->getRequestValue($request, 'user_id', 0), $uid); $cid = BaseApi::getContactIDForSearchterm($this->getRequestValue($request, 'screen_name', ''), $this->getRequestValue($request, 'profileurl', ''), $this->getRequestValue($request, 'user_id', 0), $uid);
$count = $this->getRequestValue($request, 'count', 20, 1, 100); $count = $this->getRequestValue($request, 'count', 20, 1, 100);

View file

@ -8,7 +8,6 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Attach as MAttach; use Friendica\Model\Attach as MAttach;
@ -43,7 +42,7 @@ class Attach extends BaseModule
$data = MAttach::getData($item); $data = MAttach::getData($item);
if (is_null($data)) { if (is_null($data)) {
Logger::notice('NULL data for attachment with id ' . $item['id']); $this->logger->notice('NULL data for attachment with id ' . $item['id']);
throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('Item was not found.')); throw new \Friendica\Network\HTTPException\NotFoundException(DI::l10n()->t('Item was not found.'));
} }

View file

@ -14,7 +14,6 @@ use Friendica\App\Router;
use Friendica\AppHelper; use Friendica\AppHelper;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -227,7 +226,7 @@ class BaseApi extends BaseModule
self::setBoundaries($post_item['uri-id']); self::setBoundaries($post_item['uri-id']);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
Logger::debug('Error processing page boundary calculation, skipping', ['error' => $e]); $this->logger->debug('Error processing page boundary calculation, skipping', ['error' => $e]);
} }
} }
@ -455,7 +454,7 @@ class BaseApi extends BaseModule
$posts_week = Post::countThread($condition); $posts_week = Post::countThread($condition);
if ($posts_week > $throttle_week) { if ($posts_week > $throttle_week) {
Logger::notice('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]); $this->logger->notice('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
$error = $this->t('Too Many Requests'); $error = $this->t('Too Many Requests');
$error_description = $this->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week); $error_description = $this->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week);
$errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
@ -471,7 +470,7 @@ class BaseApi extends BaseModule
$posts_month = Post::countThread($condition); $posts_month = Post::countThread($condition);
if ($posts_month > $throttle_month) { if ($posts_month > $throttle_month) {
Logger::notice('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]); $this->logger->notice('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
$error = $this->t('Too Many Requests'); $error = $this->t('Too Many Requests');
$error_description = $this->tt('Monthly posting limit of %d post reached. The post was rejected.', 'Monthly posting limit of %d posts reached. The post was rejected.', $throttle_month); $error_description = $this->tt('Monthly posting limit of %d post reached. The post was rejected.', 'Monthly posting limit of %d posts reached. The post was rejected.', $throttle_month);
$errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);

View file

@ -9,7 +9,6 @@ namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Content\Pager; use Friendica\Content\Pager;
use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Search; use Friendica\Core\Search;
use Friendica\DI; use Friendica\DI;
@ -64,11 +63,19 @@ class BaseSearch extends BaseModule
$search = Network::convertToIdn($search); $search = Network::convertToIdn($search);
if (DI::mode()->isMobile()) { if (DI::mode()->isMobile()) {
$itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network', $itemsPerPage = DI::pConfig()->get(
DI::config()->get('system', 'itemspage_network_mobile')); DI::userSession()->getLocalUserId(),
'system',
'itemspage_mobile_network',
DI::config()->get('system', 'itemspage_network_mobile')
);
} else { } else {
$itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network', $itemsPerPage = DI::pConfig()->get(
DI::config()->get('system', 'itemspage_network')); DI::userSession()->getLocalUserId(),
'system',
'itemspage_network',
DI::config()->get('system', 'itemspage_network')
);
} }
$pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage); $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
@ -132,7 +139,8 @@ class BaseSearch extends BaseModule
'$filtered' => $filtered ? DI::l10n()->tt( '$filtered' => $filtered ? DI::l10n()->tt(
'%d result was filtered out because your node blocks the domain it is registered on. You can review the list of domains your node is currently blocking in the <a href="/friendica">About page</a>.', '%d result was filtered out because your node blocks the domain it is registered on. You can review the list of domains your node is currently blocking in the <a href="/friendica">About page</a>.',
'%d results were filtered out because your node blocks the domain they are registered on. You can review the list of domains your node is currently blocking in the <a href="/friendica">About page</a>.', '%d results were filtered out because your node blocks the domain they are registered on. You can review the list of domains your node is currently blocking in the <a href="/friendica">About page</a>.',
$filtered) : '', $filtered
) : '',
'$contacts' => $entries, '$contacts' => $entries,
'$paginate' => $pager->renderFull($results->getTotal()), '$paginate' => $pager->renderFull($results->getTotal()),
]); ]);

View file

@ -12,7 +12,6 @@ use Friendica\Content\ContactSelector;
use Friendica\Content\Nav; use Friendica\Content\Nav;
use Friendica\Content\Pager; use Friendica\Content\Pager;
use Friendica\Content\Widget; use Friendica\Content\Widget;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Theme; use Friendica\Core\Theme;
@ -121,7 +120,7 @@ class Contact extends BaseModule
try { try {
UpdateContact::add(Worker::PRIORITY_HIGH, $contact_id); UpdateContact::add(Worker::PRIORITY_HIGH, $contact_id);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['contact' => $contact]); DI::logger()->notice($e->getMessage(), ['contact' => $contact]);
} }
} }
@ -567,11 +566,11 @@ class Contact extends BaseModule
$alt_text = DI::l10n()->t('Mutual Friendship'); $alt_text = DI::l10n()->t('Mutual Friendship');
break; break;
case Model\Contact::FOLLOWER; case Model\Contact::FOLLOWER:
$alt_text = DI::l10n()->t('is a fan of yours'); $alt_text = DI::l10n()->t('is a fan of yours');
break; break;
case Model\Contact::SHARING; case Model\Contact::SHARING:
$alt_text = DI::l10n()->t('you are a fan of'); $alt_text = DI::l10n()->t('you are a fan of');
break; break;

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\OAuth; namespace Friendica\Module\OAuth;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
use Friendica\Security\OAuth; use Friendica\Security\OAuth;
@ -36,18 +35,18 @@ class Authorize extends BaseApi
], $request); ], $request);
if ($request['response_type'] != 'code') { if ($request['response_type'] != 'code') {
Logger::warning('Unsupported or missing response type', ['request' => $request]); $this->logger->warning('Unsupported or missing response type', ['request' => $request]);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity($this->t('Unsupported or missing response type'))); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity($this->t('Unsupported or missing response type')));
} }
if (empty($request['client_id']) || empty($request['redirect_uri'])) { if (empty($request['client_id']) || empty($request['redirect_uri'])) {
Logger::warning('Incomplete request data', ['request' => $request]); $this->logger->warning('Incomplete request data', ['request' => $request]);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity($this->t('Incomplete request data'))); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity($this->t('Incomplete request data')));
} }
$application = OAuth::getApplication($request['client_id'], $request['client_secret'], $request['redirect_uri']); $application = OAuth::getApplication($request['client_id'], $request['client_secret'], $request['redirect_uri']);
if (empty($application)) { if (empty($application)) {
Logger::warning('An application could not be fetched.', ['request' => $request]); $this->logger->warning('An application could not be fetched.', ['request' => $request]);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity()); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity());
} }
@ -59,14 +58,14 @@ class Authorize extends BaseApi
$uid = DI::userSession()->getLocalUserId(); $uid = DI::userSession()->getLocalUserId();
if (empty($uid)) { if (empty($uid)) {
Logger::info('Redirect to login'); $this->logger->info('Redirect to login');
DI::appHelper()->redirect('login?' . http_build_query(['return_authorize' => $redirect])); DI::appHelper()->redirect('login?' . http_build_query(['return_authorize' => $redirect]));
} else { } else {
Logger::info('Already logged in user', ['uid' => $uid]); $this->logger->info('Already logged in user', ['uid' => $uid]);
} }
if (!OAuth::existsTokenForUser($application, $uid) && !DI::session()->get('oauth_acknowledge')) { if (!OAuth::existsTokenForUser($application, $uid) && !DI::session()->get('oauth_acknowledge')) {
Logger::info('Redirect to acknowledge'); $this->logger->info('Redirect to acknowledge');
DI::appHelper()->redirect('oauth/acknowledge?' . http_build_query(['return_authorize' => $redirect, 'application' => $application['name']])); DI::appHelper()->redirect('oauth/acknowledge?' . http_build_query(['return_authorize' => $redirect, 'application' => $application['name']]));
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Module\OAuth; namespace Friendica\Module\OAuth;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\User; use Friendica\Model\User;
use Friendica\Module\BaseApi; use Friendica\Module\BaseApi;
@ -58,7 +57,8 @@ class Token extends BaseApi
if (empty($request['client_id']) || empty($request['client_secret'])) { if (empty($request['client_id']) || empty($request['client_secret'])) {
$this->logger->warning('Incomplete request data', ['request' => $request]); $this->logger->warning('Incomplete request data', ['request' => $request]);
$this->logAndJsonError(401, $this->errorFactory->Unauthorized('invalid_client', $this->t('Incomplete request data')));; $this->logAndJsonError(401, $this->errorFactory->Unauthorized('invalid_client', $this->t('Incomplete request data')));
;
} }
$application = OAuth::getApplication($request['client_id'], $request['client_secret'], $request['redirect_uri']); $application = OAuth::getApplication($request['client_id'], $request['client_secret'], $request['redirect_uri']);
@ -69,7 +69,7 @@ class Token extends BaseApi
$grant_type = (string) $request['grant_type']; $grant_type = (string) $request['grant_type'];
if (!in_array($grant_type, ['client_credentials', 'authorization_code'])) { if (!in_array($grant_type, ['client_credentials', 'authorization_code'])) {
Logger::warning('Unsupported or missing grant type', ['request' => $_REQUEST]); $this->logger->warning('Unsupported or missing grant type', ['request' => $_REQUEST]);
$this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity($this->t('Unsupported or missing grant type'))); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity($this->t('Unsupported or missing grant type')));
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\OpenWebAuthToken; use Friendica\Model\OpenWebAuthToken;
@ -60,7 +59,7 @@ class Owa extends BaseModule
$verified = HTTPSignature::verifyMagic($contact['pubkey']); $verified = HTTPSignature::verifyMagic($contact['pubkey']);
if ($verified && $verified['header_signed'] && $verified['header_valid']) { if ($verified && $verified['header_signed'] && $verified['header_valid']) {
Logger::debug('OWA header', ['addr' => $contact['addr'], 'data' => $verified]); $this->logger->debug('OWA header', ['addr' => $contact['addr'], 'data' => $verified]);
$ret['success'] = true; $ret['success'] = true;
$token = Strings::getRandomHex(32); $token = Strings::getRandomHex(32);
@ -77,10 +76,10 @@ class Owa extends BaseModule
openssl_public_encrypt($token, $result, $contact['pubkey']); openssl_public_encrypt($token, $result, $contact['pubkey']);
$ret['encrypted_token'] = Strings::base64UrlEncode($result); $ret['encrypted_token'] = Strings::base64UrlEncode($result);
} else { } else {
Logger::info('OWA fail', ['id' => $contact['id'], 'addr' => $contact['addr'], 'url' => $contact['url']]); $this->logger->info('OWA fail', ['id' => $contact['id'], 'addr' => $contact['addr'], 'url' => $contact['url']]);
} }
} else { } else {
Logger::info('Contact not found', ['handle' => $handle]); $this->logger->info('Contact not found', ['handle' => $handle]);
} }
} }
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\Contact\Header; use Friendica\Contact\Header;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -27,6 +26,7 @@ use Friendica\Network\HTTPException;
use Friendica\Network\HTTPException\NotModifiedException; use Friendica\Network\HTTPException\NotModifiedException;
use Friendica\Object\Image; use Friendica\Object\Image;
use Friendica\Security\OpenWebAuth; use Friendica\Security\OpenWebAuth;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Images; use Friendica\Util\Images;
use Friendica\Util\ParseUrl; use Friendica\Util\ParseUrl;
use Friendica\Util\Proxy; use Friendica\Util\Proxy;
@ -104,11 +104,11 @@ class Photo extends BaseApi
} }
if (empty($id)) { if (empty($id)) {
Logger::notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]); $this->logger->notice('No picture id was detected', ['parameters' => $this->parameters, 'query' => DI::args()->getQueryString()]);
throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.')); throw new HTTPException\NotFoundException(DI::l10n()->t('The Photo is not available.'));
} }
$photo = self::getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL); $photo = $this->getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL);
} else { } else {
$photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME); $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
$scale = 0; $scale = 0;
@ -172,7 +172,7 @@ class Photo extends BaseApi
$data = microtime(true) - $stamp; $data = microtime(true) - $stamp;
if (empty($imgdata)) { if (empty($imgdata)) {
Logger::warning('Invalid photo', ['id' => $photo['id']]); $this->logger->warning('Invalid photo', ['id' => $photo['id']]);
if (in_array($photo['backend-class'], [ExternalResource::NAME])) { if (in_array($photo['backend-class'], [ExternalResource::NAME])) {
$reference = json_decode($photo['backend-ref'], true); $reference = json_decode($photo['backend-ref'], true);
$error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']); $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']);
@ -232,7 +232,7 @@ class Photo extends BaseApi
$rest = $total - ($fetch + $data + $checksum + $output); $rest = $total - ($fetch + $data + $checksum + $output);
if (!is_null($scale) && ($scale < 4)) { if (!is_null($scale) && ($scale < 4)) {
Logger::debug('Performance:', [ $this->logger->debug('Performance:', [
'scale' => $scale, 'resource' => $photo['resource-id'], 'scale' => $scale, 'resource' => $photo['resource-id'],
'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3), 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3),
'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3), 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3),
@ -251,7 +251,7 @@ class Photo extends BaseApi
* @param int $customsize Custom size (?) * @param int $customsize Custom size (?)
* @return array|bool Array on success, false on error * @return array|bool Array on success, false on error
*/ */
private static function getPhotoById(int $id, string $type, int $customsize) private function getPhotoById(int $id, string $type, int $customsize)
{ {
switch ($type) { switch ($type) {
case 'preview': case 'preview':
@ -297,7 +297,7 @@ class Photo extends BaseApi
return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0); return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0);
case 'contact': case 'contact':
$fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'blurhash', 'xmpp', 'addr', 'network', 'failed', 'updated']; $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'blurhash', 'xmpp', 'addr', 'network', 'failed', 'updated', 'next-update'];
$contact = Contact::getById($id, $fields); $contact = Contact::getById($id, $fields);
if (empty($contact)) { if (empty($contact)) {
return false; return false;
@ -355,29 +355,29 @@ class Photo extends BaseApi
} else { } else {
// Only update federated accounts that hadn't failed before and hadn't been updated recently // Only update federated accounts that hadn't failed before and hadn't been updated recently
$update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed'] $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed']
&& ((time() - strtotime($contact['updated']) > 86400)); && ($contact['next-update'] < DateTimeFormat::utcNow());
if ($update) { if ($update) {
$curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE, HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]); $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE, HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]);
$update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404); $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404);
Logger::debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]); $this->logger->debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
} }
if ($update) { if ($update) {
try { try {
UpdateContact::add(Worker::PRIORITY_LOW, $id); UpdateContact::add(Worker::PRIORITY_LOW, $id);
Logger::info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]); $this->logger->info('Invalid file, contact update initiated', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
Logger::notice($e->getMessage(), ['id' => $id, 'contact' => $contact]); $this->logger->notice($e->getMessage(), ['id' => $id, 'contact' => $contact]);
} }
} else { } else {
Logger::info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]); $this->logger->info('Invalid file', ['cid' => $id, 'url' => $contact['url'], 'avatar' => $url]);
} }
} }
if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) { if (!empty($mimetext) && ($mime[0] != 'image') && ($mimetext != 'application/octet-stream')) {
Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]); $this->logger->info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]);
$mimetext = ''; $mimetext = '';
} }
if (!empty($mimetext)) { if (!empty($mimetext)) {
Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]); $this->logger->debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]);
} }
} }

View file

@ -14,7 +14,6 @@ use Friendica\Content\Text\BBCode;
use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Session\Capability\IHandleUserSessions; use Friendica\Core\Session\Capability\IHandleUserSessions;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -89,7 +88,7 @@ class Register extends BaseModule
if ($max_dailies) { if ($max_dailies) {
$count = DBA::count('user', ['`register_date` > UTC_TIMESTAMP - INTERVAL 1 day']); $count = DBA::count('user', ['`register_date` > UTC_TIMESTAMP - INTERVAL 1 day']);
if ($count >= $max_dailies) { if ($count >= $max_dailies) {
Logger::notice('max daily registrations exceeded.'); $this->logger->notice('max daily registrations exceeded.');
DI::sysmsg()->addNotice(DI::l10n()->t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.')); DI::sysmsg()->addNotice(DI::l10n()->t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.'));
return ''; return '';
} }
@ -250,7 +249,7 @@ class Register extends BaseModule
// Is there text in the tar pit? // Is there text in the tar pit?
if (!empty($arr['email'])) { if (!empty($arr['email'])) {
Logger::info('Tar pit', $arr); $this->logger->info('Tar pit', $arr);
DI::sysmsg()->addNotice(DI::l10n()->t('You have entered too much information.')); DI::sysmsg()->addNotice(DI::l10n()->t('You have entered too much information.'));
DI::baseUrl()->redirect('register/'); DI::baseUrl()->redirect('register/');
} }
@ -273,7 +272,7 @@ class Register extends BaseModule
} }
if ($arr['email'] != $arr['repeat']) { if ($arr['email'] != $arr['repeat']) {
Logger::info('Mail mismatch', $arr); $this->logger->info('Mail mismatch', $arr);
DI::sysmsg()->addNotice(DI::l10n()->t('Please enter the identical mail address in the second field.')); DI::sysmsg()->addNotice(DI::l10n()->t('Please enter the identical mail address in the second field.'));
$regdata = ['email' => $arr['email'], 'nickname' => $arr['nickname'], 'username' => $arr['username']]; $regdata = ['email' => $arr['email'], 'nickname' => $arr['nickname'], 'username' => $arr['username']];
DI::baseUrl()->redirect('register?' . http_build_query($regdata)); DI::baseUrl()->redirect('register?' . http_build_query($regdata));
@ -345,9 +344,11 @@ class Register extends BaseModule
DI::baseUrl()->redirect(); DI::baseUrl()->redirect();
} else { } else {
DI::sysmsg()->addNotice( DI::sysmsg()->addNotice(
DI::l10n()->t('Failed to send email message. Here your accout details:<br> login: %s<br> password: %s<br><br>You can change your password after login.', DI::l10n()->t(
'Failed to send email message. Here your accout details:<br> login: %s<br> password: %s<br><br>You can change your password after login.',
$user['email'], $user['email'],
$result['password']) $result['password']
)
); );
} }
} else { } else {

View file

@ -15,7 +15,6 @@ use Friendica\Content\Text\HTML;
use Friendica\Content\Widget; use Friendica\Content\Widget;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\Search; use Friendica\Core\Search;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -60,12 +59,14 @@ class Index extends BaseSearch
// 10 requests are "free", after the 11th only a call per minute is allowed // 10 requests are "free", after the 11th only a call per minute is allowed
$free_crawls = intval(DI::config()->get('system', 'free_crawls')); $free_crawls = intval(DI::config()->get('system', 'free_crawls'));
if ($free_crawls == 0) if ($free_crawls == 0) {
$free_crawls = 10; $free_crawls = 10;
}
$crawl_permit_period = intval(DI::config()->get('system', 'crawl_permit_period')); $crawl_permit_period = intval(DI::config()->get('system', 'crawl_permit_period'));
if ($crawl_permit_period == 0) if ($crawl_permit_period == 0) {
$crawl_permit_period = 10; $crawl_permit_period = 10;
}
$remote = $this->remoteAddress; $remote = $this->remoteAddress;
$result = DI::cache()->get('remote_search:' . $remote); $result = DI::cache()->get('remote_search:' . $remote);
@ -134,7 +135,7 @@ class Index extends BaseSearch
// Don't perform a fulltext or tag search on search results that look like an URL // Don't perform a fulltext or tag search on search results that look like an URL
// Tags don't look like an URL and the fulltext search does only work with natural words // Tags don't look like an URL and the fulltext search does only work with natural words
if (parse_url($search, PHP_URL_SCHEME) && parse_url($search, PHP_URL_HOST)) { if (parse_url($search, PHP_URL_SCHEME) && parse_url($search, PHP_URL_HOST)) {
Logger::info('Skipping tag and fulltext search since the search looks like a URL.', ['q' => $search]); $this->logger->info('Skipping tag and fulltext search since the search looks like a URL.', ['q' => $search]);
DI::sysmsg()->addNotice(DI::l10n()->t('No results.')); DI::sysmsg()->addNotice(DI::l10n()->t('No results.'));
return $o; return $o;
} }
@ -147,11 +148,19 @@ class Index extends BaseSearch
// No items will be shown if the member has a blocked profile wall. // No items will be shown if the member has a blocked profile wall.
if (DI::mode()->isMobile()) { if (DI::mode()->isMobile()) {
$itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network', $itemsPerPage = DI::pConfig()->get(
DI::config()->get('system', 'itemspage_network_mobile')); DI::userSession()->getLocalUserId(),
'system',
'itemspage_mobile_network',
DI::config()->get('system', 'itemspage_network_mobile')
);
} else { } else {
$itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network', $itemsPerPage = DI::pConfig()->get(
DI::config()->get('system', 'itemspage_network')); DI::userSession()->getLocalUserId(),
'system',
'itemspage_network',
DI::config()->get('system', 'itemspage_network')
);
} }
$last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0; $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0;
@ -159,11 +168,11 @@ class Index extends BaseSearch
$pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage); $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage);
if ($tag) { if ($tag) {
Logger::info('Start tag search.', ['q' => $search, 'start' => $pager->getStart(), 'items' => $pager->getItemsPerPage(), 'last' => $last_uriid]); $this->logger->info('Start tag search.', ['q' => $search, 'start' => $pager->getStart(), 'items' => $pager->getItemsPerPage(), 'last' => $last_uriid]);
$uriids = Tag::getURIIdListByTag($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid); $uriids = Tag::getURIIdListByTag($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
$count = Tag::countByTag($search, DI::userSession()->getLocalUserId()); $count = Tag::countByTag($search, DI::userSession()->getLocalUserId());
} else { } else {
Logger::info('Start fulltext search.', ['q' => $search]); $this->logger->info('Start fulltext search.', ['q' => $search]);
$uriids = Post\Content::getURIIdListBySearch($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid); $uriids = Post\Content::getURIIdListBySearch($search, DI::userSession()->getLocalUserId(), $pager->getStart(), $pager->getItemsPerPage(), $last_uriid);
$count = Post\Content::countBySearch($search, DI::userSession()->getLocalUserId()); $count = Post\Content::countBySearch($search, DI::userSession()->getLocalUserId());
} }
@ -197,7 +206,7 @@ class Index extends BaseSearch
'$title' => $title '$title' => $title
]); ]);
Logger::info('Start Conversation.', ['q' => $search]); $this->logger->info('Start Conversation.', ['q' => $search]);
$o .= DI::conversation()->render($items, Conversation::MODE_SEARCH, false, false, 'commented', DI::userSession()->getLocalUserId()); $o .= DI::conversation()->render($items, Conversation::MODE_SEARCH, false, false, 'commented', DI::userSession()->getLocalUserId());

View file

@ -9,9 +9,7 @@ namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Content; use Friendica\Content;
use Friendica\Core\Logger;
use Friendica\Core\Renderer; use Friendica\Core\Renderer;
use Friendica\Core\System;
use Friendica\DI; use Friendica\DI;
/** /**

View file

@ -7,7 +7,7 @@
namespace Friendica\Network\HTTPClient\Response; namespace Friendica\Network\HTTPClient\Response;
use Friendica\Core\Logger; use Friendica\DI;
use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses; use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use GuzzleHttp\RedirectMiddleware; use GuzzleHttp\RedirectMiddleware;
@ -65,7 +65,7 @@ class GuzzleResponse extends Response implements ICanHandleHttpResponses, Respon
} }
if (!$this->isSuccess) { if (!$this->isSuccess) {
Logger::debug('debug', ['info' => $this->getHeaders()]); DI::logger()->debug('debug', ['info' => $this->getHeaders()]);
} }
if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) { if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) {

View file

@ -12,7 +12,6 @@ use DomXPath;
use Exception; use Exception;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -116,7 +115,7 @@ class Probe
$data['photo'] = Network::addBasePath($data['photo'], $data['url']); $data['photo'] = Network::addBasePath($data['photo'], $data['url']);
if (!Network::isValidHttpUrl($data['photo'])) { if (!Network::isValidHttpUrl($data['photo'])) {
Logger::warning('Invalid URL for photo', ['url' => $data['url'], 'photo' => $data['photo']]); DI::logger()->warning('Invalid URL for photo', ['url' => $data['url'], 'photo' => $data['photo']]);
unset($data['photo']); unset($data['photo']);
} }
} }
@ -213,13 +212,13 @@ class Probe
$xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20); $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20);
Logger::info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url]); DI::logger()->info('Probing', ['host' => $host, 'ssl_url' => $ssl_url, 'url' => $url]);
$xrd = null; $xrd = null;
try { try {
$curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return []; return [];
} }
@ -234,7 +233,7 @@ class Probe
$host_url = 'https://' . $host; $host_url = 'https://' . $host;
} }
} elseif ($curlResult->isTimeout()) { } elseif ($curlResult->isTimeout()) {
Logger::info('Probing timeout', ['url' => $ssl_url]); DI::logger()->info('Probing timeout', ['url' => $ssl_url]);
self::$isTimeout = true; self::$isTimeout = true;
return []; return [];
} }
@ -243,12 +242,12 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return []; return [];
} }
$connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0); $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0);
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
Logger::info('Probing timeout', ['url' => $url]); DI::logger()->info('Probing timeout', ['url' => $url]);
self::$isTimeout = true; self::$isTimeout = true;
return []; return [];
} elseif ($connection_error && $ssl_connection_error) { } elseif ($connection_error && $ssl_connection_error) {
@ -261,13 +260,13 @@ class Probe
$host_url = 'http://' . $host; $host_url = 'http://' . $host;
} }
if (!is_object($xrd)) { if (!is_object($xrd)) {
Logger::info('No xrd object found', ['host' => $host]); DI::logger()->info('No xrd object found', ['host' => $host]);
return []; return [];
} }
$links = XML::elementToArray($xrd); $links = XML::elementToArray($xrd);
if (!isset($links['xrd']['link'])) { if (!isset($links['xrd']['link'])) {
Logger::info('No xrd data found', ['host' => $host]); DI::logger()->info('No xrd data found', ['host' => $host]);
return []; return [];
} }
@ -290,13 +289,13 @@ class Probe
} }
if (Network::isUrlBlocked($host_url)) { if (Network::isUrlBlocked($host_url)) {
Logger::info('Domain is blocked', ['url' => $host]); DI::logger()->info('Domain is blocked', ['url' => $host]);
return []; return [];
} }
self::$baseurl = $host_url; self::$baseurl = $host_url;
Logger::info('Probing successful', ['host' => $host]); DI::logger()->info('Probing successful', ['host' => $host]);
return $lrdd; return $lrdd;
} }
@ -317,7 +316,7 @@ class Probe
$webfinger = $data['webfinger']; $webfinger = $data['webfinger'];
if (empty($webfinger['links'])) { if (empty($webfinger['links'])) {
Logger::info('No webfinger links found', ['uri' => $uri]); DI::logger()->info('No webfinger links found', ['uri' => $uri]);
return []; return [];
} }
@ -464,7 +463,7 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return false; return false;
} }
if (!$curlResult->isSuccess()) { if (!$curlResult->isSuccess()) {
@ -631,7 +630,7 @@ class Probe
$baseurl = self::$baseurl; $baseurl = self::$baseurl;
} }
} else { } else {
Logger::info('URI was not detectable', ['uri' => $uri]); DI::logger()->info('URI was not detectable', ['uri' => $uri]);
return []; return [];
} }
@ -672,7 +671,7 @@ class Probe
private static function getWebfinger(string $template, string $type, string $uri, string $addr): ?array private static function getWebfinger(string $template, string $type, string $uri, string $addr): ?array
{ {
if (Network::isUrlBlocked($template)) { if (Network::isUrlBlocked($template)) {
Logger::info('Domain is blocked', ['url' => $template]); DI::logger()->info('Domain is blocked', ['url' => $template]);
return null; return null;
} }
@ -734,7 +733,7 @@ class Probe
$parts = parse_url($uri); $parts = parse_url($uri);
if (empty($parts['scheme']) && empty($parts['host']) && (empty($parts['path']) || strpos($parts['path'], '@') === false)) { if (empty($parts['scheme']) && empty($parts['host']) && (empty($parts['path']) || strpos($parts['path'], '@') === false)) {
Logger::info('URI was not detectable, probe for AT Protocol now', ['uri' => $uri]); DI::logger()->info('URI was not detectable, probe for AT Protocol now', ['uri' => $uri]);
return self::atProtocol($uri); return self::atProtocol($uri);
} }
@ -748,7 +747,7 @@ class Probe
return self::mail($uri, $uid); return self::mail($uri, $uid);
} }
Logger::info('Probing start', ['uri' => $uri]); DI::logger()->info('Probing start', ['uri' => $uri]);
if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) { if (!empty($ap_profile['addr']) && ($ap_profile['addr'] != $uri)) {
$data = self::getWebfingerArray($ap_profile['addr']); $data = self::getWebfingerArray($ap_profile['addr']);
@ -821,7 +820,7 @@ class Probe
$result['url'] = $uri; $result['url'] = $uri;
} }
Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]); DI::logger()->info('Probing done', ['uri' => $uri, 'network' => $result['network']]);
return $result; return $result;
} }
@ -906,7 +905,7 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($url, 'application/x-zot+json', [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($url, 'application/x-zot+json', [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return $data; return $data;
} }
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
@ -1017,7 +1016,7 @@ class Probe
[HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout', 20), HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO] [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout', 20), HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]
); );
} catch (\Throwable $e) { } catch (\Throwable $e) {
Logger::notice($e->getMessage(), ['url' => $url, 'type' => $type, 'class' => get_class($e)]); DI::logger()->notice($e->getMessage(), ['url' => $url, 'type' => $type, 'class' => get_class($e)]);
return null; return null;
} }
@ -1030,7 +1029,7 @@ class Probe
$webfinger = json_decode($data, true); $webfinger = json_decode($data, true);
if (!empty($webfinger)) { if (!empty($webfinger)) {
if (!isset($webfinger['links'])) { if (!isset($webfinger['links'])) {
Logger::info('No json webfinger links', ['url' => $url]); DI::logger()->info('No json webfinger links', ['url' => $url]);
return []; return [];
} }
return $webfinger; return $webfinger;
@ -1039,13 +1038,13 @@ class Probe
// If it is not JSON, maybe it is XML // If it is not JSON, maybe it is XML
$xrd = XML::parseString($data, true); $xrd = XML::parseString($data, true);
if (!is_object($xrd)) { if (!is_object($xrd)) {
Logger::info('No webfinger data retrievable', ['url' => $url]); DI::logger()->info('No webfinger data retrievable', ['url' => $url]);
return []; return [];
} }
$xrd_arr = XML::elementToArray($xrd); $xrd_arr = XML::elementToArray($xrd);
if (!isset($xrd_arr['xrd']['link'])) { if (!isset($xrd_arr['xrd']['link'])) {
Logger::info('No XML webfinger links', ['url' => $url]); DI::logger()->info('No XML webfinger links', ['url' => $url]);
return []; return [];
} }
@ -1092,7 +1091,7 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return $data; return $data;
} }
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
@ -1101,13 +1100,13 @@ class Probe
} }
$content = $curlResult->getBodyString(); $content = $curlResult->getBodyString();
if (!$content) { if (!$content) {
Logger::info('Empty body', ['url' => $noscrape_url]); DI::logger()->info('Empty body', ['url' => $noscrape_url]);
return $data; return $data;
} }
$json = json_decode($content, true); $json = json_decode($content, true);
if (!is_array($json)) { if (!is_array($json)) {
Logger::info('No json data', ['url' => $noscrape_url]); DI::logger()->info('No json data', ['url' => $noscrape_url]);
return $data; return $data;
} }
@ -1257,7 +1256,7 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return []; return [];
} }
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
@ -1521,7 +1520,7 @@ class Probe
self::$isTimeout = true; self::$isTimeout = true;
return $short ? false : []; return $short ? false : [];
} }
Logger::debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]); DI::logger()->debug('Fetched public key', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $pubkey]);
$pubkey = $curlResult->getBodyString(); $pubkey = $curlResult->getBodyString();
} }
@ -1552,7 +1551,7 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return []; return [];
} }
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
@ -1672,7 +1671,9 @@ class Probe
$parts = array_filter(explode('/', $path), 'strlen'); $parts = array_filter(explode('/', $path), 'strlen');
$absolutes = []; $absolutes = [];
foreach ($parts as $part) { foreach ($parts as $part) {
if ('.' == $part) continue; if ('.' == $part) {
continue;
}
if ('..' == $part) { if ('..' == $part) {
array_pop($absolutes); array_pop($absolutes);
} else { } else {
@ -1866,7 +1867,7 @@ class Probe
} }
$msgs = Email::poll($mbox, $uri); $msgs = Email::poll($mbox, $uri);
Logger::info('Messages found', ['uri' => $uri, 'count' => count($msgs)]); DI::logger()->info('Messages found', ['uri' => $uri, 'count' => count($msgs)]);
if (!count($msgs)) { if (!count($msgs)) {
return []; return [];
@ -1953,7 +1954,7 @@ class Probe
$fixed = $scheme . $host . $port . $path . $query . $fragment; $fixed = $scheme . $host . $port . $path . $query . $fragment;
Logger::debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]); DI::logger()->debug('Avatar fixed', ['base' => $base, 'avatar' => $avatar, 'fixed' => $fixed]);
return $fixed; return $fixed;
} }
@ -2015,7 +2016,7 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return ''; return '';
} }
@ -2055,7 +2056,7 @@ class Probe
if (is_string($outbox['first']) && ($outbox['first'] != $feed)) { if (is_string($outbox['first']) && ($outbox['first'] != $feed)) {
return self::updateFromOutbox($outbox['first'], $data); return self::updateFromOutbox($outbox['first'], $data);
} else { } else {
Logger::warning('Unexpected data', ['outbox' => $outbox]); DI::logger()->warning('Unexpected data', ['outbox' => $outbox]);
} }
return ''; return '';
} else { } else {
@ -2096,7 +2097,7 @@ class Probe
try { try {
$curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return ''; return '';
} }
if (!$curlResult->isSuccess() || !$curlResult->getBodyString()) { if (!$curlResult->isSuccess() || !$curlResult->getBodyString()) {
@ -2120,7 +2121,7 @@ class Probe
$updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null; $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null;
if (empty($published) || empty($updated)) { if (empty($published) || empty($updated)) {
Logger::notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]); DI::logger()->notice('Invalid entry for XPath.', ['entry' => $entry, 'url' => $data['url']]);
continue; continue;
} }

Some files were not shown because too many files have changed in this diff Show more