From e7eaa8d8a95cfb4d6d1d227008d6ed1765f57cb3 Mon Sep 17 00:00:00 2001 From: Art4 Date: Sun, 12 Jan 2025 21:04:38 +0000 Subject: [PATCH 01/91] Add composer script to partial fix code style --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 23dc4d4992..89c8a9f41d 100644 --- a/composer.json +++ b/composer.json @@ -171,6 +171,7 @@ "cs:fix": [ "@cs:install", "bin/dev/php-cs-fixer/vendor/bin/php-cs-fixer fix" - ] + ], + "cs:fix-develop": "TARGET_BRANCH=develop COMMAND=fix bin/dev/fix-codestyle.sh" } } From bf3004e4bfaf5edc5a26da282ad3cc3dec7a1962 Mon Sep 17 00:00:00 2001 From: Art4 Date: Sun, 12 Jan 2025 21:13:19 +0000 Subject: [PATCH 02/91] Replace Logger with DI::logger() in Page and BaseModule class --- src/App/Page.php | 3 ++- src/BaseModule.php | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/App/Page.php b/src/App/Page.php index 2fb18c4c5d..6470afd6b8 100644 --- a/src/App/Page.php +++ b/src/App/Page.php @@ -22,6 +22,7 @@ use Friendica\Core\Renderer; use Friendica\Core\Session\Model\UserSession; use Friendica\Core\System; use Friendica\Core\Theme; +use Friendica\DI; use Friendica\Network\HTTPException; use Friendica\Util\Images; use Friendica\Util\Network; @@ -102,7 +103,7 @@ class Page implements ArrayAccess $load = number_format(System::currentLoad(), 2); $runtime = number_format(microtime(true) - $this->timestamp, 3); 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'] ?? '']); } } diff --git a/src/BaseModule.php b/src/BaseModule.php index 908f750ba9..8c69fdcce8 100644 --- a/src/BaseModule.php +++ b/src/BaseModule.php @@ -412,8 +412,8 @@ abstract class BaseModule implements ICanHandleRequests public static function checkFormSecurityTokenRedirectOnError(string $err_redirect, string $typename = '', string $formname = 'form_security_token') { if (!self::checkFormSecurityToken($typename, $formname)) { - Logger::notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename); - Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]); + DI::logger()->notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename); + DI::logger()->debug('checkFormSecurityToken failed', ['request' => $_REQUEST]); DI::sysmsg()->addNotice(self::getFormSecurityStandardErrorMessage()); DI::baseUrl()->redirect($err_redirect); } @@ -422,8 +422,8 @@ abstract class BaseModule implements ICanHandleRequests public static function checkFormSecurityTokenForbiddenOnError(string $typename = '', string $formname = 'form_security_token') { if (!self::checkFormSecurityToken($typename, $formname)) { - Logger::notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename); - Logger::debug('checkFormSecurityToken failed', ['request' => $_REQUEST]); + DI::logger()->notice('checkFormSecurityToken failed: user ' . DI::userSession()->getLocalUserNickname() . ' - form element ' . $typename); + DI::logger()->debug('checkFormSecurityToken failed', ['request' => $_REQUEST]); throw new \Friendica\Network\HTTPException\ForbiddenException(); } From cb7534c82329cfe1e0d4298ea98fa542c8016c2b Mon Sep 17 00:00:00 2001 From: Art4 Date: Sun, 12 Jan 2025 21:14:33 +0000 Subject: [PATCH 03/91] Replace Logger with DI::logger() in Contact namespace --- src/Contact/Avatar.php | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/src/Contact/Avatar.php b/src/Contact/Avatar.php index 04f8778a59..5bafa07e24 100644 --- a/src/Contact/Avatar.php +++ b/src/Contact/Avatar.php @@ -47,36 +47,36 @@ class Avatar if (($avatar != $contact['avatar']) || $force) { 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'])) { $fields['photo'] = $contact['photo']; $fields['thumb'] = $contact['thumb']; $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; } try { $fetchResult = HTTPSignature::fetchRaw($avatar, 0, [HttpClientOptions::ACCEPT_CONTENT => [HttpClientAccept::IMAGE]]); } catch (\Exception $exception) { - Logger::notice('Avatar is invalid', ['avatar' => $avatar, 'exception' => $exception]); + DI::logger()->notice('Avatar is invalid', ['avatar' => $avatar, 'exception' => $exception]); return $fields; } if (!$fetchResult->isSuccess()) { - Logger::debug('Fetching was unsuccessful', ['avatar' => $avatar]); + DI::logger()->debug('Fetching was unsuccessful', ['avatar' => $avatar]); return $fields; } $img_str = $fetchResult->getBodyString(); if (empty($img_str)) { - Logger::debug('Avatar is invalid', ['avatar' => $avatar]); + DI::logger()->debug('Avatar is invalid', ['avatar' => $avatar]); return $fields; } $image = new Image($img_str, $fetchResult->getContentType(), $avatar); if (!$image->isValid()) { - Logger::debug('Avatar picture is invalid', ['avatar' => $avatar]); + DI::logger()->debug('Avatar picture is invalid', ['avatar' => $avatar]); return $fields; } @@ -89,7 +89,7 @@ class Avatar $fields['thumb'] = self::storeAvatarCache($image, $filename, Proxy::PIXEL_THUMB, $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; } @@ -155,36 +155,36 @@ class Avatar if (!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)) { - 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)) { - 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())) { - 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_group = filegroup($filepath); 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)) { - 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(); 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 ''; } @@ -257,7 +257,7 @@ class Avatar $localFile = self::getCacheFile($avatar); if (!empty($localFile)) { @unlink($localFile); - Logger::debug('Unlink avatar', ['avatar' => $avatar, 'local' => $localFile]); + DI::logger()->debug('Unlink avatar', ['avatar' => $avatar, 'local' => $localFile]); } } @@ -277,11 +277,11 @@ class Avatar if (!file_exists($basepath)) { // We only automatically create the folder when it is in the web root 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 ''; } 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 ''; } } From 16d3c363915925189dbcbae7c0aa2a486e8f983c Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 08:54:34 +0000 Subject: [PATCH 04/91] Replace Logger with DI::logger() in update.php --- update.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/update.php b/update.php index 493c095809..e77ca3e446 100644 --- a/update.php +++ b/update.php @@ -95,7 +95,7 @@ function update_1298() $fail++; } else { DBA::update('profile', [$translateKey => $key], ['id' => $data['id']]); - Logger::notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key, + DI::logger()->notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key, 'was' => $data[$translateKey]]); Contact::updateSelfFromUserID($data['id']); @@ -105,7 +105,7 @@ function update_1298() } } - Logger::notice($translateKey . ' fix completed', ['action' => 'update', 'translateKey' => $translateKey, 'Success' => $success, 'Fail' => $fail ]); + DI::logger()->notice($translateKey . ' fix completed', ['action' => 'update', 'translateKey' => $translateKey, 'Success' => $success, 'Fail' => $fail ]); } return Update::SUCCESS; } @@ -126,7 +126,7 @@ function update_1309() $deliver_options = ['priority' => Worker::PRIORITY_MEDIUM, 'dont_fork' => true]; Worker::add($deliver_options, 'Delivery', Delivery::POST, $item['id'], $entry['cid']); - Logger::info('Added delivery worker', ['item' => $item['id'], 'contact' => $entry['cid']]); + DI::logger()->info('Added delivery worker', ['item' => $item['id'], 'contact' => $entry['cid']]); DBA::delete('queue', ['id' => $entry['id']]); } return Update::SUCCESS; @@ -1388,7 +1388,7 @@ function update_1535() DI::config()->set('system', 'compute_circle_counts', true); } DI::config()->delete('system', 'compute_group_counts'); - + return Update::SUCCESS; } From ace375aacb5e3abb514cbfd200fb85c61d3f8371 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 08:55:34 +0000 Subject: [PATCH 05/91] Replace Logger with DI::logger() in theme folder --- view/theme/frio/theme.php | 2 +- view/theme/vier/style.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/view/theme/frio/theme.php b/view/theme/frio/theme.php index a1ab35805b..3779b3a5f4 100644 --- a/view/theme/frio/theme.php +++ b/view/theme/frio/theme.php @@ -65,7 +65,7 @@ function frio_install() Hook::register('nav_info', 'view/theme/frio/theme.php', 'frio_remote_nav'); Hook::register('display_item', 'view/theme/frio/theme.php', 'frio_display_item'); - Logger::info('installed theme frio'); + DI::logger()->info('installed theme frio'); } /** diff --git a/view/theme/vier/style.php b/view/theme/vier/style.php index 9c32e41bce..694fd663b2 100644 --- a/view/theme/vier/style.php +++ b/view/theme/vier/style.php @@ -37,7 +37,7 @@ foreach (['style', $style] as $file) { $modified = $stylemodified; } } else { - Logger::warning('Missing CSS file', ['file' => $stylecssfile, 'uid' => $uid]); + DI::logger()->warning('Missing CSS file', ['file' => $stylecssfile, 'uid' => $uid]); } } $modified = gmdate('r', $modified); From ef0fe65c07a34a9192a1b2b36806332d56e42f86 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 08:56:33 +0000 Subject: [PATCH 06/91] Replace Logger with DI::logger() in mod folder --- mod/item.php | 14 +++++++------- mod/photos.php | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/mod/item.php b/mod/item.php index c47dbac44d..efc603f983 100644 --- a/mod/item.php +++ b/mod/item.php @@ -56,7 +56,7 @@ function item_post() */ if (!$preview && !empty($_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); } else { DI::session()->set('post-random', $_REQUEST['post_id_random']); @@ -165,7 +165,7 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat // This enables interaction like starring and saving into folders if ($toplevel_item['uid'] == 0) { $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']; @@ -197,7 +197,7 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat $post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]); 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) { DI::baseUrl()->redirect($return_path); } @@ -213,7 +213,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']); } - Logger::debug('post_complete'); + DI::logger()->debug('post_complete'); item_post_return(DI::baseUrl(), $return_path); // NOTREACHED @@ -297,7 +297,7 @@ function item_process(array $post, array $request, bool $preview, string $return } if (!empty($post['cancel'])) { - Logger::info('mod_item: post cancelled by addon.'); + DI::logger()->info('mod_item: post cancelled by addon.'); if ($return_path) { DI::baseUrl()->redirect($return_path); } @@ -324,7 +324,7 @@ function item_post_return($baseurl, $return_path) $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload']; } - Logger::debug('post_json', ['json' => $json]); + DI::logger()->debug('post_json', ['json' => $json]); System::jsonExit($json); } @@ -444,7 +444,7 @@ function drop_item(int $id, string $return = ''): string item_redirect_after_action($item, $return); //NOTREACHED } 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::baseUrl()->redirect('display/' . $item['guid']); //NOTREACHED diff --git a/mod/photos.php b/mod/photos.php index c9fa60bca0..04b62055c2 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -277,7 +277,7 @@ function photos_post() } 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); From d4c90d41a03db651f85a60ae3e02853e05031d73 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 09:26:08 +0000 Subject: [PATCH 07/91] remove unused Logger imports --- mod/item.php | 1 - mod/photos.php | 1 - update.php | 1 - view/theme/frio/theme.php | 2 -- view/theme/vier/style.php | 1 - 5 files changed, 6 deletions(-) diff --git a/mod/item.php b/mod/item.php index efc603f983..f4dcf187fa 100644 --- a/mod/item.php +++ b/mod/item.php @@ -19,7 +19,6 @@ use Friendica\Content\Conversation; use Friendica\Content\Text\BBCode; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Core\Worker; diff --git a/mod/photos.php b/mod/photos.php index 04b62055c2..779d229000 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -13,7 +13,6 @@ use Friendica\Content\Text\BBCode; use Friendica\Core\ACL; use Friendica\Core\Addon; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Renderer; use Friendica\Core\System; use Friendica\Database\DBA; diff --git a/update.php b/update.php index e77ca3e446..b954247162 100644 --- a/update.php +++ b/update.php @@ -30,7 +30,6 @@ use Friendica\Contact\LocalRelationship\Entity\LocalRelationship; use Friendica\Core\Config\ValueObject\Cache; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Storage\Capability\ICanReadFromStorage; use Friendica\Core\Storage\Type\Database as DatabaseStorage; diff --git a/view/theme/frio/theme.php b/view/theme/frio/theme.php index 3779b3a5f4..1d9db39f77 100644 --- a/view/theme/frio/theme.php +++ b/view/theme/frio/theme.php @@ -16,13 +16,11 @@ use Friendica\App\Mode; use Friendica\AppHelper; use Friendica\Content\Text\Plaintext; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Renderer; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Contact; use Friendica\Model\Item; -use Friendica\Model\Profile; const FRIO_SCHEME_ACCENT_BLUE = '#1e87c2'; const FRIO_SCHEME_ACCENT_RED = '#b50404'; diff --git a/view/theme/vier/style.php b/view/theme/vier/style.php index 694fd663b2..7590ef248e 100644 --- a/view/theme/vier/style.php +++ b/view/theme/vier/style.php @@ -7,7 +7,6 @@ * */ -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Network\HTTPException\NotModifiedException; From 8c89c3777575a22c484221c1072946c8933cf34c Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 09:32:41 +0000 Subject: [PATCH 08/91] Replace Logger with DI::logger() in Content namespace --- src/Content/Item.php | 15 +++++++-------- src/Content/PageInfo.php | 5 ++--- src/Content/Text/BBCode.php | 13 ++++++------- src/Content/Text/Markdown.php | 3 +-- src/Content/Widget/VCard.php | 3 +-- 5 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/Content/Item.php b/src/Content/Item.php index 7343c06aff..d6e4cb7d59 100644 --- a/src/Content/Item.php +++ b/src/Content/Item.php @@ -14,7 +14,6 @@ use Friendica\Content\Text\BBCode\Video; use Friendica\Content\Text\HTML; use Friendica\Core\Hook; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues; use Friendica\Core\Protocol; use Friendica\Core\Session\Capability\IHandleUserSessions; @@ -520,18 +519,18 @@ class Item $only_to_group = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]); $private_id = $contact['id']; $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'] . '>') { $private_group = false; $only_to_group = true; $private_id = $contact['id']; $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 { - 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)) { // 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']; $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)) { - 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; } @@ -654,7 +653,7 @@ class Item $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]); if (!DBA::isResult($shared_item)) { - Logger::notice('Post does not exist.', ['guid' => $guid]); + DI::logger()->notice('Post does not exist.', ['guid' => $guid]); return ''; } @@ -1087,7 +1086,7 @@ class Item $expire_date = time() - ($expire_interval * 86400); $created_date = strtotime($created); 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; } } diff --git a/src/Content/PageInfo.php b/src/Content/PageInfo.php index 0557984776..99863b8910 100644 --- a/src/Content/PageInfo.php +++ b/src/Content/PageInfo.php @@ -8,7 +8,6 @@ namespace Friendica\Content; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Network\HTTPException; use Friendica\Util\ParseUrl; @@ -28,7 +27,7 @@ class PageInfo */ 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); 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; } diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index 900032c33e..458041f4bc 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -16,7 +16,6 @@ use Friendica\Content\OEmbed; use Friendica\Content\PageInfo; use Friendica\Content\Smilies; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\DI; @@ -328,7 +327,7 @@ class BBCode // than the maximum, then don't waste time looking for the images 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; $new_body = ''; @@ -348,7 +347,7 @@ class BBCode if (($textlen + $img_start) > $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); $textlen = $maxlen; } @@ -362,7 +361,7 @@ class BBCode if (($textlen + $img_end) > $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); $textlen = $maxlen; } @@ -385,11 +384,11 @@ class BBCode if (($textlen + strlen($orig_body)) > $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); } } 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; } @@ -2107,7 +2106,7 @@ class BBCode try { return (string)Uri::fromParts($parts); } 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; } } diff --git a/src/Content/Text/Markdown.php b/src/Content/Text/Markdown.php index 211369f712..f0ac888ab2 100644 --- a/src/Content/Text/Markdown.php +++ b/src/Content/Text/Markdown.php @@ -7,7 +7,6 @@ namespace Friendica\Content\Text; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Contact; @@ -97,7 +96,7 @@ class Markdown { // @TODO Temporary until we find the source of the null value to finally set the correct type-hint if (is_null($s)) { - Logger::warning('Received null value'); + DI::logger()->warning('Received null value'); return ''; } diff --git a/src/Content/Widget/VCard.php b/src/Content/Widget/VCard.php index 7feac4403c..b3943720d2 100644 --- a/src/Content/Widget/VCard.php +++ b/src/Content/Widget/VCard.php @@ -9,7 +9,6 @@ namespace Friendica\Content\Widget; use Friendica\Content\ContactSelector; use Friendica\Content\Text\BBCode; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\DI; @@ -34,7 +33,7 @@ class VCard public static function getHTML(array $contact, bool $hide_mention = false, bool $hide_follow = false): string { 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); From e3cf6b9c5462db5f43cd3d01a686c1871e7fdd48 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 09:39:19 +0000 Subject: [PATCH 09/91] Replace Logger with DI::logger() in Core classes --- src/Core/Addon.php | 6 +++--- src/Core/Protocol.php | 7 ++++--- src/Core/Search.php | 7 +++---- src/Core/System.php | 18 ++++++++--------- src/Core/Theme.php | 2 +- src/Core/Update.php | 46 +++++++++++++++++++++---------------------- 6 files changed, 43 insertions(+), 43 deletions(-) diff --git a/src/Core/Addon.php b/src/Core/Addon.php index 1119f2d392..42848da5ff 100644 --- a/src/Core/Addon.php +++ b/src/Core/Addon.php @@ -117,7 +117,7 @@ class 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); @include_once('addon/' . $addon . '/' . $addon . '.php'); @@ -150,7 +150,7 @@ class Addon 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); @include_once($addon_file_path); if (function_exists($addon . '_install')) { @@ -189,7 +189,7 @@ class Addon continue; } - Logger::debug("Addon {addon}: {action}", ['action' => 'reload', 'addon' => $name]); + DI::logger()->debug("Addon {addon}: {action}", ['action' => 'reload', 'addon' => $name]); self::uninstall($name); self::install($name); diff --git a/src/Core/Protocol.php b/src/Core/Protocol.php index e723b13d45..b170d4c881 100644 --- a/src/Core/Protocol.php +++ b/src/Core/Protocol.php @@ -8,6 +8,7 @@ namespace Friendica\Core; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Model\User; use Friendica\Network\HTTPException; use Friendica\Protocol\ActivityPub; @@ -123,7 +124,7 @@ class Protocol if ($protocol == self::DIASPORA) { $contact = Diaspora::sendShare($owner, $contact); - Logger::notice('share returns: ' . $contact); + DI::logger()->notice('share returns: ' . $contact); } elseif (in_array($protocol, [self::ACTIVITYPUB, self::DFRN])) { $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']); if (empty($activity_id)) { @@ -132,7 +133,7 @@ class Protocol } $success = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $owner['uid'], $activity_id); - Logger::notice('Follow returns: ' . $success); + DI::logger()->notice('Follow returns: ' . $success); } return true; @@ -150,7 +151,7 @@ class Protocol public static function unfollow(array $contact, array $owner): ?bool { 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; } diff --git a/src/Core/Search.php b/src/Core/Search.php index 776a0a0e50..56509b3b93 100644 --- a/src/Core/Search.php +++ b/src/Core/Search.php @@ -16,7 +16,6 @@ use Friendica\Network\HTTPException; use Friendica\Object\Search\ContactResult; use Friendica\Object\Search\ResultList; use Friendica\Util\Network; -use Friendica\Util\Strings; 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 { - 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); @@ -200,7 +199,7 @@ class Search */ 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()) { return []; @@ -223,7 +222,7 @@ class Search try { $curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTDISCOVER]); } 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 []; } if ($curlResult->isSuccess()) { diff --git a/src/Core/System.php b/src/Core/System.php index 32fdcf3b83..df494bec5d 100644 --- a/src/Core/System.php +++ b/src/Core/System.php @@ -322,7 +322,7 @@ class System } 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); @@ -340,7 +340,7 @@ class System public static function httpError($httpCode, $message = '', $content = '') { 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); @@ -373,7 +373,7 @@ class System public static function jsonError($httpCode, $content, $content_type = 'application/json') { 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); self::jsonExit($content, $content_type); @@ -520,7 +520,7 @@ class System public static function externalRedirect($url, $code = 302) { 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); } @@ -564,27 +564,27 @@ class System private static function isDirectoryUsable(string $directory): bool { if (empty($directory)) { - Logger::warning('Directory is empty. This shouldn\'t happen.'); + DI::logger()->warning('Directory is empty. This shouldn\'t happen.'); return false; } 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; } 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; } 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; } 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; } diff --git a/src/Core/Theme.php b/src/Core/Theme.php index eedc64e066..dac930ceb1 100644 --- a/src/Core/Theme.php +++ b/src/Core/Theme.php @@ -191,7 +191,7 @@ class Theme return true; } 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; } } diff --git a/src/Core/Update.php b/src/Core/Update.php index b6bf0e5a2d..7a221c38e1 100644 --- a/src/Core/Update.php +++ b/src/Core/Update.php @@ -178,7 +178,7 @@ class Update // If the Lock is acquired, never release it automatically to avoid double updates 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) $retryBuild = DI::config()->get('system', 'build'); @@ -192,7 +192,7 @@ class Update } 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'); return ''; } @@ -202,12 +202,12 @@ class Update // run the pre_update_nnnn functions in update.php 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', DateTimeFormat::utcNow() . ' ' . date('e'), $version)); $r = self::runUpdateFunction($version, 'pre_update', $sendMail); 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::lock()->release('dbupdate'); DI::config()->beginTransaction() @@ -216,12 +216,12 @@ class Update ->commit(); return $r; } else { - Logger::notice('Pre update executed.', ['version' => $version]); + DI::logger()->notice('Pre update executed.', ['version' => $version]); } } // update the structure in one call - Logger::notice('Execute structure update'); + DI::logger()->notice('Execute structure update'); $retval = DBStructure::performUpdate(false, $verbose); if (!empty($retval)) { if ($sendMail) { @@ -230,7 +230,7 @@ class Update $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::lock()->release('dbupdate'); DI::config()->beginTransaction() @@ -239,17 +239,17 @@ class Update ->commit(); return $retval; } 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 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', DateTimeFormat::utcNow() . ' ' . date('e'), $version)); $r = self::runUpdateFunction($version, 'update', $sendMail); 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::lock()->release('dbupdate'); DI::config()->beginTransaction() @@ -259,7 +259,7 @@ class Update return $r; } else { DI::config()->set('system', 'build', $version); - Logger::notice('Post update executed.', ['version' => $version]); + DI::logger()->notice('Post update executed.', ['version' => $version]); } } @@ -271,12 +271,12 @@ class Update ->delete('system', 'maintenance_reason') ->commit(); - Logger::notice('Update success.', ['from' => $stored, 'to' => $current]); + DI::logger()->notice('Update success.', ['from' => $stored, 'to' => $current]); if ($sendMail) { self::updateSuccessful($stored, $current); } } else { - Logger::warning('Update lock could not be acquired'); + DI::logger()->warning('Update lock could not be acquired'); } } } @@ -297,7 +297,7 @@ class Update { $funcname = $prefix . '_' . $version; - Logger::notice('Update function start.', ['function' => $funcname]); + DI::logger()->notice('Update function start.', ['function' => $funcname]); if (function_exists($funcname)) { // There could be a lot of processes running or about to run. @@ -310,9 +310,9 @@ class Update if (DI::lock()->acquire('dbupdate_function', 120, Cache\Enum\Duration::INFINITE)) { // call the specific update - Logger::notice('Pre update function start.', ['function' => $funcname]); + DI::logger()->notice('Pre update function start.', ['function' => $funcname]); $retval = $funcname(); - Logger::notice('Update function done.', ['function' => $funcname]); + DI::logger()->notice('Update function done.', ['function' => $funcname]); if ($retval) { if ($sendMail) { @@ -322,20 +322,20 @@ class Update 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'); return false; } else { DI::lock()->release('dbupdate_function'); - Logger::notice('Update function finished.', ['function' => $funcname]); + DI::logger()->notice('Update function finished.', ['function' => $funcname]); return true; } } else { - Logger::error('Locking failed.', ['function' => $funcname]); + DI::logger()->error('Locking failed.', ['function' => $funcname]); return false; } } else { - Logger::notice('Update function skipped.', ['function' => $funcname]); + DI::logger()->notice('Update function skipped.', ['function' => $funcname]); return true; } } @@ -352,7 +352,7 @@ class Update { $adminEmails = User::getAdminListForEmailing(['uid', 'language', 'email']); 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; } @@ -376,7 +376,7 @@ class Update DI::emailer()->send($email); } - Logger::alert('Database structure update failed.', ['error' => $error_message]); + DI::logger()->alert('Database structure update failed.', ['error' => $error_message]); } /** @@ -404,6 +404,6 @@ class Update DI::emailer()->send($email); } - Logger::debug('Database structure update successful.'); + DI::logger()->debug('Database structure update successful.'); } } From 0213001acb91a0838d30aae00551a102d30b7769 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 09:41:37 +0000 Subject: [PATCH 10/91] Replace Logger with DI::logger() in Worker classes --- src/Core/Worker.php | 98 +++++++++++++++++++------------------- src/Core/Worker/Cron.php | 27 +++++------ src/Core/Worker/Daemon.php | 9 ++-- 3 files changed, 66 insertions(+), 68 deletions(-) diff --git a/src/Core/Worker.php b/src/Core/Worker.php index c84de94f63..995239cde9 100644 --- a/src/Core/Worker.php +++ b/src/Core/Worker.php @@ -71,7 +71,7 @@ class Worker // At first check the maximum load. We shouldn't continue with a high load if (DI::system()->isMaxLoadReached()) { - Logger::notice('Pre check: maximum load reached, quitting.'); + DI::logger()->notice('Pre check: maximum load reached, quitting.'); return; } @@ -109,7 +109,7 @@ class Worker foreach ($r as $entry) { // The work will be done if (!self::execute($entry)) { - Logger::warning('Process execution failed, quitting.', ['entry' => $entry]); + DI::logger()->warning('Process execution failed, quitting.', ['entry' => $entry]); return; } @@ -131,14 +131,14 @@ class Worker if (DI::lock()->acquire(self::LOCK_WORKER, 0)) { // Count active workers and compare them with a maximum value that depends on the load if (self::tooMuchWorkers()) { - Logger::info('Active worker limit reached, quitting.'); + DI::logger()->info('Active worker limit reached, quitting.'); DI::lock()->release(self::LOCK_WORKER); return; } // Check free memory if (DI::system()->isMinMemoryReached()) { - Logger::warning('Memory limit reached, quitting.'); + DI::logger()->warning('Memory limit reached, quitting.'); DI::lock()->release(self::LOCK_WORKER); return; } @@ -149,7 +149,7 @@ class Worker // Quit the worker once every cron interval 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); if (Worker\Daemon::isMode()) { Worker\IPC::SetJobState(true); @@ -164,7 +164,7 @@ class Worker if (Worker\Daemon::isMode()) { 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 if (self::tooMuchWorkers()) { - Logger::info('Active worker limit reached, quitting.'); + DI::logger()->info('Active worker limit reached, quitting.'); return false; } // Do we have too few memory? if (DI::system()->isMinMemoryReached()) { - Logger::warning('Memory limit reached, quitting.'); + DI::logger()->warning('Memory limit reached, quitting.'); return false; } // Possibly there are too much database connections if (self::maxConnectionsReached()) { - Logger::warning('Maximum connections reached, quitting.'); + DI::logger()->warning('Maximum connections reached, quitting.'); return false; } // Possibly there are too much database processes that block the system if (DI::system()->isMaxProcessesReached()) { - Logger::warning('Maximum processes reached, quitting.'); + DI::logger()->warning('Maximum processes reached, quitting.'); return false; } @@ -322,19 +322,19 @@ class Worker // Quit when in maintenance 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; } // Constantly check the number of parallel database processes 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; } // Constantly check the number of available database connections to let the frontend be accessible at any time if (self::maxConnectionsReached()) { - Logger::warning('Max connection reached for process', ['pid' => $mypid]); + DI::logger()->warning('Max connection reached for process', ['pid' => $mypid]); return false; } @@ -348,7 +348,7 @@ class Worker } if (empty($argv)) { - Logger::warning('Parameter is empty', ['queue' => $queue]); + DI::logger()->warning('Parameter is empty', ['queue' => $queue]); return false; } @@ -387,7 +387,7 @@ class Worker } 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); DBA::delete('workerqueue', ['id' => $queue['id']]); self::$db_duration = (microtime(true) - $stamp); @@ -424,7 +424,7 @@ class Worker self::$db_duration = (microtime(true) - $stamp); self::$db_duration_write += (microtime(true) - $stamp); } else { - Logger::warning('Function does not exist', ['function' => $funcname]); + DI::logger()->warning('Function does not exist', ['function' => $funcname]); $stamp = (float)microtime(true); DBA::delete('workerqueue', ['id' => $queue['id']]); self::$db_duration = (microtime(true) - $stamp); @@ -477,7 +477,7 @@ class Worker { $cooldown = DI::config()->get('system', 'worker_cooldown', 0); if ($cooldown > 0) { - Logger::debug('Wait for cooldown.', ['cooldown' => $cooldown]); + DI::logger()->debug('Wait for cooldown.', ['cooldown' => $cooldown]); if ($cooldown < 1) { usleep($cooldown * 1000000); } else { @@ -501,7 +501,7 @@ class Worker while ($load = System::getLoadAvg($processes_cooldown != 0)) { if (($load_cooldown > 0) && ($load['average1'] > $load_cooldown)) { 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; } sleep(1); @@ -509,7 +509,7 @@ class Worker } if (($processes_cooldown > 0) && ($load['scheduled'] > $processes_cooldown)) { 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; } sleep(1); @@ -519,7 +519,7 @@ class Worker } 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 // The processlist only shows entries of the current user 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; 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; } } @@ -705,14 +705,14 @@ class Worker if ($used == 0) { 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; if ($level < $maxlevel) { 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; } @@ -815,16 +815,16 @@ class Worker $high_running = self::processWithPriorityActive($top_priority); 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; } } - 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. 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()) { Worker\IPC::SetJobState(true); } else { @@ -840,10 +840,10 @@ class Worker && !DBA::exists('workerqueue', ["`done` AND `executed` > ?", DateTimeFormat::utc('now - ' . $max_idletime . ' second')]) ) { 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; } 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(); if (empty($priority)) { - Logger::info('No tasks found'); + DI::logger()->info('No tasks found'); return []; } @@ -948,7 +948,7 @@ class Worker } DBA::close($tasks); - Logger::info('Found:', ['priority' => $priority, 'id' => $ids]); + DI::logger()->info('Found:', ['priority' => $priority, 'id' => $ids]); return $ids; } @@ -987,7 +987,7 @@ class Worker foreach ($priorities as $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; } } @@ -1009,14 +1009,14 @@ class Worker $i = 0; foreach ($running as $priority => $workers) { 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; } } if (!empty($waiting)) { $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; } @@ -1090,7 +1090,7 @@ class Worker $stamp = (float)microtime(true); 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( 'workerqueue', ['executed' => DateTimeFormat::utcNow(), 'pid' => $worker_pid], @@ -1155,7 +1155,7 @@ class Worker private static function forkProcess(bool $do_cron) { if (DI::system()->isMinMemoryReached()) { - Logger::warning('Memory limit reached - quitting'); + DI::logger()->warning('Memory limit reached - quitting'); return; } @@ -1165,21 +1165,21 @@ class Worker $pid = pcntl_fork(); if ($pid == -1) { DBA::connect(); - Logger::warning('Could not spawn worker'); + DI::logger()->warning('Could not spawn worker'); return; } elseif ($pid) { // The parent process continues here DBA::connect(); Worker\IPC::SetJobState(true, $pid); - Logger::info('Spawned new worker', ['pid' => $pid]); + DI::logger()->info('Spawned new worker', ['pid' => $pid]); $cycles = 0; while (Worker\IPC::JobsExists($pid) && (++$cycles < 100)) { 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; } @@ -1194,7 +1194,7 @@ class Worker 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); @@ -1202,7 +1202,7 @@ class Worker Worker\IPC::SetJobState(false, $process->pid); DI::process()->delete($process); - Logger::info('Worker ended', ['pid' => $process->pid]); + DI::logger()->info('Worker ended', ['pid' => $process->pid]); exit(); } @@ -1292,7 +1292,7 @@ class Worker $added = 0; 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; } @@ -1377,7 +1377,7 @@ class Worker $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; } @@ -1419,7 +1419,7 @@ class Worker $new_retrial = self::getNextRetrial($queue, $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; } @@ -1435,7 +1435,7 @@ class Worker $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); $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; $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) { // Calculate the window duration @@ -1467,7 +1467,7 @@ class Worker // Quit when the last cron execution had been after the previous window $last_cron = DI::keyValue()->get('last_cron_daily'); 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; } } @@ -1483,9 +1483,9 @@ class Worker } 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 { - 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; diff --git a/src/Core/Worker/Cron.php b/src/Core/Worker/Cron.php index b3940363c3..5e50a9159d 100644 --- a/src/Core/Worker/Cron.php +++ b/src/Core/Worker/Cron.php @@ -7,7 +7,6 @@ namespace Friendica\Core\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -32,7 +31,7 @@ class Cron */ public static function run() { - Logger::info('Add cron entries'); + DI::logger()->info('Add cron entries'); // Check for spooled items Worker::add(['priority' => Worker::PRIORITY_HIGH, 'force_priority' => true], 'SpoolPost'); @@ -99,7 +98,7 @@ class Cron // How long is the process already running? $duration = (time() - strtotime($entry["executed"])) / 60; 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); // We killed the stale process. @@ -116,7 +115,7 @@ class Cron DBA::update('workerqueue', ['executed' => DBA::NULL_DATETIME, 'created' => DateTimeFormat::utcNow(), 'priority' => $new_priority, 'pid' => 0], ['id' => $entry["id"]] ); } 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 +155,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()"); while ($delivery = DBA::fetch($deliveries)) { 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']); } if (($delivery['failed'] == 0) && $delivery['shared'] && !empty($delivery['gsid']) && GServer::isReachableById($delivery['gsid'])) { $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; } elseif ($delivery['failed'] < 3) { $priority = Worker::PRIORITY_HIGH; @@ -174,7 +173,7 @@ class Cron } 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 +181,9 @@ class Cron // Optimizing this table only last seconds if (DI::config()->get('system', 'optimize_tables')) { - Logger::info('Optimize start'); + DI::logger()->info('Optimize start'); DBA::optimizeTable('post-delivery'); - Logger::info('Optimize end'); + DI::logger()->info('Optimize end'); } } @@ -195,7 +194,7 @@ class Cron { foreach(DI::deliveryQueueItemRepo()->selectAggregateByServerId() as $delivery) { 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')); } @@ -210,15 +209,15 @@ class Cron } 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 if (DI::config()->get('system', 'optimize_tables')) { - Logger::info('Optimize start'); + DI::logger()->info('Optimize start'); DI::deliveryQueueItemRepo()->optimizeStorage(); - Logger::info('Optimize end'); + DI::logger()->info('Optimize end'); } } @@ -237,7 +236,7 @@ class Cron 'datetime' => $contact['created'], 'hash' => Strings::getRandomHex() ]; - Logger::notice('Adding missing intro', ['fields' => $fields]); + DI::logger()->notice('Adding missing intro', ['fields' => $fields]); DBA::insert('intro', $fields); } } diff --git a/src/Core/Worker/Daemon.php b/src/Core/Worker/Daemon.php index ee5f7a98ae..6d5729b013 100644 --- a/src/Core/Worker/Daemon.php +++ b/src/Core/Worker/Daemon.php @@ -8,7 +8,6 @@ namespace Friendica\Core\Worker; use Friendica\App\Mode; -use Friendica\Core\Logger; use Friendica\DI; /** @@ -98,11 +97,11 @@ class Daemon $pid = intval(file_get_contents($pidfile)); if (posix_kill($pid, 0)) { - Logger::info('Daemon process is running', ['pid' => $pid]); + DI::logger()->info('Daemon process is running', ['pid' => $pid]); return; } - Logger::warning('Daemon process is not running', ['pid' => $pid]); + DI::logger()->warning('Daemon process is not running', ['pid' => $pid]); self::spawn(); } @@ -114,8 +113,8 @@ class Daemon */ private static function spawn() { - Logger::notice('Starting new daemon process'); + DI::logger()->notice('Starting new daemon process'); DI::system()->run('bin/console.php', ['start']); - Logger::notice('New daemon process started'); + DI::logger()->notice('New daemon process started'); } } From 615f96012fa6954594d431994c73b710fe6ad687 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 09:44:21 +0000 Subject: [PATCH 11/91] Replace Logger with DI::logger() in Database classes --- src/Database/DBStructure.php | 5 +- src/Database/PostUpdate.php | 185 +++++++++++++++++------------------ 2 files changed, 94 insertions(+), 96 deletions(-) diff --git a/src/Database/DBStructure.php b/src/Database/DBStructure.php index 098a47d675..2e26453767 100644 --- a/src/Database/DBStructure.php +++ b/src/Database/DBStructure.php @@ -8,7 +8,6 @@ namespace Friendica\Database; use Exception; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Item; use Friendica\Model\User; @@ -238,7 +237,7 @@ class DBStructure $errors = ''; - Logger::info('updating structure'); + DI::logger()->info('updating structure'); // Get the current structure $database = []; @@ -251,7 +250,7 @@ class DBStructure foreach ($tables as $table) { $table = current($table); - Logger::info('updating structure', ['table' => $table]); + DI::logger()->info('updating structure', ['table' => $table]); $database[$table] = self::tableStructure($table); } } diff --git a/src/Database/PostUpdate.php b/src/Database/PostUpdate.php index 65c8e98c22..4db87bb429 100644 --- a/src/Database/PostUpdate.php +++ b/src/Database/PostUpdate.php @@ -7,7 +7,6 @@ namespace Friendica\Database; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\DI; 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_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]; DBA::update('item-delivery-data', ['queue_count' => -1], $condition); if (DBA::errorNo() != 0) { - Logger::error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage()); + DI::logger()->error('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage()); return false; } - Logger::info('Processed rows: ' . DBA::affectedRows()); + DI::logger()->info('Processed rows: ' . DBA::affectedRows()); DI::keyValue()->set('post_update_version', 1297); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -173,7 +172,7 @@ class PostUpdate return true; } - Logger::info('Start'); + DI::logger()->info('Start'); $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact` WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2` @@ -183,14 +182,14 @@ class PostUpdate Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0); 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']); } DBA::close($contact); DI::keyValue()->set('post_update_version', 1322); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -215,7 +214,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1329_id') ?? 0; - Logger::info('Start', ['item' => $id]); + DI::logger()->info('Start', ['item' => $id]); $start_id = $id; $rows = 0; @@ -224,7 +223,7 @@ class PostUpdate $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params); 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; } @@ -239,11 +238,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1329); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -270,7 +269,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1341_id') ?? 0; - Logger::info('Start', ['item' => $id]); + DI::logger()->info('Start', ['item' => $id]); $rows = 0; @@ -279,7 +278,7 @@ class PostUpdate ORDER BY `uri-id` LIMIT 100000", '%#%', '%@%', '%!%', $id); 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; } @@ -295,13 +294,13 @@ class PostUpdate 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 // The other entries will then be processed with the regular functionality if ($rows < 1000) { DI::keyValue()->set('post_update_version', 1341); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -328,7 +327,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1342_id') ?? 0; - Logger::info('Start', ['item' => $id]); + DI::logger()->info('Start', ['item' => $id]); $rows = 0; @@ -340,7 +339,7 @@ class PostUpdate Tag::HASHTAG, Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION, $id); 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; } @@ -371,13 +370,13 @@ class PostUpdate 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 // The other entries will then be processed with the regular functionality if ($rows < 1000) { DI::keyValue()->set('post_update_version', 1342); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -404,7 +403,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1345_id') ?? 0; - Logger::info('Start', ['item' => $id]); + DI::logger()->info('Start', ['item' => $id]); $rows = 0; @@ -415,7 +414,7 @@ class PostUpdate WHERE `iid` >= ? ORDER BY `iid` LIMIT 10000", $id); 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; } @@ -429,13 +428,13 @@ class PostUpdate 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 // The other entries will then be processed with the regular functionality if ($rows < 100) { DI::keyValue()->set('post_update_version', 1345); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -487,7 +486,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1346_id') ?? 0; - Logger::info('Start', ['item' => $id]); + DI::logger()->info('Start', ['item' => $id]); $rows = 0; @@ -496,7 +495,7 @@ class PostUpdate ['order' => ['oid'], 'limit' => 1000, 'group_by' => ['oid']]); 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; } @@ -521,13 +520,13 @@ class PostUpdate 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 // The other entries will then be processed with the regular functionality if ($rows < 10) { DI::keyValue()->set('post_update_version', 1346); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -555,7 +554,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1347_id') ?? 0; - Logger::info('Start', ['item' => $id]); + DI::logger()->info('Start', ['item' => $id]); $start_id = $id; $rows = 0; @@ -566,7 +565,7 @@ class PostUpdate WHERE `item`.`id` >= ? AND `item`.`vid` IS NULL ORDER BY `item`.`id` LIMIT 10000", Item::GRAVITY_ACTIVITY, $id); 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; } @@ -590,11 +589,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1347); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -617,7 +616,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1348_id') ?? 0; - Logger::info('Start', ['contact' => $id]); + DI::logger()->info('Start', ['contact' => $id]); $start_id = $id; $rows = 0; @@ -626,7 +625,7 @@ class PostUpdate $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params); 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; } @@ -643,11 +642,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1348); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -670,7 +669,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1349_id') ?? ''; - Logger::info('Start', ['apcontact' => $id]); + DI::logger()->info('Start', ['apcontact' => $id]); $start_id = $id; $rows = 0; @@ -679,7 +678,7 @@ class PostUpdate $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params); 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; } @@ -696,11 +695,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1349); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -721,7 +720,7 @@ class PostUpdate return true; } - Logger::info('Start'); + DI::logger()->info('Start'); $deleted = 0; $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro']; @@ -744,7 +743,7 @@ class PostUpdate DBA::close($photos); DI::keyValue()->set('post_update_version', 1383); - Logger::info('Done', ['deleted' => $deleted]); + DI::logger()->info('Done', ['deleted' => $deleted]); return true; } @@ -763,13 +762,13 @@ class PostUpdate } $condition = ["`hash` IS NULL"]; - Logger::info('Start', ['rest' => DBA::count('photo', $condition)]); + DI::logger()->info('Start', ['rest' => DBA::count('photo', $condition)]); $rows = 0; $photos = DBA::select('photo', [], $condition, ['limit' => 100]); 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; } @@ -782,11 +781,11 @@ class PostUpdate } DBA::close($photos); - Logger::info('Processed', ['rows' => $rows]); + DI::logger()->info('Processed', ['rows' => $rows]); if ($rows <= 100) { DI::keyValue()->set('post_update_version', 1384); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -813,13 +812,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)", '']; - Logger::info('Start', ['rest' => DBA::count('item', $condition)]); + DI::logger()->info('Start', ['rest' => DBA::count('item', $condition)]); $rows = 0; $items = DBA::select('item', ['uri-id', 'uid', 'extid'], $condition, ['order' => ['id'], 'limit' => 10000]); 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; } @@ -829,11 +828,11 @@ class PostUpdate } DBA::close($items); - Logger::info('Processed', ['rows' => $rows]); + DI::logger()->info('Processed', ['rows' => $rows]); if ($rows <= 100) { DI::keyValue()->set('post_update_version', 1400); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -855,13 +854,13 @@ class PostUpdate } $condition = ["`uri-id` IS NULL"]; - Logger::info('Start', ['rest' => DBA::count('contact', $condition)]); + DI::logger()->info('Start', ['rest' => DBA::count('contact', $condition)]); $rows = 0; $contacts = DBA::select('contact', ['id', 'url'], $condition, ['limit' => 1000]); 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; } @@ -871,11 +870,11 @@ class PostUpdate } DBA::close($contacts); - Logger::info('Processed', ['rows' => $rows]); + DI::logger()->info('Processed', ['rows' => $rows]); if ($rows <= 100) { DI::keyValue()->set('post_update_version', 1424); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -902,13 +901,13 @@ class PostUpdate } $condition = ["`uri-id` IS NULL"]; - Logger::info('Start', ['rest' => DBA::count('fcontact', $condition)]); + DI::logger()->info('Start', ['rest' => DBA::count('fcontact', $condition)]); $rows = 0; $fcontacts = DBA::select('fcontact', ['id', 'url', 'guid'], $condition, ['limit' => 1000]); 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; } @@ -923,11 +922,11 @@ class PostUpdate } DBA::close($fcontacts); - Logger::info('Processed', ['rows' => $rows]); + DI::logger()->info('Processed', ['rows' => $rows]); if ($rows <= 100) { DI::keyValue()->set('post_update_version', 1425); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -949,13 +948,13 @@ class PostUpdate } $condition = ["`uri-id` IS NULL"]; - Logger::info('Start', ['rest' => DBA::count('apcontact', $condition)]); + DI::logger()->info('Start', ['rest' => DBA::count('apcontact', $condition)]); $rows = 0; $apcontacts = DBA::select('apcontact', ['url', 'uuid'], $condition, ['limit' => 1000]); 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; } @@ -970,11 +969,11 @@ class PostUpdate } DBA::close($apcontacts); - Logger::info('Processed', ['rows' => $rows]); + DI::logger()->info('Processed', ['rows' => $rows]); if ($rows <= 100) { DI::keyValue()->set('post_update_version', 1426); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -996,13 +995,13 @@ class PostUpdate } $condition = ["`uri-id` IS NULL"]; - Logger::info('Start', ['rest' => DBA::count('event', $condition)]); + DI::logger()->info('Start', ['rest' => DBA::count('event', $condition)]); $rows = 0; $events = DBA::select('event', ['id', 'uri', 'guid'], $condition, ['limit' => 1000]); 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; } @@ -1017,11 +1016,11 @@ class PostUpdate } DBA::close($events); - Logger::info('Processed', ['rows' => $rows]); + DI::logger()->info('Processed', ['rows' => $rows]); if ($rows <= 100) { DI::keyValue()->set('post_update_version', 1427); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -1049,7 +1048,7 @@ class PostUpdate $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; $received = ''; @@ -1060,7 +1059,7 @@ class PostUpdate Conversation::PARCEL_ACTIVITYPUB, $id, 1000); 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; } @@ -1088,11 +1087,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1452); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -1114,7 +1113,7 @@ class PostUpdate return true; } - Logger::info('Start'); + DI::logger()->info('Start'); $posts = DBA::select('post-view', ['uri-id'], ['conversation' => './']); while ($post = DBA::fetch($posts)) { @@ -1127,7 +1126,7 @@ class PostUpdate DBA::close($posts); DI::keyValue()->set('post_update_version', 1483); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -1147,14 +1146,14 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1484_id') ?? 0; - Logger::info('Start', ['id' => $id]); + DI::logger()->info('Start', ['id' => $id]); $rows = 0; $contacts = DBA::select('contact', ['id', 'uid', 'uri-id', 'url'], ["`id` > ?", $id], ['order' => ['id'], 'limit' => 1000]); 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; } @@ -1171,11 +1170,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1484); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -1198,7 +1197,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1506_id') ?? 0; - Logger::info('Start', ['contact' => $id]); + DI::logger()->info('Start', ['contact' => $id]); $start_id = $id; $rows = 0; @@ -1207,7 +1206,7 @@ class PostUpdate $contacts = DBA::select('contact', ['id', 'url'], $condition, $params); 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; } @@ -1228,11 +1227,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1506); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -1255,7 +1254,7 @@ class PostUpdate $id = DI::keyValue()->get('post_update_version_1507_id') ?? ''; - Logger::info('Start', ['apcontact' => $id]); + DI::logger()->info('Start', ['apcontact' => $id]); $start_id = $id; $rows = 0; @@ -1264,7 +1263,7 @@ class PostUpdate $apcontacts = DBA::select('apcontact', ['url', 'gsid', 'sharedinbox', 'inbox'], $condition, $params); 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; } @@ -1283,11 +1282,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1507); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -1314,14 +1313,14 @@ class PostUpdate $id = (int)($post['uri-id'] ?? 0); } - Logger::info('Start', ['uri-id' => $id]); + DI::logger()->info('Start', ['uri-id' => $id]); $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]); 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; } @@ -1334,11 +1333,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1544); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } @@ -1368,7 +1367,7 @@ class PostUpdate try { Post\Engagement::storeFromItem($item); } 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); @@ -1379,7 +1378,7 @@ class PostUpdate $id = (int)($post['uri-id'] ?? 0); } - Logger::info('Start', ['uri-id' => $id]); + DI::logger()->info('Start', ['uri-id' => $id]); $rows = 0; @@ -1393,7 +1392,7 @@ class PostUpdate $posts = Post::selectPosts(['uri-id', 'created'], $condition, ['order' => ['uri-id' => true], 'limit' => 1000]); 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; } @@ -1406,11 +1405,11 @@ class PostUpdate 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) { DI::keyValue()->set('post_update_version', 1550); - Logger::info('Done'); + DI::logger()->info('Done'); return true; } From 39448160f16d89b107fe2a32d55450c33f1e8f85 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 09:51:46 +0000 Subject: [PATCH 12/91] Replace Logger with DI::logger() in Model Post classes --- src/Model/Post.php | 17 ++++---- src/Model/Post/Delayed.php | 7 ++-- src/Model/Post/Engagement.php | 15 ++++--- src/Model/Post/History.php | 9 ++-- src/Model/Post/Link.php | 11 +++-- src/Model/Post/Media.php | 65 ++++++++++++++--------------- src/Model/Post/SearchIndex.php | 3 +- src/Model/Post/UserNotification.php | 7 ++-- 8 files changed, 63 insertions(+), 71 deletions(-) diff --git a/src/Model/Post.php b/src/Model/Post.php index 3118e2e84c..765ad023ac 100644 --- a/src/Model/Post.php +++ b/src/Model/Post.php @@ -8,7 +8,6 @@ namespace Friendica\Model; use BadMethodCallException; -use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\Database\DBA; use Friendica\DI; @@ -621,7 +620,7 @@ class Post { $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 unset($fields['id']); @@ -647,7 +646,7 @@ class Post $puids = array_column($rows, 'post-user-id'); if (!DBA::update('post-user', $update_fields, ['id' => $puids])) { 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; } $affected_count += DBA::affectedRows(); @@ -664,7 +663,7 @@ class Post $uriids = array_column($rows, 'uri-id'); if (!DBA::update('post-content', $update_fields, ['uri-id' => $uriids])) { 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; } $affected_count += DBA::affectedRows(); @@ -687,7 +686,7 @@ class Post if (!DBA::update('post', $update_fields, ['uri-id' => $uriids])) { 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; } $affected_count += DBA::affectedRows(); @@ -704,7 +703,7 @@ class Post $uriids = array_column($rows, 'uri-id'); if (!DBA::update('post-delivery-data', $update_fields, ['uri-id' => $uriids])) { 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; } $affected_count += DBA::affectedRows(); @@ -721,7 +720,7 @@ class Post $uriids = array_column($rows, 'uri-id'); if (!DBA::update('post-thread', $update_fields, ['uri-id' => $uriids])) { 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; } $affected_count += DBA::affectedRows(); @@ -738,7 +737,7 @@ class Post $thread_puids = array_column($rows, 'post-user-id'); if (!DBA::update('post-thread-user', $update_fields, ['post-user-id' => $thread_puids])) { 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; } $affected_count += DBA::affectedRows(); @@ -749,7 +748,7 @@ class Post DBA::commit(); - Logger::info('Updated posts', ['rows' => $affected]); + DI::logger()->info('Updated posts', ['rows' => $affected]); return $affected; } diff --git a/src/Model/Post/Delayed.php b/src/Model/Post/Delayed.php index 666e55c3d4..2e30ba1a59 100644 --- a/src/Model/Post/Delayed.php +++ b/src/Model/Post/Delayed.php @@ -7,7 +7,6 @@ namespace Friendica\Model\Post; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Core\Worker; 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 = []) { 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; } @@ -58,7 +57,7 @@ class Delayed 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); if (!$wid) { @@ -181,7 +180,7 @@ class Delayed $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'])) { $uri = $item['uri']; diff --git a/src/Model/Post/Engagement.php b/src/Model/Post/Engagement.php index b48818437c..621d3ee9ec 100644 --- a/src/Model/Post/Engagement.php +++ b/src/Model/Post/Engagement.php @@ -9,7 +9,6 @@ namespace Friendica\Model\Post; use Friendica\Content\Text\BBCode; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -48,7 +47,7 @@ class Engagement public static function storeFromItem(array $item): int { 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; } @@ -59,7 +58,7 @@ class Engagement ['uri-id' => $item['parent-uri-id']]); 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; } @@ -114,16 +113,16 @@ class Engagement ]) ]; 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; } $exists = DBA::exists('post-engagement', ['uri-id' => $engagement['uri-id']]); if ($exists) { $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 { $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; } @@ -369,11 +368,11 @@ class Engagement { $limit = self::getCreationDateLimit(true); if (empty($limit)) { - Logger::notice('Expiration limit not reached'); + DI::logger()->notice('Expiration limit not reached'); return; } 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 diff --git a/src/Model/Post/History.php b/src/Model/Post/History.php index 03b6da19d0..192a82996c 100644 --- a/src/Model/Post/History.php +++ b/src/Model/Post/History.php @@ -7,7 +7,6 @@ namespace Friendica\Model\Post; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Database\Database; use Friendica\DI; @@ -28,12 +27,12 @@ class History $post = Post::selectFirstPost($fields, ['uri-id' => $uri_id]); if (empty($post)) { - Logger::warning('Post not found', ['uri-id' => $uri_id]); + DI::logger()->warning('Post not found', ['uri-id' => $uri_id]); return; } 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; } @@ -49,9 +48,9 @@ class History if ($update) { 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 { - 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']]); } } } diff --git a/src/Model/Post/Link.php b/src/Model/Post/Link.php index 64901c2c28..2315928186 100644 --- a/src/Model/Post/Link.php +++ b/src/Model/Post/Link.php @@ -7,7 +7,6 @@ namespace Friendica\Model\Post; -use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\Database\DBA; use Friendica\DI; @@ -53,14 +52,14 @@ class Link } 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; } $link = DBA::selectFirst('post-link', ['id'], ['uri-id' => $uriId, 'url' => $url]); if (!empty($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 { $fields = self::fetchMimeType($url); $fields['uri-id'] = $uriId; @@ -68,7 +67,7 @@ class Link DBA::insert('post-link', $fields, Database::INSERT_IGNORE); $id = DBA::lastInsertId(); - Logger::info('Inserted', $fields); + DI::logger()->info('Inserted', $fields); } if (empty($id)) { @@ -114,12 +113,12 @@ class Link try { $curlResult = HTTPSignature::fetchRaw($url, 0, [HttpClientOptions::TIMEOUT => $timeout, HttpClientOptions::ACCEPT_CONTENT => $accept]); } catch (\Exception $exception) { - Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]); + DI::logger()->notice('Error fetching url', ['url' => $url, 'exception' => $exception]); return []; } if (!$curlResult->isSuccess()) { - Logger::notice('Fetching unsuccessful', ['url' => $url]); + DI::logger()->notice('Fetching unsuccessful', ['url' => $url]); return []; } diff --git a/src/Model/Post/Media.php b/src/Model/Post/Media.php index f05b5e0016..7384f71ca5 100644 --- a/src/Model/Post/Media.php +++ b/src/Model/Post/Media.php @@ -9,7 +9,6 @@ namespace Friendica\Model\Post; use Friendica\Content\PageInfo; use Friendica\Content\Text\BBCode; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -67,12 +66,12 @@ class Media public static function insert(array $media, bool $force = false): bool { 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; } 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; } @@ -80,12 +79,12 @@ class Media // 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']]); 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; } 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; } @@ -97,7 +96,7 @@ class Media // We are storing as fast as possible to avoid duplicated network requests // when fetching additional information for pictures and other content. $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; $media = self::fetchAdditionalData($media); @@ -106,9 +105,9 @@ class Media if (array_diff_assoc($media, $stored)) { $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 { - Logger::info('Nothing to update', ['media' => $media]); + DI::logger()->info('Nothing to update', ['media' => $media]); } return $result; } @@ -183,7 +182,7 @@ class Media return $media; } 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() ?? '')); } } 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) { - 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); } - 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) { $imagedata = Images::getInfoFromURLCached($media['url'], empty($media['description'])); @@ -228,10 +227,10 @@ class Media $media['blurhash'] = $imagedata['blurhash'] ?? null; if (!empty($imagedata['description']) && empty($media['description'])) { $media['description'] = $imagedata['description']; - Logger::debug('Detected text for image', $media); + DI::logger()->debug('Detected text for image', $media); } } 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]); 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']; return $media; } 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']; return $media; } @@ -324,7 +323,7 @@ class Media !empty($item['plink']) && Strings::compareLink($item['plink'], $media['url']) && 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']; return $media; } @@ -357,7 +356,7 @@ class Media $media['publisher-name'] = $gserver['site_name'] ?? 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; } @@ -399,7 +398,7 @@ class Media $media['publisher-name'] = $gserver['site_name'] ?? 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; } @@ -415,7 +414,7 @@ class Media if (empty($data['images'][0]['src']) && empty($data['text']) && empty($data['title'])) { if (!empty($media['preview'])) { $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 { $media['preview'] = $data['images'][0]['src'] ?? null; @@ -489,7 +488,7 @@ class Media public static function addType(array $data): array { if (empty($data['mimetype'])) { - Logger::info('No MimeType provided', ['media' => $data]); + DI::logger()->info('No MimeType provided', ['media' => $data]); return $data; } @@ -501,7 +500,7 @@ class Media { $type = explode('/', current(explode(';', $mimeType))); if (count($type) < 2) { - Logger::info('Unknown MimeType', ['type' => $type, 'media' => $mimeType]); + DI::logger()->info('Unknown MimeType', ['type' => $type, 'media' => $mimeType]); return self::UNKNOWN; } @@ -536,10 +535,10 @@ class Media $type = self::APPLICATION; } else { $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; } @@ -777,15 +776,15 @@ class Media // Search for pure links if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) { 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); if ($result && !in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA])) { 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) { - Logger::debug('Media had been added', ['uri-id' => $uriid, 'url' => $url]); + DI::logger()->debug('Media had been added', ['uri-id' => $uriid, 'url' => $url]); } 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 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) { 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); if ($result && !in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA])) { 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) { - Logger::debug('Media has been added', ['uri-id' => $uriid, 'url' => $url]); + DI::logger()->debug('Media has been added', ['uri-id' => $uriid, 'url' => $url]); } 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; } - Logger::info('Adding attachment data', ['data' => $data]); + DI::logger()->info('Adding attachment data', ['data' => $data]); $attachment = [ 'uri-id' => $uriid, 'type' => self::HTML, diff --git a/src/Model/Post/SearchIndex.php b/src/Model/Post/SearchIndex.php index 61410871e2..1c57f77942 100644 --- a/src/Model/Post/SearchIndex.php +++ b/src/Model/Post/SearchIndex.php @@ -8,7 +8,6 @@ namespace Friendica\Model\Post; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -74,7 +73,7 @@ class SearchIndex return; } 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 diff --git a/src/Model/Post/UserNotification.php b/src/Model/Post/UserNotification.php index 35c3d7891c..e72d3ac353 100644 --- a/src/Model/Post/UserNotification.php +++ b/src/Model/Post/UserNotification.php @@ -10,7 +10,6 @@ namespace Friendica\Model\Post; use BadMethodCallException; use Exception; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\Database\DBA; use Friendica\DI; @@ -174,14 +173,14 @@ class UserNotification continue; } 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; } } 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)) { - 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; } } @@ -313,7 +312,7 @@ class UserNotification 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]; Post\User::update($item['uri-id'], $uid, $fields); From b88fd9168fc445dee7bf3839875544d72345bfb7 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 10:00:51 +0000 Subject: [PATCH 13/91] Replace Logger with DI::logger() in Factory classes --- src/Factory/Api/Mastodon/Status.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Factory/Api/Mastodon/Status.php b/src/Factory/Api/Mastodon/Status.php index 8cf9f3d8e7..fc1715c1d5 100644 --- a/src/Factory/Api/Mastodon/Status.php +++ b/src/Factory/Api/Mastodon/Status.php @@ -12,7 +12,6 @@ use Friendica\Content\ContactSelector; use Friendica\Content\Item as ContentItem; use Friendica\Content\Smilies; use Friendica\Content\Text\BBCode; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -309,7 +308,7 @@ class Status extends BaseFactory try { $reshare = $this->createFromUriId($uriId, $uid, $display_quote, false, false)->toArray(); } 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 = []; } } else { @@ -320,7 +319,7 @@ class Status extends BaseFactory try { $in_reply = $this->createFromUriId($item['thr-parent-id'], $uid, $display_quote, false, false)->toArray(); } 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 = []; } } else { @@ -361,7 +360,7 @@ class Status extends BaseFactory try { $quote = $this->createFromUriId($quote_id, $uid, false, false, false)->toArray(); } 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 = []; } } else { From 5b4faf811f815a60fd4752b064ffd651a811eee8 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 10:04:49 +0000 Subject: [PATCH 14/91] Replace Logger with DI::logger() in Model Contact classes --- src/Model/Contact.php | 145 ++++++++++++++++----------------- src/Model/Contact/Relation.php | 61 +++++++------- src/Model/Contact/User.php | 9 +- 3 files changed, 106 insertions(+), 109 deletions(-) diff --git a/src/Model/Contact.php b/src/Model/Contact.php index a0e186b40e..083f66287f 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -15,7 +15,6 @@ use Friendica\Content\Conversation as ConversationContent; use Friendica\Content\Pager; use Friendica\Content\Text\HTML; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\Core\System; @@ -182,7 +181,7 @@ class Contact $contact = DBA::selectFirst('contact', [], ['id' => DBA::lastInsertId()]); if (!DBA::isResult($contact)) { // 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; } @@ -190,23 +189,23 @@ class Contact DBA::insert('account-user', $fields, Database::INSERT_IGNORE); $account_user = DBA::selectFirst('account-user', ['id'], ['uid' => $contact['uid'], 'uri-id' => $contact['uri-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']) { $duplicate = DBA::selectFirst('contact', [], ['id' => $account_user['id'], 'deleted' => false]); if (!empty($duplicate['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; } else { $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); 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']); } @@ -221,7 +220,7 @@ class Contact */ 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]); return DBA::delete('contact', ['id' => $id]); } @@ -370,7 +369,7 @@ class Contact try { UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); } catch (\InvalidArgumentException $e) { - Logger::notice($e->getMessage(), ['contact' => $contact]); + DI::logger()->notice($e->getMessage(), ['contact' => $contact]); } } @@ -567,11 +566,11 @@ class Contact // And fetch the result $contact = DBA::selectFirst('contact', ['baseurl'], ['id' => $contact['id']]); if (empty($contact['baseurl'])) { - Logger::info('No baseurl for contact', ['url' => $url]); + DI::logger()->info('No baseurl for contact', ['url' => $url]); 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']; } @@ -1090,10 +1089,10 @@ class Contact return; } } 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 if ($contact['archive'] || $contact['self']) { @@ -1157,7 +1156,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. $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false]; @@ -1310,7 +1309,7 @@ class Contact $contact_id = 0; 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; } @@ -1325,19 +1324,19 @@ class Contact try { UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); } 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))) { - 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; } } 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; } 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; } @@ -1369,7 +1368,7 @@ class Contact } 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['photo'] = $personal_contact['avatar']; $data['account-type'] = $personal_contact['contact-type']; @@ -1381,12 +1380,12 @@ class Contact } 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; } 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; } @@ -1398,7 +1397,7 @@ class Contact $contact = self::selectFirst(['id'], ['nurl' => $urls, 'uid' => $uid]); if (!empty($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 +1423,37 @@ class Contact $contact = DBA::selectFirst('contact', ['id'], $condition, ['order' => ['id']]); if (DBA::isResult($contact)) { $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 { $contact_id = self::insert($fields); 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) { - Logger::warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]); + DI::logger()->warning('Contact was not inserted', ['url' => $url, 'uid' => $uid]); return 0; } } 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) { try { DI::dsprContact()->updateFromProbeArray($data); } catch (NotFoundException $e) { - Logger::notice($e->getMessage(), ['url' => $url, 'data' => $data]); + DI::logger()->notice($e->getMessage(), ['url' => $url, 'data' => $data]); } 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])) { try { DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]); } 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) { - 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 +1462,7 @@ class Contact // Don't return a number for a deleted account 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; } @@ -1812,16 +1811,16 @@ class Contact 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']))) { - 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); return; } } 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); return; } 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); return; } @@ -2303,7 +2302,7 @@ class Contact } if (!empty($avatar) && !Network::isValidHttpUrl($avatar)) { - Logger::warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]); + DI::logger()->warning('Invalid avatar', ['cid' => $cid, 'avatar' => $avatar]); $avatar = ''; } @@ -2327,7 +2326,7 @@ class Contact } } } catch (\Exception $exception) { - Logger::notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]); + DI::logger()->notice('Error fetching avatar', ['avatar' => $avatar, 'exception' => $exception]); return; } } elseif (!empty($contact['blurhash'])) { @@ -2337,7 +2336,7 @@ class Contact } 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; } @@ -2346,7 +2345,7 @@ class Contact if (($uid != 0) && !in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) { $pcid = self::getIdForURL($contact['url'], 0, false); 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); return; } @@ -2380,7 +2379,7 @@ class Contact 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB), '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; @@ -2390,7 +2389,7 @@ class Contact $local_uid = User::getIdForURL($contact['url']); if (!empty($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 +2406,7 @@ class Contact foreach ($data as $image_uri) { $image_rid = Photo::ridFromURI($image_uri); 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; } } @@ -2425,7 +2424,7 @@ class Contact 'avatar-date' => DateTimeFormat::utcNow(), ]; $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 { $update = false; } @@ -2466,7 +2465,7 @@ class Contact $cids[] = $cid; $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]); } @@ -2476,7 +2475,7 @@ class Contact $condition = ['self' => false, 'nurl' => Strings::normaliseLink($url)]; $contacts = DBA::select('contact', ['id', 'uid'], $condition); 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']); } } @@ -2508,7 +2507,7 @@ class Contact private static function updateContact(int $id, int $uid, int $uri_id, string $url, array $fields) { 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; } @@ -2517,7 +2516,7 @@ class Contact // Archive or unarchive the contact. $contact = DBA::selectFirst('contact', [], ['id' => $id]); 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; } @@ -2564,29 +2563,29 @@ class Contact if (!empty($account_user['uri-id']) && ($account_user['uri-id'] != $uri_id)) { if ($account_user['uid'] == $uid) { $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 { // 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]); if (!empty($account_user['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; } elseif (!DBA::exists('contact', ['id' => $account_user['id'], 'deleted' => false])) { $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; } - 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); } 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 { - 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 +2612,7 @@ class Contact } $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 $condition = ["`nurl` = ? AND `uid` = ? AND `id` != ? AND NOT `self` AND NOT `deleted`", $nurl, $uid, $first]; @@ -2626,7 +2625,7 @@ class Contact Worker::add(Worker::PRIORITY_HIGH, 'MergeContact', $first, $duplicate['id'], $uid); } DBA::close($duplicates); - Logger::info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]); + DI::logger()->info('Duplicates handled', ['uid' => $uid, 'nurl' => $nurl]); return true; } @@ -2649,7 +2648,7 @@ class Contact $stamp = (float)microtime(true); self::updateFromProbe($id); - Logger::debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url']]); + DI::logger()->debug('Contact data is updated.', ['duration' => round((float)microtime(true) - $stamp, 3), 'id' => $id, 'url' => $contact['url']]); return true; } @@ -2698,17 +2697,17 @@ class Contact try { DI::dsprContact()->updateFromProbeArray($data); } 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) { - 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])) { try { DI::dsprContact()->updateFromProbeArray($data['networks'][Protocol::DIASPORA]); } 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) { - 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 +2788,7 @@ class Contact if (self::isLocal($ret['url'])) { if ($contact['uid'] == 0) { - Logger::info('Local contacts are not updated here.'); + DI::logger()->info('Local contacts are not updated here.'); } else { self::updateFromPublicContact($id, $contact); } @@ -2797,7 +2796,7 @@ class Contact } 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); // Delete all contacts with the same URL @@ -2844,7 +2843,7 @@ class Contact } 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]); return false; } @@ -2857,10 +2856,10 @@ class 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]); - Logger::info('Not updating relay', ['id' => $id, 'url' => $contact['url']]); + DI::logger()->info('Not updating relay', ['id' => $id, 'url' => $contact['url']]); 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]); return false; } @@ -2874,7 +2873,7 @@ class Contact if (Strings::normaliseLink($ret['url']) != Strings::normaliseLink($contact['url'])) { $cid = self::getIdForURL($ret['url'], 0, false); 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); } } @@ -2904,7 +2903,7 @@ class Contact } $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; @@ -3006,7 +3005,7 @@ class Contact } if (!empty($fields)) { self::update($fields, ['id' => $id, 'self' => false]); - Logger::info('Updating local contact', ['id' => $id]); + DI::logger()->info('Updating local contact', ['id' => $id]); } } @@ -3243,7 +3242,7 @@ class Contact try { UpdateContact::add(Worker::PRIORITY_HIGH, $contact['id']); } catch (\InvalidArgumentException $e) { - Logger::notice($e->getMessage(), ['contact' => $contact]); + DI::logger()->notice($e->getMessage(), ['contact' => $contact]); } } @@ -3297,7 +3296,7 @@ class Contact if (!empty($contact)) { 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; } @@ -3330,7 +3329,7 @@ class Contact } else { // send email notification to owner? 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; } @@ -3492,7 +3491,7 @@ class Contact $contacts = DBA::select('contact', ['id', 'uid', 'name', 'url', 'bd'], $condition); 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); @@ -3774,7 +3773,7 @@ class Contact UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); ++$updated; } catch (\InvalidArgumentException $e) { - Logger::notice($e->getMessage(), ['contact' => $contact]); + DI::logger()->notice($e->getMessage(), ['contact' => $contact]); } } else { ++$unchanged; diff --git a/src/Model/Contact/Relation.php b/src/Model/Contact/Relation.php index 036213045f..76e0a7ac63 100644 --- a/src/Model/Contact/Relation.php +++ b/src/Model/Contact/Relation.php @@ -9,7 +9,6 @@ namespace Friendica\Model\Contact; use Exception; use Friendica\Content\Widget; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -67,7 +66,7 @@ class Relation { $contact = Contact::selectFirst(['id', 'url', 'network'], ['id' => Contact::getPublicIdByUserId($uid)]); 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; } @@ -87,22 +86,22 @@ class Relation { $contact = Contact::getByURL($url); if (empty($contact)) { - Logger::info('Contact not found', ['url' => $url]); + DI::logger()->info('Contact not found', ['url' => $url]); return; } if (!self::isDiscoverable($url, $contact)) { - Logger::info('Contact is not discoverable', ['url' => $url]); + DI::logger()->info('Contact is not discoverable', ['url' => $url]); return; } $uid = User::getIdForURL($url); 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]); $followings = self::getContacts($uid, [Contact::SHARING, Contact::FRIEND]); } 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); if (!empty($apcontact['followers']) && is_string($apcontact['followers'])) { @@ -117,7 +116,7 @@ class Relation $followings = []; } } 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 = []; $followings = []; } @@ -137,7 +136,7 @@ class Relation { if (empty($followers) && empty($followings)) { 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; } @@ -162,7 +161,7 @@ class Relation $follower_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) { $actor = Contact::getIdForURL($contact); if (!empty($actor)) { @@ -186,7 +185,7 @@ class Relation } 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; } @@ -260,34 +259,34 @@ class Relation } 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; } if ($contact_discovery != self::DISCOVERY_ALL) { $local = DBA::exists('contact', ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($url), 0]); 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; } if ($contact_discovery == self::DISCOVERY_INTERACTOR) { $interactor = DBA::exists('contact-relation', ["`relation-cid` = ? AND `last-interaction` > ?", $contact['id'], DBA::NULL_DATETIME]); 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; } } } elseif ($contact['created'] > DateTimeFormat::utc('now - 1 day')) { // 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; } if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) { $apcontact = APContact::getByURL($url, false); 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; } } @@ -366,7 +365,7 @@ class Relation $totallimit = $start + $limit; $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; @@ -394,7 +393,7 @@ class Relation 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) { return array_slice($contacts, $start, $limit); @@ -419,7 +418,7 @@ class Relation } 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) { return array_slice($contacts, $start, $limit); @@ -440,7 +439,7 @@ class Relation } 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) { return array_slice($contacts, $start, $limit); @@ -461,7 +460,7 @@ class Relation } 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); } @@ -714,7 +713,7 @@ class Relation public static function countCommonFollows(int $sourceId, int $targetId, array $condition = []): int { $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`)', $sourceId, $targetId] ); @@ -737,7 +736,7 @@ class Relation public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false) { $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`)", $sourceId, $targetId] ); @@ -759,7 +758,7 @@ class Relation public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = []): int { $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`)", $sourceId, $targetId] ); @@ -782,7 +781,7 @@ class Relation public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false) { $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`)", $sourceId, $targetId] ); @@ -803,7 +802,7 @@ class Relation $days = DI::config()->get('channel', 'interaction_score_days'); $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); $view = Verb::getID(Activity::VIEW); @@ -814,7 +813,7 @@ class Relation $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 (?, ?, ?)", $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` 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`", @@ -828,7 +827,7 @@ class Relation $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 (?, ?, ?)", $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` 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`", @@ -842,7 +841,7 @@ class Relation $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 (?, ?, ?)", $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`", $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); @@ -855,7 +854,7 @@ class Relation $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 (?, ?, ?)", $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`", $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); @@ -868,7 +867,7 @@ class Relation $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` > ?", $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`", $contact_id, $uid, DateTimeFormat::utc('now - ' . $days . ' day')); @@ -878,6 +877,6 @@ class Relation } DBA::close($posts); - Logger::debug('Calculation - end', ['uid' => $uid]); + DI::logger()->debug('Calculation - end', ['uid' => $uid]); } } diff --git a/src/Model/Contact/User.php b/src/Model/Contact/User.php index 8e0f033fe6..e7f5699556 100644 --- a/src/Model/Contact/User.php +++ b/src/Model/Contact/User.php @@ -8,7 +8,6 @@ namespace Friendica\Model\Contact; use Exception; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -41,7 +40,7 @@ class User } 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; } @@ -53,7 +52,7 @@ class User if (!empty($contact['uri-id']) && DBA::isResult($pcontact)) { $pcid = $pcontact['id']; } 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; } @@ -64,7 +63,7 @@ class User $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; } @@ -91,7 +90,7 @@ class User } $update_fields['cid'] = $contact['pid']; $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); From a0e2c82c62c503ca4e3b7bd2e3d3a0225187975c Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 10:16:02 +0000 Subject: [PATCH 15/91] Replace Logger with DI::logger() in Model classes --- src/Model/APContact.php | 29 ++-- src/Model/Circle.php | 9 +- src/Model/Event.php | 3 +- src/Model/GServer.php | 61 +++++---- src/Model/Item.php | 263 ++++++++++++++++++------------------- src/Model/ItemURI.php | 3 +- src/Model/Mail.php | 7 +- src/Model/Photo.php | 79 ++++++----- src/Model/Profile.php | 5 +- src/Model/Subscription.php | 4 +- src/Model/Tag.php | 35 +++-- src/Model/User.php | 21 ++- 12 files changed, 253 insertions(+), 266 deletions(-) diff --git a/src/Model/APContact.php b/src/Model/APContact.php index 10534498ac..e88cccd619 100644 --- a/src/Model/APContact.php +++ b/src/Model/APContact.php @@ -9,7 +9,6 @@ namespace Friendica\Model; use Friendica\Content\Text\HTML; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; @@ -95,12 +94,12 @@ class APContact public static function getByURL(string $url, bool $update = null): array { if (empty($url) || Network::isUrlBlocked($url)) { - Logger::info('Domain is blocked', ['url' => $url]); + DI::logger()->info('Domain is blocked', ['url' => $url]); return []; } if (!Network::isValidHttpUrl($url) && !filter_var($url, FILTER_VALIDATE_EMAIL)) { - Logger::info('Invalid URL', ['url' => $url]); + DI::logger()->info('Invalid URL', ['url' => $url]); return []; } @@ -156,7 +155,7 @@ class APContact $cachekey = 'apcontact:' . ItemURI::getIdByURI($url); $result = DI::cache()->get($cachekey); 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)) { return $fetched_contact; } @@ -192,7 +191,7 @@ class APContact $failed = true; } } catch (\Exception $exception) { - Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]); + DI::logger()->notice('Error fetching url', ['url' => $url, 'exception' => $exception]); $failed = true; } @@ -291,7 +290,7 @@ class APContact try { $apcontact['addr'] = $apcontact['nick'] . '@' . (new Uri($apcontact['url']))->getAuthority(); } 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'] = ''; } } @@ -371,7 +370,7 @@ class APContact $apcontact['photo'] = Network::addBasePath($apcontact['photo'], $apcontact['url']); 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'] = ''; } } @@ -457,9 +456,9 @@ class APContact if (in_array($name, APContact\Endpoint::ENDPOINT_NAMES)) { $key = array_search($name, APContact\Endpoint::ENDPOINT_NAMES); 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'])) { - Logger::debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]); + DI::logger()->debug('Unknown endpoint', ['name' => $name, 'endpoint' => $endpoint['@id']]); } } } @@ -468,7 +467,7 @@ class APContact // We delete the old entry when the URL is changed 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]); } @@ -481,7 +480,7 @@ class 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']]) ?: []; } @@ -532,7 +531,7 @@ class APContact public static function markForArchival(array $apcontact) { 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']); } @@ -542,7 +541,7 @@ class APContact $apcontact['sharedinbox']]); if (!$available) { // 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']); } } @@ -557,11 +556,11 @@ class APContact public static function unmarkForArchival(array $apcontact) { 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']); } 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']); } } diff --git a/src/Model/Circle.php b/src/Model/Circle.php index a81e359d8b..00b4b16d5d 100644 --- a/src/Model/Circle.php +++ b/src/Model/Circle.php @@ -9,7 +9,6 @@ namespace Friendica\Model; use Friendica\BaseModule; use Friendica\Content\Widget; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\Database\Database; @@ -495,7 +494,7 @@ class Circle } DBA::close($stmt); - Logger::info('Got circles', $display_circles); + DI::logger()->info('Got circles', $display_circles); $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('circle_selection.tpl'), [ '$id' => $id, @@ -608,7 +607,7 @@ class Circle */ 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']); if (empty($contact) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY) || !$contact['manually-approve']) { return 0; @@ -638,7 +637,7 @@ class Circle */ 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']); if (empty($contact)) { @@ -673,6 +672,6 @@ class Circle } 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])]); } } diff --git a/src/Model/Event.php b/src/Model/Event.php index f98c8cdd0c..86567681e1 100644 --- a/src/Model/Event.php +++ b/src/Model/Event.php @@ -10,7 +10,6 @@ namespace Friendica\Model; use Friendica\Content\Feature; use Friendica\Content\Text\BBCode; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Renderer; use Friendica\Core\System; use Friendica\Database\DBA; @@ -219,7 +218,7 @@ class Event } DBA::delete('event', ['id' => $event_id]); - Logger::info("Deleted event", ['id' => $event_id]); + DI::logger()->info("Deleted event", ['id' => $event_id]); } /** diff --git a/src/Model/GServer.php b/src/Model/GServer.php index a0c1be7bfc..933ca8d74c 100644 --- a/src/Model/GServer.php +++ b/src/Model/GServer.php @@ -10,7 +10,6 @@ namespace Friendica\Model; use DOMDocument; use DOMXPath; use Exception; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Worker; use Friendica\Database\Database; @@ -114,7 +113,7 @@ class GServer $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => Strings::normaliseLink($url)]); 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)) { self::setBlockedById($gserver['id']); @@ -336,7 +335,7 @@ class GServer } 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); return false; } @@ -350,12 +349,12 @@ class GServer } 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']); } - 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 { - 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); @@ -381,7 +380,7 @@ class GServer $fields['network'] = $network; } 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()) { UpdateGServer::add(Worker::PRIORITY_LOW, $gserver['url']); @@ -403,7 +402,7 @@ class GServer $gserver = DBA::selectFirst('gserver', ['url', 'failed', 'next_contact'], ['id' => $gsid]); if (DBA::isResult($gserver) && !$gserver['failed']) { 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()) { 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]); if (DBA::isResult($gserver)) { 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]); if (DBA::isResult($gserver)) { 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)]); if (DBA::isResult($gserver)) { 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']]); } } @@ -454,7 +453,7 @@ class GServer self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(), 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null], ['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)) { self::archiveContacts($gserver['id']); } @@ -464,7 +463,7 @@ class GServer self::insert(['url' => $url, 'nurl' => $nurl, 'network' => Protocol::PHANTOM, 'created' => 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 +492,7 @@ class GServer try { return (string)self::cleanUri(new Uri($dirtyUrl)); } catch (\Throwable $e) { - Logger::warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]); + DI::logger()->warning('Invalid URL', ['dirtyUrl' => $dirtyUrl]); return ''; } } @@ -533,14 +532,14 @@ class GServer */ 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; // Remove URL content that is not supposed to exist for a server url $url = rtrim(self::cleanURL($url), '/'); if (empty($url)) { - Logger::notice('Empty URL.'); + DI::logger()->notice('Empty URL.'); return false; } @@ -566,7 +565,7 @@ class GServer // 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))) || (((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); if (!self::getID($valid_url, true) && !Network::isUrlBlocked($valid_url)) { self::detect($valid_url, $network, $only_nodeinfo); @@ -576,7 +575,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)) && (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); unset($parts['path']); $valid_url = (string)Uri::fromParts($parts); @@ -587,7 +586,7 @@ class GServer } 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)) && @@ -617,7 +616,7 @@ class GServer } 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); return false; } elseif (empty($serverdata)) { @@ -820,14 +819,14 @@ class GServer $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]); $max_users = max($apcontacts, $contacts); 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]); } 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')]); 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]); } } @@ -835,7 +834,7 @@ class GServer 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')]); 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]); } } @@ -847,7 +846,7 @@ class GServer if (!empty($systemactor)) { $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; @@ -864,7 +863,7 @@ class GServer */ 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]); if (!$curlResult->isSuccess()) { @@ -947,7 +946,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); } @@ -1072,7 +1071,7 @@ class GServer foreach ($nodeinfo['links'] as $link) { 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; } @@ -2277,7 +2276,7 @@ class GServer $serverdata['register_policy'] = Register::CLOSED; break; 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; break; } @@ -2507,10 +2506,10 @@ class GServer ['order' => ['RAND()']]); 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']); - 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); $fields = ['last_poco_query' => DateTimeFormat::utcNow()]; @@ -2651,7 +2650,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]); } diff --git a/src/Model/Item.php b/src/Model/Item.php index 594185c451..64cf1d7968 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -16,7 +16,6 @@ use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; use Friendica\Core\Hook; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\Core\System; @@ -215,7 +214,7 @@ class Item 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); @@ -236,7 +235,7 @@ class Item if ($item['origin'] && empty($item['quote-uri-id'])) { $quote_id = Post\Media::getActivityUriId($item['uri-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; } } @@ -332,7 +331,7 @@ class Item if ($item['uid'] == $uid) { self::markForDeletionById($item['id'], Worker::PRIORITY_HIGH); } 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); @@ -348,7 +347,7 @@ class Item */ 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 $fields = [ 'id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin', @@ -357,12 +356,12 @@ class Item ]; $item = Post::selectFirst($fields, ['id' => $item_id]); if (!DBA::isResult($item)) { - Logger::info('Item not found.', ['id' => $item_id]); + DI::logger()->info('Item not found.', ['id' => $item_id]); return false; } 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; } @@ -444,7 +443,7 @@ class Item 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; } @@ -554,7 +553,7 @@ class Item 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']]); return $self['id']; } @@ -577,7 +576,7 @@ class Item $spool = $spoolpath . '/' . $file; 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 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']]; if (Post::exists($condition)) { - Logger::notice('Found already existing item', $condition); + DI::logger()->notice('Found already existing item', $condition); return true; } @@ -601,7 +600,7 @@ class Item 'network' => [$item['network'], Protocol::DFRN] ]; 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; } @@ -609,7 +608,7 @@ class Item if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) { $condition = ['guid' => $item['guid'], 'uid' => $item['uid']]; 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; } } @@ -620,7 +619,7 @@ class Item * 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])) { - 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; } @@ -637,47 +636,47 @@ class Item { // 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']))) { - Logger::notice('No body, no title.'); + DI::logger()->notice('No body, no title.'); return false; } if (!empty($item['uid'])) { $owner = User::getOwnerDataById($item['uid'], false); 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; } 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; } } 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; } 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; } 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; } 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; } if ($item['verb'] == Activity::FOLLOW) { 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. - 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; } @@ -687,7 +686,7 @@ class Item ]; if (Post::exists($condition)) { // 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; } } @@ -716,7 +715,7 @@ class Item if (DBA::isResult($existing)) { // We only log the entries with a different user id than 0. Otherwise we would have too many false positives if ($item['uid'] != 0) { - Logger::notice('Item already existed for user', [ + DI::logger()->notice('Item already existed for user', [ 'uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'network' => $item['network'], @@ -776,18 +775,18 @@ class Item $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]); } 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); } } 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 []; } 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 []; } @@ -805,12 +804,12 @@ class Item if (!DBA::isResult($toplevel_parent) && $item['origin']) { $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); } 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 []; } @@ -839,7 +838,7 @@ class Item 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 } @@ -971,7 +970,7 @@ class Item if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) { $user = User::getById($uid, ['account-type']); 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; } } @@ -1014,7 +1013,7 @@ class Item !empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) && 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; } @@ -1067,7 +1066,7 @@ class Item // If its a post that originated here then tag the thread as "mention" if ($item['origin'] && $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 @@ -1149,7 +1148,7 @@ class Item } if (!empty($item['cancel'])) { - Logger::notice('post cancelled by addon.'); + DI::logger()->notice('post cancelled by addon.'); return 0; } @@ -1193,13 +1192,13 @@ class Item if (!empty($quote_id)) { // This is one of these "should not happen" situations. // 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; } } 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']); } @@ -1232,7 +1231,7 @@ class Item if ($item['origin'] && empty($item['quote-uri-id'])) { $quote_id = Post\Media::getActivityUriId($item['uri-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; } } @@ -1242,7 +1241,7 @@ class Item $ev = Event::fromBBCode($item['body']); 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['uid'] = $item['uid']; $ev['uri'] = $item['uri']; @@ -1263,7 +1262,7 @@ class Item $event_id = Event::store($ev); $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']]; if (Post::exists($condition)) { - Logger::notice('Item is already inserted - aborting', $condition); + DI::logger()->notice('Item is already inserted - aborting', $condition); return 0; } $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item); 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; } @@ -1343,12 +1342,12 @@ class 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]); if (!DBA::isResult($posted_item)) { // 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); return 0; } @@ -1385,7 +1384,7 @@ class Item // Get the user information for the logging $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; } @@ -1418,15 +1417,15 @@ class Item if ($transmit) { 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; } 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; } 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; } @@ -1434,7 +1433,7 @@ class Item if (($posted_item['verb'] == Activity::FOLLOW) && (!$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; } } @@ -1520,25 +1519,25 @@ class Item $item = Post::selectFirst(['id', 'private', 'network', 'language', 'owner-id'], ['uri-id' => $uri_id, 'uid' => 0]); if (empty($item['id'])) { - Logger::debug('Post not found', ['uri-id' => $uri_id]); + DI::logger()->debug('Post not found', ['uri-id' => $uri_id]); return; } 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; } $engagement = DBA::selectFirst('post-engagement', ['searchtext', 'media-type'], ['uri-id' => $uri_id]); if (empty($engagement['searchtext'])) { - Logger::debug('No engagement found', ['uri-id' => $uri_id]); + DI::logger()->debug('No engagement found', ['uri-id' => $uri_id]); return; } $language = !empty($item['language']) ? array_key_first(json_decode($item['language'], true)) : ''; $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; 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 ]; 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_gid = '<' . Circle::FOLLOWERS . '>'; $deny_cid = ''; $deny_gid = ''; self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid); } 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++; } - 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']] ); 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; } $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]); if (!DBA::isResult($author)) { - Logger::error('Author not found', ['id' => $item['author-id']]); + DI::logger()->error('Author not found', ['id' => $item['author-id']]); return; } @@ -1637,24 +1636,24 @@ class Item $cid = Contact::getIdForURL($author['url'], $item['uid']); 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; } if ($author['contact-type'] != Contact::TYPE_COMMUNITY) { 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; } 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; } } 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) { - 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 { - 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; } } $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) { $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]; $parent = Post::selectFirst(['owner-id'], $condition); if (!DBA::isResult($parent)) { - Logger::warning('Item not found', ['condition' => $condition]); + DI::logger()->warning('Item not found', ['condition' => $condition]); return; } @@ -1720,7 +1719,7 @@ class Item ]; $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition); if (!DBA::isResult($item)) { - Logger::warning('Item not found', ['condition' => $condition]); + DI::logger()->warning('Item not found', ['condition' => $condition]); return; } @@ -1803,26 +1802,26 @@ class Item public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int { 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; } $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]); 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; } if (($uid != 0) && ($item['gravity'] == self::GRAVITY_PARENT)) { $owner = User::getOwnerDataById($uid); 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; } } 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; } @@ -1840,7 +1839,7 @@ class Item 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]) ) { - 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; } @@ -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 (!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; } - 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])) { 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; } - 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); - 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; } @@ -1879,7 +1878,7 @@ class Item // Fetch the origin user for the post $origin_uid = self::GetOriginUidForUriId($uri_id, $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; } @@ -1955,11 +1954,11 @@ class Item if (!empty($event)) { // 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']]); - 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']; } @@ -1997,9 +1996,9 @@ class Item $distributed = self::insert($item, $notify); 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 { - 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; } @@ -2065,7 +2064,7 @@ class 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); - 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. // This means that we have to distribute the comment by ourselves. @@ -2194,7 +2193,7 @@ class Item $author = Contact::selectFirst(['about'], ['id' => $author_id]); if (!empty($author['about'])) { $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; } } @@ -2375,7 +2374,7 @@ class Item $hostPart = $host ?: $parsed['host'] ?? ''; 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 @@ -2560,26 +2559,26 @@ class Item { $owner = User::getOwnerDataById($uid); 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; } 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; } $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [self::GRAVITY_PARENT, self::GRAVITY_COMMENT], 'origin' => false]); 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; } if ($item['gravity'] == self::GRAVITY_PARENT) { 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 { - 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']]); return true; } @@ -2589,14 +2588,14 @@ class Item Hook::callAll('tagged', $arr); } else { 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 { - 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; } } - 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) { $allow_cid = ''; @@ -2608,7 +2607,7 @@ class Item 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; } @@ -2641,7 +2640,7 @@ class Item 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']); } @@ -2654,34 +2653,34 @@ class Item // Prevent the forwarding of posts that are forwarded if (!empty($datarray['extid']) && ($datarray['extid'] == Protocol::DFRN)) { - Logger::info('Already forwarded'); + DI::logger()->info('Already forwarded'); return false; } // Prevent to forward already forwarded posts if ($datarray['app'] == DI::baseUrl()->getHost()) { - Logger::info('Already forwarded (second test)'); + DI::logger()->info('Already forwarded (second test)'); return false; } // Only forward posts if ($datarray['verb'] != Activity::POST) { - Logger::info('No post'); + DI::logger()->info('No post'); return false; } if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) { - Logger::info('Not public'); + DI::logger()->info('Not public'); return 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; } $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( 'contact', @@ -2689,7 +2688,7 @@ class Item ['uid' => $contact['uid'], 'self' => true] ); 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; } @@ -2723,7 +2722,7 @@ class Item // Store the original post $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 { $datarray['app'] = 'Feed'; $result = true; @@ -2752,7 +2751,7 @@ class Item return $s; } - Logger::info('check for photos'); + DI::logger()->info('check for photos'); $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://')); $orig_body = $s; @@ -2766,7 +2765,7 @@ class Item $img_st_close++; // make it point to AFTER the closing bracket $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/')) { // Only embed locally hosted photos @@ -2805,7 +2804,7 @@ class Item $photo_img = Photo::getImageForPhoto($photo); // 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)) { - Logger::info('scaling photo'); + DI::logger()->info('scaling photo'); $width = intval($match[1]); $height = intval($match[2]); @@ -2816,9 +2815,9 @@ class Item $data = $photo_img->asString(); $type = $photo_img->getType(); - Logger::info('replacing photo'); + DI::logger()->info('replacing photo'); $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; } 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; } @@ -3021,11 +3020,11 @@ class Item 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]); 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; } @@ -3040,7 +3039,7 @@ class Item if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) { $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]); 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; } } @@ -3049,14 +3048,14 @@ class Item // Retrieves the local post owner $owner = User::getOwnerDataById($uid); if (empty($owner)) { - Logger::info('Empty owner for user', ['uid' => $uid]); + DI::logger()->info('Empty owner for user', ['uid' => $uid]); return false; } // Retrieve the current logged in user's public contact $author_id = Contact::getPublicIdByUserId($uid); if (empty($author_id)) { - Logger::info('Empty public contact'); + DI::logger()->info('Empty public contact'); return false; } @@ -3091,7 +3090,7 @@ class Item $activity = Activity::ANNOUNCE; break; default: - Logger::warning('unknown verb', ['verb' => $verb, 'item' => $item_id]); + DI::logger()->warning('unknown verb', ['verb' => $verb, 'item' => $item_id]); 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 { - 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); 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; } @@ -4216,7 +4215,7 @@ class Item Hook::callAll('item_by_link', $hookData); 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; } @@ -4225,7 +4224,7 @@ class Item $curlResult = DI::httpClient()->head($uri, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::JSON_AS, HttpClientOptions::REQUEST => HttpClientRequest::ACTIVITYPUB]); $mimetype = $curlResult->getContentType(); } 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; } } @@ -4236,7 +4235,7 @@ class Item $curlResult = HTTPSignature::fetchRaw($uri, $uid); $mimetype = $curlResult->getContentType(); } 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; } } @@ -4246,7 +4245,7 @@ class Item if (!empty($fetched_uri)) { $item_id = self::searchByLink($fetched_uri, $uid); 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; } } @@ -4254,18 +4253,18 @@ class Item $item_id = Diaspora::fetchByURL($uri); 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; } - 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; } /** * Fetch the uri-id of a quoted post by searching for data in the body or attached media * - * @param string $body The body of the + * @param string $body The body of the * @param int $uid The id of the user * @return integer */ @@ -4277,14 +4276,14 @@ class Item } 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; } if (!empty($shared['guid'])) { $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]); 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']; } } @@ -4292,7 +4291,7 @@ class Item if (!empty($shared['message_id'])) { $shared_item = Post::selectFirst(['uri-id'], ['uri' => $shared['message_id'], 'uid' => [0, $uid]]); 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']; } } @@ -4300,7 +4299,7 @@ class Item if (!empty($shared['link'])) { $shared_item = Post::selectFirst(['uri-id'], ['plink' => $shared['link'], 'uid' => [0, $uid]]); 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']; } } @@ -4308,17 +4307,17 @@ class Item $url = $shared['message_id'] ?: $shared['link']; $id = self::fetchByLink($url, 0, ActivityPub\Receiver::COMPLETION_ASYNC); 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; } $shared_item = Post::selectFirst(['uri-id'], ['id' => $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']; } - 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; } diff --git a/src/Model/ItemURI.php b/src/Model/ItemURI.php index cd13f89033..57b5b841a7 100644 --- a/src/Model/ItemURI.php +++ b/src/Model/ItemURI.php @@ -7,7 +7,6 @@ namespace Friendica\Model; -use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\Database\DBA; use Friendica\DI; @@ -32,7 +31,7 @@ class ItemURI $itemuri = DBA::selectFirst('item-uri', ['id', 'guid'], ['uri' => $fields['uri']]); if (!DBA::isResult($itemuri)) { // This shouldn't happen - Logger::warning('Item-uri not found', $fields); + DI::logger()->warning('Item-uri not found', $fields); return null; } diff --git a/src/Model/Mail.php b/src/Model/Mail.php index e417e3c15d..84542d33e2 100644 --- a/src/Model/Mail.php +++ b/src/Model/Mail.php @@ -8,7 +8,6 @@ namespace Friendica\Model; use Friendica\Core\ACL; -use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Core\Worker; use Friendica\Database\DBA; @@ -58,7 +57,7 @@ class Mail if (DBA::exists('mail', ['uri' => $msg['uri'], 'uid' => $msg['uid']])) { DBA::unlock(); - Logger::info('duplicate message already delivered.'); + DI::logger()->info('duplicate message already delivered.'); return false; } @@ -94,7 +93,7 @@ class Mail 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']; @@ -170,7 +169,7 @@ class Mail } if (!$convid) { - Logger::warning('conversation not found.'); + DI::logger()->warning('conversation not found.'); return -4; } diff --git a/src/Model/Photo.php b/src/Model/Photo.php index 857802d305..c275753960 100644 --- a/src/Model/Photo.php +++ b/src/Model/Photo.php @@ -8,7 +8,6 @@ namespace Friendica\Model; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; @@ -583,7 +582,7 @@ class Photo $photo_failure = false; 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; } @@ -592,10 +591,10 @@ class Photo try { $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::MEDIAPROXY]); } 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; } - 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(); $type = $ret->getContentType(); } else { @@ -615,24 +614,24 @@ class Photo $maximagesize = Strings::getBytesFromShorthand(DI::config()->get('system', '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) { $image->toStatic(); $image = new Image($image->asString(), image_type_to_mime_type(IMAGETYPE_PNG)); $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) { foreach ([160, 80] as $pixels) { 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); $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); @@ -869,9 +868,9 @@ class Photo if (!self::exists($condition)) { $photo = self::selectFirst(['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'uid'], ['resource-id' => $image_rid]); if (!DBA::isResult($photo)) { - Logger::info('Image not found', ['resource-id' => $image_rid]); + DI::logger()->info('Image not found', ['resource-id' => $image_rid]); } else { - Logger::info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]); + DI::logger()->info('Mismatching permissions', ['condition' => $condition, 'photo' => $photo]); } continue; } @@ -910,7 +909,7 @@ class Photo ]; $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); } @@ -1010,7 +1009,7 @@ class Photo // Scale down to multiples of 640 until the maximum size isn't exceeded anymore foreach ([5120, 2560, 1280, 640, 320] as $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); $filesize = strlen($image->asString()); $width = $image->getWidth(); @@ -1033,7 +1032,7 @@ class Photo $max_length = DI::config()->get('system', 'max_image_length'); if ($max_length > 0) { $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'))); @@ -1052,10 +1051,10 @@ class Photo try { $ret = DI::httpClient()->get($image_url, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::MEDIAPROXY]); } 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 []; } - 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(); $type = $ret->getContentType(); } else { @@ -1064,7 +1063,7 @@ class Photo } if (empty($img_str)) { - Logger::notice('Empty content'); + DI::logger()->notice('Empty content'); return []; } @@ -1086,10 +1085,10 @@ class Photo */ private static function uploadImage(array $files): array { - Logger::info('starting new upload'); + DI::logger()->info('starting new upload'); if (empty($files)) { - Logger::notice('Empty upload file'); + DI::logger()->notice('Empty upload file'); return []; } @@ -1134,16 +1133,16 @@ class Photo } if (empty($src)) { - Logger::notice('No source file name', ['files' => $files]); + DI::logger()->notice('No source file name', ['files' => $files]); 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); $image = new Image($imagedata, $filetype, $filename); if (!$image->isValid()) { - Logger::notice('Image is unvalid', ['files' => $files]); + DI::logger()->notice('Image is unvalid', ['files' => $files]); return []; } @@ -1177,13 +1176,13 @@ class Photo { $user = User::getOwnerDataById($uid); if (empty($user)) { - Logger::notice('User not found', ['uid' => $uid]); + DI::logger()->notice('User not found', ['uid' => $uid]); return []; } $data = self::uploadImage($files); if (empty($data)) { - Logger::info('upload failed'); + DI::logger()->info('upload failed'); 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); 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 []; } $condition = ['resource-id' => $resource_id]; $photo = self::selectFirst(['id', 'datasize', 'width', 'height', 'type'], $condition, ['order' => ['width' => true]]); if (empty($photo)) { - Logger::notice('Photo not found', ['condition' => $condition]); + DI::logger()->notice('Photo not found', ['condition' => $condition]); return []; } @@ -1224,7 +1223,7 @@ class Photo $picture['picture'] = DI::baseUrl() . '/photo/' . $resource_id . '-0.' . $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; } @@ -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); 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; } @@ -1291,17 +1290,17 @@ class Photo if (!empty($files)) { $data = self::uploadImage($files); if (empty($data)) { - Logger::info('upload failed'); + DI::logger()->info('upload failed'); return ''; } } elseif (!empty($url)) { $data = self::loadImageFromURL($url); if (empty($data)) { - Logger::info('loading from external url failed'); + DI::logger()->info('loading from external url failed'); return ''; } } else { - Logger::info('Neither files nor url provided'); + DI::logger()->info('Neither files nor url provided'); return ''; } @@ -1314,7 +1313,7 @@ class Photo $album = DI::l10n()->t(self::PROFILE_PHOTOS); // 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) { $image->scaleDown(300); @@ -1322,7 +1321,7 @@ class Photo $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 4, self::USER_AVATAR); 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) { @@ -1331,7 +1330,7 @@ class Photo $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 5, self::USER_AVATAR); 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) { @@ -1340,10 +1339,10 @@ class Photo $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 6, self::USER_AVATAR); 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]; self::update(['profile' => false, 'photo-type' => self::DEFAULT], $condition); @@ -1369,17 +1368,17 @@ class Photo if (!empty($files)) { $data = self::uploadImage($files); if (empty($data)) { - Logger::info('upload failed'); + DI::logger()->info('upload failed'); return ''; } } elseif (!empty($url)) { $data = self::loadImageFromURL($url); if (empty($data)) { - Logger::info('loading from external url failed'); + DI::logger()->info('loading from external url failed'); return ''; } } else { - Logger::info('Neither files nor url provided'); + DI::logger()->info('Neither files nor url provided'); return ''; } @@ -1397,10 +1396,10 @@ class Photo $r = self::store($image, $uid, 0, $resource_id, $filename, $album, 3, self::USER_BANNER); 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]; self::update(['photo-type' => self::DEFAULT], $condition); diff --git a/src/Model/Profile.php b/src/Model/Profile.php index a8c9d32c07..3732d0d696 100644 --- a/src/Model/Profile.php +++ b/src/Model/Profile.php @@ -13,7 +13,6 @@ use Friendica\Content\Text\BBCode; use Friendica\Content\Widget\ContactBlock; use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\Core\Search; @@ -202,7 +201,7 @@ class Profile { $profile = User::getOwnerDataByNick($nickname); if (!isset($profile['account_removed']) || $profile['account_removed']) { - Logger::info('profile error: ' . DI::args()->getQueryString()); + DI::logger()->info('profile error: ' . DI::args()->getQueryString()); return []; } @@ -433,7 +432,7 @@ class Profile $p['url'] = Contact::magicLinkById($cid, $profile['url']); 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) { diff --git a/src/Model/Subscription.php b/src/Model/Subscription.php index be18a1af78..d07a0aa411 100644 --- a/src/Model/Subscription.php +++ b/src/Model/Subscription.php @@ -7,13 +7,11 @@ namespace Friendica\Model; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory; use Friendica\Navigation\Notifications\Entity\Notification as NotificationEntity; -use Friendica\Object\Api\Mastodon\Notification; use Minishlink\WebPush\VAPID; class Subscription @@ -133,7 +131,7 @@ class Subscription $subscriptions = DBA::select('subscription', [], ['uid' => $notification->uid, $type => true]); 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); } DBA::close($subscriptions); diff --git a/src/Model/Tag.php b/src/Model/Tag.php index 07767b4991..e5182a5379 100644 --- a/src/Model/Tag.php +++ b/src/Model/Tag.php @@ -9,7 +9,6 @@ namespace Friendica\Model; use Friendica\Content\Text\BBCode; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -101,11 +100,11 @@ class Tag } 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); - Logger::debug('Got id for contact', ['cid' => $cid, 'url' => $url]); + DI::logger()->debug('Got id for contact', ['cid' => $cid, 'url' => $url]); if (empty($cid)) { $tag = DBA::selectFirst('tag', ['name', 'type'], ['url' => $url]); @@ -141,14 +140,14 @@ class Tag $condition = $fields; $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]; if (DBA::exists('post-tag', $condition)) { - Logger::info('Tag already exists', $fields); + DI::logger()->info('Tag already exists', $fields); return; } } 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'])) { $target = $tag['type']; 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; } } if ($url == ActivityPub::PUBLIC_COLLECTION) { $target = self::PUBLIC_COLLECTION; - Logger::debug('Public collection', ['url' => $url]); + DI::logger()->debug('Public collection', ['url' => $url]); } else { if (DBA::exists('apcontact', ['followers' => $url])) { $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)) { $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)) { $content = HTTPSignature::fetch($url); if (!empty($content['type']) && ($content['type'] == 'OrderedCollection')) { $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)) { - Logger::debug('No type could be detected', ['url' => $url]); + DI::logger()->debug('No type could be detected', ['url' => $url]); } return $target; @@ -238,7 +237,7 @@ class Tag // Also log type $fields['type'] = $type; - Logger::error('No tag id created', $fields); + DI::logger()->error('No tag id created', $fields); return 0; } @@ -305,7 +304,7 @@ class Tag */ 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)) { $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) { - Logger::info('Check for tags', ['uri-id' => $uriId]); + DI::logger()->info('Check for tags', ['uri-id' => $uriId]); $result = BBCode::getTags($body); if (empty($result)) { return; } - Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]); + DI::logger()->info('Found tags', ['uri-id' => $uriId, 'result' => $result]); foreach ($result as $tag) { if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) { @@ -397,7 +396,7 @@ class Tag 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']]); } @@ -576,7 +575,7 @@ class Tag break; default: - Logger::warning('Unknown tag type found', $tag); + DI::logger()->warning('Unknown tag type found', $tag); } } DBA::close($taglist); @@ -832,7 +831,7 @@ class Tag foreach (self::getByURIId($uriId, [self::HASHTAG]) as $tag) { foreach (self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']) as $uid) { $uids[$uid][] = $tag['name']; - } + } } return $uids; diff --git a/src/Model/User.php b/src/Model/User.php index f837146c8b..e8b3060b2a 100644 --- a/src/Model/User.php +++ b/src/Model/User.php @@ -15,7 +15,6 @@ use Friendica\App; use Friendica\Content\Pager; use Friendica\Core\Hook; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Search; use Friendica\Core\System; @@ -857,7 +856,7 @@ class User $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']); // 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]); @@ -898,7 +897,7 @@ class User return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\Enums\PasswordStatus::EXPOSED; } catch (Exception $e) { - Logger::error('Password Exposed Exception: ' . $e->getMessage(), [ + DI::logger()->error('Password Exposed Exception: ' . $e->getMessage(), [ 'code' => $e->getCode(), 'file' => $e->getFile(), '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)))); 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; $username_min_length = $username_max_length; $username_max_length = $tmp; @@ -1409,7 +1408,7 @@ class User try { $curlResult = DI::httpClient()->get($photo, HttpClientAccept::IMAGE, [HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]); 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(); $type = $curlResult->getContentType(); } else { @@ -1417,7 +1416,7 @@ class User $type = ''; } } 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 = ''; $type = ''; } @@ -1777,7 +1776,7 @@ class User 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); if (!$user) { @@ -2086,19 +2085,19 @@ class User $register_policy = DI::config()->get('config', 'register_policy'); 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; } $users = DBA::count('user', ['blocked' => false, 'account_removed' => false, 'account_expired' => false]); if (($users >= $max_registered_users) && ($register_policy == Module\Register::OPEN)) { 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)) { 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 { - 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]); } } } From f817308080b5c4be2f114f5aa2b720f41035f90a Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 10:17:26 +0000 Subject: [PATCH 16/91] Replace Logger with DI::logger() in Moderation classes --- src/Moderation/Repository/Report.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Moderation/Repository/Report.php b/src/Moderation/Repository/Report.php index 1ead42446a..69ca81c167 100644 --- a/src/Moderation/Repository/Report.php +++ b/src/Moderation/Repository/Report.php @@ -8,8 +8,8 @@ namespace Friendica\Moderation\Repository; use Friendica\BaseEntity; -use Friendica\Core\Logger; use Friendica\Database\Database; +use Friendica\DI; use Friendica\Model\Post; use Friendica\Moderation\Factory; use Friendica\Moderation\Collection; @@ -73,7 +73,7 @@ final class Report extends \Friendica\BaseRepository if (Post::exists(['uri-id' => $post->uriId])) { $this->db->insert('report-post', ['rid' => $newReportId, 'uri-id' => $post->uriId, 'status' => $post->status]); } 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]); } } From 105c73760987bb22fa21de142a4293bacdb41278 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 10:32:57 +0000 Subject: [PATCH 17/91] Replace Logger with $this->logger in Module BaseApi class --- src/BaseModule.php | 1 - src/Module/BaseApi.php | 7 +++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/src/BaseModule.php b/src/BaseModule.php index 8c69fdcce8..27f156bef0 100644 --- a/src/BaseModule.php +++ b/src/BaseModule.php @@ -12,7 +12,6 @@ use Friendica\Capabilities\ICanHandleRequests; use Friendica\Capabilities\ICanCreateResponses; use Friendica\Core\Hook; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Model\User; use Friendica\Module\Response; diff --git a/src/Module/BaseApi.php b/src/Module/BaseApi.php index db7328128c..1176143ce8 100644 --- a/src/Module/BaseApi.php +++ b/src/Module/BaseApi.php @@ -14,7 +14,6 @@ use Friendica\App\Router; use Friendica\AppHelper; use Friendica\BaseModule; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Contact; @@ -227,7 +226,7 @@ class BaseApi extends BaseModule self::setBoundaries($post_item['uri-id']); } } 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); 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_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); @@ -471,7 +470,7 @@ class BaseApi extends BaseModule $posts_month = Post::countThread($condition); 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_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); From 86432310199818d1999e748c0907bc0d88c82ea3 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 11:00:50 +0000 Subject: [PATCH 18/91] Replace Logger with $this->logger in Module classes --- src/Module/Attach.php | 3 +-- src/Module/Contact.php | 3 +-- src/Module/Owa.php | 7 +++---- src/Module/Photo.php | 23 +++++++++++------------ src/Module/Register.php | 7 +++---- 5 files changed, 19 insertions(+), 24 deletions(-) diff --git a/src/Module/Attach.php b/src/Module/Attach.php index 1afc2baaad..bb852394b0 100644 --- a/src/Module/Attach.php +++ b/src/Module/Attach.php @@ -8,7 +8,6 @@ namespace Friendica\Module; use Friendica\BaseModule; -use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\DI; use Friendica\Model\Attach as MAttach; @@ -43,7 +42,7 @@ class Attach extends BaseModule $data = MAttach::getData($item); 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.')); } diff --git a/src/Module/Contact.php b/src/Module/Contact.php index 5a939158ef..293b082618 100644 --- a/src/Module/Contact.php +++ b/src/Module/Contact.php @@ -12,7 +12,6 @@ use Friendica\Content\ContactSelector; use Friendica\Content\Nav; use Friendica\Content\Pager; use Friendica\Content\Widget; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\Core\Theme; @@ -121,7 +120,7 @@ class Contact extends BaseModule try { UpdateContact::add(Worker::PRIORITY_HIGH, $contact_id); } catch (\InvalidArgumentException $e) { - Logger::notice($e->getMessage(), ['contact' => $contact]); + DI::logger()->notice($e->getMessage(), ['contact' => $contact]); } } diff --git a/src/Module/Owa.php b/src/Module/Owa.php index aadead3169..d7599a82c0 100644 --- a/src/Module/Owa.php +++ b/src/Module/Owa.php @@ -8,7 +8,6 @@ namespace Friendica\Module; use Friendica\BaseModule; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Model\Contact; use Friendica\Model\OpenWebAuthToken; @@ -60,7 +59,7 @@ class Owa extends BaseModule $verified = HTTPSignature::verifyMagic($contact['pubkey']); 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; $token = Strings::getRandomHex(32); @@ -77,10 +76,10 @@ class Owa extends BaseModule openssl_public_encrypt($token, $result, $contact['pubkey']); $ret['encrypted_token'] = Strings::base64UrlEncode($result); } 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 { - Logger::info('Contact not found', ['handle' => $handle]); + $this->logger->info('Contact not found', ['handle' => $handle]); } } } diff --git a/src/Module/Photo.php b/src/Module/Photo.php index 30e6d57672..e176efbddf 100644 --- a/src/Module/Photo.php +++ b/src/Module/Photo.php @@ -8,7 +8,6 @@ namespace Friendica\Module; use Friendica\Contact\Header; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -104,11 +103,11 @@ class Photo extends BaseApi } 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.')); } - $photo = self::getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL); + $photo = $this->getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL); } else { $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME); $scale = 0; @@ -172,7 +171,7 @@ class Photo extends BaseApi $data = microtime(true) - $stamp; 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])) { $reference = json_decode($photo['backend-ref'], true); $error = DI::l10n()->t('Invalid external resource with url %s.', $reference['url']); @@ -232,7 +231,7 @@ class Photo extends BaseApi $rest = $total - ($fetch + $data + $checksum + $output); if (!is_null($scale) && ($scale < 4)) { - Logger::debug('Performance:', [ + $this->logger->debug('Performance:', [ 'scale' => $scale, 'resource' => $photo['resource-id'], 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3), 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3), @@ -251,7 +250,7 @@ class Photo extends BaseApi * @param int $customsize Custom size (?) * @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) { case 'preview': @@ -359,25 +358,25 @@ class Photo extends BaseApi if ($update) { $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE, HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]); $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) { try { 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) { - Logger::notice($e->getMessage(), ['id' => $id, 'contact' => $contact]); + $this->logger->notice($e->getMessage(), ['id' => $id, 'contact' => $contact]); } } 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')) { - Logger::info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]); + $this->logger->info('Unexpected Content-Type', ['mime' => $mimetext, 'url' => $url]); $mimetext = ''; } if (!empty($mimetext)) { - Logger::debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]); + $this->logger->debug('Expected Content-Type', ['mime' => $mimetext, 'url' => $url]); } } diff --git a/src/Module/Register.php b/src/Module/Register.php index 927264e2a5..575301f777 100644 --- a/src/Module/Register.php +++ b/src/Module/Register.php @@ -14,7 +14,6 @@ use Friendica\Content\Text\BBCode; use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Hook; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Renderer; use Friendica\Core\Session\Capability\IHandleUserSessions; use Friendica\Core\Worker; @@ -89,7 +88,7 @@ class Register extends BaseModule if ($max_dailies) { $count = DBA::count('user', ['`register_date` > UTC_TIMESTAMP - INTERVAL 1 day']); 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.')); return ''; } @@ -250,7 +249,7 @@ class Register extends BaseModule // Is there text in the tar pit? 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::baseUrl()->redirect('register/'); } @@ -273,7 +272,7 @@ class Register extends BaseModule } 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.')); $regdata = ['email' => $arr['email'], 'nickname' => $arr['nickname'], 'username' => $arr['username']]; DI::baseUrl()->redirect('register?' . http_build_query($regdata)); From c9588fcbb07f34db8ea804068b52c493a2da1c24 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 11:41:58 +0000 Subject: [PATCH 19/91] Replace Logger with $this->logger in Module ActivityPub classes --- src/Module/ActivityPub/Inbox.php | 5 ++--- src/Module/ActivityPub/Objects.php | 8 +++----- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/src/Module/ActivityPub/Inbox.php b/src/Module/ActivityPub/Inbox.php index 23715ceb21..f654b3853b 100644 --- a/src/Module/ActivityPub/Inbox.php +++ b/src/Module/ActivityPub/Inbox.php @@ -7,7 +7,6 @@ namespace Friendica\Module\ActivityPub; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; @@ -66,7 +65,7 @@ class Inbox extends BaseApi } 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(); } @@ -78,7 +77,7 @@ class Inbox extends BaseApi } $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)); - Logger::notice('Incoming message stored', ['file' => $tempfile]); + $this->logger->notice('Incoming message stored', ['file' => $tempfile]); } if (!empty($this->parameters['nickname'])) { diff --git a/src/Module/ActivityPub/Objects.php b/src/Module/ActivityPub/Objects.php index 9b72a52cee..1fa7b2fec5 100644 --- a/src/Module/ActivityPub/Objects.php +++ b/src/Module/ActivityPub/Objects.php @@ -8,8 +8,6 @@ namespace Friendica\Module\ActivityPub; use Friendica\BaseModule; -use Friendica\Core\Logger; -use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Contact; @@ -39,7 +37,7 @@ class Objects extends BaseModule $itemuri = DBA::selectFirst('item-uri', ['id'], ['guid' => $this->parameters['guid']]); 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 { // 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(); @@ -48,9 +46,9 @@ class Objects extends BaseModule $itemuri = DBA::selectFirst('item-uri', ['guid', 'id'], ['uri' => [$url, $nurl, $ssl_url]]); 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 { - Logger::info('URL not found.', ['url' => $url]); + $this->logger->info('URL not found.', ['url' => $url]); throw new HTTPException\NotFoundException(); } } From 6f91b16403a203ed50423a1bcc007e4712d982c8 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 11:43:47 +0000 Subject: [PATCH 20/91] Replace Logger with $this->logger in Module OAuth classes --- src/Module/OAuth/Authorize.php | 13 ++++++------- src/Module/OAuth/Token.php | 3 +-- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/Module/OAuth/Authorize.php b/src/Module/OAuth/Authorize.php index 8179bfa886..db1ee3b703 100644 --- a/src/Module/OAuth/Authorize.php +++ b/src/Module/OAuth/Authorize.php @@ -7,7 +7,6 @@ namespace Friendica\Module\OAuth; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Module\BaseApi; use Friendica\Security\OAuth; @@ -36,18 +35,18 @@ class Authorize extends BaseApi ], $request); 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'))); } 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'))); } $application = OAuth::getApplication($request['client_id'], $request['client_secret'], $request['redirect_uri']); 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()); } @@ -59,14 +58,14 @@ class Authorize extends BaseApi $uid = DI::userSession()->getLocalUserId(); if (empty($uid)) { - Logger::info('Redirect to login'); + $this->logger->info('Redirect to login'); DI::appHelper()->redirect('login?' . http_build_query(['return_authorize' => $redirect])); } 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')) { - 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']])); } diff --git a/src/Module/OAuth/Token.php b/src/Module/OAuth/Token.php index 9ce760790b..6d7f1a3507 100644 --- a/src/Module/OAuth/Token.php +++ b/src/Module/OAuth/Token.php @@ -7,7 +7,6 @@ namespace Friendica\Module\OAuth; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Model\User; use Friendica\Module\BaseApi; @@ -69,7 +68,7 @@ class Token extends BaseApi $grant_type = (string) $request['grant_type']; 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'))); } From b0a5494a8f93faeee95a48da64e920e0f1d10803 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 11:53:38 +0000 Subject: [PATCH 21/91] Replace Logger with $this->logger in Module Mastodon classes --- src/Module/Api/Mastodon/Accounts/Statuses.php | 4 +--- .../Api/Mastodon/Accounts/UpdateCredentials.php | 5 ++--- src/Module/Api/Mastodon/Bookmarks.php | 4 +--- src/Module/Api/Mastodon/Directory.php | 4 +--- src/Module/Api/Mastodon/Favourited.php | 4 +--- src/Module/Api/Mastodon/Media.php | 13 ++++++------- src/Module/Api/Mastodon/Search.php | 3 +-- src/Module/Api/Mastodon/Timelines/Home.php | 3 +-- src/Module/Api/Mastodon/Timelines/ListTimeline.php | 3 +-- .../Api/Mastodon/Timelines/PublicTimeline.php | 3 +-- src/Module/Api/Mastodon/Timelines/Tag.php | 4 +--- src/Module/Api/Mastodon/Trends/Statuses.php | 3 +-- 12 files changed, 18 insertions(+), 35 deletions(-) diff --git a/src/Module/Api/Mastodon/Accounts/Statuses.php b/src/Module/Api/Mastodon/Accounts/Statuses.php index c67476b4ba..679e6e8c3d 100644 --- a/src/Module/Api/Mastodon/Accounts/Statuses.php +++ b/src/Module/Api/Mastodon/Accounts/Statuses.php @@ -7,9 +7,7 @@ namespace Friendica\Module\Api\Mastodon\Accounts; -use Friendica\Core\Logger; use Friendica\Core\Protocol; -use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Conversation; @@ -104,7 +102,7 @@ class Statuses extends BaseApi $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } 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); diff --git a/src/Module/Api/Mastodon/Accounts/UpdateCredentials.php b/src/Module/Api/Mastodon/Accounts/UpdateCredentials.php index 0f920ef2a4..30a33f1e3b 100644 --- a/src/Module/Api/Mastodon/Accounts/UpdateCredentials.php +++ b/src/Module/Api/Mastodon/Accounts/UpdateCredentials.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Mastodon\Accounts; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Contact; use Friendica\Model\Photo; @@ -71,9 +70,9 @@ class UpdateCredentials extends BaseApi $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'])) { Photo::uploadAvatar($uid, $request['avatar']); diff --git a/src/Module/Api/Mastodon/Bookmarks.php b/src/Module/Api/Mastodon/Bookmarks.php index 99ac8b9efc..b0f0ca34a5 100644 --- a/src/Module/Api/Mastodon/Bookmarks.php +++ b/src/Module/Api/Mastodon/Bookmarks.php @@ -7,8 +7,6 @@ namespace Friendica\Module\Api\Mastodon; -use Friendica\Core\Logger; -use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Post; @@ -64,7 +62,7 @@ class Bookmarks extends BaseApi try { $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); } 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); diff --git a/src/Module/Api/Mastodon/Directory.php b/src/Module/Api/Mastodon/Directory.php index da86fa388f..bc6f84c084 100644 --- a/src/Module/Api/Mastodon/Directory.php +++ b/src/Module/Api/Mastodon/Directory.php @@ -7,9 +7,7 @@ namespace Friendica\Module\Api\Mastodon; -use Friendica\Core\Logger; use Friendica\Core\Protocol; -use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Module\BaseApi; @@ -34,7 +32,7 @@ class Directory extends BaseApi 'local' => false, // Only return local accounts. ], $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']) { $table = 'owner-view'; diff --git a/src/Module/Api/Mastodon/Favourited.php b/src/Module/Api/Mastodon/Favourited.php index 53dfef0722..3d9ec883bc 100644 --- a/src/Module/Api/Mastodon/Favourited.php +++ b/src/Module/Api/Mastodon/Favourited.php @@ -7,8 +7,6 @@ namespace Friendica\Module\Api\Mastodon; -use Friendica\Core\Logger; -use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Item; @@ -66,7 +64,7 @@ class Favourited extends BaseApi try { $statuses[] = DI::mstdnStatus()->createFromUriId($item['thr-parent-id'], $uid, $display_quotes); } 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); diff --git a/src/Module/Api/Mastodon/Media.php b/src/Module/Api/Mastodon/Media.php index b15f1cc81c..5dbcfc3687 100644 --- a/src/Module/Api/Mastodon/Media.php +++ b/src/Module/Api/Mastodon/Media.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Mastodon; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Attach; 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 ], $request); - Logger::info('Photo post', ['request' => $request, 'files' => $_FILES]); + $this->logger->info('Photo post', ['request' => $request, 'files' => $_FILES]); 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()); } @@ -45,7 +44,7 @@ class Media extends BaseApi if (in_array($type, [Post\Media::IMAGE, Post\Media::UNKNOWN, Post\Media::APPLICATION])) { $media = Photo::upload($uid, $request['file'], '', null, null, '', '', $request['description']); if (!empty($media)) { - Logger::info('Uploaded photo', ['media' => $media]); + $this->logger->info('Uploaded photo', ['media' => $media]); $this->jsonExit(DI::mstdnAttachment()->createFromPhoto($media['id'])); } elseif ($type == Post\Media::IMAGE) { $this->jsonExit(DI::mstdnAttachment()->createFromPhoto($media['id'])); @@ -58,20 +57,20 @@ class Media extends BaseApi $maxFileSize = Strings::getBytesFromShorthand(DI::config()->get('system', 'maxfilesize')); if ($fileSize <= 0) { - Logger::notice('Filesize is invalid', ['size' => $fileSize, 'request' => $request]); + $this->logger->notice('Filesize is invalid', ['size' => $fileSize, 'request' => $request]); @unlink($tempFileName); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity()); } 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); $this->logAndJsonError(422, $this->errorFactory->UnprocessableEntity()); } $id = Attach::storeFile($tempFileName, self::getCurrentUserID(), $fileName, $request['file']['type'], '<' . Contact::getPublicIdByUserId(self::getCurrentUserID()) . '>'); @unlink($tempFileName); - Logger::info('Uploaded media', ['id' => $id]); + $this->logger->info('Uploaded media', ['id' => $id]); $this->jsonExit(DI::mstdnAttachment()->createFromAttach($id)); } diff --git a/src/Module/Api/Mastodon/Search.php b/src/Module/Api/Mastodon/Search.php index 45556bc3aa..831ac010f8 100644 --- a/src/Module/Api/Mastodon/Search.php +++ b/src/Module/Api/Mastodon/Search.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Mastodon; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -173,7 +172,7 @@ class Search extends BaseApi try { $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); } 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); diff --git a/src/Module/Api/Mastodon/Timelines/Home.php b/src/Module/Api/Mastodon/Timelines/Home.php index 5272ce0b9a..c798a05ae7 100644 --- a/src/Module/Api/Mastodon/Timelines/Home.php +++ b/src/Module/Api/Mastodon/Timelines/Home.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Mastodon\Timelines; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Item; @@ -79,7 +78,7 @@ class Home extends BaseApi $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } 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); diff --git a/src/Module/Api/Mastodon/Timelines/ListTimeline.php b/src/Module/Api/Mastodon/Timelines/ListTimeline.php index 249955fdb3..88ae013012 100644 --- a/src/Module/Api/Mastodon/Timelines/ListTimeline.php +++ b/src/Module/Api/Mastodon/Timelines/ListTimeline.php @@ -11,7 +11,6 @@ use Friendica\App\Arguments; use Friendica\App\BaseURL; use Friendica\AppHelper; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Contact; @@ -84,7 +83,7 @@ class ListTimeline extends BaseApi $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } 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]); } } diff --git a/src/Module/Api/Mastodon/Timelines/PublicTimeline.php b/src/Module/Api/Mastodon/Timelines/PublicTimeline.php index 411a159037..3327757c11 100644 --- a/src/Module/Api/Mastodon/Timelines/PublicTimeline.php +++ b/src/Module/Api/Mastodon/Timelines/PublicTimeline.php @@ -12,7 +12,6 @@ use Friendica\App\BaseURL; use Friendica\AppHelper; use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -113,7 +112,7 @@ class PublicTimeline extends BaseApi $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } 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]); } } diff --git a/src/Module/Api/Mastodon/Timelines/Tag.php b/src/Module/Api/Mastodon/Timelines/Tag.php index bfe54db0df..155c4c7582 100644 --- a/src/Module/Api/Mastodon/Timelines/Tag.php +++ b/src/Module/Api/Mastodon/Timelines/Tag.php @@ -7,9 +7,7 @@ namespace Friendica\Module\Api\Mastodon\Timelines; -use Friendica\Core\Logger; use Friendica\Core\Protocol; -use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Item; @@ -107,7 +105,7 @@ class Tag extends BaseApi try { $statuses[] = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); } 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); diff --git a/src/Module/Api/Mastodon/Trends/Statuses.php b/src/Module/Api/Mastodon/Trends/Statuses.php index 142766593d..ea28647395 100644 --- a/src/Module/Api/Mastodon/Trends/Statuses.php +++ b/src/Module/Api/Mastodon/Trends/Statuses.php @@ -12,7 +12,6 @@ use Friendica\App\BaseURL; use Friendica\AppHelper; use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -67,7 +66,7 @@ class Statuses extends BaseApi try { $trending[] = DI::mstdnStatus()->createFromUriId($status['uri-id'], $uid, $display_quotes); } 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); From d4873dbc6b27f5b826412e1acd6ba4cb36c27f78 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 11:55:30 +0000 Subject: [PATCH 22/91] Replace Logger with $this->logger in Module Twitter classes --- src/Module/Api/Twitter/Favorites.php | 3 +-- src/Module/Api/Twitter/Friendships/Destroy.php | 9 ++++----- src/Module/Api/Twitter/Media/Metadata/Create.php | 3 +-- src/Module/Api/Twitter/Media/Upload.php | 4 +--- src/Module/Api/Twitter/Statuses/Show.php | 3 +-- src/Module/Api/Twitter/Statuses/UserTimeline.php | 3 +-- 6 files changed, 9 insertions(+), 16 deletions(-) diff --git a/src/Module/Api/Twitter/Favorites.php b/src/Module/Api/Twitter/Favorites.php index 4c0841147f..f2fda383f6 100644 --- a/src/Module/Api/Twitter/Favorites.php +++ b/src/Module/Api/Twitter/Favorites.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Twitter; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Model\Item; use Friendica\Module\BaseApi; @@ -29,7 +28,7 @@ class Favorites extends BaseApi // in friendica starred item are private // 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 $count = $this->getRequestValue($request, 'count', 20, 1, 100); diff --git a/src/Module/Api/Twitter/Friendships/Destroy.php b/src/Module/Api/Twitter/Friendships/Destroy.php index cf014134c0..840f8c1155 100644 --- a/src/Module/Api/Twitter/Friendships/Destroy.php +++ b/src/Module/Api/Twitter/Friendships/Destroy.php @@ -12,7 +12,6 @@ use Friendica\App\Arguments; use Friendica\App\BaseURL; use Friendica\AppHelper; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Factory\Api\Twitter\User as TwitterUser; use Friendica\Model\Contact; use Friendica\Model\User; @@ -47,21 +46,21 @@ class Destroy extends ContactEndpoint $owner = User::getOwnerDataById($uid); 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'); } $contact_id = BaseApi::getContactIDForSearchterm($this->getRequestValue($request, 'screen_name', ''), $this->getRequestValue($request, 'profileurl', ''), $this->getRequestValue($request, 'user_id', 0), 0); 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'); } // Get Contact by given id $ucid = Contact::getUserContactId($contact_id, $uid); 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'); } @@ -71,7 +70,7 @@ class Destroy extends ContactEndpoint try { Contact::unfollow($contact); } 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'); } diff --git a/src/Module/Api/Twitter/Media/Metadata/Create.php b/src/Module/Api/Twitter/Media/Metadata/Create.php index 049e6f7061..a12550f7a4 100644 --- a/src/Module/Api/Twitter/Media/Metadata/Create.php +++ b/src/Module/Api/Twitter/Media/Metadata/Create.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Twitter\Media\Metadata; -use Friendica\Core\Logger; use Friendica\Model\Photo; use Friendica\Module\BaseApi; use Friendica\Network\HTTPException\BadRequestException; @@ -44,7 +43,7 @@ class Create extends BaseApi 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]; diff --git a/src/Module/Api/Twitter/Media/Upload.php b/src/Module/Api/Twitter/Media/Upload.php index 897705539c..67bc65b6b8 100644 --- a/src/Module/Api/Twitter/Media/Upload.php +++ b/src/Module/Api/Twitter/Media/Upload.php @@ -7,8 +7,6 @@ namespace Friendica\Module\Api\Twitter\Media; -use Friendica\Core\Logger; -use Friendica\DI; use Friendica\Model\Photo; use Friendica\Module\BaseApi; use Friendica\Network\HTTPException\BadRequestException; @@ -49,7 +47,7 @@ class Upload extends BaseApi "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); } diff --git a/src/Module/Api/Twitter/Statuses/Show.php b/src/Module/Api/Twitter/Statuses/Show.php index 98a5e3c799..075f6311f6 100644 --- a/src/Module/Api/Twitter/Statuses/Show.php +++ b/src/Module/Api/Twitter/Statuses/Show.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Twitter\Statuses; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Module\BaseApi; use Friendica\DI; @@ -34,7 +33,7 @@ class Show extends BaseApi 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']); diff --git a/src/Module/Api/Twitter/Statuses/UserTimeline.php b/src/Module/Api/Twitter/Statuses/UserTimeline.php index 1332ca113e..64e6ec4309 100644 --- a/src/Module/Api/Twitter/Statuses/UserTimeline.php +++ b/src/Module/Api/Twitter/Statuses/UserTimeline.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\Twitter\Statuses; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\Contact; @@ -27,7 +26,7 @@ class UserTimeline extends BaseApi $this->checkAllowedScope(BaseApi::SCOPE_READ); $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); $count = $this->getRequestValue($request, 'count', 20, 1, 100); From c6cef6bbceb1e063b2f82a3d4ebefa3623a3bcf9 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 11:56:22 +0000 Subject: [PATCH 23/91] Replace Logger with $this->logger in all Module classes --- src/Module/Api/GNUSocial/Statusnet/Conversation.php | 3 +-- src/Module/Search/Index.php | 9 ++++----- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/Module/Api/GNUSocial/Statusnet/Conversation.php b/src/Module/Api/GNUSocial/Statusnet/Conversation.php index b30e58f867..41f101350a 100644 --- a/src/Module/Api/GNUSocial/Statusnet/Conversation.php +++ b/src/Module/Api/GNUSocial/Statusnet/Conversation.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Api\GNUSocial\Statusnet; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Module\BaseApi; use Friendica\DI; @@ -40,7 +39,7 @@ class Conversation extends BaseApi $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 $item = Post::selectFirst(['parent-uri-id'], ['uri-id' => $id]); diff --git a/src/Module/Search/Index.php b/src/Module/Search/Index.php index 122b6c569b..eecd195169 100644 --- a/src/Module/Search/Index.php +++ b/src/Module/Search/Index.php @@ -15,7 +15,6 @@ use Friendica\Content\Text\HTML; use Friendica\Content\Widget; use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Renderer; use Friendica\Core\Search; use Friendica\Database\DBA; @@ -134,7 +133,7 @@ class Index extends BaseSearch // 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 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.')); return $o; } @@ -159,11 +158,11 @@ class Index extends BaseSearch $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage); 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); $count = Tag::countByTag($search, DI::userSession()->getLocalUserId()); } 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); $count = Post\Content::countBySearch($search, DI::userSession()->getLocalUserId()); } @@ -197,7 +196,7 @@ class Index extends BaseSearch '$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()); From 0b20a9c92366837d7ba19019346eb872f3fb09ce Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 11:58:29 +0000 Subject: [PATCH 24/91] Replace Logger with DI::logger() in Network classes --- .../HTTPClient/Response/GuzzleResponse.php | 4 +- src/Network/Probe.php | 75 +++++++++---------- 2 files changed, 39 insertions(+), 40 deletions(-) diff --git a/src/Network/HTTPClient/Response/GuzzleResponse.php b/src/Network/HTTPClient/Response/GuzzleResponse.php index e6ca46b3d1..0e246a0cb0 100644 --- a/src/Network/HTTPClient/Response/GuzzleResponse.php +++ b/src/Network/HTTPClient/Response/GuzzleResponse.php @@ -7,7 +7,7 @@ namespace Friendica\Network\HTTPClient\Response; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Network\HTTPClient\Capability\ICanHandleHttpResponses; use GuzzleHttp\Psr7\Response; use GuzzleHttp\RedirectMiddleware; @@ -65,7 +65,7 @@ class GuzzleResponse extends Response implements ICanHandleHttpResponses, Respon } if (!$this->isSuccess) { - Logger::debug('debug', ['info' => $this->getHeaders()]); + DI::logger()->debug('debug', ['info' => $this->getHeaders()]); } if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) { diff --git a/src/Network/Probe.php b/src/Network/Probe.php index d17582f96b..fc064b0f9e 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -12,7 +12,6 @@ use DomXPath; use Exception; use Friendica\Content\Text\HTML; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -116,7 +115,7 @@ class Probe $data['photo'] = Network::addBasePath($data['photo'], $data['url']); 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']); } } @@ -213,13 +212,13 @@ class Probe $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; try { $curlResult = DI::httpClient()->get($ssl_url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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 []; } @@ -234,7 +233,7 @@ class Probe $host_url = 'https://' . $host; } } elseif ($curlResult->isTimeout()) { - Logger::info('Probing timeout', ['url' => $ssl_url]); + DI::logger()->info('Probing timeout', ['url' => $ssl_url]); self::$isTimeout = true; return []; } @@ -243,12 +242,12 @@ class Probe try { $curlResult = DI::httpClient()->get($url, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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 []; } $connection_error = ($curlResult->getErrorNumber() == CURLE_COULDNT_CONNECT) || ($curlResult->getReturnCode() == 0); if ($curlResult->isTimeout()) { - Logger::info('Probing timeout', ['url' => $url]); + DI::logger()->info('Probing timeout', ['url' => $url]); self::$isTimeout = true; return []; } elseif ($connection_error && $ssl_connection_error) { @@ -261,13 +260,13 @@ class Probe $host_url = 'http://' . $host; } if (!is_object($xrd)) { - Logger::info('No xrd object found', ['host' => $host]); + DI::logger()->info('No xrd object found', ['host' => $host]); return []; } $links = XML::elementToArray($xrd); if (!isset($links['xrd']['link'])) { - Logger::info('No xrd data found', ['host' => $host]); + DI::logger()->info('No xrd data found', ['host' => $host]); return []; } @@ -290,13 +289,13 @@ class Probe } if (Network::isUrlBlocked($host_url)) { - Logger::info('Domain is blocked', ['url' => $host]); + DI::logger()->info('Domain is blocked', ['url' => $host]); return []; } self::$baseurl = $host_url; - Logger::info('Probing successful', ['host' => $host]); + DI::logger()->info('Probing successful', ['host' => $host]); return $lrdd; } @@ -317,7 +316,7 @@ class Probe $webfinger = $data['webfinger']; if (empty($webfinger['links'])) { - Logger::info('No webfinger links found', ['uri' => $uri]); + DI::logger()->info('No webfinger links found', ['uri' => $uri]); return []; } @@ -464,7 +463,7 @@ class Probe try { $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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; } if (!$curlResult->isSuccess()) { @@ -631,7 +630,7 @@ class Probe $baseurl = self::$baseurl; } } else { - Logger::info('URI was not detectable', ['uri' => $uri]); + DI::logger()->info('URI was not detectable', ['uri' => $uri]); return []; } @@ -672,7 +671,7 @@ class Probe private static function getWebfinger(string $template, string $type, string $uri, string $addr): ?array { if (Network::isUrlBlocked($template)) { - Logger::info('Domain is blocked', ['url' => $template]); + DI::logger()->info('Domain is blocked', ['url' => $template]); return null; } @@ -734,7 +733,7 @@ class Probe $parts = parse_url($uri); 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); } @@ -748,7 +747,7 @@ class Probe 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)) { $data = self::getWebfingerArray($ap_profile['addr']); @@ -821,7 +820,7 @@ class Probe $result['url'] = $uri; } - Logger::info('Probing done', ['uri' => $uri, 'network' => $result['network']]); + DI::logger()->info('Probing done', ['uri' => $uri, 'network' => $result['network']]); return $result; } @@ -906,7 +905,7 @@ class Probe try { $curlResult = DI::httpClient()->get($url, 'application/x-zot+json', [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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; } if ($curlResult->isTimeout()) { @@ -1017,7 +1016,7 @@ class Probe [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout', 20), HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO] ); } 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; } @@ -1030,7 +1029,7 @@ class Probe $webfinger = json_decode($data, true); if (!empty($webfinger)) { if (!isset($webfinger['links'])) { - Logger::info('No json webfinger links', ['url' => $url]); + DI::logger()->info('No json webfinger links', ['url' => $url]); return []; } return $webfinger; @@ -1039,13 +1038,13 @@ class Probe // If it is not JSON, maybe it is XML $xrd = XML::parseString($data, true); if (!is_object($xrd)) { - Logger::info('No webfinger data retrievable', ['url' => $url]); + DI::logger()->info('No webfinger data retrievable', ['url' => $url]); return []; } $xrd_arr = XML::elementToArray($xrd); if (!isset($xrd_arr['xrd']['link'])) { - Logger::info('No XML webfinger links', ['url' => $url]); + DI::logger()->info('No XML webfinger links', ['url' => $url]); return []; } @@ -1092,7 +1091,7 @@ class Probe try { $curlResult = DI::httpClient()->get($noscrape_url, HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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; } if ($curlResult->isTimeout()) { @@ -1101,13 +1100,13 @@ class Probe } $content = $curlResult->getBodyString(); if (!$content) { - Logger::info('Empty body', ['url' => $noscrape_url]); + DI::logger()->info('Empty body', ['url' => $noscrape_url]); return $data; } $json = json_decode($content, true); if (!is_array($json)) { - Logger::info('No json data', ['url' => $noscrape_url]); + DI::logger()->info('No json data', ['url' => $noscrape_url]); return $data; } @@ -1257,7 +1256,7 @@ class Probe try { $curlResult = DI::httpClient()->get($hcard_url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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 []; } if ($curlResult->isTimeout()) { @@ -1521,7 +1520,7 @@ class Probe self::$isTimeout = true; 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(); } @@ -1552,7 +1551,7 @@ class Probe try { $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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 []; } if ($curlResult->isTimeout()) { @@ -1716,7 +1715,7 @@ class Probe } else { return []; } - + $profile = DI::atProtocol()->XRPCGet('app.bsky.actor.getProfile', ['actor' => $did]); if (empty($profile) || empty($profile->did)) { return []; @@ -1735,11 +1734,11 @@ class Probe 'poll' => ATProtocol::WEB . '/profile/' . $profile->did . '/rss', 'photo' => $profile->avatar ?? '', ]; - + if (!empty($profile->description)) { $data['about'] = HTML::toBBCode($profile->description); } - + if (!empty($profile->banner)) { $data['header'] = $profile->banner; } @@ -1866,7 +1865,7 @@ class Probe } $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)) { return []; @@ -1953,7 +1952,7 @@ class Probe $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; } @@ -2015,7 +2014,7 @@ class Probe try { $curlResult = DI::httpClient()->get($gserver['noscrape'] . '/' . $data['nick'], HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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 ''; } @@ -2055,7 +2054,7 @@ class Probe if (is_string($outbox['first']) && ($outbox['first'] != $feed)) { return self::updateFromOutbox($outbox['first'], $data); } else { - Logger::warning('Unexpected data', ['outbox' => $outbox]); + DI::logger()->warning('Unexpected data', ['outbox' => $outbox]); } return ''; } else { @@ -2096,7 +2095,7 @@ class Probe try { $curlResult = DI::httpClient()->get($data['poll'], HttpClientAccept::ATOM_XML, [HttpClientOptions::REQUEST => HttpClientRequest::CONTACTINFO]); } 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 ''; } if (!$curlResult->isSuccess() || !$curlResult->getBodyString()) { @@ -2120,7 +2119,7 @@ class Probe $updated = !empty($updated_item->nodeValue) ? DateTimeFormat::utc($updated_item->nodeValue) : null; 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; } From 33b5ba35d4c5bde72c165e53fac5ceff3ec0272c Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:01:48 +0000 Subject: [PATCH 25/91] Replace Logger with DI::logger() in Object classes --- src/Object/Post.php | 13 ++++++------- src/Object/Thread.php | 13 ++++++------- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/src/Object/Post.php b/src/Object/Post.php index bc0ade1a0a..37b530b679 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -11,7 +11,6 @@ use Friendica\Content\ContactSelector; use Friendica\Content\Feature; use Friendica\Core\Addon; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Renderer; use Friendica\DI; @@ -782,10 +781,10 @@ class Post public function addChild(Post $item) { if (!$item->getId()) { - Logger::error('Post object has no id', ['post' => $item]); + DI::logger()->error('Post object has no id', ['post' => $item]); return false; } elseif ($this->getChild($item->getId())) { - Logger::warning('Post object already exists', ['post' => $item]); + DI::logger()->warning('Post object already exists', ['post' => $item]); return false; } @@ -793,13 +792,13 @@ class Post * Only add what will be displayed */ if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) { - Logger::warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]); + DI::logger()->warning('Post object does not belong to local user', ['post' => $item, 'local_user' => DI::userSession()->getLocalUserId()]); return false; } elseif ( DI::activity()->match($item->getDataValue('verb'), Activity::LIKE) || DI::activity()->match($item->getDataValue('verb'), Activity::DISLIKE) ) { - Logger::warning('Post objects is a like/dislike', ['post' => $item]); + DI::logger()->warning('Post objects is a like/dislike', ['post' => $item]); return false; } @@ -884,7 +883,7 @@ class Post } } - Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').'); + DI::logger()->info('[WARN] Item::removeChild : Item is not a child (' . $id . ').'); return false; } @@ -947,7 +946,7 @@ class Post public function getDataValue(string $name) { if (!isset($this->data[$name])) { - // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".'); + // DI::logger()->info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".'); return false; } diff --git a/src/Object/Thread.php b/src/Object/Thread.php index 2363ab197d..88534f2918 100644 --- a/src/Object/Thread.php +++ b/src/Object/Thread.php @@ -8,7 +8,6 @@ namespace Friendica\Object; use Friendica\Content\Conversation; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\DI; use Friendica\Protocol\Activity; @@ -77,7 +76,7 @@ class Thread $this->writable = $writable; break; default: - Logger::info('[ERROR] Conversation::setMode : Unhandled mode ('. $mode .').'); + DI::logger()->info('[ERROR] Conversation::setMode : Unhandled mode ('. $mode .').'); return false; break; } @@ -138,12 +137,12 @@ class Thread $item_id = $item->getId(); if (!$item_id) { - Logger::info('[ERROR] Conversation::addThread : Item has no ID!!'); + DI::logger()->info('[ERROR] Conversation::addThread : Item has no ID!!'); return false; } if ($this->getParent($item->getId())) { - Logger::info('[WARN] Conversation::addThread : Thread already exists ('. $item->getId() .').'); + DI::logger()->info('[WARN] Conversation::addThread : Thread already exists ('. $item->getId() .').'); return false; } @@ -151,12 +150,12 @@ class Thread * Only add will be displayed */ if ($item->getDataValue('network') === Protocol::MAIL && DI::userSession()->getLocalUserId() != $item->getDataValue('uid')) { - Logger::info('[WARN] Conversation::addThread : Thread is a mail ('. $item->getId() .').'); + DI::logger()->info('[WARN] Conversation::addThread : Thread is a mail ('. $item->getId() .').'); return false; } if ($item->getDataValue('verb') === Activity::LIKE || $item->getDataValue('verb') === Activity::DISLIKE) { - Logger::info('[WARN] Conversation::addThread : Thread is a (dis)like ('. $item->getId() .').'); + DI::logger()->info('[WARN] Conversation::addThread : Thread is a (dis)like ('. $item->getId() .').'); return false; } @@ -190,7 +189,7 @@ class Thread $item_data = $item->getTemplateData($conv_responses, $formSecurityToken); if (!$item_data) { - Logger::info('[ERROR] Conversation::getTemplateData : Failed to get item template data ('. $item->getId() .').'); + DI::logger()->info('[ERROR] Conversation::getTemplateData : Failed to get item template data ('. $item->getId() .').'); return false; } $result[] = $item_data; From c335754decba654611ef34162df23fe7376a0271 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:07:05 +0000 Subject: [PATCH 26/91] Change static methods to dynamic in Mastodon Search class --- src/Module/Api/Mastodon/Search.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Module/Api/Mastodon/Search.php b/src/Module/Api/Mastodon/Search.php index 831ac010f8..532b45dd99 100644 --- a/src/Module/Api/Mastodon/Search.php +++ b/src/Module/Api/Mastodon/Search.php @@ -53,7 +53,7 @@ class Search extends BaseApi $result = ['accounts' => [], 'statuses' => [], 'hashtags' => []]; 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'])) { // Curbing the search if we got an exact result @@ -63,7 +63,7 @@ class Search extends BaseApi } 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'])) { // Curbing the search if we got an exact result @@ -73,7 +73,7 @@ class Search extends BaseApi } 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); @@ -91,7 +91,7 @@ class Search extends BaseApi * @throws \Friendica\Network\HTTPException\NotFoundException * @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)) && $id = Contact::getIdForURL($q, 0, $resolve ? null : false) @@ -120,7 +120,7 @@ class Search extends BaseApi * @throws \Friendica\Network\HTTPException\NotFoundException * @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)) { // Unique post search, any offset greater than 0 should return empty result @@ -185,7 +185,7 @@ class Search extends BaseApi 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, '#'); From 5d6be2aeb4872da5b4c9498a1984f67c1373be76 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:36:39 +0000 Subject: [PATCH 27/91] Replace Logger with DI::logger() in DFRN Protocol class --- src/Protocol/DFRN.php | 111 +++++++++++++++++++++--------------------- 1 file changed, 55 insertions(+), 56 deletions(-) diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index 93b0d7f9ba..3e28fe53f3 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -13,7 +13,6 @@ use DOMNode; use DOMXPath; use Friendica\App; use Friendica\Content\Text\BBCode; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -716,7 +715,7 @@ class DFRN $mentioned = []; if (!$item['parent']) { - Logger::warning('Item without parent found.', ['type' => $type, 'item' => $item]); + DI::logger()->warning('Item without parent found.', ['type' => $type, 'item' => $item]); return null; } @@ -938,14 +937,14 @@ class DFRN { if (!$public_batch) { if (empty($contact['addr'])) { - Logger::notice('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.'); + DI::logger()->notice('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.'); if (Contact::updateFromProbe($contact['id'])) { $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]); $contact['addr'] = $new_contact['addr']; } if (empty($contact['addr'])) { - Logger::notice('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']); + DI::logger()->notice('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']); return -21; } } @@ -953,7 +952,7 @@ class DFRN try { $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey; } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) { - Logger::notice('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']); + DI::logger()->notice('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']); return -22; } } else { @@ -974,7 +973,7 @@ class DFRN $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']); if (empty($dest_url)) { - Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]); + DI::logger()->info('Empty destination', ['public' => $public_batch, 'contact' => $contact]); return -24; } @@ -983,7 +982,7 @@ class DFRN try { $postResult = DI::httpClient()->post($dest_url, $envelope, ['Content-Type' => $content_type], 0, HttpClientRequest::DFRN); } 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 -25; } @@ -995,7 +994,7 @@ class DFRN } if (empty($curl_stat) || empty($xml)) { - Logger::notice('Empty answer from ' . $contact['id'] . ' - ' . $dest_url); + DI::logger()->notice('Empty answer from ' . $contact['id'] . ' - ' . $dest_url); return -9; // timed out } @@ -1004,8 +1003,8 @@ class DFRN } if (strpos($xml, 'notice('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url); + DI::logger()->debug('Returned XML: ' . $xml); return 3; } @@ -1021,7 +1020,7 @@ class DFRN } if (!empty($res->message)) { - Logger::info('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message); + DI::logger()->info('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message); } return intval($res->status); @@ -1063,7 +1062,7 @@ class DFRN $author["contact-id"] = $contact_old["id"]; $author["network"] = $contact_old["network"]; } else { - Logger::info('Contact not found', ['condition' => $condition]); + DI::logger()->info('Contact not found', ['condition' => $condition]); $author["contact-unknown"] = true; $contact = Contact::getByURL($author["link"], null, ["id", "network"]); @@ -1112,12 +1111,12 @@ class DFRN } if (empty($author['avatar'])) { - Logger::notice('Empty author: ' . $xml); + DI::logger()->notice('Empty author: ' . $xml); $author['avatar'] = ''; } if (DBA::isResult($contact_old) && !$onlyfetch) { - Logger::info("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated."); + DI::logger()->info("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated."); $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]]; @@ -1178,7 +1177,7 @@ class DFRN // If the "hide" element is present then the profile isn't searchable. $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true"); - Logger::info("Hidden status for contact " . $contact_old["url"] . ": " . $hide); + DI::logger()->info("Hidden status for contact " . $contact_old["url"] . ": " . $hide); // If the contact isn't searchable then set the contact to "hidden". // Problem: This can be manually overridden by the user. @@ -1318,7 +1317,7 @@ class DFRN */ private static function processMail(DOMXPath $xpath, DOMNode $mail, array $importer) { - Logger::info("Processing mails"); + DI::logger()->info("Processing mails"); $msg = []; $msg['uid'] = $importer['importer_uid']; @@ -1346,7 +1345,7 @@ class DFRN */ private static function processSuggestion(DOMXPath $xpath, DOMNode $suggestion, array $importer) { - Logger::info('Processing suggestions'); + DI::logger()->info('Processing suggestions'); $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion); $cid = Contact::getIdForURL($url); @@ -1422,7 +1421,7 @@ class DFRN */ private static function processRelocation(DOMXPath $xpath, DOMNode $relocation, array $importer): bool { - Logger::info("Processing relocations"); + DI::logger()->info("Processing relocations"); /// @TODO Rewrite this to one statement $relocate = []; @@ -1452,7 +1451,7 @@ class DFRN // update contact $old = Contact::selectFirst(['photo', 'url'], ['id' => $importer['id'], 'uid' => $importer['importer_uid']]); if (!DBA::isResult($old)) { - Logger::warning('Existing contact had not been fetched', ['id' => $importer['id']]); + DI::logger()->warning('Existing contact had not been fetched', ['id' => $importer['id']]); return false; } @@ -1475,7 +1474,7 @@ class DFRN Contact::updateAvatar($importer['id'], $relocate['avatar'], true); - Logger::info('Contacts are updated.'); + DI::logger()->info('Contacts are updated.'); /// @TODO /// merge with current record, current contents have priority @@ -1558,7 +1557,7 @@ class DFRN */ private static function processVerbs(int $entrytype, array $importer, array &$item) { - Logger::info('Process verb ' . $item['verb'] . ' and object-type ' . $item['object-type'] . ' for entrytype ' . $entrytype); + DI::logger()->info('Process verb ' . $item['verb'] . ' and object-type ' . $item['object-type'] . ' for entrytype ' . $entrytype); if (($entrytype == self::TOP_LEVEL) && !empty($importer['id'])) { // The filling of the "contact" variable is done for legacy reasons @@ -1570,22 +1569,22 @@ class DFRN // Big question: Do we need these functions? They were part of the "consume_feed" function. // This function once was responsible for DFRN and OStatus. if ($activity->match($item['verb'], Activity::FOLLOW)) { - Logger::info("New follower"); + DI::logger()->info("New follower"); Contact::addRelationship($importer, $contact, $item); return false; } if ($activity->match($item['verb'], Activity::UNFOLLOW)) { - Logger::info("Lost follower"); + DI::logger()->info("Lost follower"); Contact::removeFollower($contact); return false; } if ($activity->match($item['verb'], Activity::REQ_FRIEND)) { - Logger::info("New friend request"); + DI::logger()->info("New friend request"); Contact::addRelationship($importer, $contact, $item, true); return false; } if ($activity->match($item['verb'], Activity::UNFRIEND)) { - Logger::info("Lost sharer"); + DI::logger()->info("Lost sharer"); Contact::removeSharer($contact); return false; } @@ -1631,7 +1630,7 @@ class DFRN if ($xt->type == Activity\ObjectType::NOTE) { $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer['importer_uid']]); if (!DBA::isResult($item_tag)) { - Logger::warning('Post had not been fetched', ['uri' => $xt->id, 'uid' => $importer['importer_uid']]); + DI::logger()->warning('Post had not been fetched', ['uri' => $xt->id, 'uid' => $importer['importer_uid']]); return false; } @@ -1696,23 +1695,23 @@ class DFRN { if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)", Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) { - Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]); + DI::logger()->debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]); return true; } if ($importer['importer_uid'] != 0) { - Logger::debug('Message is directed to a user - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'importer' => $importer['importer_uid']]); + DI::logger()->debug('Message is directed to a user - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'importer' => $importer['importer_uid']]); return true; } if ($item['uri'] != $item['thr-parent']) { - Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); + DI::logger()->debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); return true; } $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name'); if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN)) { - Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]); + DI::logger()->debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]); return true; } else { return false; @@ -1735,7 +1734,7 @@ class DFRN */ private static function processEntry(array $header, DOMXPath $xpath, DOMNode $entry, array $importer, string $xml, int $protocol) { - Logger::info("Processing entries"); + DI::logger()->info("Processing entries"); $item = $header; @@ -1751,7 +1750,7 @@ class DFRN ); // Is there an existing item? if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) { - Logger::info("Item " . $item['uri'] . " (" . $item['edited'] . ") already existed."); + DI::logger()->info("Item " . $item['uri'] . " (" . $item['edited'] . ") already existed."); return; } @@ -1961,10 +1960,10 @@ class DFRN // Is it an event? if (($item['object-type'] == Activity\ObjectType::EVENT) && !$owner_unknown) { - Logger::info("Item " . $item['uri'] . " seems to contain an event."); + DI::logger()->info("Item " . $item['uri'] . " seems to contain an event."); $ev = Event::fromBBCode($item['body']); if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) { - Logger::info("Event in item " . $item['uri'] . " was found."); + DI::logger()->info("Event in item " . $item['uri'] . " was found."); $ev['cid'] = $importer['id']; $ev['uid'] = $importer['importer_uid']; $ev['uri'] = $item['uri']; @@ -1984,7 +1983,7 @@ class DFRN } $event_id = Event::store($ev); - Logger::info('Event was stored', ['id' => $event_id]); + DI::logger()->info('Event was stored', ['id' => $event_id]); $item = Event::getItemArrayForImportedId($event_id, $item); } @@ -1992,13 +1991,13 @@ class DFRN } if (!self::processVerbs($entrytype, $importer, $item)) { - Logger::info("Exiting because 'processVerbs' told us so"); + DI::logger()->info("Exiting because 'processVerbs' told us so"); return; } // This check is done here to be able to receive connection requests in "processVerbs" if (($entrytype == self::TOP_LEVEL) && $owner_unknown) { - Logger::info("Item won't be stored because user " . $importer['importer_uid'] . " doesn't follow " . $item['owner-link'] . "."); + DI::logger()->info("Item won't be stored because user " . $importer['importer_uid'] . " doesn't follow " . $item['owner-link'] . "."); return; } @@ -2006,9 +2005,9 @@ class DFRN // Update content if 'updated' changes if (DBA::isResult($current)) { if (self::updateContent($current, $item, $importer, $entrytype)) { - Logger::info("Item " . $item['uri'] . " was updated."); + DI::logger()->info("Item " . $item['uri'] . " was updated."); } else { - Logger::info("Item " . $item['uri'] . " already existed."); + DI::logger()->info("Item " . $item['uri'] . " already existed."); } return; } @@ -2016,20 +2015,20 @@ class DFRN if (in_array($entrytype, [self::REPLY, self::REPLY_RC])) { if (($item['uid'] != 0) && !Post::exists(['uid' => $item['uid'], 'uri' => $item['thr-parent']])) { if (DI::pConfig()->get($item['uid'], 'system', 'accept_only_sharer') == Item::COMPLETION_NONE) { - Logger::info('Completion is set to "none", so we stop here.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); + DI::logger()->info('Completion is set to "none", so we stop here.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); return; } if (!Contact::isSharing($item['owner-id'], $item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) { - Logger::info('Contact is not sharing with the user', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); + DI::logger()->info('Contact is not sharing with the user', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); return; } if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && DI::pConfig()->get($item['uid'], 'system', 'accept_only_sharer') == Item::COMPLETION_COMMENT) { - Logger::info('Completion is set to "comment", but this is an activity. so we stop here.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); + DI::logger()->info('Completion is set to "comment", but this is an activity. so we stop here.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); return; } - Logger::debug('Post is accepted.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); + DI::logger()->debug('Post is accepted.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); } else { - Logger::debug('Thread parent exists.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); + DI::logger()->debug('Thread parent exists.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); } // Will be overwritten for sharing accounts in Item::insert @@ -2039,7 +2038,7 @@ class DFRN $posted_id = Item::insert($item); if ($posted_id) { - Logger::info("Reply from contact " . $item['contact-id'] . " was stored with id " . $posted_id); + DI::logger()->info("Reply from contact " . $item['contact-id'] . " was stored with id " . $posted_id); if ($item['uid'] == 0) { Item::distribute($posted_id); @@ -2049,7 +2048,7 @@ class DFRN } } else { // $entrytype == self::TOP_LEVEL if (($item['uid'] != 0) && !Contact::isSharing($item['owner-id'], $item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) { - Logger::info('Contact is not sharing with the user', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); + DI::logger()->info('Contact is not sharing with the user', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]); return; } @@ -2064,7 +2063,7 @@ class DFRN $posted_id = $notify; } - Logger::info("Item was stored with id " . $posted_id); + DI::logger()->info("Item was stored with id " . $posted_id); if ($item['uid'] == 0) { Item::distribute($posted_id); @@ -2083,7 +2082,7 @@ class DFRN */ private static function processDeletion(DOMXPath $xpath, DOMNode $deletion, array $importer) { - Logger::info("Processing deletions"); + DI::logger()->info("Processing deletions"); $uri = null; foreach ($deletion->attributes as $attributes) { @@ -2099,18 +2098,18 @@ class DFRN $condition = ['uri' => $uri, 'uid' => $importer['importer_uid']]; $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition); if (!DBA::isResult($item)) { - Logger::info('Item with URI ' . $uri . ' for user ' . $importer['importer_uid'] . ' was not found.'); + DI::logger()->info('Item with URI ' . $uri . ' for user ' . $importer['importer_uid'] . ' was not found.'); return; } if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) { - Logger::notice('Item is filed. It will not be deleted.', ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer['importer_uid']]); + DI::logger()->notice('Item is filed. It will not be deleted.', ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer['importer_uid']]); return; } // When it is a starting post it has to belong to the person that wants to delete it if (($item['gravity'] == Item::GRAVITY_PARENT) && ($item['contact-id'] != $importer['id'])) { - Logger::info('Item with URI ' . $uri . ' do not belong to contact ' . $importer['id'] . ' - ignoring deletion.'); + DI::logger()->info('Item with URI ' . $uri . ' do not belong to contact ' . $importer['id'] . ' - ignoring deletion.'); return; } @@ -2118,7 +2117,7 @@ class DFRN if (($item['gravity'] != Item::GRAVITY_PARENT) && ($item['contact-id'] != $importer['id'])) { $condition = ['id' => $item['parent'], 'contact-id' => $importer['id']]; if (!Post::exists($condition)) { - Logger::info('Item with URI ' . $uri . ' was not found or must not be deleted by contact ' . $importer['id'] . ' - ignoring deletion.'); + DI::logger()->info('Item with URI ' . $uri . ' was not found or must not be deleted by contact ' . $importer['id'] . ' - ignoring deletion.'); return; } } @@ -2127,7 +2126,7 @@ class DFRN return; } - Logger::info('deleting item '.$item['id'].' uri='.$uri); + DI::logger()->info('deleting item '.$item['id'].' uri='.$uri); Item::markForDeletion(['id' => $item['id']]); } @@ -2190,7 +2189,7 @@ class DFRN self::fetchauthor($xpath, $doc->firstChild, $importer, 'dfrn:owner', false, $xml); } - Logger::info("Import DFRN message for user " . $importer['importer_uid'] . " from contact " . $importer['id']); + DI::logger()->info("Import DFRN message for user " . $importer['importer_uid'] . " from contact " . $importer['id']); if (!empty($importer['gsid']) && ($protocol == Conversation::PARCEL_DIASPORA_DFRN)) { GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN); @@ -2263,7 +2262,7 @@ class DFRN self::processDeletion($xpath, $deletion, $importer); } if (count($deletions) > 0) { - Logger::info(count($deletions) . ' deletions had been processed'); + DI::logger()->info(count($deletions) . ' deletions had been processed'); return 200; } } @@ -2273,7 +2272,7 @@ class DFRN self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol); } - Logger::info("Import done for user " . $importer['importer_uid'] . " from contact " . $importer['id']); + DI::logger()->info("Import done for user " . $importer['importer_uid'] . " from contact " . $importer['id']); return 200; } From abc456e587f031b4d91e746faccf221d6a18e3d3 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:37:29 +0000 Subject: [PATCH 28/91] Replace Logger with DI::logger() in Delivery Protocol class --- src/Protocol/Delivery.php | 57 +++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/src/Protocol/Delivery.php b/src/Protocol/Delivery.php index c18de6264c..d13b106aeb 100644 --- a/src/Protocol/Delivery.php +++ b/src/Protocol/Delivery.php @@ -9,7 +9,6 @@ namespace Friendica\Protocol; use Friendica\Contact\FriendSuggest\Collection\FriendSuggests; use Friendica\Contact\FriendSuggest\Exception\FriendSuggestNotFoundException; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Worker; use Friendica\Database\DBA; @@ -42,7 +41,7 @@ class Delivery */ public static function deliver(string $cmd, int $post_uriid, int $contact_id, int $sender_uid = 0): bool { - Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid, 'contact' => $contact_id]); + DI::logger()->info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid, 'contact' => $contact_id]); $top_level = false; $followup = false; @@ -71,7 +70,7 @@ class Delivery } else { $item = Post::selectFirst(['id', 'parent'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]); if (!DBA::isResult($item) || empty($item['parent'])) { - Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]); + DI::logger()->warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]); return true; } $target_id = intval($item['id']); @@ -97,12 +96,12 @@ class Delivery DBA::close($itemdata); if (empty($target_item)) { - Logger::warning("No target item data. Quitting here.", ['id' => $target_id]); + DI::logger()->warning("No target item data. Quitting here.", ['id' => $target_id]); return true; } if (empty($parent)) { - Logger::warning('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here."); + DI::logger()->warning('Parent ' . $parent_id . ' for item ' . $target_id . "wasn't found. Quitting here."); self::setFailedQueue($cmd, $target_item); return true; } @@ -112,7 +111,7 @@ class Delivery } elseif (!empty($target_item['uid'])) { $uid = $target_item['uid']; } else { - Logger::info('Only public users for item ' . $target_id); + DI::logger()->info('Only public users for item ' . $target_id); self::setFailedQueue($cmd, $target_item); return true; } @@ -126,7 +125,7 @@ class Delivery } if (!empty($contact_id) && Contact::isArchived($contact_id)) { - Logger::info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]); + DI::logger()->info('Contact is archived', ['id' => $contact_id, 'cmd' => $cmd, 'item' => $target_item['id']]); self::setFailedQueue($cmd, $target_item); return true; } @@ -161,7 +160,7 @@ class Delivery */ if (!$top_level && ($parent['wall'] == 0) && stristr($target_item['uri'], $localhost)) { - Logger::info('Followup ' . $target_item["guid"]); + DI::logger()->info('Followup ' . $target_item["guid"]); // local followup to remote post $followup = true; } @@ -176,7 +175,7 @@ class Delivery } if (empty($items)) { - Logger::warning('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]); + DI::logger()->warning('No delivery data', ['command' => $cmd, 'uri-id' => $post_uriid, 'cid' => $contact_id]); } $owner = User::getOwnerDataById($uid); @@ -206,11 +205,11 @@ class Delivery // This is done since the uri wouldn't match (Diaspora doesn't transmit it) // Also transmit relayed posts from Diaspora contacts via Diaspora. if (($contact['network'] != Protocol::DIASPORA) && in_array(Protocol::DIASPORA, [$parent['network'] ?? '', $thr_parent['network'] ?? '', $target_item['network'] ?? ''])) { - Logger::info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]); + DI::logger()->info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]); $contact['network'] = Protocol::DIASPORA; } - Logger::notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]); + DI::logger()->notice('Delivering', ['cmd' => $cmd, 'uri-id' => $post_uriid, 'followup' => $followup, 'network' => $contact['network']]); switch ($contact['network']) { case Protocol::DFRN: @@ -273,11 +272,11 @@ class Delivery // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora if (Diaspora::getReshareDetails($target_item) && Diaspora::isSupportedByContactUrl($contact['addr'])) { - Logger::info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => $target_item_id]); + DI::logger()->info('Reshare will be transmitted via Diaspora', ['url' => $contact['url'], 'guid' => $target_item_id]); return self::deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup); } - Logger::info('Deliver ' . ($target_item_id ?? 'relocation') . ' via DFRN to ' . ($contact['addr'] ?? '' ?: $contact['url'])); + DI::logger()->info('Deliver ' . ($target_item_id ?? 'relocation') . ' via DFRN to ' . ($contact['addr'] ?? '' ?: $contact['url'])); if ($cmd == self::MAIL) { $item = $target_item; @@ -309,7 +308,7 @@ class Delivery $atom = DFRN::entries($msgitems, $owner); } - Logger::debug('Notifier entry: ' . $contact['url'] . ' ' . ($target_item_id ?? 'relocation') . ' entry: ' . $atom); + DI::logger()->debug('Notifier entry: ' . $contact['url'] . ' ' . ($target_item_id ?? 'relocation') . ' entry: ' . $atom); $protocol = Post\DeliveryData::DFRN; @@ -323,7 +322,7 @@ class Delivery // We never spool failed relay deliveries if ($public_dfrn) { - Logger::info('Relay delivery to ' . $contact['url'] . ' with guid ' . $target_item['guid'] . ' returns ' . $deliver_status); + DI::logger()->info('Relay delivery to ' . $contact['url'] . ' with guid ' . $target_item['guid'] . ' returns ' . $deliver_status); $success = ($deliver_status >= 200) && ($deliver_status <= 299); @@ -345,7 +344,7 @@ class Delivery $deliver_status = DFRN::transmit($owner, $contact, $atom); } - Logger::info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => $target_item_id, 'return' => $deliver_status]); + DI::logger()->info('DFRN Delivery', ['cmd' => $cmd, 'url' => $contact['url'], 'guid' => $target_item_id, 'return' => $deliver_status]); if (($deliver_status >= 200) && ($deliver_status <= 299)) { // We successfully delivered a message, the contact is alive @@ -361,7 +360,7 @@ class Delivery // The message could not be delivered. We mark the contact as "dead" Contact::markForArchival($contact); - Logger::info('Delivery failed: defer message', ['id' => $target_item_id]); + DI::logger()->info('Delivery failed: defer message', ['id' => $target_item_id]); if (!Worker::defer() && $cmd == Delivery::POST) { Post\DeliveryData::incrementQueueFailed($target_item['uri-id']); } @@ -397,7 +396,7 @@ class Delivery $loc = $contact['addr']; } - Logger::notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]); + DI::logger()->notice('Deliver via Diaspora', ['target' => $target_item['id'], 'guid' => $target_item['guid'], 'to' => $loc]); if (!DI::config()->get('system', 'diaspora_enabled')) { return true; @@ -420,22 +419,22 @@ class Delivery $deliver_status = Diaspora::sendAccountMigration($owner, $contact, $owner['uid']); } elseif ($target_item['deleted'] && (($target_item['uri'] === $target_item['parent-uri']) || $followup)) { // top-level retraction - Logger::notice('diaspora retract: ' . $loc); + DI::logger()->notice('diaspora retract: ' . $loc); $deliver_status = Diaspora::sendRetraction($target_item, $owner, $contact, $public_message); } elseif ($followup) { // send comments and likes to owner to relay - Logger::notice('diaspora followup: ' . $loc); + DI::logger()->notice('diaspora followup: ' . $loc); $deliver_status = Diaspora::sendFollowup($target_item, $owner, $contact, $public_message); } elseif ($target_item['uri'] !== $target_item['parent-uri']) { // we are the relay - send comments, likes and relayable_retractions to our conversants - Logger::notice('diaspora relay: ' . $loc); + DI::logger()->notice('diaspora relay: ' . $loc); $deliver_status = Diaspora::sendRelay($target_item, $owner, $contact, $public_message); } elseif ($top_level && !$walltowall) { // currently no workable solution for sending walltowall - Logger::notice('diaspora status: ' . $loc); + DI::logger()->notice('diaspora status: ' . $loc); $deliver_status = Diaspora::sendStatus($target_item, $owner, $contact, $public_message); } else { - Logger::warning('Unknown mode', ['command' => $cmd, 'target' => $loc]); + DI::logger()->warning('Unknown mode', ['command' => $cmd, 'target' => $loc]); return true; } @@ -459,7 +458,7 @@ class Delivery } if (empty($contact['contact-type']) || ($contact['contact-type'] != Contact::TYPE_RELAY)) { - Logger::info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]); + DI::logger()->info('Delivery failed: defer message', ['id' => ($target_item['guid'] ?? '') ?: $target_item['id']]); // defer message for redelivery if (!Worker::defer() && $cmd == Delivery::POST) { Post\DeliveryData::incrementQueueFailed($target_item['uri-id']); @@ -508,10 +507,10 @@ class Delivery $data = json_decode($thr_parent['object'], true); if (!empty($data['reply_to'])) { $addr = $data['reply_to'][0]['mailbox'] . '@' . $data['reply_to'][0]['host']; - Logger::info('Use "reply-to" address of the thread parent', ['addr' => $addr]); + DI::logger()->info('Use "reply-to" address of the thread parent', ['addr' => $addr]); } elseif (!empty($data['from'])) { $addr = $data['from'][0]['mailbox'] . '@' . $data['from'][0]['host']; - Logger::info('Use "from" address of the thread parent', ['addr' => $addr]); + DI::logger()->info('Use "from" address of the thread parent', ['addr' => $addr]); } } @@ -520,7 +519,7 @@ class Delivery return true; } - Logger::info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]); + DI::logger()->info('About to deliver via mail', ['guid' => $target_item['guid'], 'to' => $addr]); $reply_to = ''; $mailacct = DBA::selectFirst('mailacct', ['reply_to'], ['uid' => $owner['uid']]); @@ -583,10 +582,10 @@ class Delivery if ($success) { // Success Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::MAIL); - Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]); + DI::logger()->info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]); } else { // Failed - Logger::warning('Delivery of mail has FAILED', ['to' => $addr, 'subject' => $subject, 'guid' => $target_item['guid']]); + DI::logger()->warning('Delivery of mail has FAILED', ['to' => $addr, 'subject' => $subject, 'guid' => $target_item['guid']]); } return $success; } From 6ead2d1738eed87306a2fc90dd6e64a223ba9a71 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:37:44 +0000 Subject: [PATCH 29/91] Replace Logger with DI::logger() in Diaspora Protocol class --- src/Protocol/Diaspora.php | 331 +++++++++++++++++++------------------- 1 file changed, 165 insertions(+), 166 deletions(-) diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index b791c2572f..952f6f3b96 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -11,7 +11,6 @@ use Friendica\Content\Feature; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\Markdown; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Core\Worker; @@ -69,7 +68,7 @@ class Diaspora public static function participantsForThread(array $item, array $contacts): array { if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) { - Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]); + DI::logger()->info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]); return $contacts; } @@ -99,7 +98,7 @@ class Diaspora } if (!$exists) { - Logger::info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]); + DI::logger()->info('Add participant to receiver list', ['parent' => $item['parent-guid'], 'item' => $item['guid'], 'participant' => $contact['url']]); $contacts[] = $contact; } } @@ -122,14 +121,14 @@ class Diaspora $basedom = XML::parseString($envelope, true); if (!is_object($basedom)) { - Logger::notice('Envelope is no XML file'); + DI::logger()->notice('Envelope is no XML file'); return false; } $children = $basedom->children(ActivityNamespace::SALMON_ME); if (sizeof($children) == 0) { - Logger::notice('XML has no children'); + DI::logger()->notice('XML has no children'); return false; } @@ -154,7 +153,7 @@ class Diaspora $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg); if ($handle == '') { - Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope); + DI::logger()->notice('No author could be decoded. Discarding. Message: ' . $envelope); return false; } @@ -164,13 +163,13 @@ class Diaspora throw new \InvalidArgumentException(); } } catch (\InvalidArgumentException $e) { - Logger::notice("Couldn't get a key for handle " . $handle . ". Discarding."); + DI::logger()->notice("Couldn't get a key for handle " . $handle . ". Discarding."); return false; } $verify = Crypto::rsaVerify($signable_data, $sig, $key); if (!$verify) { - Logger::notice('Message from ' . $handle . ' did not verify. Discarding.'); + DI::logger()->notice('Message from ' . $handle . ' did not verify. Discarding.'); return false; } @@ -227,7 +226,7 @@ class Diaspora if (is_object($data)) { try { if (!isset($data->aes_key) || !isset($data->encrypted_magic_envelope)) { - Logger::info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]); + DI::logger()->info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]); throw new \RuntimeException('Missing keys "aes_key" and/or "encrypted_magic_envelope"'); } @@ -239,12 +238,12 @@ class Diaspora $j_outer_key_bundle = json_decode($outer_key_bundle); if (!is_object($j_outer_key_bundle)) { - Logger::info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]); + DI::logger()->info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]); throw new \RuntimeException('Unable to decode outer key bundle'); } if (!isset($j_outer_key_bundle->iv) || !isset($j_outer_key_bundle->key)) { - Logger::info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]); + DI::logger()->info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]); throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon'); } @@ -253,7 +252,7 @@ class Diaspora $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext); } catch (\Throwable $e) { - Logger::notice('Outer Salmon did not verify. Discarding.'); + DI::logger()->notice('Outer Salmon did not verify. Discarding.'); if ($no_exit) { return false; } else { @@ -267,7 +266,7 @@ class Diaspora $basedom = XML::parseString($xml, true); if (!is_object($basedom)) { - Logger::notice('Received data does not seem to be an XML. Discarding. ' . $xml); + DI::logger()->notice('Received data does not seem to be an XML. Discarding. ' . $xml); if ($no_exit) { return false; } else { @@ -293,7 +292,7 @@ class Diaspora $key_id = $base->sig[0]->attributes()->key_id[0]; $author_addr = base64_decode($key_id); if ($author_addr == '') { - Logger::notice('No author could be decoded. Discarding. Message: ' . $xml); + DI::logger()->notice('No author could be decoded. Discarding. Message: ' . $xml); if ($no_exit) { return false; } else { @@ -308,7 +307,7 @@ class Diaspora throw new \InvalidArgumentException(); } } catch (\InvalidArgumentException $e) { - Logger::notice("Couldn't get a key for handle " . $author_addr . ". Discarding."); + DI::logger()->notice("Couldn't get a key for handle " . $author_addr . ". Discarding."); if ($no_exit) { return false; } else { @@ -318,7 +317,7 @@ class Diaspora $verify = Crypto::rsaVerify($signed_data, $signature, $key); if (!$verify) { - Logger::notice('Message did not verify. Discarding.'); + DI::logger()->notice('Message did not verify. Discarding.'); if ($no_exit) { return false; } else { @@ -352,7 +351,7 @@ class Diaspora $basedom = XML::parseString($xml); if (!is_object($basedom)) { - Logger::notice('XML is not parseable.'); + DI::logger()->notice('XML is not parseable.'); return false; } $children = $basedom->children('https://joindiaspora.com/protocol'); @@ -366,7 +365,7 @@ class Diaspora } else { // This happens with posts from a relais if (empty($privKey)) { - Logger::info('This is no private post in the old format'); + DI::logger()->info('This is no private post in the old format'); return false; } @@ -385,7 +384,7 @@ class Diaspora $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext); - Logger::info('decrypted', ['data' => $decrypted]); + DI::logger()->info('decrypted', ['data' => $decrypted]); $idom = XML::parseString($decrypted); $inner_iv = base64_decode($idom->iv); @@ -395,7 +394,7 @@ class Diaspora try { $author = WebFingerUri::fromString($idom->author_id); } catch (\Throwable $e) { - Logger::notice('Could not retrieve author URI.', ['idom' => $idom]); + DI::logger()->notice('Could not retrieve author URI.', ['idom' => $idom]); throw new \Friendica\Network\HTTPException\BadRequestException(); } @@ -413,7 +412,7 @@ class Diaspora } if (!$base) { - Logger::notice('unable to locate salmon data in xml'); + DI::logger()->notice('unable to locate salmon data in xml'); throw new HTTPException\BadRequestException(); } @@ -450,21 +449,21 @@ class Diaspora // Once we have the author URI, go to the web and try to find their public key // (first this will look it up locally if it is in the diaspora-contact cache) // This will also convert diaspora public key from pkcs#1 to pkcs#8 - Logger::info('Fetching key for ' . $author); + DI::logger()->info('Fetching key for ' . $author); $key = self::key($author); if (!$key) { - Logger::notice('Could not retrieve author key.'); + DI::logger()->notice('Could not retrieve author key.'); throw new HTTPException\BadRequestException(); } $verify = Crypto::rsaVerify($signed_data, $signature, $key); if (!$verify) { - Logger::notice('Message did not verify. Discarding.'); + DI::logger()->notice('Message did not verify. Discarding.'); throw new HTTPException\BadRequestException(); } - Logger::info('Message verified.'); + DI::logger()->info('Message verified.'); return [ 'message' => $inner_decrypted, @@ -487,12 +486,12 @@ class Diaspora public static function dispatchPublic(array $msg, int $direction) { if (!DI::config()->get('system', 'diaspora_enabled')) { - Logger::notice('Diaspora is disabled'); + DI::logger()->notice('Diaspora is disabled'); return false; } if (!($fields = self::validPosting($msg))) { - Logger::notice('Invalid posting', ['msg' => $msg]); + DI::logger()->notice('Invalid posting', ['msg' => $msg]); return false; } @@ -527,7 +526,7 @@ class Diaspora if (is_null($fields)) { $private = true; if (!($fields = self::validPosting($msg))) { - Logger::notice('Invalid posting', ['msg' => $msg]); + DI::logger()->notice('Invalid posting', ['msg' => $msg]); return false; } } else { @@ -536,12 +535,12 @@ class Diaspora $type = $fields->getName(); - Logger::info('Received message', ['type' => $type, 'sender' => $sender->getAddr(), 'user' => $importer['uid']]); + DI::logger()->info('Received message', ['type' => $type, 'sender' => $sender->getAddr(), 'user' => $importer['uid']]); switch ($type) { case 'account_migration': if (!$private) { - Logger::notice('Message with type ' . $type . ' is not private, quitting.'); + DI::logger()->notice('Message with type ' . $type . ' is not private, quitting.'); return false; } return self::receiveAccountMigration($importer, $fields); @@ -554,14 +553,14 @@ class Diaspora case 'contact': if (!$private) { - Logger::notice('Message with type ' . $type . ' is not private, quitting.'); + DI::logger()->notice('Message with type ' . $type . ' is not private, quitting.'); return false; } return self::receiveContactRequest($importer, $fields); case 'conversation': if (!$private) { - Logger::notice('Message with type ' . $type . ' is not private, quitting.'); + DI::logger()->notice('Message with type ' . $type . ' is not private, quitting.'); return false; } return self::receiveConversation($importer, $msg, $fields); @@ -571,14 +570,14 @@ class Diaspora case 'message': if (!$private) { - Logger::notice('Message with type ' . $type . ' is not private, quitting.'); + DI::logger()->notice('Message with type ' . $type . ' is not private, quitting.'); return false; } return self::receiveMessage($importer, $fields); case 'participation': if (!$private) { - Logger::notice('Message with type ' . $type . ' is not private, quitting.'); + DI::logger()->notice('Message with type ' . $type . ' is not private, quitting.'); return false; } return self::receiveParticipation($importer, $fields, $direction); @@ -591,7 +590,7 @@ class Diaspora case 'profile': if (!$private) { - Logger::notice('Message with type ' . $type . ' is not private, quitting.'); + DI::logger()->notice('Message with type ' . $type . ' is not private, quitting.'); return false; } return self::receiveProfile($importer, $fields); @@ -606,7 +605,7 @@ class Diaspora return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction); default: - Logger::notice('Unknown message type ' . $type); + DI::logger()->notice('Unknown message type ' . $type); return false; } } @@ -628,7 +627,7 @@ class Diaspora $element = XML::parseString($msg['message']); if (!is_object($element)) { - Logger::info('No valid XML', ['message' => $msg['message']]); + DI::logger()->info('No valid XML', ['message' => $msg['message']]); return false; } @@ -645,7 +644,7 @@ class Diaspora $type = $element->getName(); $orig_type = $type; - Logger::debug('Got message', ['type' => $type, 'message' => $msg['message']]); + DI::logger()->debug('Got message', ['type' => $type, 'message' => $msg['message']]); // All retractions are handled identically from now on. // In the new version there will only be "retraction". @@ -722,7 +721,7 @@ class Diaspora // This is something that shouldn't happen at all. if (in_array($type, ['status_message', 'reshare', 'profile'])) { if ($msg['author'] != $fields->author) { - Logger::notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]); + DI::logger()->notice('Message handle is not the same as envelope sender. Quitting this message.', ['author1' => $msg['author'], 'author2' => $fields->author]); return false; } } @@ -733,25 +732,25 @@ class Diaspora } if (!isset($author_signature) && ($msg['author'] == $fields->author)) { - Logger::debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]); + DI::logger()->debug('No author signature, but the sender matches the author', ['type' => $type, 'msg-author' => $msg['author'], 'message' => $msg['message']]); return $fields; } // No author_signature? This is a must, so we quit. if (!isset($author_signature)) { - Logger::info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]); + DI::logger()->info('No author signature', ['type' => $type, 'msg-author' => $msg['author'], 'fields-author' => $fields->author, 'message' => $msg['message']]); return false; } if (isset($parent_author_signature)) { $key = self::key(WebFingerUri::fromString($msg['author'])); if (empty($key)) { - Logger::info('No key found for parent', ['author' => $msg['author']]); + DI::logger()->info('No key found for parent', ['author' => $msg['author']]); return false; } if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) { - Logger::info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]); + DI::logger()->info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]); return false; } } @@ -762,12 +761,12 @@ class Diaspora throw new \InvalidArgumentException(); } } catch (\Throwable $e) { - Logger::info('No key found', ['author' => $fields->author]); + DI::logger()->info('No key found', ['author' => $fields->author]); return false; } if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) { - Logger::info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]); + DI::logger()->info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]); return false; } else { return $fields; @@ -785,7 +784,7 @@ class Diaspora */ private static function key(WebFingerUri $uri): string { - Logger::info('Fetching diaspora key', ['handle' => $uri->getAddr()]); + DI::logger()->info('Fetching diaspora key', ['handle' => $uri->getAddr()]); try { return DI::dsprContact()->getByAddr($uri)->pubKey; } catch (NotFoundException | \InvalidArgumentException $e) { @@ -856,7 +855,7 @@ class Diaspora // ); // // $contact["rel"] = Contact::FRIEND; - // Logger::notice("defining user ".$contact["nick"]." as friend"); + // DI::logger()->notice("defining user ".$contact["nick"]." as friend"); //} // Contact server is blocked @@ -894,7 +893,7 @@ class Diaspora { $contact = self::contactByHandle($importer['uid'], $contact_uri); if (!$contact) { - Logger::notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found'); + DI::logger()->notice('A Contact for handle ' . $contact_uri . ' and user ' . $importer['uid'] . ' was not found'); // If a contact isn't found, we accept it anyway if it is a comment if ($is_comment && ($importer['uid'] != 0)) { return self::contactByHandle(0, $contact_uri); @@ -906,7 +905,7 @@ class Diaspora } if (!self::postAllow($importer, $contact, $is_comment)) { - Logger::notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']); + DI::logger()->notice('The handle: ' . $contact_uri . ' is not allowed to post to user ' . $importer['uid']); return false; } return $contact; @@ -925,7 +924,7 @@ class Diaspora { $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]); if (DBA::isResult($item)) { - Logger::notice('Message already exists.', ['uid' => $uid, 'guid' => $guid, 'id' => $item['id']]); + DI::logger()->notice('Message already exists.', ['uid' => $uid, 'guid' => $guid, 'id' => $item['id']]); return $item['id']; } @@ -1031,7 +1030,7 @@ class Diaspora $server = $serverparts['scheme'] . '://' . $serverparts['host']; - Logger::info('Trying to fetch item ' . $guid . ' from ' . $server); + DI::logger()->info('Trying to fetch item ' . $guid . ' from ' . $server); $msg = self::message($guid, $server); @@ -1039,7 +1038,7 @@ class Diaspora return false; } - Logger::info('Successfully fetched item ' . $guid . ' from ' . $server); + DI::logger()->info('Successfully fetched item ' . $guid . ' from ' . $server); // Now call the dispatcher return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED); @@ -1067,16 +1066,16 @@ class Diaspora // This will work for new Diaspora servers and Friendica servers from 3.5 $source_url = $server . '/fetch/post/' . urlencode($guid); - Logger::info('Fetch post from ' . $source_url); + DI::logger()->info('Fetch post from ' . $source_url); $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC, 0, '', HttpClientRequest::DIASPORA); if ($envelope) { - Logger::info('Envelope was fetched.'); + DI::logger()->info('Envelope was fetched.'); $x = self::verifyMagicEnvelope($envelope); if (!$x) { - Logger::info('Envelope could not be verified.'); + DI::logger()->info('Envelope could not be verified.'); } else { - Logger::info('Envelope was verified.'); + DI::logger()->info('Envelope was verified.'); } } else { $x = false; @@ -1094,11 +1093,11 @@ class Diaspora if ($source_xml->post->reshare) { // Reshare of a reshare - old Diaspora version - Logger::info('Message is a reshare'); + DI::logger()->info('Message is a reshare'); return self::message($source_xml->post->reshare->root_guid, $server, ++$level); } elseif ($source_xml->getName() == 'reshare') { // Reshare of a reshare - new Diaspora version - Logger::info('Message is a new reshare'); + DI::logger()->info('Message is a new reshare'); return self::message($source_xml->root_guid, $server, ++$level); } @@ -1115,7 +1114,7 @@ class Diaspora $author = WebFingerUri::fromString($author_handle); } catch (\InvalidArgumentException $e) { // If this isn't a "status_message" then quit - Logger::info("Message doesn't seem to be a status message"); + DI::logger()->info("Message doesn't seem to be a status message"); return false; } @@ -1140,7 +1139,7 @@ class Diaspora { // Check for Diaspora (and Friendica) typical paths if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) { - Logger::notice('Invalid url', ['url' => $url]); + DI::logger()->notice('Invalid url', ['url' => $url]); return false; } @@ -1148,20 +1147,20 @@ class Diaspora $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]); if (DBA::isResult($item)) { - Logger::info('Found', ['id' => $item['id']]); + DI::logger()->info('Found', ['id' => $item['id']]); return $item['id']; } - Logger::info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]); + DI::logger()->info('Fetch GUID from origin', ['guid' => $guid, 'server' => $matches[1]]); $ret = self::storeByGuid($guid, $matches[1], true); - Logger::info('Result', ['ret' => $ret]); + DI::logger()->info('Result', ['ret' => $ret]); $item = Post::selectFirst(['id'], ['guid' => $guid, 'uid' => $uid]); if (DBA::isResult($item)) { - Logger::info('Found', ['id' => $item['id']]); + DI::logger()->info('Found', ['id' => $item['id']]); return $item['id']; } else { - Logger::notice('Not found', ['guid' => $guid, 'uid' => $uid]); + DI::logger()->notice('Not found', ['guid' => $guid, 'uid' => $uid]); return false; } } @@ -1199,20 +1198,20 @@ class Diaspora } if ($result) { - Logger::info('Fetched missing item ' . $guid . ' - result: ' . $result); + DI::logger()->info('Fetched missing item ' . $guid . ' - result: ' . $result); $item = Post::selectFirst($fields, $condition); } } catch (HTTPException\NotFoundException $e) { - Logger::notice('Unable to retrieve author details', ['author' => $author->getAddr()]); + DI::logger()->notice('Unable to retrieve author details', ['author' => $author->getAddr()]); } } if (!DBA::isResult($item)) { - Logger::notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid); + DI::logger()->notice('Parent item not found: parent: ' . $guid . ' - user: ' . $uid); return false; } else { - Logger::info('Parent item found: parent: ' . $guid . ' - user: ' . $uid); + DI::logger()->info('Parent item found: parent: ' . $guid . ' - user: ' . $uid); return $item; } } @@ -1274,28 +1273,28 @@ class Diaspora { $contact = Contact::getByURL($addr); if (empty($contact)) { - Logger::info('No contact data for address', ['addr' => $addr]); + DI::logger()->info('No contact data for address', ['addr' => $addr]); return ''; } if (empty($contact['baseurl'])) { $contact['baseurl'] = 'https://' . substr($addr, strpos($addr, '@') + 1); - Logger::info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]); + DI::logger()->info('Create baseurl from address', ['baseurl' => $contact['baseurl'], 'url' => $contact['url']]); } $platform = ''; $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]); if (!empty($gserver['platform'])) { $platform = strtolower($gserver['platform']); - Logger::info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]); + DI::logger()->info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]); } if (!in_array($platform, ['diaspora', 'friendica', 'hubzilla', 'socialhome'])) { if (self::isHubzilla($contact['url'])) { - Logger::info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]); + DI::logger()->info('Detected unknown platform as Hubzilla', ['platform' => $platform, 'url' => $contact['url']]); $platform = 'hubzilla'; } elseif ($contact['network'] == Protocol::DFRN) { - Logger::info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]); + DI::logger()->info('Detected unknown platform as Friendica', ['platform' => $platform, 'url' => $contact['url']]); $platform = 'friendica'; } } @@ -1313,7 +1312,7 @@ class Diaspora } if ($platform != 'diaspora') { - Logger::info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]); + DI::logger()->info('Unknown platform', ['platform' => $platform, 'url' => $contact['url']]); return ''; } @@ -1340,7 +1339,7 @@ class Diaspora $old_author = WebFingerUri::fromString(XML::unescape($data->author)); $new_author = WebFingerUri::fromString(XML::unescape($data->profile->author)); } catch (\Throwable $e) { - Logger::notice('Cannot find handles for sender and user', ['data' => $data]); + DI::logger()->notice('Cannot find handles for sender and user', ['data' => $data]); return false; } @@ -1348,17 +1347,17 @@ class Diaspora $contact = self::contactByHandle($importer['uid'], $old_author); if (!$contact) { - Logger::notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']); + DI::logger()->notice('Cannot find contact for sender: ' . $old_author . ' and user ' . $importer['uid']); return false; } - Logger::info('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']); + DI::logger()->info('Got migration for ' . $old_author . ', to ' . $new_author . ' with user ' . $importer['uid']); // Check signature $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author; $key = self::key($old_author); if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) { - Logger::notice('No valid signature for migration.'); + DI::logger()->notice('No valid signature for migration.'); return false; } @@ -1368,7 +1367,7 @@ class Diaspora // change the technical stuff in contact $data = Probe::uri($new_author); if ($data['network'] == Protocol::PHANTOM) { - Logger::notice("Account for " . $new_author . " couldn't be probed."); + DI::logger()->notice("Account for " . $new_author . " couldn't be probed."); return false; } @@ -1386,7 +1385,7 @@ class Diaspora Contact::update($fields, ['addr' => $old_author->getAddr()]); - Logger::info('Contacts are updated.'); + DI::logger()->info('Contacts are updated.'); return true; } @@ -1409,7 +1408,7 @@ class Diaspora } DBA::close($contacts); - Logger::info('Removed contacts for ' . $author_handle); + DI::logger()->info('Removed contacts for ' . $author_handle); return true; } @@ -1528,7 +1527,7 @@ class Diaspora try { $author_url = (string)DI::dsprContact()->getByAddr($author)->url; } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) { - Logger::notice('Unable to find author details', ['author' => $author->getAddr()]); + DI::logger()->notice('Unable to find author details', ['author' => $author->getAddr()]); return false; } @@ -1592,7 +1591,7 @@ class Diaspora } if (DI::contentItem()->isTooOld($datarray['created'], $datarray['uid'])) { - Logger::info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); + DI::logger()->info('Comment is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); return false; } @@ -1603,7 +1602,7 @@ class Diaspora } if ($message_id) { - Logger::info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id); + DI::logger()->info('Stored comment ' . $datarray['guid'] . ' with message id ' . $message_id); if ($datarray['uid'] == 0) { Item::distribute($message_id, json_encode($data)); } @@ -1654,7 +1653,7 @@ class Diaspora $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at)); if ($msg_conversation_guid != $guid) { - Logger::notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]); + DI::logger()->notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]); return false; } @@ -1697,7 +1696,7 @@ class Diaspora $messages = $data->message; if (!count($messages)) { - Logger::notice('Empty conversation'); + DI::logger()->notice('Empty conversation'); return false; } @@ -1727,7 +1726,7 @@ class Diaspora } } if (!$conversation) { - Logger::warning('Unable to create conversation.'); + DI::logger()->warning('Unable to create conversation.'); return false; } @@ -1786,7 +1785,7 @@ class Diaspora try { $author_url = (string)DI::dsprContact()->getByAddr($author)->url; } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) { - Logger::notice('Unable to find author details', ['author' => $author->getAddr()]); + DI::logger()->notice('Unable to find author details', ['author' => $author->getAddr()]); return false; } @@ -1850,7 +1849,7 @@ class Diaspora } if (DI::contentItem()->isTooOld($datarray['created'], $datarray['uid'])) { - Logger::info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); + DI::logger()->info('Like is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); return false; } @@ -1861,7 +1860,7 @@ class Diaspora } if ($message_id) { - Logger::info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id); + DI::logger()->info('Stored like ' . $datarray['guid'] . ' with message id ' . $message_id); if ($datarray['uid'] == 0) { Item::distribute($message_id, json_encode($data)); } @@ -1899,14 +1898,14 @@ class Diaspora $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid]; $conversation = DBA::selectFirst('conv', [], $condition); if (!DBA::isResult($conversation)) { - Logger::notice('Conversation not available.'); + DI::logger()->notice('Conversation not available.'); return false; } try { $author = DI::dsprContact()->getByAddr($author_uri); } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) { - Logger::notice('Unable to find author details', ['author' => $author_uri->getAddr()]); + DI::logger()->notice('Unable to find author details', ['author' => $author_uri->getAddr()]); return false; } @@ -1967,18 +1966,18 @@ class Diaspora } if (!$toplevel_parent_item['origin']) { - Logger::info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]); + DI::logger()->info('Not our origin. Participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]); } if (!in_array($toplevel_parent_item['private'], [Item::PUBLIC, Item::UNLISTED])) { - Logger::info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]); + DI::logger()->info('Item is not public, participation is ignored', ['parent_guid' => $parent_guid, 'guid' => $guid, 'author' => $author]); return false; } try { $author_url = (string)DI::dsprContact()->getByAddr($author)->url; } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) { - Logger::notice('unable to find author details', ['author' => $author->getAddr()]); + DI::logger()->notice('unable to find author details', ['author' => $author->getAddr()]); return false; } @@ -2013,13 +2012,13 @@ class Diaspora $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow(); if (DI::contentItem()->isTooOld($datarray['created'], $datarray['uid'])) { - Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); + DI::logger()->info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); return false; } $message_id = Item::insert($datarray); - Logger::info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]); + DI::logger()->info('Participation stored', ['id' => $message_id, 'guid' => $guid, 'parent_guid' => $parent_guid, 'author' => $author]); // Send all existing comments and likes to the requesting server $comments = Post::select( @@ -2028,21 +2027,21 @@ class Diaspora ); while ($comment = Post::fetch($comments)) { if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) { - Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]); + DI::logger()->info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]); continue; } if ($comment['author-network'] == Protocol::ACTIVITYPUB) { - Logger::info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]); + DI::logger()->info('Comments from ActivityPub authors are not relayed', ['item' => $comment['id']]); continue; } if ($comment['parent-author-network'] == Protocol::ACTIVITYPUB) { - Logger::info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]); + DI::logger()->info('Comments to comments from ActivityPub authors are not relayed', ['item' => $comment['id']]); continue; } - Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]); + DI::logger()->info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]); if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) { Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1); } @@ -2160,7 +2159,7 @@ class Diaspora Contact::update($fields, ['id' => $contact['id']]); - Logger::info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']); + DI::logger()->info('Profile of contact ' . $contact['id'] . ' stored for user ' . $importer['uid']); return true; } @@ -2223,7 +2222,7 @@ class Diaspora // That makes us friends. if ($contact) { if ($following) { - Logger::info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.'); + DI::logger()->info('Author ' . $author . ' (Contact ' . $contact['id'] . ') wants to follow us.'); self::receiveRequestMakeFriend($importer, $contact); // refetch the contact array @@ -2234,36 +2233,36 @@ class Diaspora if (in_array($contact['rel'], [Contact::FRIEND])) { $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]); if (DBA::isResult($user)) { - Logger::info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']); + DI::logger()->info('Sending share message to author ' . $author . ' - Contact: ' . $contact['id'] . ' - User: ' . $importer['uid']); self::sendShare($user, $contact); } } return true; } else { - Logger::info("Author " . $author . " doesn't want to follow us anymore."); + DI::logger()->info("Author " . $author . " doesn't want to follow us anymore."); Contact::removeFollower($contact); return true; } } if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) { - Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored."); + DI::logger()->info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored."); return false; } elseif (!$following && !$sharing) { - Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored."); + DI::logger()->info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored."); return false; } elseif (!$following && $sharing) { - Logger::info("Author " . $author . " wants to share with us."); + DI::logger()->info("Author " . $author . " wants to share with us."); } elseif ($following && $sharing) { - Logger::info("Author " . $author . " wants to have a bidirectional connection."); + DI::logger()->info("Author " . $author . " wants to have a bidirectional connection."); } elseif ($following && !$sharing) { - Logger::info("Author " . $author . " wants to listen to us."); + DI::logger()->info("Author " . $author . " wants to listen to us."); } try { $author_url = (string)DI::dsprContact()->getByAddr($author)->url; } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) { - Logger::notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]); + DI::logger()->notice('Cannot resolve diaspora handle for recipient', ['author' => $author->getAddr(), 'recipient' => $recipient]); return false; } @@ -2283,7 +2282,7 @@ class Diaspora if ($result === true) { $contact_record = self::contactByHandle($importer['uid'], $author); if (!$contact_record) { - Logger::info('unable to locate newly created contact record.'); + DI::logger()->info('unable to locate newly created contact record.'); return false; } @@ -2383,7 +2382,7 @@ class Diaspora self::fetchGuid($datarray); if (DI::contentItem()->isTooOld($datarray['created'], $datarray['uid'])) { - Logger::info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); + DI::logger()->info('Reshare is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); return false; } @@ -2392,7 +2391,7 @@ class Diaspora self::sendParticipation($contact, $datarray); if ($message_id) { - Logger::info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id); + DI::logger()->info('Stored reshare ' . $datarray['guid'] . ' with message id ' . $message_id); if ($datarray['uid'] == 0) { Item::distribute($message_id); } @@ -2407,14 +2406,14 @@ class Diaspora $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]); if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) { - Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]); + DI::logger()->debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]); $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]); } elseif (DBA::isResult($shared_item)) { - Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]); + DI::logger()->debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]); } if (!DBA::isResult($shared_item)) { - Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]); + DI::logger()->notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]); return 0; } @@ -2440,7 +2439,7 @@ class Diaspora try { $author = DI::dsprContact()->getByAddr($author_uri); } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) { - Logger::notice('Unable to find details for author', ['author' => $author_uri->getAddr()]); + DI::logger()->notice('Unable to find details for author', ['author' => $author_uri->getAddr()]); return false; } @@ -2458,13 +2457,13 @@ class Diaspora $r = Post::select($fields, $condition); if (!DBA::isResult($r)) { - Logger::notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.'); + DI::logger()->notice('Target guid ' . $target_guid . ' was not found on this system for user ' . $importer['uid'] . '.'); return false; } while ($item = Post::fetch($r)) { if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) { - Logger::info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted."); + DI::logger()->info("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted."); continue; } @@ -2473,13 +2472,13 @@ class Diaspora // Only delete it if the parent author really fits if (!Strings::compareLink($parent['author-link'], $contact_url) && !Strings::compareLink($item['author-link'], $contact_url)) { - Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url); + DI::logger()->info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact_url); continue; } Item::markForDeletion(['id' => $item['id']]); - Logger::info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']); + DI::logger()->info('Deleted target ' . $target_guid . ' (' . $item['id'] . ') from user ' . $item['uid'] . ' parent: ' . $item['parent']); } DBA::close($r); @@ -2502,7 +2501,7 @@ class Diaspora $contact = self::contactByHandle($importer['uid'], $sender); if (!$contact && (in_array($target_type, ['Contact', 'Person']))) { - Logger::notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']); + DI::logger()->notice('Cannot find contact for sender: ' . $sender . ' and user ' . $importer['uid']); return false; } @@ -2510,7 +2509,7 @@ class Diaspora $contact = []; } - Logger::info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']); + DI::logger()->info('Got retraction for ' . $target_type . ', sender ' . $sender . ' and user ' . $importer['uid']); switch ($target_type) { case 'Comment': @@ -2526,7 +2525,7 @@ class Diaspora break; default: - Logger::notice('Unknown target type ' . $target_type); + DI::logger()->notice('Unknown target type ' . $target_type); return false; } return true; @@ -2546,18 +2545,18 @@ class Diaspora { $contact = Contact::getByURL($author); if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) { - Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]); + DI::logger()->debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]); return true; } if ($direction == self::FORCED_FETCH) { - Logger::debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]); + DI::logger()->debug('Post is a forced fetch - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]); return true; } $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name'); if (Relay::isSolicitedPost($tags, $body, $contact['id'], $item['uri'], Protocol::DIASPORA)) { - Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]); + DI::logger()->debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]); return true; } else { return false; @@ -2575,7 +2574,7 @@ class Diaspora private static function storePhotoAsMedia(int $uriid, $photo) { // @TODO Need to find object type, roland@f.haeder.net - Logger::debug('photo=' . get_class($photo)); + DI::logger()->debug('photo=' . get_class($photo)); $data = [ 'uri-id' => $uriid, 'type' => Post\Media::IMAGE, @@ -2728,7 +2727,7 @@ class Diaspora self::fetchGuid($datarray); if (DI::contentItem()->isTooOld($datarray['created'], $datarray['uid'])) { - Logger::info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); + DI::logger()->info('Status is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); return false; } @@ -2737,7 +2736,7 @@ class Diaspora self::sendParticipation($contact, $datarray); if ($message_id) { - Logger::info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id); + DI::logger()->info('Stored item ' . $datarray['guid'] . ' with message id ' . $message_id); if ($datarray['uid'] == 0) { Item::distribute($message_id); } @@ -2791,11 +2790,11 @@ class Diaspora */ public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string { - Logger::debug('Message: ' . $msg); + DI::logger()->debug('Message: ' . $msg); // without a public key nothing will work if (!$pubkey) { - Logger::notice('pubkey missing: contact id: ' . $contact['id']); + DI::logger()->notice('pubkey missing: contact id: ' . $contact['id']); return false; } @@ -2946,11 +2945,11 @@ class Diaspora } if (!$dest_url) { - Logger::notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch); + DI::logger()->notice('No URL for contact: ' . $contact['id'] . ' batch mode =' . $public_batch); return 0; } - Logger::info('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url); + DI::logger()->info('transmit: ' . $logid . '-' . $guid . ' ' . $dest_url); if (!intval(DI::config()->get('system', 'diaspora_test'))) { $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json'); @@ -2958,12 +2957,12 @@ class Diaspora try { $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type], 0, HttpClientRequest::DIASPORA); } 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 0; } $return_code = $postResult->getReturnCode(); } else { - Logger::notice('test_mode'); + DI::logger()->notice('test_mode'); return 200; } @@ -2974,7 +2973,7 @@ class Diaspora GServer::setReachableById($contact['gsid'], Protocol::DIASPORA); } - Logger::info('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code); + DI::logger()->info('transmit: ' . $logid . '-' . $guid . ' to ' . $dest_url . ' returns: ' . $return_code); return $return_code ? $return_code : -1; } @@ -3030,14 +3029,14 @@ class Diaspora // The "addr" field should always be filled. // If this isn't the case, it will raise a notice some lines later. // And in the log we will see where it came from, and we can handle it there. - Logger::notice('Empty addr', ['contact' => $contact]); + DI::logger()->notice('Empty addr', ['contact' => $contact]); } $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $pubkey ?? '', $public_batch); $return_code = self::transmit($contact, $envelope, $public_batch, $guid); - Logger::info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]); + DI::logger()->info('Transmitted message', ['owner' => $owner['uid'], 'target' => $contact['addr'], 'type' => $type, 'guid' => $guid, 'result' => $return_code]); return $return_code; } @@ -3086,7 +3085,7 @@ class Diaspora 'parent_guid' => $item['guid'] ]; - Logger::info('Send participation for ' . $item['guid'] . ' by ' . $author_handle); + DI::logger()->info('Send participation for ' . $item['guid'] . ' by ' . $author_handle); // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR); @@ -3119,7 +3118,7 @@ class Diaspora 'signature' => $signature ]; - Logger::info('Send account migration', ['msg' => $message]); + DI::logger()->info('Send account migration', ['msg' => $message]); return self::buildAndTransmit($owner, $contact, 'account_migration', $message); } @@ -3165,7 +3164,7 @@ class Diaspora 'sharing' => 'true' ]; - Logger::info('Send share', ['msg' => $message]); + DI::logger()->info('Send share', ['msg' => $message]); return self::buildAndTransmit($owner, $contact, 'contact', $message); } @@ -3188,7 +3187,7 @@ class Diaspora 'sharing' => 'false' ]; - Logger::info('Send unshare', ['msg' => $message]); + DI::logger()->info('Send unshare', ['msg' => $message]); return self::buildAndTransmit($owner, $contact, 'contact', $message); } @@ -3559,7 +3558,7 @@ class Diaspora $attend_answer = 'tentative'; break; default: - Logger::warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']); + DI::logger()->warning('Unknown verb ' . $item['verb'] . ' in item ' . $item['guid']); return false; } @@ -3592,7 +3591,7 @@ class Diaspora $toplevel_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['id' => $item['parent'], 'parent' => $item['parent']]); if (!DBA::isResult($toplevel_item)) { - Logger::error('Missing parent conversation item', ['parent' => $item['parent']]); + DI::logger()->error('Missing parent conversation item', ['parent' => $item['parent']]); return false; } @@ -3698,7 +3697,7 @@ class Diaspora $type = 'comment'; } - Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')'); + DI::logger()->info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')'); $msg = json_decode($item['signed_text'] ?? '', true); @@ -3717,12 +3716,12 @@ class Diaspora $message[$field] = $data; } } else { - Logger::info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']); + DI::logger()->info('Signature text for item ' . $item['guid'] . ' (' . $item['id'] . ') could not be extracted: ' . $item['signed_text']); } $message['parent_author_signature'] = self::signature($owner, $message); - Logger::info('Relayed data', ['msg' => $message]); + DI::logger()->info('Relayed data', ['msg' => $message]); return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']); } @@ -3759,7 +3758,7 @@ class Diaspora 'target_type' => $target_type ]; - Logger::info('Got message', ['msg' => $message]); + DI::logger()->info('Got message', ['msg' => $message]); return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']); } @@ -3781,7 +3780,7 @@ class Diaspora $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]); if (!DBA::isResult($cnv)) { - Logger::notice('Conversation not found.'); + DI::logger()->notice('Conversation not found.'); return -1; } @@ -3955,23 +3954,23 @@ class Diaspora public static function sendProfile(int $uid, array $recipients = []) { if (!$uid) { - Logger::warning('Parameter "uid" is empty'); + DI::logger()->warning('Parameter "uid" is empty'); return; } $owner = User::getOwnerDataById($uid); if (empty($owner)) { - Logger::warning('Cannot fetch User record', ['uid' => $uid]); + DI::logger()->warning('Cannot fetch User record', ['uid' => $uid]); return; } if (empty($recipients)) { - Logger::debug('No recipients provided, fetching for user', ['uid' => $uid]); + DI::logger()->debug('No recipients provided, fetching for user', ['uid' => $uid]); $recipients = DBA::selectToArray('contact', [], ['network' => Protocol::DIASPORA, 'uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]); } if (empty($recipients)) { - Logger::warning('Cannot fetch recipients', ['uid' => $uid]); + DI::logger()->warning('Cannot fetch recipients', ['uid' => $uid]); return; } @@ -3980,7 +3979,7 @@ class Diaspora // @todo Split this into single worker jobs foreach ($recipients as $recipient) { if ((empty($recipient['gsid']) || GServer::isReachableById($recipient['gsid'])) && !Contact\User::isBlocked($recipient['id'], $uid)) { - Logger::info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']); + DI::logger()->info('Send updated profile data for user ' . $uid . ' to contact ' . $recipient['id']); self::buildAndTransmit($owner, $recipient, 'profile', $message); } } @@ -3999,12 +3998,12 @@ class Diaspora { $owner = User::getOwnerDataById($uid); if (empty($owner)) { - Logger::info('No owner post, so not storing signature', ['uid' => $uid]); + DI::logger()->info('No owner post, so not storing signature', ['uid' => $uid]); return false; } if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) { - Logger::warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);; + DI::logger()->warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);; return false; } @@ -4034,7 +4033,7 @@ class Diaspora } else { $contact = Contact::getById($item['author-id'], ['url']); if (empty($contact['url'])) { - Logger::warning('Author Contact not found', ['author-id' => $item['author-id']]); + DI::logger()->warning('Author Contact not found', ['author-id' => $item['author-id']]); return false; } $url = $contact['url']; @@ -4042,13 +4041,13 @@ class Diaspora $uid = User::getIdForURL($url); if (empty($uid)) { - Logger::info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']); + DI::logger()->info('No owner post, so not storing signature', ['url' => $contact['url'] ?? 'No contact loaded']); return false; } $owner = User::getOwnerDataById($uid); if (empty($owner)) { - Logger::info('No owner post, so not storing signature'); + DI::logger()->info('No owner post, so not storing signature'); return false; } @@ -4058,7 +4057,7 @@ class Diaspora } if (!self::parentSupportDiaspora($item['thr-parent-id'], $uid)) { - Logger::info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]); + DI::logger()->info('One of the parents does not support Diaspora. A signature will not be created.', ['uri-id' => $item['uri-id'], 'guid' => $item['guid']]); return false; } @@ -4085,17 +4084,17 @@ class Diaspora { $parent_post = Post::selectFirst(['gravity', 'signed_text', 'author-link', 'thr-parent-id', 'protocol'], ['uri-id' => $parent_id, 'uid' => [0, $uid]]); if (empty($parent_post['thr-parent-id'])) { - Logger::warning('Parent post does not exist.', ['parent-id' => $parent_id]); + DI::logger()->warning('Parent post does not exist.', ['parent-id' => $parent_id]); return false; } if (!self::isSupportedByContactUrl($parent_post['author-link'])) { - Logger::info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]); + DI::logger()->info('Parent author is no Diaspora contact.', ['parent-id' => $parent_id]); return false; } if (($parent_post['protocol'] != Conversation::PARCEL_DIASPORA) && ($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) { - Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]); + DI::logger()->info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]); return false; } From d4afcc0b7eb6d17309f652a953012f89003abd1a Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:38:48 +0000 Subject: [PATCH 30/91] Replace Logger with DI::logger() in Email Protocol class --- src/Protocol/Email.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Protocol/Email.php b/src/Protocol/Email.php index e44c9a7085..a2d87eeaa9 100644 --- a/src/Protocol/Email.php +++ b/src/Protocol/Email.php @@ -8,10 +8,10 @@ namespace Friendica\Protocol; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; use Friendica\Core\Protocol; +use Friendica\DI; use Friendica\Model\Item; use Friendica\Util\Strings; use IMAP\Connection; @@ -38,12 +38,12 @@ class Email $errors = imap_errors(); if (!empty($errors)) { - Logger::notice('IMAP Errors occurred', ['errors' => $errors]); + DI::logger()->notice('IMAP Errors occurred', ['errors' => $errors]); } $alerts = imap_alerts(); if (!empty($alerts)) { - Logger::notice('IMAP Alerts occurred: ', ['alerts' => $alerts]); + DI::logger()->notice('IMAP Alerts occurred: ', ['alerts' => $alerts]); } if (empty($errors) && empty($alerts)) { @@ -67,7 +67,7 @@ class Email if (!$search1) { $search1 = []; } else { - Logger::debug("Found mails from ".$email_addr); + DI::logger()->debug("Found mails from ".$email_addr); Item::incrementInbound(Protocol::MAIL); } @@ -75,7 +75,7 @@ class Email if (!$search2) { $search2 = []; } else { - Logger::debug("Found mails to ".$email_addr); + DI::logger()->debug("Found mails to ".$email_addr); Item::incrementInbound(Protocol::MAIL); } @@ -83,7 +83,7 @@ class Email if (!$search3) { $search3 = []; } else { - Logger::debug("Found mails cc ".$email_addr); + DI::logger()->debug("Found mails cc ".$email_addr); Item::incrementInbound(Protocol::MAIL); } @@ -131,7 +131,7 @@ class Email $struc = (($mbox && $uid) ? @imap_fetchstructure($mbox, $uid, FT_UID) : null); if (!$struc) { - Logger::notice("IMAP structure couldn't be fetched", ['uid' => $uid]); + DI::logger()->notice("IMAP structure couldn't be fetched", ['uid' => $uid]); return $ret; } @@ -395,7 +395,7 @@ class Email //$message = '' . $html . ''; //$message = html2plain($html); - Logger::notice('notifier: email delivery to ' . $addr); + DI::logger()->notice('notifier: email delivery to ' . $addr); $success = mail($addr, $subject, $body, $headers); if ($success) { Item::incrementOutbound(Protocol::MAIL); From bf8df261ad7c25b5ff066d27655532838e891a44 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:39:20 +0000 Subject: [PATCH 31/91] Replace Logger with DI::logger() in Feed Protocol class --- src/Protocol/Feed.php | 45 +++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index da635884d9..4fea37e4e8 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -15,7 +15,6 @@ use Friendica\Contact\LocalRelationship\Entity\LocalRelationship; use Friendica\Content\PageInfo; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Worker; use Friendica\Database\DBA; @@ -56,15 +55,15 @@ class Feed $dryRun = empty($importer) && empty($contact); if ($dryRun) { - Logger::info("Test Atom/RSS feed"); + DI::logger()->info("Test Atom/RSS feed"); } else { - Logger::info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']); + DI::logger()->info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']); } $xml = trim($xml); if (empty($xml)) { - Logger::info('XML is empty.'); + DI::logger()->info('XML is empty.'); return []; } @@ -274,7 +273,7 @@ class Feed $datarray['direction'] = Conversation::PULL; if (!is_object($entries)) { - Logger::info("There are no entries in this feed."); + DI::logger()->info("There are no entries in this feed."); return []; } @@ -383,7 +382,7 @@ class Feed try { $item['plink'] = DI::httpClient()->finalUrl($item['plink']); } catch (TransferException $exception) { - Logger::notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]); + DI::logger()->notice('Item URL couldn\'t get expanded', ['url' => $item['plink'], 'exception' => $exception]); } } @@ -442,7 +441,7 @@ class Feed if (DBA::isResult($previous)) { // Use the creation date when the post had been stored. It can happen this date changes in the feed. $creation_dates[] = $previous['created']; - Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']); + DI::logger()->info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']); continue; } $creation_dates[] = DateTimeFormat::utc($item['created']); @@ -550,10 +549,10 @@ class Feed $items[] = $item; break; } elseif (!Item::isValid($item)) { - Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]); + DI::logger()->info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]); continue; } elseif (DI::contentItem()->isTooOld($item['created'], $item['uid'])) { - Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]); + DI::logger()->info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]); continue; } @@ -673,7 +672,7 @@ class Feed $item['post-type'] = Item::PT_NOTE; } - Logger::info('Stored feed', ['item' => $item]); + DI::logger()->info('Stored feed', ['item' => $item]); $notify = Item::isRemoteSelf($contact, $item); $item['wall'] = (bool)$notify; @@ -702,7 +701,7 @@ class Feed ]; } } else { - Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]); + DI::logger()->info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item['uri']]); } } @@ -713,7 +712,7 @@ class Feed // Posts shouldn't be delayed more than a day $interval = min(1440, self::getPollInterval($contact)); $delay = max(round(($interval * 60) / $total), 60 * $min_posting); - Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]); + DI::logger()->info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]); } else { $delay = 0; } @@ -790,7 +789,7 @@ class Feed private static function adjustPollFrequency(array $contact, array $creation_dates) { if ($contact['network'] != Protocol::FEED) { - Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]); + DI::logger()->info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]); return; } @@ -831,22 +830,22 @@ class Feed } if (count($creation_dates) == 1) { - Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); + DI::logger()->info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); $priority = 8; // Poll once a day } if (empty($priority) && (((time() / 86400) - $newest) > 730)) { - Logger::info('Feed had not posted for two years, switching to monthly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); + DI::logger()->info('Feed had not posted for two years, switching to monthly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); $priority = 10; // Poll every month } if (empty($priority) && (((time() / 86400) - $newest) > 365)) { - Logger::info('Feed had not posted for a year, switching to weekly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); + DI::logger()->info('Feed had not posted for a year, switching to weekly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); $priority = 9; // Poll every week } if (empty($priority) && empty($frequency)) { - Logger::info('Feed had not posted for at least a week, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); + DI::logger()->info('Feed had not posted for at least a week, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); $priority = 8; // Poll once a day } @@ -883,15 +882,15 @@ class Feed } else { $priority = 7; // Poll twice a day } - Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); + DI::logger()->info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); } } else { - Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); + DI::logger()->info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); $priority = 8; // Poll once a day } if ($contact['rating'] != $priority) { - Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); + DI::logger()->notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]); Contact::update(['rating' => $priority], ['id' => $contact['id']]); } } @@ -1066,7 +1065,7 @@ class Feed $feeddata = trim($doc->saveXML()); - Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]); + DI::logger()->info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner['nickname'], 'filter' => $filter, 'created' => $previous_created]); return $feeddata; } @@ -1153,7 +1152,7 @@ class Feed private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement { if (($item['gravity'] != Item::GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) { - Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]); + DI::logger()->info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]); } $entry = self::entryHeader($doc, $owner, $item, false); @@ -1307,7 +1306,7 @@ class Feed if (!HTML::isHTML($body)) { $html = BBCode::convert($body, false, BBCode::EXTERNAL); if ($body != $html) { - Logger::debug('Body contained no HTML', ['original' => $body, 'converted' => $html]); + DI::logger()->debug('Body contained no HTML', ['original' => $body, 'converted' => $html]); $body = $html; } } From ab1e0638fb27d0bb15fe5805d0ea855839e34706 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:39:50 +0000 Subject: [PATCH 32/91] Replace Logger with DI::logger() in Relay Protocol class --- src/Protocol/Relay.php | 47 +++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 24 deletions(-) diff --git a/src/Protocol/Relay.php b/src/Protocol/Relay.php index ec0b0f25f5..994772d191 100644 --- a/src/Protocol/Relay.php +++ b/src/Protocol/Relay.php @@ -11,7 +11,6 @@ use Exception; use Friendica\Content\Smilies; use Friendica\Content\Text\BBCode; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -54,24 +53,24 @@ class Relay $config = DI::config(); if (Contact::hasFollowers($authorid)) { - Logger::info('Author has got followers on this server - accepted', ['network' => $network, 'url' => $url, 'author' => $authorid, 'tags' => $tags]); + DI::logger()->info('Author has got followers on this server - accepted', ['network' => $network, 'url' => $url, 'author' => $authorid, 'tags' => $tags]); return true; } $scope = $config->get('system', 'relay_scope'); if ($scope == self::SCOPE_NONE) { - Logger::info('Server does not accept relay posts - rejected', ['network' => $network, 'url' => $url]); + DI::logger()->info('Server does not accept relay posts - rejected', ['network' => $network, 'url' => $url]); return false; } if (Contact::isBlocked($authorid)) { - Logger::info('Author is blocked - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]); + DI::logger()->info('Author is blocked - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]); return false; } if (Contact::isHidden($authorid)) { - Logger::info('Author is hidden - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]); + DI::logger()->info('Author is hidden - rejected', ['author' => $authorid, 'network' => $network, 'url' => $url]); return false; } @@ -101,7 +100,7 @@ class Relay $content_cleaned = mb_strtolower(BBCode::toPlaintext($cleaned, false)); if (strlen($content_cleaned) < strlen($content) / 2) { - Logger::info('Possible hashtag spam detected - rejected', ['hashtags' => $tags, 'network' => $network, 'url' => $url, 'causer' => $causer, 'content' => $content]); + DI::logger()->info('Possible hashtag spam detected - rejected', ['hashtags' => $tags, 'network' => $network, 'url' => $url, 'causer' => $causer, 'content' => $content]); return false; } } @@ -109,35 +108,35 @@ class Relay foreach ($tags as $tag) { $tag = mb_strtolower($tag); if (in_array($tag, $denyTags)) { - Logger::info('Unwanted hashtag found - rejected', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]); + DI::logger()->info('Unwanted hashtag found - rejected', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]); return false; } if (in_array($tag, $tagList)) { - Logger::info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]); + DI::logger()->info('Subscribed hashtag found - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]); return true; } // We check with "strpos" for performance issues. Only when this is true, the regular expression check is used // RegExp is taken from here: https://medium.com/@shiba1014/regex-word-boundaries-with-unicode-207794f6e7ed if ((strpos($content, $tag) !== false) && preg_match('/(?<=[\s,.:;"\']|^)' . preg_quote($tag, '/') . '(?=[\s,.:;"\']|$)/', $content)) { - Logger::info('Subscribed hashtag found in content - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]); + DI::logger()->info('Subscribed hashtag found in content - accepted', ['hashtag' => $tag, 'network' => $network, 'url' => $url, 'causer' => $causer]); return true; } } } if (!self::isWantedLanguage($body, 0, $authorid, $languages)) { - Logger::info('Unwanted or Undetected language found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]); + DI::logger()->info('Unwanted or Undetected language found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]); return false; } if ($scope == self::SCOPE_ALL) { - Logger::info('Server accept all posts - accepted', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]); + DI::logger()->info('Server accept all posts - accepted', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]); return true; } - Logger::info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]); + DI::logger()->info('No matching hashtags found - rejected', ['network' => $network, 'url' => $url, 'causer' => $causer, 'tags' => $tags]); return false; } @@ -181,7 +180,7 @@ class Relay } if (empty($body) || Smilies::isEmojiPost($body)) { - Logger::debug('Empty body or only emojis', ['body' => $body]); + DI::logger()->debug('Empty body or only emojis', ['body' => $body]); return true; } @@ -189,17 +188,17 @@ class Relay foreach ($detected as $language) { if (in_array($language, $user_languages)) { - Logger::debug('Wanted language found in detected languages', ['language' => $language, 'detected' => $detected, 'userlang' => $user_languages, 'body' => $body]); + DI::logger()->debug('Wanted language found in detected languages', ['language' => $language, 'detected' => $detected, 'userlang' => $user_languages, 'body' => $body]); return true; } } foreach ($languages as $language) { if (in_array($language, $user_languages)) { - Logger::debug('Wanted language found in defined languages', ['language' => $language, 'languages' => $languages, 'detected' => $detected, 'userlang' => $user_languages, 'body' => $body]); + DI::logger()->debug('Wanted language found in defined languages', ['language' => $language, 'languages' => $languages, 'detected' => $detected, 'userlang' => $user_languages, 'body' => $body]); return true; } } - Logger::debug('No wanted language found', ['languages' => $languages, 'detected' => $detected, 'userlang' => $user_languages, 'body' => $body]); + DI::logger()->debug('No wanted language found', ['languages' => $languages, 'detected' => $detected, 'userlang' => $user_languages, 'body' => $body]); return false; } @@ -216,9 +215,9 @@ class Relay if (in_array($gserver['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) { $system = APContact::getByURL($gserver['url'] . '/friendica'); if (!empty($system['sharedinbox'])) { - Logger::info('Successfully probed for relay contact', ['server' => $gserver['url']]); + DI::logger()->info('Successfully probed for relay contact', ['server' => $gserver['url']]); $id = Contact::updateFromProbeByURL($system['url']); - Logger::info('Updated relay contact', ['server' => $gserver['url'], 'id' => $id]); + DI::logger()->info('Updated relay contact', ['server' => $gserver['url'], 'id' => $id]); return; } } @@ -231,10 +230,10 @@ class Relay if (DBA::isResult($old)) { $fields['gsid'] = $gserver['id']; $fields['contact-type'] = Contact::TYPE_RELAY; - Logger::info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]); + DI::logger()->info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]); } } elseif (empty($fields) && $old['unsearchable']) { - Logger::info('No content to update, quitting', ['server' => $gserver['url']]); + DI::logger()->info('No content to update, quitting', ['server' => $gserver['url']]); return; } @@ -242,7 +241,7 @@ class Relay $fields['updated'] = DateTimeFormat::utcNow(); $fields['unsearchable'] = true; - Logger::info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]); + DI::logger()->info('Update relay contact', ['server' => $gserver['url'], 'id' => $old['id'], 'fields' => $fields]); Contact::update($fields, ['id' => $old['id']], $old); } else { $default = ['created' => DateTimeFormat::utcNow(), @@ -258,7 +257,7 @@ class Relay $fields = array_merge($default, $fields); - Logger::info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]); + DI::logger()->info('Create relay contact', ['server' => $gserver['url'], 'fields' => $fields]); Contact::insert($fields); } } @@ -291,7 +290,7 @@ class Relay } if (!empty($relay_contact)) { - Logger::info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]); + DI::logger()->info('Relay contact will be marked for archival', ['id' => $relay_contact['id'], 'url' => $relay_contact['url']]); Contact::markForArchival($relay_contact); } } @@ -421,7 +420,7 @@ class Relay { foreach (self::getList() as $server) { $success = ActivityPub\Transmitter::sendRelayFollow($server['url']); - Logger::debug('Resubscribed', ['profile' => $server['url'], 'success' => $success]); + DI::logger()->debug('Resubscribed', ['profile' => $server['url'], 'success' => $success]); } } } From 6de75e4b9b3696a769718f6106b181381f5e1e6f Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:40:44 +0000 Subject: [PATCH 33/91] Replace Logger with DI::logger() in ZOT Protocol class --- src/Protocol/ZOT.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Protocol/ZOT.php b/src/Protocol/ZOT.php index 24704ec237..b5604bcc84 100644 --- a/src/Protocol/ZOT.php +++ b/src/Protocol/ZOT.php @@ -9,7 +9,6 @@ namespace Friendica\Protocol; use Friendica\App; use Friendica\Core\Addon; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Module; use Friendica\Module\Register; @@ -30,7 +29,7 @@ class ZOT public static function isRequest(): bool { if (stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/x-zot+json')) { - Logger::debug('Is ZOT request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); + DI::logger()->debug('Is ZOT request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); return true; } From bc53c9b2082acacace58cc79c535e236610cc3b5 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:45:38 +0000 Subject: [PATCH 34/91] Replace Logger with DI::logger() in ActivityPub Protocol classes --- src/Protocol/ActivityPub.php | 17 +- src/Protocol/ActivityPub/ClientToServer.php | 17 +- src/Protocol/ActivityPub/Delivery.php | 17 +- src/Protocol/ActivityPub/Fetch.php | 10 +- src/Protocol/ActivityPub/Processor.php | 275 ++++++++++---------- src/Protocol/ActivityPub/Queue.php | 21 +- src/Protocol/ActivityPub/Receiver.php | 141 +++++----- src/Protocol/ActivityPub/Transmitter.php | 61 +++-- 8 files changed, 276 insertions(+), 283 deletions(-) diff --git a/src/Protocol/ActivityPub.php b/src/Protocol/ActivityPub.php index 55ba315d83..9bef5479cd 100644 --- a/src/Protocol/ActivityPub.php +++ b/src/Protocol/ActivityPub.php @@ -7,7 +7,6 @@ namespace Friendica\Protocol; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\DI; @@ -87,12 +86,12 @@ class ActivityPub { header('Vary: Accept', false); if (stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') || stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json')) { - Logger::debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); + DI::logger()->debug('Is AP request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); return true; } if (stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json')) { - Logger::debug('Is JSON request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); + DI::logger()->debug('Is JSON request', ['accept' => $_SERVER['HTTP_ACCEPT'], 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '']); return true; } @@ -232,7 +231,7 @@ class ActivityPub $start_timestamp = $start_timestamp ?: time(); if ((time() - $start_timestamp) > 60) { - Logger::info('Fetch time limit reached', ['url' => $url, 'uid' => $uid]); + DI::logger()->info('Fetch time limit reached', ['url' => $url, 'uid' => $uid]); return []; } @@ -284,24 +283,24 @@ class ActivityPub $signer = HTTPSignature::getSigner('', $_SERVER); if (!$signer) { - Logger::debug('No signer or invalid signature', ['uid' => $uid, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'called_by' => $called_by]); + DI::logger()->debug('No signer or invalid signature', ['uid' => $uid, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'called_by' => $called_by]); return false; } $apcontact = APContact::getByURL($signer); if (empty($apcontact)) { - Logger::info('APContact not found', ['uid' => $uid, 'handle' => $signer, 'called_by' => $called_by]); + DI::logger()->info('APContact not found', ['uid' => $uid, 'handle' => $signer, 'called_by' => $called_by]); return false; } if (empty($apcontact['gsid']) || empty($apcontact['baseurl'])) { - Logger::debug('No server found', ['uid' => $uid, 'signer' => $signer, 'called_by' => $called_by]); + DI::logger()->debug('No server found', ['uid' => $uid, 'signer' => $signer, 'called_by' => $called_by]); return false; } $contact = Contact::getByURL($signer, false, ['id', 'baseurl', 'gsid']); if (!empty($contact) && Contact\User::isBlocked($contact['id'], $uid)) { - Logger::info('Requesting contact is blocked', ['uid' => $uid, 'id' => $contact['id'], 'signer' => $signer, 'baseurl' => $contact['baseurl'], 'called_by' => $called_by]); + DI::logger()->info('Requesting contact is blocked', ['uid' => $uid, 'id' => $contact['id'], 'signer' => $signer, 'baseurl' => $contact['baseurl'], 'called_by' => $called_by]); return false; } @@ -318,7 +317,7 @@ class ActivityPub return false; } - Logger::debug('Server is an accepted requester', ['uid' => $uid, 'id' => $apcontact['gsid'], 'url' => $apcontact['baseurl'], 'signer' => $signer, 'called_by' => $called_by]); + DI::logger()->debug('Server is an accepted requester', ['uid' => $uid, 'id' => $apcontact['gsid'], 'url' => $apcontact['baseurl'], 'signer' => $signer, 'called_by' => $called_by]); return true; } diff --git a/src/Protocol/ActivityPub/ClientToServer.php b/src/Protocol/ActivityPub/ClientToServer.php index 989d12bea0..c95732d3b9 100644 --- a/src/Protocol/ActivityPub/ClientToServer.php +++ b/src/Protocol/ActivityPub/ClientToServer.php @@ -8,7 +8,6 @@ namespace Friendica\Protocol\ActivityPub; use Friendica\Content\Text\Markdown; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\DBA; use Friendica\DI; @@ -39,24 +38,24 @@ class ClientToServer { $ldactivity = JsonLD::compact($activity); if (empty($ldactivity)) { - Logger::notice('Invalid activity', ['activity' => $activity, 'uid' => $uid]); + DI::logger()->notice('Invalid activity', ['activity' => $activity, 'uid' => $uid]); return []; } $type = JsonLD::fetchElement($ldactivity, '@type'); if (!$type) { - Logger::notice('Empty type', ['activity' => $ldactivity, 'uid' => $uid]); + DI::logger()->notice('Empty type', ['activity' => $ldactivity, 'uid' => $uid]); return []; } $object_id = JsonLD::fetchElement($ldactivity, 'as:object', '@id') ?? ''; $object_type = Receiver::fetchObjectType($ldactivity, $object_id, $uid); if (!$object_type && !$object_id) { - Logger::notice('Empty object type or id', ['activity' => $ldactivity, 'uid' => $uid]); + DI::logger()->notice('Empty object type or id', ['activity' => $ldactivity, 'uid' => $uid]); return []; } - Logger::debug('Processing activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'activity' => $ldactivity]); + DI::logger()->debug('Processing activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'activity' => $ldactivity]); return self::routeActivities($type, $object_type, $object_id, $uid, $application, $ldactivity); } @@ -105,7 +104,7 @@ class ClientToServer { $object_data = self::processObject($ldactivity['as:object']); $item = ClientToServer::processContent($object_data, $application, $uid); - Logger::debug('Got data', ['item' => $item, 'object' => $object_data]); + DI::logger()->debug('Got data', ['item' => $item, 'object' => $object_data]); $id = Item::insert($item, true); if (!empty($id)) { @@ -131,18 +130,18 @@ class ClientToServer $id = Item::fetchByLink($object_id, $uid, ActivityPub\Receiver::COMPLETION_ASYNC); $original_post = Post::selectFirst(['uri-id'], ['uid' => $uid, 'origin' => true, 'id' => $id]); if (empty($original_post)) { - Logger::debug('Item not found or does not belong to the user', ['id' => $id, 'uid' => $uid, 'object_id' => $object_id, 'activity' => $ldactivity]); + DI::logger()->debug('Item not found or does not belong to the user', ['id' => $id, 'uid' => $uid, 'object_id' => $object_id, 'activity' => $ldactivity]); return []; } $object_data = self::processObject($ldactivity['as:object']); $item = ClientToServer::processContent($object_data, $application, $uid); if (empty($item['title']) && empty($item['body'])) { - Logger::debug('Empty body and title', ['id' => $id, 'uid' => $uid, 'object_id' => $object_id, 'activity' => $ldactivity]); + DI::logger()->debug('Empty body and title', ['id' => $id, 'uid' => $uid, 'object_id' => $object_id, 'activity' => $ldactivity]); return []; } $post = ['title' => $item['title'], 'body' => $item['body']]; - Logger::debug('Got data', ['id' => $id, 'uid' => $uid, 'item' => $post]); + DI::logger()->debug('Got data', ['id' => $id, 'uid' => $uid, 'item' => $post]); Item::update($post, ['id' => $id]); Item::updateDisplayCache($original_post['uri-id']); diff --git a/src/Protocol/ActivityPub/Delivery.php b/src/Protocol/ActivityPub/Delivery.php index 5a1d851b38..865d962d4a 100644 --- a/src/Protocol/ActivityPub/Delivery.php +++ b/src/Protocol/ActivityPub/Delivery.php @@ -7,7 +7,6 @@ namespace Friendica\Protocol\ActivityPub; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -50,7 +49,7 @@ class Delivery if ($result['serverfailure']) { // In a timeout situation we assume that every delivery to that inbox will time out. // So we set the flag and try all deliveries at a later time. - Logger::notice('Inbox delivery has a server failure', ['inbox' => $inbox]); + DI::logger()->notice('Inbox delivery has a server failure', ['inbox' => $inbox]); $serverfail = true; } Worker::coolDown(); @@ -61,7 +60,7 @@ class Delivery } } - Logger::debug('Inbox delivery done', ['inbox' => $inbox, 'posts' => count($posts), 'failed' => count($uri_ids), 'serverfailure' => $serverfail]); + DI::logger()->debug('Inbox delivery done', ['inbox' => $inbox, 'posts' => count($posts), 'failed' => count($uri_ids), 'serverfailure' => $serverfail]); return ['success' => empty($uri_ids), 'uri_ids' => $uri_ids]; } @@ -84,11 +83,11 @@ class Delivery if (empty($item_id) && !empty($uri_id) && !empty($uid)) { $item = Post::selectFirst(['id', 'parent', 'origin', 'gravity', 'verb'], ['uri-id' => $uri_id, 'uid' => [$uid, 0]], ['order' => ['uid' => true]]); if (empty($item['id'])) { - Logger::warning('Item not found, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]); + DI::logger()->warning('Item not found, removing delivery', ['uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]); Post\Delivery::remove($uri_id, $inbox); return ['success' => true, 'serverfailure' => false, 'drop' => false]; } elseif (!DI::config()->get('system', 'redistribute_activities') && !$item['origin'] && ($item['gravity'] == Item::GRAVITY_ACTIVITY)) { - Logger::notice('Activities are not relayed, removing delivery', ['verb' => $item['verb'], 'uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]); + DI::logger()->notice('Activities are not relayed, removing delivery', ['verb' => $item['verb'], 'uri-id' => $uri_id, 'uid' => $uid, 'cmd' => $cmd, 'inbox' => $inbox]); Post\Delivery::remove($uri_id, $inbox); return ['success' => true, 'serverfailure' => false, 'drop' => false]; } else { @@ -122,7 +121,7 @@ class Delivery $success = $response->isSuccess(); $serverfail = $response->isTimeout(); } catch (\Throwable $th) { - Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); + DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); $response = null; $success = false; $serverfail = true; @@ -154,7 +153,7 @@ class Delivery $actor = self:: fetchActorForRelayInbox($inbox); if (!empty($actor)) { $drop = !ActivityPub\Transmitter::sendRelayFollow($actor); - Logger::notice('Resubscribed to relay', ['url' => $actor, 'success' => !$drop]); + DI::logger()->notice('Resubscribed to relay', ['url' => $actor, 'success' => !$drop]); } elseif ($cmd == ProtocolDelivery::DELETION) { // Remote systems not always accept our deletion requests, so we drop them if rejected. // Situation is: In Friendica we allow the thread owner to delete foreign comments to their thread. @@ -164,7 +163,7 @@ class Delivery } - Logger::notice('Delivery failed', ['retcode' => $response->getReturnCode() ?? 0, 'serverfailure' => $serverfail, 'drop' => $drop, 'runtime' => round($runtime, 3), 'uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox]); + DI::logger()->notice('Delivery failed', ['retcode' => $response->getReturnCode() ?? 0, 'serverfailure' => $serverfail, 'drop' => $drop, 'runtime' => round($runtime, 3), 'uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox]); } if ($uri_id) { if ($success) { @@ -180,7 +179,7 @@ class Delivery self::setSuccess($receivers, $success); - Logger::debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]); + DI::logger()->debug('Delivered', ['uri-id' => $uri_id, 'uid' => $uid, 'item_id' => $item_id, 'cmd' => $cmd, 'inbox' => $inbox, 'success' => $success, 'serverfailure' => $serverfail, 'drop' => $drop]); if (($success || $drop) && in_array($cmd, [ProtocolDelivery::POST])) { Post\DeliveryData::incrementQueueDone($uri_id, Post\DeliveryData::ACTIVITYPUB); diff --git a/src/Protocol/ActivityPub/Fetch.php b/src/Protocol/ActivityPub/Fetch.php index fa7b52996b..3c787981ab 100644 --- a/src/Protocol/ActivityPub/Fetch.php +++ b/src/Protocol/ActivityPub/Fetch.php @@ -7,9 +7,9 @@ namespace Friendica\Protocol\ActivityPub; -use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Util\DateTimeFormat; /** @@ -22,7 +22,7 @@ class Fetch DBA::insert('fetch-entry', ['url' => $url, 'created' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE); $fetch = DBA::selectFirst('fetch-entry', ['id'], ['url' => $url]); - Logger::debug('Added fetch entry', ['url' => $url, 'fetch' => $fetch]); + DI::logger()->debug('Added fetch entry', ['url' => $url, 'fetch' => $fetch]); return $fetch['id'] ?? 0; } @@ -38,7 +38,7 @@ class Fetch } DBA::update('fetch-entry', ['wid' => $wid], ['url' => $url]); - Logger::debug('Worker id set', ['url' => $url, 'wid' => $wid]); + DI::logger()->debug('Worker id set', ['url' => $url, 'wid' => $wid]); } /** @@ -48,14 +48,14 @@ class Fetch { $fetch = DBA::selectFirst('fetch-entry', ['id', 'wid'], ['url' => $url]); if (empty($fetch['id'])) { - Logger::debug('No entry found for url', ['url' => $url]); + DI::logger()->debug('No entry found for url', ['url' => $url]); return false; } // We don't have a workerqueue id yet. So most likely is isn't assigned yet. // To avoid the ramping up of another fetch request we simply claim that there is a waiting worker. if (!empty($fetch['id']) && empty($fetch['wid'])) { - Logger::debug('Entry without worker found for url', ['url' => $url]); + DI::logger()->debug('Entry without worker found for url', ['url' => $url]); return true; } diff --git a/src/Protocol/ActivityPub/Processor.php b/src/Protocol/ActivityPub/Processor.php index b50397dc75..6cc401f05e 100644 --- a/src/Protocol/ActivityPub/Processor.php +++ b/src/Protocol/ActivityPub/Processor.php @@ -11,7 +11,6 @@ use Friendica\Content\Text\BBCode; use Friendica\Content\Text\HTML; use Friendica\Content\Text\Markdown; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Core\Worker; @@ -204,7 +203,7 @@ class Processor Post\QuestionOption::update($item['uri-id'], $key, $option); } - Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]); + DI::logger()->debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]); } /** @@ -218,7 +217,7 @@ class Processor { $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type', 'private'], ['uri' => $activity['id']]); if (!DBA::isResult($item)) { - Logger::notice('No existing item, item will be created', ['uri' => $activity['id']]); + DI::logger()->notice('No existing item, item will be created', ['uri' => $activity['id']]); $item = self::createItem($activity, false); if (empty($item)) { Queue::remove($activity); @@ -278,7 +277,7 @@ class Processor $event['nofinish'] = empty($event['finish']); $event['location'] = $activity['location']; - Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]); + DI::logger()->info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]); Event::store($event); } @@ -318,14 +317,14 @@ class Processor if (!empty($item['context'])) { $conversation = Post::selectFirstThread(['uri'], ['context' => $item['context']]); if (!empty($conversation)) { - Logger::debug('Got context', ['context' => $item['context'], 'parent' => $conversation]); + DI::logger()->debug('Got context', ['context' => $item['context'], 'parent' => $conversation]); $item['parent-uri'] = $conversation['uri']; $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']); } } elseif (!empty($item['conversation'])) { $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]); if (!empty($conversation)) { - Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]); + DI::logger()->debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]); $item['parent-uri'] = $conversation['uri']; $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']); } @@ -333,9 +332,9 @@ class Processor $conversation = []; } - Logger::debug('Create Item', ['id' => $activity['id'], 'conversation' => $item['conversation'] ?? '']); + DI::logger()->debug('Create Item', ['id' => $activity['id'], 'conversation' => $item['conversation'] ?? '']); if (empty($activity['author']) && empty($activity['actor'])) { - Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]); + DI::logger()->notice('Missing author and actor. We quit here.', ['activity' => $activity]); Queue::remove($activity); return []; } @@ -354,7 +353,7 @@ class Processor $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? ''; if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != Item::GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) { - Logger::notice('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]); + DI::logger()->notice('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]); if (!$fetch_parents) { Queue::remove($activity); } @@ -416,12 +415,12 @@ class Processor $actor = Contact::getById($activity['thread-completion'], ['url']); $item['causer-link'] = $actor['url']; $item['causer-id'] = $activity['thread-completion']; - Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]); + DI::logger()->info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]); } else { // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts $item['causer-link'] = $item['owner-link']; $item['causer-id'] = $item['owner-id']; - Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]); + DI::logger()->info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]); } $item['owner-link'] = $item['author-link']; @@ -432,7 +431,7 @@ class Processor foreach ($activity['receiver_urls']['as:audience'] as $audience) { $actor = APContact::getByURL($audience, false); if (($actor['type'] ?? 'Person') == 'Group') { - Logger::debug('Group post detected via audience.', ['audience' => $audience, 'actor' => $activity['actor'], 'author' => $activity['author']]); + DI::logger()->debug('Group post detected via audience.', ['audience' => $audience, 'actor' => $activity['actor'], 'author' => $activity['author']]); $item['isGroup'] = true; $item['group-link'] = $item['owner-link'] = $audience; $item['owner-id'] = Contact::getIdForURL($audience); @@ -444,7 +443,7 @@ class Processor } if (!$item['isGroup'] && (($owner['type'] ?? 'Person') == 'Group')) { - Logger::debug('Group post detected via owner.', ['actor' => $activity['actor'], 'author' => $activity['author']]); + DI::logger()->debug('Group post detected via owner.', ['actor' => $activity['actor'], 'author' => $activity['author']]); $item['isGroup'] = true; $item['group-link'] = $item['owner-link']; } elseif (!empty($item['causer-link'])) { @@ -452,7 +451,7 @@ class Processor } if (!$item['isGroup'] && (($causer['type'] ?? 'Person') == 'Group')) { - Logger::debug('Group post detected via causer.', ['actor' => $activity['actor'], 'author' => $activity['author'], 'causer' => $item['causer-link']]); + DI::logger()->debug('Group post detected via causer.', ['actor' => $activity['actor'], 'author' => $activity['author'], 'causer' => $item['causer-link']]); $item['isGroup'] = true; $item['group-link'] = $item['causer-link']; } @@ -476,7 +475,7 @@ class Processor $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]); if (empty($item['uri-id'])) { - Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]); + DI::logger()->warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]); return []; } @@ -484,7 +483,7 @@ class Processor $item = self::processContent($activity, $item); if (empty($item)) { - Logger::info('Message was not processed'); + DI::logger()->info('Message was not processed'); Queue::remove($activity); return []; } @@ -554,12 +553,12 @@ class Processor $activity['callstack'] = self::addToCallstack($activity['callstack'] ?? []); if (self::isFetched($activity['reply-to-id'])) { - Logger::info('Id is already fetched', ['id' => $activity['reply-to-id']]); + DI::logger()->info('Id is already fetched', ['id' => $activity['reply-to-id']]); return ''; } if (in_array($activity['reply-to-id'], $activity['children'] ?? [])) { - Logger::notice('reply-to-id is already in the list of children', ['id' => $activity['reply-to-id'], 'children' => $activity['children'], 'depth' => count($activity['children'])]); + DI::logger()->notice('reply-to-id is already in the list of children', ['id' => $activity['reply-to-id'], 'children' => $activity['children'], 'depth' => count($activity['children'])]); return ''; } @@ -574,20 +573,20 @@ class Processor $recursion_depth = $activity['recursion-depth'] ?? 0; if (!$in_background && ($recursion_depth < DI::config()->get('system', 'max_recursion_depth'))) { - Logger::info('Parent not found. Try to refetch it.', ['completion' => $completion, 'recursion-depth' => $recursion_depth, 'parent' => $activity['reply-to-id']]); + DI::logger()->info('Parent not found. Try to refetch it.', ['completion' => $completion, 'recursion-depth' => $recursion_depth, 'parent' => $activity['reply-to-id']]); $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO); if (empty($result) && self::isActivityGone($activity['reply-to-id'])) { - Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]); + DI::logger()->notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]); if (!empty($activity['entry-id'])) { Queue::deleteById($activity['entry-id']); } } elseif (!empty($result)) { $post = Post::selectFirstPost(['uri'], ['uri' => [$result, $activity['reply-to-id']]]); if (!empty($post['uri'])) { - Logger::info('The activity has been fetched and created.', ['result' => $result, 'uri' => $post['uri']]); + DI::logger()->info('The activity has been fetched and created.', ['result' => $result, 'uri' => $post['uri']]); return $post['uri']; } else { - Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]); + DI::logger()->notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]); if (!empty($activity['entry-id'])) { Queue::deleteById($activity['entry-id']); } @@ -595,7 +594,7 @@ class Processor } return ''; } elseif (self::isActivityGone($activity['reply-to-id'])) { - Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]); + DI::logger()->notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]); if ($in_background) { // fetching in background is done for all activities where we have got the conversation // There we only delete the single activity and not the whole thread since we can store the @@ -606,19 +605,19 @@ class Processor } return ''; } elseif ($in_background) { - Logger::notice('Fetching is done in the background.', ['parent' => $activity['reply-to-id']]); + DI::logger()->notice('Fetching is done in the background.', ['parent' => $activity['reply-to-id']]); } else { - Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]); + DI::logger()->notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]); } if (!Fetch::hasWorker($activity['reply-to-id'])) { - Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]); + DI::logger()->notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]); Fetch::add($activity['reply-to-id']); $activity['recursion-depth'] = 0; $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC); Fetch::setWorkerId($activity['reply-to-id'], $wid); } else { - Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]); + DI::logger()->debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]); } return ''; @@ -640,7 +639,7 @@ class Processor try { $curlResult = HTTPSignature::fetchRaw($url, 0); } catch (\Exception $exception) { - Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]); + DI::logger()->notice('Error fetching url', ['url' => $url, 'exception' => $exception]); return true; } @@ -677,7 +676,7 @@ class Processor { $owner = Contact::getIdForURL($activity['actor']); - Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]); + DI::logger()->info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]); Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]); Queue::remove($activity); } @@ -703,12 +702,12 @@ class Processor } if (($item['author-link'] != $activity['actor']) && !$item['origin']) { - Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]); + DI::logger()->info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]); continue; } Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']); - Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]); + DI::logger()->info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]); } } @@ -725,7 +724,7 @@ class Processor $activity['reply-to-id'] = $activity['object_id']; $item = self::createItem($activity, false); if (empty($item)) { - Logger::debug('Activity was not prepared', ['id' => $activity['object_id']]); + DI::logger()->debug('Activity was not prepared', ['id' => $activity['object_id']]); return; } @@ -795,7 +794,7 @@ class Processor return; } - Logger::debug('Add post to featured collection', ['post' => $post]); + DI::logger()->debug('Add post to featured collection', ['post' => $post]); Post\Collection::add($post['uri-id'], Post\Collection::FEATURED, $post['author-id']); Queue::remove($activity); @@ -814,7 +813,7 @@ class Processor return; } - Logger::debug('Remove post from featured collection', ['post' => $post]); + DI::logger()->debug('Remove post from featured collection', ['post' => $post]); Post\Collection::remove($post['uri-id'], Post\Collection::FEATURED); Queue::remove($activity); @@ -860,7 +859,7 @@ class Processor $event_id = Event::store($event); - Logger::info('Event was stored', ['id' => $event_id]); + DI::logger()->info('Event was stored', ['id' => $event_id]); return $event_id; } @@ -907,15 +906,15 @@ class Processor if ($id) { $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]); $item['quote-uri-id'] = $shared_item['uri-id']; - Logger::debug('Quote is found', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'quote-uri-id' => $item['quote-uri-id']]); + DI::logger()->debug('Quote is found', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'quote-uri-id' => $item['quote-uri-id']]); } elseif ($uri_id = ItemURI::getIdByURI($activity['quote-url'], false)) { - Logger::info('Quote was not fetched but the uri-id existed', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'quote-uri-id' => $uri_id]); + DI::logger()->info('Quote was not fetched but the uri-id existed', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'quote-uri-id' => $uri_id]); $item['quote-uri-id'] = $uri_id; } elseif (Queue::exists($activity['quote-url'], 'as:Create')) { $item['quote-uri-id'] = ItemURI::getIdByURI($activity['quote-url']); - Logger::info('Quote is queued but not processed yet', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'quote-uri-id' => $item['quote-uri-id']]); + DI::logger()->info('Quote is queued but not processed yet', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'quote-uri-id' => $item['quote-uri-id']]); } else { - Logger::notice('Quote was not fetched', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url']]); + DI::logger()->notice('Quote was not fetched', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url']]); } } @@ -934,7 +933,7 @@ class Processor if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == Item::GRAVITY_COMMENT)) { $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]); if (!DBA::isResult($parent)) { - Logger::warning('Unknown parent item.', ['uri' => $parent_uri]); + DI::logger()->warning('Unknown parent item.', ['uri' => $parent_uri]); return false; } $content = self::removeImplicitMentionsFromBody($content, $parent); @@ -946,7 +945,7 @@ class Processor foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) { $actor = APContact::getByURL($tag[2], false); if (($actor['type'] ?? 'Person') == 'Group') { - Logger::debug('Group post detected via exclusive mention.', ['mention' => $actor['url'], 'actor' => $activity['actor'], 'author' => $activity['author']]); + DI::logger()->debug('Group post detected via exclusive mention.', ['mention' => $actor['url'], 'actor' => $activity['actor'], 'author' => $activity['author']]); $item['isGroup'] = true; $item['group-link'] = $item['owner-link'] = $actor['url']; $item['owner-id'] = Contact::getIdForURL($actor['url']); @@ -1042,38 +1041,38 @@ class Processor // The checks are split to improve the support when searching why a message was accepted. if (count($activity['receiver']) != 1) { // The message has more than one receiver, so it is wanted. - Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); + DI::logger()->debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); return true; } if ($item['private'] == Item::PRIVATE) { // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver. - Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); + DI::logger()->debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); return true; } if (!empty($activity['from-relay'])) { // We check relay posts at another place. When it arrived here, the message is already checked. - Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); + DI::logger()->debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); return true; } if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUNCE])) { // Manual completions and completions caused by reshares are allowed without any further checks. - Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); + DI::logger()->debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); return true; } if ($item['gravity'] != Item::GRAVITY_PARENT) { // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched // This can possibly be improved in the future. - Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); + DI::logger()->debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); return true; } $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name'); if (Relay::isSolicitedPost($tags, $item['title'] . ' ' . ($item['content-warning'] ?? '') . ' ' . $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB, $activity['thread-completion'] ?? 0)) { - Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); + DI::logger()->debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]); return true; } else { return false; @@ -1164,7 +1163,7 @@ class Processor } elseif (($item['post-reason'] == Item::PR_FOLLOWER) && !empty($activity['from-relay'])) { // When a post arrives via a relay and we follow the author, we have to override the causer. // Otherwise the system assumes that we follow the relay. (See "addRowInformation") - Logger::debug('Relay post for follower', ['receiver' => $receiver, 'guid' => $item['guid'], 'relay' => $activity['from-relay']]); + DI::logger()->debug('Relay post for follower', ['receiver' => $receiver, 'guid' => $item['guid'], 'relay' => $activity['from-relay']]); $item['causer-id'] = ($item['gravity'] == Item::GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id']; } @@ -1189,13 +1188,13 @@ class Processor if (($receiver != 0) && ($item['gravity'] == Item::GRAVITY_PARENT) && !in_array($item['post-reason'], [Item::PR_FOLLOWER, Item::PR_TAG, Item::PR_TO, Item::PR_CC, Item::PR_AUDIENCE])) { if (!$item['isGroup']) { if ($item['post-reason'] == Item::PR_BCC) { - Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id'], 'url' => $item['uri']]); + DI::logger()->info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id'], 'url' => $item['uri']]); continue; } if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE) && in_array($activity['thread-children-type'] ?? '', Receiver::ACTIVITY_TYPES)) { - Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring', + DI::logger()->info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring', ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]); continue; } @@ -1210,11 +1209,11 @@ class Processor if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE) && ((!$isGroup && !$item['isGroup'] && ($activity['type'] != 'as:Announce')) || !Contact::isSharingByURL($activity['actor'], $receiver))) { - Logger::info('Actor is a non sharer, is no group or it is no announce', ['uid' => $receiver, 'actor' => $activity['actor'], 'url' => $item['uri'], 'type' => $activity['type']]); + DI::logger()->info('Actor is a non sharer, is no group or it is no announce', ['uid' => $receiver, 'actor' => $activity['actor'], 'url' => $item['uri'], 'type' => $activity['type']]); continue; } - Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]); + DI::logger()->info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]); } if (!self::hasParents($item, $receiver)) { @@ -1229,12 +1228,12 @@ class Processor $item_id = Item::insert($item); if ($item_id) { - Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]); + DI::logger()->info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]); $success = true; } else { - Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]); + DI::logger()->notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]); if (($item['uid'] == 0) && (count($activity['receiver']) > 1)) { - Logger::info('Public item was aborted. We skip for all users.', ['uri' => $item['uri']]); + DI::logger()->info('Public item was aborted. We skip for all users.', ['uri' => $item['uri']]); break; } } @@ -1255,7 +1254,7 @@ class Processor $author = APContact::getByURL($item['owner-link'], false); // We send automatic follow requests for reshared messages. (We don't need though for group posts) if ($author['type'] != 'Group') { - Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]); + DI::logger()->info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]); ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']); } } @@ -1314,15 +1313,15 @@ class Processor $stored = Item::storeForUserByUriId($item['parent-uri-id'], $receiver, $fields); $has_parents = (bool)$stored; if ($stored) { - Logger::notice('Inserted missing parent post', ['stored' => $stored, 'uid' => $receiver, 'parent' => $item['parent-uri']]); + DI::logger()->notice('Inserted missing parent post', ['stored' => $stored, 'uid' => $receiver, 'parent' => $item['parent-uri']]); } else { - Logger::notice('Parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]); + DI::logger()->notice('Parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]); return false; } } elseif ($add_parent) { - Logger::debug('Parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]); + DI::logger()->debug('Parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'parent' => $item['parent-uri']]); } else { - Logger::debug('Parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'parent' => $item['parent-uri']]); + DI::logger()->debug('Parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'parent' => $item['parent-uri']]); } } @@ -1333,14 +1332,14 @@ class Processor $stored = Item::storeForUserByUriId($item['thr-parent-id'], $receiver, $fields); $has_parents = $has_parents || (bool)$stored; if ($stored) { - Logger::notice('Inserted missing thread parent post', ['stored' => $stored, 'uid' => $receiver, 'thread-parent' => $item['thr-parent']]); + DI::logger()->notice('Inserted missing thread parent post', ['stored' => $stored, 'uid' => $receiver, 'thread-parent' => $item['thr-parent']]); } else { - Logger::notice('Thread parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]); + DI::logger()->notice('Thread parent could not be added.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]); } } elseif ($add_parent) { - Logger::debug('Thread parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]); + DI::logger()->debug('Thread parent does not exist.', ['uid' => $receiver, 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]); } else { - Logger::debug('Thread parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]); + DI::logger()->debug('Thread parent should not be added.', ['uid' => $receiver, 'gravity' => $item['gravity'], 'verb' => $item['verb'], 'guid' => $item['guid'], 'uri' => $item['uri'], 'thread-parent' => $item['thr-parent']]); } } @@ -1403,12 +1402,12 @@ class Processor } elseif ($host = parse_url($receiver, PHP_URL_HOST)) { $name = $host; } else { - Logger::warning('Unable to coerce name from receiver', ['element' => $element, 'type' => $type, 'receiver' => $receiver]); + DI::logger()->warning('Unable to coerce name from receiver', ['element' => $element, 'type' => $type, 'receiver' => $receiver]); $name = ''; } $target = Tag::getTargetType($receiver); - Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]); + DI::logger()->debug('Got target type', ['type' => $target, 'url' => $receiver]); Tag::store($uriid, $type, $name, $receiver, $target); } } @@ -1429,7 +1428,7 @@ class Processor } elseif ($host = parse_url($capability, PHP_URL_HOST)) { $name = $host; } else { - Logger::warning('Unable to coerce name from capability', ['element' => $element, 'type' => $type, 'capability' => $capability]); + DI::logger()->warning('Unable to coerce name from capability', ['element' => $element, 'type' => $type, 'capability' => $capability]); $name = ''; } $restricted = false; @@ -1452,16 +1451,16 @@ class Processor private static function postMail(array $item) { if (($item['gravity'] != Item::GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) { - Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]); + DI::logger()->info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]); return false; } if (!Contact::isFollower($item['contact-id'], $item['uid']) && !Contact::isSharing($item['contact-id'], $item['uid'])) { - Logger::info('Contact is not a sharer or follower, mail will be discarded.', ['item' => $item]); + DI::logger()->info('Contact is not a sharer or follower, mail will be discarded.', ['item' => $item]); return false; } - Logger::info('Direct Message', $item); + DI::logger()->info('Direct Message', $item); $msg = []; $msg['uid'] = $item['uid']; @@ -1517,17 +1516,17 @@ class Processor */ public static function fetchFeaturedPosts(string $url) { - Logger::info('Fetch featured posts', ['contact' => $url]); + DI::logger()->info('Fetch featured posts', ['contact' => $url]); $apcontact = APContact::getByURL($url); if (empty($apcontact['featured'])) { - Logger::info('Contact does not have a featured collection', ['contact' => $url]); + DI::logger()->info('Contact does not have a featured collection', ['contact' => $url]); return; } $pcid = Contact::getIdForURL($url, 0, false); if (empty($pcid)) { - Logger::notice('Contact not found', ['contact' => $url]); + DI::logger()->notice('Contact not found', ['contact' => $url]); return; } @@ -1540,11 +1539,11 @@ class Processor $featured = ActivityPub::fetchItems($apcontact['featured']); if (empty($featured)) { - Logger::info('Contact does not have featured posts', ['contact' => $url]); + DI::logger()->info('Contact does not have featured posts', ['contact' => $url]); foreach ($old_featured as $uri_id) { Post\Collection::remove($uri_id, Post\Collection::FEATURED); - Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]); + DI::logger()->debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]); } return; } @@ -1562,10 +1561,10 @@ class Processor if (!empty($item['uri-id'])) { if (!$item['featured']) { Post\Collection::add($item['uri-id'], Post\Collection::FEATURED, $item['author-id']); - Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]); + DI::logger()->debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]); $new++; } else { - Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]); + DI::logger()->debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]); $old++; } @@ -1579,10 +1578,10 @@ class Processor foreach ($old_featured as $uri_id) { Post\Collection::remove($uri_id, Post\Collection::FEATURED); - Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]); + DI::logger()->debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]); } - Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]); + DI::logger()->info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]); } public static function fetchCachedActivity(string $url, int $uid): array @@ -1592,9 +1591,9 @@ class Processor if (!is_null($object)) { if (!empty($object)) { - Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]); + DI::logger()->debug('Fetch from cache', ['url' => $url, 'uid' => $uid]); } else { - Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]); + DI::logger()->debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]); } return $object; } @@ -1606,14 +1605,14 @@ class Processor } if (empty($object)) { - Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]); + DI::logger()->notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]); // We perform negative caching. DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES); return []; } if (empty($object['id'])) { - Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]); + DI::logger()->notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]); return []; } @@ -1623,7 +1622,7 @@ class Processor DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES); - Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]); + DI::logger()->debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]); return $object; } @@ -1647,14 +1646,14 @@ class Processor } if (!empty($child['children']) && in_array($url, $child['children'])) { - Logger::notice('id is already in the list of children', ['depth' => count($child['children']), 'children' => $child['children'], 'id' => $url]); + DI::logger()->notice('id is already in the list of children', ['depth' => count($child['children']), 'children' => $child['children'], 'id' => $url]); return null; } try { $curlResult = HTTPSignature::fetchRaw($url, $uid); } catch (\Exception $exception) { - Logger::notice('Error fetching url', ['url' => $url, 'exception' => $exception]); + DI::logger()->notice('Error fetching url', ['url' => $url, 'exception' => $exception]); return ''; } @@ -1673,7 +1672,7 @@ class Processor } if (empty($object) || !is_array($object)) { - Logger::notice('Invalid JSON data', ['url' => $url, 'content-type' => $curlResult->getContentType()]); + DI::logger()->notice('Invalid JSON data', ['url' => $url, 'content-type' => $curlResult->getContentType()]); return null; } @@ -1724,7 +1723,7 @@ class Processor if (Item::searchByLink($object_id)) { return $object_id; } - Logger::debug('Fetch announced activity', ['type' => $type, 'id' => $object_id, 'actor' => $relay_actor, 'signer' => $signer]); + DI::logger()->debug('Fetch announced activity', ['type' => $type, 'id' => $object_id, 'actor' => $relay_actor, 'signer' => $signer]); if (!self::alreadyKnown($object_id, $child['id'] ?? '')) { $child['callstack'] = self::addToCallstack($child['callstack'] ?? []); @@ -1745,7 +1744,7 @@ class Processor $ldactivity['callstack'] = $child['callstack'] ?? []; // This check is mostly superfluous, since there are similar checks before. This covers the case, when the fetched id doesn't match the url if (in_array($activity['id'], $ldactivity['children'])) { - Logger::notice('Fetched id is already in the list of children. It will not be processed.', ['id' => $activity['id'], 'children' => $ldactivity['children'], 'depth' => count($ldactivity['children'])]); + DI::logger()->notice('Fetched id is already in the list of children. It will not be processed.', ['id' => $activity['id'], 'children' => $ldactivity['children'], 'depth' => count($ldactivity['children'])]); return null; } if (!empty($child['id'])) { @@ -1783,11 +1782,11 @@ class Processor } if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) { - Logger::info('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]); + DI::logger()->info('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]); } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer, '', $completion)) { - Logger::info('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]); + DI::logger()->info('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]); } else { - Logger::info('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]); + DI::logger()->info('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]); } return $activity['id']; @@ -1812,7 +1811,7 @@ class Processor $maximum_fetchreplies_depth = DI::config()->get('system', 'max_fetchreplies_depth'); if (max($callstack_count, $system_count) == $maximum_fetchreplies_depth) { - Logger::notice('Maximum callstack depth reached', ['max' => $maximum_fetchreplies_depth, 'count' => $callstack_count, 'system-count' => $system_count, 'replies' => $url, 'callstack' => $child['callstack'] ?? [], 'system' => $callstack]); + DI::logger()->notice('Maximum callstack depth reached', ['max' => $maximum_fetchreplies_depth, 'count' => $callstack_count, 'system-count' => $system_count, 'replies' => $url, 'callstack' => $child['callstack'] ?? [], 'system' => $callstack]); return; } @@ -1820,10 +1819,10 @@ class Processor $replies = ActivityPub::fetchItems($url); if (empty($replies)) { - Logger::notice('No replies', ['replies' => $url]); + DI::logger()->notice('No replies', ['replies' => $url]); return; } - Logger::notice('Fetch replies - start', ['replies' => $url, 'callstack' => $child['callstack'], 'system' => $callstack]); + DI::logger()->notice('Fetch replies - start', ['replies' => $url, 'callstack' => $child['callstack'], 'system' => $callstack]); $fetched = 0; foreach ($replies as $reply) { $id = ''; @@ -1835,11 +1834,11 @@ class Processor continue; } if (!empty($child['children']) && in_array($id, $child['children'])) { - Logger::debug('Replies id is already in the list of children', ['depth' => count($child['children']), 'children' => $child['children'], 'id' => $id]); + DI::logger()->debug('Replies id is already in the list of children', ['depth' => count($child['children']), 'children' => $child['children'], 'id' => $id]); continue; } if (parse_url($id, PHP_URL_HOST) == parse_url($url, PHP_URL_HOST)) { - Logger::debug('Incluced activity will be processed', ['replies' => $url, 'id' => $id]); + DI::logger()->debug('Incluced activity will be processed', ['replies' => $url, 'id' => $id]); self::processActivity($reply, $id, $child, '', Receiver::COMPLETION_REPLIES); ++$fetched; continue; @@ -1852,22 +1851,22 @@ class Processor ++$fetched; } } - Logger::notice('Fetch replies - done', ['fetched' => $fetched, 'total' => count($replies), 'replies' => $url]); + DI::logger()->notice('Fetch replies - done', ['fetched' => $fetched, 'total' => count($replies), 'replies' => $url]); } public static function alreadyKnown(string $id, string $child): bool { if ($id == $child) { - Logger::debug('Activity is currently processed', ['id' => $id, 'child' => $child]); + DI::logger()->debug('Activity is currently processed', ['id' => $id, 'child' => $child]); return true; } elseif (Item::searchByLink($id)) { - Logger::debug('Activity already exists', ['id' => $id, 'child' => $child]); + DI::logger()->debug('Activity already exists', ['id' => $id, 'child' => $child]); return true; } elseif (Queue::exists($id, 'as:Create')) { - Logger::debug('Activity is already queued', ['id' => $id, 'child' => $child]); + DI::logger()->debug('Activity is already queued', ['id' => $id, 'child' => $child]); return true; } - Logger::debug('Activity is unknown', ['id' => $id, 'child' => $child]); + DI::logger()->debug('Activity is unknown', ['id' => $id, 'child' => $child]); return false; } @@ -1875,13 +1874,13 @@ class Processor { $ldobject = JsonLD::compact($object); if (empty($ldobject)) { - Logger::info('Invalid object', ['url' => $url]); + DI::logger()->info('Invalid object', ['url' => $url]); return $object; } $id = JsonLD::fetchElement($ldobject, '@id'); if (empty($id)) { - Logger::info('No id found in object', ['url' => $url, 'object' => $object]); + DI::logger()->info('No id found in object', ['url' => $url, 'object' => $object]); return $object; } @@ -1892,7 +1891,7 @@ class Processor return $object; } - Logger::notice('Refetch activity because of a host mismatch between requested and received id', ['url-host' => $url_host, 'id-host' => $id_host, 'url' => $url, 'id' => $id]); + DI::logger()->notice('Refetch activity because of a host mismatch between requested and received id', ['url-host' => $url_host, 'id-host' => $id_host, 'url' => $url, 'id' => $id]); return HTTPSignature::fetch($id); } @@ -1900,13 +1899,13 @@ class Processor { $ldobject = JsonLD::compact($object); if (empty($ldobject)) { - Logger::info('Invalid object'); + DI::logger()->info('Invalid object'); return false; } $id = JsonLD::fetchElement($ldobject, '@id'); if (empty($id)) { - Logger::info('No id found in object'); + DI::logger()->info('No id found in object'); return false; } @@ -1921,7 +1920,7 @@ class Processor if (!empty($actor) && !in_array($type, Receiver::CONTENT_TYPES) && !empty($object_id)) { $actor_host = parse_url($actor, PHP_URL_HOST); if ($actor_host != $id_host) { - Logger::notice('Host mismatch between received id and actor', ['id-host' => $id_host, 'actor-host' => $actor_host, 'id' => $id, 'type' => $type, 'object-id' => $object_id, 'object_type' => $object_type, 'actor' => $actor, 'attributed_to' => $attributed_to]); + DI::logger()->notice('Host mismatch between received id and actor', ['id-host' => $id_host, 'actor-host' => $actor_host, 'id' => $id, 'type' => $type, 'object-id' => $object_id, 'object_type' => $object_type, 'actor' => $actor, 'attributed_to' => $attributed_to]); return false; } if (!empty($object_type)) { @@ -1929,14 +1928,14 @@ class Processor $attributed_to_host = parse_url($object_attributed_to, PHP_URL_HOST); $object_id_host = parse_url($object_id, PHP_URL_HOST); if (!empty($attributed_to_host) && ($attributed_to_host != $object_id_host)) { - Logger::notice('Host mismatch between received object id and attributed actor', ['id-object-host' => $object_id_host, 'attributed-host' => $attributed_to_host, 'id' => $id, 'type' => $type, 'object-id' => $object_id, 'object_type' => $object_type, 'actor' => $actor, 'object_attributed_to' => $object_attributed_to]); + DI::logger()->notice('Host mismatch between received object id and attributed actor', ['id-object-host' => $object_id_host, 'attributed-host' => $attributed_to_host, 'id' => $id, 'type' => $type, 'object-id' => $object_id, 'object_type' => $object_type, 'actor' => $actor, 'object_attributed_to' => $object_attributed_to]); return false; } } } elseif (!empty($attributed_to)) { $attributed_to_host = parse_url($attributed_to, PHP_URL_HOST); if ($attributed_to_host != $id_host) { - Logger::notice('Host mismatch between received id and attributed actor', ['id-host' => $id_host, 'attributed-host' => $attributed_to_host, 'id' => $id, 'type' => $type, 'object-id' => $object_id, 'object_type' => $object_type, 'actor' => $actor, 'attributed_to' => $attributed_to]); + DI::logger()->notice('Host mismatch between received id and attributed actor', ['id-host' => $id_host, 'attributed-host' => $attributed_to_host, 'id' => $id, 'type' => $type, 'object-id' => $object_id, 'object_type' => $object_type, 'actor' => $actor, 'attributed_to' => $attributed_to]); return false; } } @@ -1977,7 +1976,7 @@ class Processor { if (empty($activity['as:object'])) { $id = JsonLD::fetchElement($activity, '@id'); - Logger::info('No object field in activity - accepted', ['id' => $id]); + DI::logger()->info('No object field in activity - accepted', ['id' => $id]); return true; } @@ -1986,7 +1985,7 @@ class Processor $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id'); $uriid = ItemURI::getIdByURI($replyto ?? ''); if (Post::exists(['uri-id' => $uriid])) { - Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]); + DI::logger()->info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]); return true; } @@ -2121,7 +2120,7 @@ class Processor Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]); - Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']); + DI::logger()->notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']); Queue::remove($activity); } @@ -2164,7 +2163,7 @@ class Processor return; } - Logger::info('Updating profile', ['object' => $activity['object_id']]); + DI::logger()->info('Updating profile', ['object' => $activity['object_id']]); Contact::updateFromProbeByURL($activity['object_id']); Queue::remove($activity); } @@ -2179,13 +2178,13 @@ class Processor public static function deletePerson(array $activity) { if (empty($activity['object_id']) || empty($activity['actor'])) { - Logger::info('Empty object id or actor.'); + DI::logger()->info('Empty object id or actor.'); Queue::remove($activity); return; } if ($activity['object_id'] != $activity['actor']) { - Logger::info('Object id does not match actor.'); + DI::logger()->info('Object id does not match actor.'); Queue::remove($activity); return; } @@ -2196,7 +2195,7 @@ class Processor } DBA::close($contacts); - Logger::info('Deleted contact', ['object' => $activity['object_id']]); + DI::logger()->info('Deleted contact', ['object' => $activity['object_id']]); Queue::remove($activity); } @@ -2215,14 +2214,14 @@ class Processor } if ($activity['object_id'] != $activity['actor']) { - Logger::notice('Object is not the actor', ['activity' => $activity]); + DI::logger()->notice('Object is not the actor', ['activity' => $activity]); Queue::remove($activity); return; } $from = Contact::getByURL($activity['object_id'], false, ['uri-id']); if (empty($from['uri-id'])) { - Logger::info('Object not found', ['activity' => $activity]); + DI::logger()->info('Object not found', ['activity' => $activity]); Queue::remove($activity); return; } @@ -2230,7 +2229,7 @@ class Processor $contacts = DBA::select('contact', ['uid', 'url'], ["`uri-id` = ? AND `uid` != ? AND `rel` IN (?, ?)", $from['uri-id'], 0, Contact::FRIEND, Contact::SHARING]); while ($from_contact = DBA::fetch($contacts)) { $result = Contact::createFromProbeForUser($from_contact['uid'], $activity['target_id']); - Logger::debug('Follower added', ['from' => $from_contact, 'result' => $result]); + DI::logger()->debug('Follower added', ['from' => $from_contact, 'result' => $result]); } DBA::close($contacts); Queue::remove($activity); @@ -2257,7 +2256,7 @@ class Processor Contact\User::setIsBlocked($cid, $uid, true); - Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]); + DI::logger()->info('Contact blocked user', ['contact' => $cid, 'user' => $uid]); Queue::remove($activity); } @@ -2282,7 +2281,7 @@ class Processor Contact\User::setIsBlocked($cid, $uid, false); - Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]); + DI::logger()->info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]); Queue::remove($activity); } @@ -2297,14 +2296,14 @@ class Processor { $account = Contact::getByURL($activity['object_id'], null, ['id', 'gsid']); if (empty($account)) { - Logger::info('Unknown account', ['activity' => $activity]); + DI::logger()->info('Unknown account', ['activity' => $activity]); Queue::remove($activity); return; } $reporter_id = Contact::getIdForURL($activity['actor']); if (empty($reporter_id)) { - Logger::info('Unknown actor', ['activity' => $activity]); + DI::logger()->info('Unknown actor', ['activity' => $activity]); Queue::remove($activity); return; } @@ -2320,7 +2319,7 @@ class Processor $report = DI::reportFactory()->createFromReportsRequest(System::getRules(true), $reporter_id, $account['id'], $account['gsid'], $activity['content'], 'other', false, $uri_ids); DI::report()->save($report); - Logger::info('Stored report', ['reporter' => $reporter_id, 'account' => $account, 'comment' => $activity['content'], 'object_ids' => $activity['object_ids']]); + DI::logger()->info('Stored report', ['reporter' => $reporter_id, 'account' => $account, 'comment' => $activity['content'], 'object_ids' => $activity['object_ids']]); } /** @@ -2342,23 +2341,23 @@ class Processor } if (empty($uid)) { - Logger::notice('User could not be detected', ['activity' => $activity]); + DI::logger()->notice('User could not be detected', ['activity' => $activity]); Queue::remove($activity); return; } $cid = Contact::getIdForURL($activity['actor'], $uid); if (empty($cid)) { - Logger::notice('No contact found', ['actor' => $activity['actor']]); + DI::logger()->notice('No contact found', ['actor' => $activity['actor']]); Queue::remove($activity); return; } $id = Transmitter::activityIDFromContact($cid); if ($id == $activity['object_id']) { - Logger::info('Successful id check', ['uid' => $uid, 'cid' => $cid]); + DI::logger()->info('Successful id check', ['uid' => $uid, 'cid' => $cid]); } else { - Logger::info('Unsuccessful id check', ['uid' => $uid, 'cid' => $cid, 'id' => $id, 'object_id' => $activity['object_id']]); + DI::logger()->info('Unsuccessful id check', ['uid' => $uid, 'cid' => $cid, 'id' => $id, 'object_id' => $activity['object_id']]); if ($check_id) { Queue::remove($activity); return; @@ -2376,7 +2375,7 @@ class Processor $condition = ['id' => $cid]; Contact::update($fields, $condition); - Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]); + DI::logger()->info('Accept contact request', ['contact' => $cid, 'user' => $uid]); Queue::remove($activity); } @@ -2396,7 +2395,7 @@ class Processor $cid = Contact::getIdForURL($activity['actor'], $uid); if (empty($cid)) { - Logger::info('No contact found', ['actor' => $activity['actor']]); + DI::logger()->info('No contact found', ['actor' => $activity['actor']]); return; } @@ -2405,11 +2404,11 @@ class Processor $contact = Contact::getById($cid, ['rel']); if ($contact['rel'] == Contact::SHARING) { Contact::remove($cid); - Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]); + DI::logger()->info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]); } elseif ($contact['rel'] == Contact::FRIEND) { Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]); } else { - Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]); + DI::logger()->info('Rejected contact request', ['contact' => $cid, 'user' => $uid]); } Queue::remove($activity); } @@ -2461,7 +2460,7 @@ class Processor $cid = Contact::getIdForURL($activity['actor'], $uid); if (empty($cid)) { - Logger::info('No contact found', ['actor' => $activity['actor']]); + DI::logger()->info('No contact found', ['actor' => $activity['actor']]); return; } @@ -2473,7 +2472,7 @@ class Processor } Contact::removeFollower($contact); - Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]); + DI::logger()->info('Undo following request', ['contact' => $cid, 'user' => $uid]); Queue::remove($activity); } @@ -2491,7 +2490,7 @@ class Processor return; } - Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]); + DI::logger()->info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]); Contact::updateFromProbe($cid); } @@ -2512,7 +2511,7 @@ class Processor $implicit_mentions = []; if (empty($parent_author['url'])) { - Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]); + DI::logger()->notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]); } else { $implicit_mentions[] = $parent_author['url']; $implicit_mentions[] = $parent_author['nurl']; @@ -2616,7 +2615,7 @@ class Processor $function = array_shift($functions); if (in_array($function, $callstack)) { - Logger::notice('Callstack already contains "' . $function . '"', ['callstack' => $callstack]); + DI::logger()->notice('Callstack already contains "' . $function . '"', ['callstack' => $callstack]); } $callstack[] = $function; diff --git a/src/Protocol/ActivityPub/Queue.php b/src/Protocol/ActivityPub/Queue.php index 8d78620c3e..bf89363de7 100644 --- a/src/Protocol/ActivityPub/Queue.php +++ b/src/Protocol/ActivityPub/Queue.php @@ -7,7 +7,6 @@ namespace Friendica\Protocol\ActivityPub; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -129,7 +128,7 @@ class Queue return; } - Logger::debug('Delete inbox-entry', ['id' => $entry['id']]); + DI::logger()->debug('Delete inbox-entry', ['id' => $entry['id']]); DBA::delete('inbox-entry', ['id' => $entry['id']]); @@ -187,7 +186,7 @@ class Queue } if (!self::isProcessable($id)) { - Logger::debug('Other queue entries need to be processed first.', ['id' => $id]); + DI::logger()->debug('Other queue entries need to be processed first.', ['id' => $id]); return false; } @@ -197,13 +196,13 @@ class Queue if ($entry['wid'] != $wid) { $workerqueue = DBA::selectFirst('workerqueue', ['pid'], ['id' => $entry['wid'], 'done' => false]); if (!empty($workerqueue['pid']) && posix_kill($workerqueue['pid'], 0)) { - Logger::notice('Entry is already processed via another process.', ['current' => $wid, 'processor' => $entry['wid']]); + DI::logger()->notice('Entry is already processed via another process.', ['current' => $wid, 'processor' => $entry['wid']]); return false; } } } - Logger::debug('Processing queue entry', ['id' => $entry['id'], 'type' => $entry['type'], 'object-type' => $entry['object-type'], 'uri' => $entry['object-id'], 'in-reply-to' => $entry['in-reply-to-id']]); + DI::logger()->debug('Processing queue entry', ['id' => $entry['id'], 'type' => $entry['type'], 'object-type' => $entry['object-type'], 'uri' => $entry['object-id'], 'in-reply-to' => $entry['in-reply-to-id']]); $activity = json_decode($entry['activity'], true); $type = $entry['type']; @@ -259,16 +258,16 @@ class Queue if (!$entry['trust'] || !self::isProcessable($entry['id'])) { continue; } - Logger::debug('Process leftover entry', $entry); + DI::logger()->debug('Process leftover entry', $entry); self::process($entry['id'], false); } DBA::close($entries); // Optimizing this table only last seconds if (DI::config()->get('system', 'optimize_tables')) { - Logger::info('Optimize start'); + DI::logger()->info('Optimize start'); DBA::optimizeTable('inbox-entry'); - Logger::info('Optimize end'); + DI::logger()->info('Optimize end'); } } @@ -316,14 +315,14 @@ class Queue if (!Processor::alreadyKnown($entry['in-reply-to-id'], '')) { // This entry belongs to some other entry that need to be fetched first if (Fetch::hasWorker($entry['in-reply-to-id'])) { - Logger::debug('Fetching of the activity is already queued', ['id' => $entry['activity-id'], 'reply-to-id' => $entry['in-reply-to-id']]); + DI::logger()->debug('Fetching of the activity is already queued', ['id' => $entry['activity-id'], 'reply-to-id' => $entry['in-reply-to-id']]); self::retrial($id); return false; } Fetch::add($entry['in-reply-to-id']); $activity = json_decode($entry['activity'], true); if (in_array($entry['in-reply-to-id'], $activity['children'] ?? [])) { - Logger::notice('reply-to-id is already in the list of children', ['id' => $entry['in-reply-to-id'], 'children' => $activity['children'], 'depth' => count($activity['children'])]); + DI::logger()->notice('reply-to-id is already in the list of children', ['id' => $entry['in-reply-to-id'], 'children' => $activity['children'], 'depth' => count($activity['children'])]); self::retrial($id); return false; } @@ -331,7 +330,7 @@ class Queue $activity['callstack'] = Processor::addToCallstack($activity['callstack'] ?? []); $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $entry['in-reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC); Fetch::setWorkerId($entry['in-reply-to-id'], $wid); - Logger::debug('Fetch missing activity', ['wid' => $wid, 'id' => $entry['activity-id'], 'reply-to-id' => $entry['in-reply-to-id']]); + DI::logger()->debug('Fetch missing activity', ['wid' => $wid, 'id' => $entry['activity-id'], 'reply-to-id' => $entry['in-reply-to-id']]); self::retrial($id); return false; } diff --git a/src/Protocol/ActivityPub/Receiver.php b/src/Protocol/ActivityPub/Receiver.php index d5a12b5218..34732022b5 100644 --- a/src/Protocol/ActivityPub/Receiver.php +++ b/src/Protocol/ActivityPub/Receiver.php @@ -11,7 +11,6 @@ use Friendica\Content\Text\BBCode; use Friendica\Database\DBA; use Friendica\Content\Text\HTML; use Friendica\Content\Text\Markdown; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Core\Worker; @@ -83,7 +82,7 @@ class Receiver { $activity = json_decode($body, true); if (empty($activity)) { - Logger::warning('Invalid body.'); + DI::logger()->warning('Invalid body.'); return; } @@ -94,7 +93,7 @@ class Receiver $apcontact = APContact::getByURL($actor); if (empty($apcontact)) { - Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]); + DI::logger()->notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]); return; } elseif (APContact::isRelay($apcontact) && self::isRelayPost($ldactivity)) { self::processRelayPost($ldactivity, $actor); @@ -105,52 +104,52 @@ class Receiver $sig_contact = HTTPSignature::getKeyIdContact($header); if (APContact::isRelay($sig_contact) && self::isRelayPost($ldactivity)) { - Logger::info('Message from a relay', ['url' => $sig_contact['url']]); + DI::logger()->info('Message from a relay', ['url' => $sig_contact['url']]); self::processRelayPost($ldactivity, $sig_contact['url']); return; } $http_signer = HTTPSignature::getSigner($body, $header); if ($http_signer === false) { - Logger::notice('Invalid HTTP signature, message will not be trusted.', ['uid' => $uid, 'actor' => $actor, 'header' => $header, 'body' => $body]); + DI::logger()->notice('Invalid HTTP signature, message will not be trusted.', ['uid' => $uid, 'actor' => $actor, 'header' => $header, 'body' => $body]); $signer = []; } elseif (empty($http_signer)) { - Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.'); + DI::logger()->info('Signer is a tombstone. The message will be discarded, the signer account is deleted.'); return; } else { - Logger::info('Valid HTTP signature', ['signer' => $http_signer]); + DI::logger()->info('Valid HTTP signature', ['signer' => $http_signer]); $signer = [$http_signer]; } - Logger::info('Message for user ' . $uid . ' is from actor ' . $actor); + DI::logger()->info('Message for user ' . $uid . ' is from actor ' . $actor); if ($http_signer === false) { $trust_source = false; } elseif (LDSignature::isSigned($activity)) { $ld_signer = LDSignature::getSigner($activity); if (empty($ld_signer)) { - Logger::info('Invalid JSON-LD signature from ' . $actor); + DI::logger()->info('Invalid JSON-LD signature from ' . $actor); } elseif ($ld_signer != $http_signer) { $signer[] = $ld_signer; } if (!empty($ld_signer && ($actor == $http_signer))) { - Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer); + DI::logger()->info('The HTTP and the JSON-LD signature belong to ' . $ld_signer); $trust_source = true; } elseif (!empty($ld_signer)) { - Logger::info('JSON-LD signature is signed by ' . $ld_signer); + DI::logger()->info('JSON-LD signature is signed by ' . $ld_signer); $trust_source = true; } elseif ($actor == $http_signer) { - Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.'); + DI::logger()->info('Bad JSON-LD signature, but HTTP signer fits the actor.'); $trust_source = true; } else { - Logger::info('Invalid JSON-LD signature and the HTTP signer is different.'); + DI::logger()->info('Invalid JSON-LD signature and the HTTP signer is different.'); $trust_source = false; } } elseif ($actor == $http_signer) { - Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.'); + DI::logger()->info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.'); $trust_source = true; } else { - Logger::info('No JSON-LD signature, different actor.'); + DI::logger()->info('No JSON-LD signature, different actor.'); $trust_source = false; } @@ -196,7 +195,7 @@ class Receiver { $type = JsonLD::fetchElement($activity, '@type'); if (!$type) { - Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]); + DI::logger()->notice('Empty type', ['activity' => $activity, 'actor' => $actor]); return; } @@ -204,43 +203,43 @@ class Receiver $object_id = JsonLD::fetchElement($activity, 'as:object', '@id'); if (empty($object_id)) { - Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]); + DI::logger()->notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]); return; } $contact = Contact::getByURL($actor); if (empty($contact)) { - Logger::info('Relay contact not found', ['actor' => $actor]); + DI::logger()->info('Relay contact not found', ['actor' => $actor]); return; } if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) { - Logger::notice('Relay is no sharer', ['actor' => $actor]); + DI::logger()->notice('Relay is no sharer', ['actor' => $actor]); return; } - Logger::debug('Process post from relay server', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]); + DI::logger()->debug('Process post from relay server', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]); $item_id = Item::searchByLink($object_id); if ($item_id) { - Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]); + DI::logger()->info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]); return; } if (!DI::config()->get('system', 'decoupled_receiver')) { $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY); if (!empty($id)) { - Logger::notice('Relayed message is fetched', ['result' => $id, 'id' => $object_id, 'actor' => $actor]); + DI::logger()->notice('Relayed message is fetched', ['result' => $id, 'id' => $object_id, 'actor' => $actor]); } else { - Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor, 'activity' => $activity]); + DI::logger()->notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor, 'activity' => $activity]); } } elseif (!Fetch::hasWorker($object_id)) { - Logger::notice('Fetching is done by worker.', ['id' => $object_id]); + DI::logger()->notice('Fetching is done by worker.', ['id' => $object_id]); Fetch::add($object_id); $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $object_id, [], $actor, self::COMPLETION_RELAY); Fetch::setWorkerId($object_id, $wid); } else { - Logger::debug('Activity will already be fetched via a worker.', ['url' => $object_id]); + DI::logger()->debug('Activity will already be fetched via a worker.', ['url' => $object_id]); } } @@ -334,25 +333,25 @@ class Receiver $fetched_type = JsonLD::fetchElement($object, '@type'); if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) { - Logger::info('Activity had been fetched successfully', ['id' => $id]); + DI::logger()->info('Activity had been fetched successfully', ['id' => $id]); $trust_source = true; $activity = $object; } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) { - Logger::info('Fetched data is the object instead of the activity', ['id' => $id]); + DI::logger()->info('Fetched data is the object instead of the activity', ['id' => $id]); $trust_source = true; unset($object['@context']); $activity['as:object'] = $object; } else { - Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]); + DI::logger()->info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]); } } else { - Logger::info('Activity could not been fetched', ['id' => $id]); + DI::logger()->info('Activity could not been fetched', ['id' => $id]); } } $actor = JsonLD::fetchElement($activity, 'as:actor', '@id'); if (empty($actor)) { - Logger::info('Empty actor', ['activity' => $activity]); + DI::logger()->info('Empty actor', ['activity' => $activity]); return []; } @@ -388,12 +387,12 @@ class Receiver $object_id = JsonLD::fetchElement($activity, 'as:object', '@id'); if (empty($object_id)) { - Logger::info('No object found'); + DI::logger()->info('No object found'); return []; } if (!is_string($object_id)) { - Logger::info('Invalid object id', ['object' => $object_id]); + DI::logger()->info('Invalid object id', ['object' => $object_id]); return []; } @@ -424,7 +423,7 @@ class Receiver // We can receive "#emojiReaction" when fetching content from Hubzilla systems $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $fetch_uid); if (empty($object_data)) { - Logger::info("Object data couldn't be processed"); + DI::logger()->info("Object data couldn't be processed"); return []; } @@ -498,7 +497,7 @@ class Receiver $account = Contact::selectFirstAccount(['platform'], ['nurl' => Strings::normaliseLink($actor)]); $platform = $account['platform'] ?? ''; - Logger::info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]); + DI::logger()->info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]); return $object_data; } @@ -571,7 +570,7 @@ class Receiver } $object_data['directmessage'] = true; - Logger::debug('Got Misskey Chat'); + DI::logger()->debug('Got Misskey Chat'); return $object_data; } @@ -612,23 +611,23 @@ class Receiver { $type = JsonLD::fetchElement($activity, '@type'); if (!$type) { - Logger::info('Empty type', ['activity' => $activity]); + DI::logger()->info('Empty type', ['activity' => $activity]); return true; } if (!DI::config()->get('system', 'process_view') && ($type == 'as:View')) { - Logger::info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]); + DI::logger()->info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]); return true; } if (!JsonLD::fetchElement($activity, 'as:object', '@id')) { - Logger::info('Empty object', ['activity' => $activity]); + DI::logger()->info('Empty object', ['activity' => $activity]); return true; } $actor = JsonLD::fetchElement($activity, 'as:actor', '@id'); if ($actor === null || $actor === '') { - Logger::info('Empty actor', ['activity' => $activity]); + DI::logger()->info('Empty actor', ['activity' => $activity]); return true; } @@ -641,7 +640,7 @@ class Receiver if (!empty($published) && $object_id !== null && in_array($type, ['as:Create', 'as:Update']) && in_array($object_type, self::CONTENT_TYPES) && ($push || ($completion != self::COMPLETION_MANUAL)) && DI::contentItem()->isTooOld($published) && !Post::exists(['uri' => $object_id])) { - Logger::debug('Activity is too old. It will not be processed', ['push' => $push, 'completion' => $completion, 'type' => $type, 'object-type' => $object_type, 'published' => $published, 'id' => $id, 'object-id' => $object_id]); + DI::logger()->debug('Activity is too old. It will not be processed', ['push' => $push, 'completion' => $completion, 'type' => $type, 'object-type' => $object_type, 'published' => $published, 'id' => $id, 'object-id' => $object_id]); return true; } } else { @@ -665,22 +664,22 @@ class Receiver if (($type == 'as:Announce') && !empty($object_type) && !in_array($object_type, self::CONTENT_TYPES) && self::isGroup($actor)) { $object_object_type = JsonLD::fetchElement($activity['as:object']['as:object'] ?? [], '@type'); if (in_array($object_type, ['as:Create']) && in_array($object_object_type, self::CONTENT_TYPES)) { - Logger::debug('Replace "create" activity with inner object', ['type' => $object_type, 'object_type' => $object_object_type]); + DI::logger()->debug('Replace "create" activity with inner object', ['type' => $object_type, 'object_type' => $object_object_type]); $activity['as:object'] = $activity['as:object']['as:object']; } elseif (in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) { - Logger::debug('Change announced activity to activity', ['type' => $object_type]); + DI::logger()->debug('Change announced activity to activity', ['type' => $object_type]); $original_actor = $actor; $type = $object_type; $activity = $activity['as:object']; } else { - Logger::info('Unhandled announced activity', ['type' => $object_type, 'object_type' => $object_object_type]); + DI::logger()->info('Unhandled announced activity', ['type' => $object_type, 'object_type' => $object_object_type]); } } // $trust_source is called by reference and is set to true if the content was retrieved successfully $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source, $original_actor); if (empty($object_data)) { - Logger::info('No object data found', ['activity' => $activity]); + DI::logger()->info('No object data found', ['activity' => $activity]); return true; } @@ -712,13 +711,13 @@ class Receiver if (($type == 'as:Create') && $trust_source && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE])) { if (self::hasArrived($object_data['object_id'])) { - Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]); + DI::logger()->info('The activity already arrived.', ['id' => $object_data['object_id']]); return true; } self::addArrivedId($object_data['object_id']); if (Queue::exists($object_data['object_id'], $type)) { - Logger::info('The activity is already added.', ['id' => $object_data['object_id']]); + DI::logger()->info('The activity is already added.', ['id' => $object_data['object_id']]); return true; } } elseif (($type == 'as:Create') && $trust_source && !self::hasArrived($object_data['object_id'])) { @@ -735,7 +734,7 @@ class Receiver } if (!$trust_source) { - Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]); + DI::logger()->info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]); return true; } @@ -743,11 +742,11 @@ class Receiver if (Queue::isProcessable($object_data['entry-id'])) { // We delay by 5 seconds to allow to accumulate all receivers $delayed = date(DateTimeFormat::MYSQL, time() + 5); - Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]); + DI::logger()->debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]); $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']); Queue::setWorkerId($object_data['entry-id'], $wid); } else { - Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]); + DI::logger()->debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]); } return false; } @@ -829,15 +828,15 @@ class Receiver if (in_array($object_data['object_type'], self::CONTENT_TYPES)) { if (!Processor::alreadyKnown($object_data['object_id'], '')) { if (ActivityPub\Processor::fetchMissingActivity($object_data['object_id'], [], $object_data['actor'], self::COMPLETION_ANNOUNCE, $uid)) { - Logger::debug('Created announced id', ['uid' => $uid, 'id' => $object_data['object_id']]); + DI::logger()->debug('Created announced id', ['uid' => $uid, 'id' => $object_data['object_id']]); Queue::remove($object_data); } else { - Logger::debug('Announced id was not created', ['uid' => $uid, 'id' => $object_data['object_id']]); + DI::logger()->debug('Announced id was not created', ['uid' => $uid, 'id' => $object_data['object_id']]); Queue::remove($object_data); return true; } } else { - Logger::info('Announced id already exists', ['uid' => $uid, 'id' => $object_data['object_id']]); + DI::logger()->info('Announced id already exists', ['uid' => $uid, 'id' => $object_data['object_id']]); Queue::remove($object_data); } @@ -957,7 +956,7 @@ class Receiver if (!empty($object_data['object_actor'])) { ActivityPub\Processor::acceptFollowUser($object_data); } else { - Logger::notice('Unhandled "accept follow" message.', ['object_data' => $object_data]); + DI::logger()->notice('Unhandled "accept follow" message.', ['object_data' => $object_data]); } } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) { ActivityPub\Processor::createActivity($object_data, Activity::ATTEND); @@ -1047,7 +1046,7 @@ class Receiver break; default: - Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']); + DI::logger()->info('Unknown activity: ' . $type . ' ' . $object_data['object_type']); return false; } return true; @@ -1085,7 +1084,7 @@ class Receiver $tempfile = tempnam(System::getTempPath(), $file); file_put_contents($tempfile, json_encode(['activity' => $activity, 'body' => $body, 'uid' => $uid, 'trust_source' => $trust_source, 'push' => $push, 'signer' => $signer, 'object_data' => $object_data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); - Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]); + DI::logger()->notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]); } /** @@ -1135,7 +1134,7 @@ class Receiver foreach ($receiver_list as $receiver) { if ($receiver == 'Public') { - Logger::warning('Not compacted public collection found', ['activity' => $activity]); + DI::logger()->warning('Not compacted public collection found', ['activity' => $activity]); $receiver = ActivityPub::PUBLIC_COLLECTION; } if ($receiver == self::PUBLIC_COLLECTION) { @@ -1186,9 +1185,9 @@ class Receiver $profile = APContact::getByURL($actor); $followers = $profile['followers'] ?? ''; $isGroup = ($profile['type'] ?? '') == 'Group'; - Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]); + DI::logger()->info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]); } else { - Logger::info('Empty actor', ['activity' => $activity]); + DI::logger()->info('Empty actor', ['activity' => $activity]); $followers = ''; $isGroup = false; } @@ -1307,11 +1306,11 @@ class Receiver if (empty($receivers) && $fetch_unlisted && Contact::isPlatform($actor, 'birdsitelive')) { $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL]; $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL]; - Logger::notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]); + DI::logger()->notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]); } elseif (empty($receivers) && in_array($activity_type, ['as:Delete', 'as:Undo'])) { $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL]; } elseif (empty($receivers)) { - Logger::notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => $activity_type]); + DI::logger()->notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => $activity_type]); } return $receivers; @@ -1408,7 +1407,7 @@ class Receiver // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field. $objectId = Item::getURIByLink($object_data['object_id']); if (!empty($objectId) && ($object_data['object_id'] != $objectId)) { - Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]); + DI::logger()->notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]); $object_data['object_id'] = $objectId; } } @@ -1437,37 +1436,37 @@ class Receiver $data = Processor::fetchCachedActivity($object_id, $uid); if (!empty($data)) { $object = JsonLD::compact($data); - Logger::info('Fetched content for ' . $object_id); + DI::logger()->info('Fetched content for ' . $object_id); } else { - Logger::info('Empty content for ' . $object_id . ', check if content is available locally.'); + DI::logger()->info('Empty content for ' . $object_id . ', check if content is available locally.'); $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]); if (!DBA::isResult($item)) { - Logger::info('Object with url ' . $object_id . ' was not found locally.'); + DI::logger()->info('Object with url ' . $object_id . ' was not found locally.'); return false; } - Logger::info('Using already stored item for url ' . $object_id); + DI::logger()->info('Using already stored item for url ' . $object_id); $data = ActivityPub\Transmitter::createNote($item); $object = JsonLD::compact($data); } $id = JsonLD::fetchElement($object, '@id'); if (empty($id)) { - Logger::info('Empty id'); + DI::logger()->info('Empty id'); return false; } if ($id != $object_id) { - Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]); + DI::logger()->info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]); return false; } } else { - Logger::info('Using original object for url ' . $object_id); + DI::logger()->info('Using original object for url ' . $object_id); } $type = JsonLD::fetchElement($object, '@type'); if (empty($type)) { - Logger::info('Empty type'); + DI::logger()->info('Empty type'); return false; } @@ -1481,7 +1480,7 @@ class Receiver return $object_data; } - Logger::info('Unhandled object type: ' . $type); + DI::logger()->info('Unhandled object type: ' . $type); return false; } @@ -1965,7 +1964,7 @@ class Receiver // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field. $replyToId = Item::getURIByLink($object_data['reply-to-id']); if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) { - Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]); + DI::logger()->notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]); $object_data['reply-to-id'] = $replyToId; } } diff --git a/src/Protocol/ActivityPub/Transmitter.php b/src/Protocol/ActivityPub/Transmitter.php index 1f03bd2118..c183b5313b 100644 --- a/src/Protocol/ActivityPub/Transmitter.php +++ b/src/Protocol/ActivityPub/Transmitter.php @@ -12,7 +12,6 @@ use Friendica\Content\Feature; use Friendica\Content\Smilies; use Friendica\Content\Text\BBCode; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; @@ -908,14 +907,14 @@ class Transmitter { $tags = Tag::getByURIId($uri_id, [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC, Tag::AUDIENCE]); if (empty($tags)) { - Logger::debug('No receivers found', ['uri-id' => $uri_id]); + DI::logger()->debug('No receivers found', ['uri-id' => $uri_id]); $post = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $uri_id, 'origin' => true]); if (!empty($post)) { ActivityPub\Transmitter::storeReceiversForItem($post); $tags = Tag::getByURIId($uri_id, [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC, Tag::AUDIENCE]); - Logger::debug('Receivers are created', ['uri-id' => $uri_id, 'receivers' => count($tags)]); + DI::logger()->debug('Receivers are created', ['uri-id' => $uri_id, 'receivers' => count($tags)]); } else { - Logger::debug('Origin item not found', ['uri-id' => $uri_id]); + DI::logger()->debug('Origin item not found', ['uri-id' => $uri_id]); } } @@ -1328,7 +1327,7 @@ class Transmitter if (!$api_mode) { $condition['parent-network'] = Protocol::NATIVE_SUPPORT; } - Logger::info('Fetching activity', $condition); + DI::logger()->info('Fetching activity', $condition); $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition); if (!DBA::isResult($item)) { return false; @@ -1351,7 +1350,7 @@ class Transmitter if (!$api_mode) { $condition['parent-network'] = Protocol::NATIVE_SUPPORT; } - Logger::info('Fetching activity', $condition); + DI::logger()->info('Fetching activity', $condition); $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition, ['order' => ['uid' => true]]); if (!DBA::isResult($item)) { return false; @@ -1375,17 +1374,17 @@ class Transmitter $data = Post\Activity::getByURIId($item['uri-id']); if (!$item['origin'] && !empty($data)) { if (!$object_mode) { - Logger::info('Return stored conversation', ['item' => $item['id']]); + DI::logger()->info('Return stored conversation', ['item' => $item['id']]); return $data; } elseif (!empty($data['object'])) { - Logger::info('Return stored conversation object', ['item' => $item['id']]); + DI::logger()->info('Return stored conversation object', ['item' => $item['id']]); return $data['object']; } } } if (!$api_mode && !$item['deleted'] && !$item['origin']) { - Logger::debug('Post is not ours and is not stored', ['id' => $item['id'], 'uri-id' => $item['uri-id']]); + DI::logger()->debug('Post is not ours and is not stored', ['id' => $item['id'], 'uri-id' => $item['uri-id']]); return false; } @@ -1467,7 +1466,7 @@ class Transmitter $uid = $item['uid']; } - Logger::info('Fetched activity', ['item' => $item['id'], 'uid' => $uid]); + DI::logger()->info('Fetched activity', ['item' => $item['id'], 'uid' => $uid]); // We only sign our own activities if (!$api_mode && !$object_mode && $item['origin']) { @@ -2118,7 +2117,7 @@ class Transmitter $signed = LDSignature::sign($data, $owner); - Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); + DI::logger()->info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); return HTTPSignature::transmit($signed, $inbox, $owner); } @@ -2146,7 +2145,7 @@ class Transmitter $signed = LDSignature::sign($data, $owner); - Logger::info('Deliver profile relocation for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); + DI::logger()->info('Deliver profile relocation for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); return HTTPSignature::transmit($signed, $inbox, $owner); } @@ -2161,7 +2160,7 @@ class Transmitter public static function sendProfileDeletion(array $owner, string $inbox): bool { if (empty($owner['uprvkey'])) { - Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $owner['uid']]); + DI::logger()->error('No private key for owner found, the deletion message cannot be processed.', ['user' => $owner['uid']]); return false; } @@ -2179,7 +2178,7 @@ class Transmitter $signed = LDSignature::sign($data, $owner); - Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); + DI::logger()->info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); return HTTPSignature::transmit($signed, $inbox, $owner); } @@ -2211,7 +2210,7 @@ class Transmitter $signed = LDSignature::sign($data, $owner); - Logger::info('Deliver profile update for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); + DI::logger()->info('Deliver profile update for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub'); return HTTPSignature::transmit($signed, $inbox, $owner); } @@ -2231,13 +2230,13 @@ class Transmitter { $profile = APContact::getByURL($target); if (empty($profile['inbox'])) { - Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); + DI::logger()->warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); return false; } $owner = User::getOwnerDataById($uid); if (empty($owner)) { - Logger::warning('No user found for actor, aborting', ['uid' => $uid]); + DI::logger()->warning('No user found for actor, aborting', ['uid' => $uid]); return false; } @@ -2255,7 +2254,7 @@ class Transmitter 'to' => [$profile['url']], ]; - Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid); + DI::logger()->info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid); $signed = LDSignature::sign($data, $owner); return HTTPSignature::transmit($signed, $profile['inbox'], $owner); @@ -2277,7 +2276,7 @@ class Transmitter { $profile = APContact::getByURL($target); if (empty($profile['inbox'])) { - Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); + DI::logger()->warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); return false; } @@ -2285,7 +2284,7 @@ class Transmitter // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account. $admin = User::getFirstAdmin(['uid']); if (!$admin) { - Logger::warning('No available admin user for transmission', ['target' => $target]); + DI::logger()->warning('No available admin user for transmission', ['target' => $target]); return false; } @@ -2297,7 +2296,7 @@ class Transmitter 'author-id' => Contact::getPublicIdByUserId($uid) ]; if (Post::exists($condition)) { - Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.'); + DI::logger()->info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.'); return false; } @@ -2313,7 +2312,7 @@ class Transmitter 'to' => [$profile['url']], ]; - Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid); + DI::logger()->info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid); $signed = LDSignature::sign($data, $owner); return HTTPSignature::transmit($signed, $profile['inbox'], $owner); @@ -2333,13 +2332,13 @@ class Transmitter { $profile = APContact::getByURL($target); if (empty($profile['inbox'])) { - Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); + DI::logger()->warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); return; } $owner = User::getOwnerDataById($uid); if (!$owner) { - Logger::notice('No user found for actor', ['uid' => $uid]); + DI::logger()->notice('No user found for actor', ['uid' => $uid]); return; } @@ -2358,7 +2357,7 @@ class Transmitter 'to' => [$profile['url']], ]; - Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id); + DI::logger()->debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id); $signed = LDSignature::sign($data, $owner); HTTPSignature::transmit($signed, $profile['inbox'], $owner); @@ -2378,7 +2377,7 @@ class Transmitter { $profile = APContact::getByURL($target); if (empty($profile['inbox'])) { - Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); + DI::logger()->warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); return false; } @@ -2397,7 +2396,7 @@ class Transmitter 'to' => [$profile['url']], ]; - Logger::debug('Sending reject to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); + DI::logger()->debug('Sending reject to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); $signed = LDSignature::sign($data, $owner); return HTTPSignature::transmit($signed, $profile['inbox'], $owner); @@ -2418,7 +2417,7 @@ class Transmitter { $profile = APContact::getByURL($target); if (empty($profile['inbox'])) { - Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); + DI::logger()->warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); return false; } @@ -2444,7 +2443,7 @@ class Transmitter 'to' => [$profile['url']], ]; - Logger::info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); + DI::logger()->info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); $signed = LDSignature::sign($data, $owner); return HTTPSignature::transmit($signed, $profile['inbox'], $owner); @@ -2465,7 +2464,7 @@ class Transmitter { $profile = APContact::getByURL($target); if (empty($profile['inbox'])) { - Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); + DI::logger()->warning('No inbox found for target', ['target' => $target, 'profile' => $profile]); return false; } @@ -2491,7 +2490,7 @@ class Transmitter 'to' => [$profile['url']], ]; - Logger::info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); + DI::logger()->info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); $signed = LDSignature::sign($data, $owner); return HTTPSignature::transmit($signed, $profile['inbox'], $owner); From 9306a56da0d23a01e9fb58dc9a3fe5e39834e742 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:47:34 +0000 Subject: [PATCH 35/91] Replace Logger with DI::logger() in Security classes --- src/Security/BasicAuth.php | 8 +++----- src/Security/OAuth.php | 12 ++++++------ src/Security/OpenWebAuth.php | 19 +++++++++---------- 3 files changed, 18 insertions(+), 21 deletions(-) diff --git a/src/Security/BasicAuth.php b/src/Security/BasicAuth.php index c5da5b9f72..a04e050c6a 100644 --- a/src/Security/BasicAuth.php +++ b/src/Security/BasicAuth.php @@ -9,12 +9,10 @@ namespace Friendica\Security; use Exception; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\User; use Friendica\Network\HTTPException\UnauthorizedException; -use Friendica\Util\DateTimeFormat; /** * Authentication via the basic auth method @@ -75,9 +73,9 @@ class BasicAuth $source = 'Twidere'; } - Logger::info('Unrecognized user-agent', ['http_user_agent' => $_SERVER['HTTP_USER_AGENT']]); + DI::logger()->info('Unrecognized user-agent', ['http_user_agent' => $_SERVER['HTTP_USER_AGENT']]); } else { - Logger::info('Empty user-agent'); + DI::logger()->info('Empty user-agent'); } if (empty($source)) { @@ -160,7 +158,7 @@ class BasicAuth if (!$do_login) { return 0; } - Logger::debug('Access denied', ['parameters' => $_SERVER]); + DI::logger()->debug('Access denied', ['parameters' => $_SERVER]); // Checking for commandline for the tests, we have to avoid to send a header if (DI::config()->get('system', 'basicauth') && (php_sapi_name() !== 'cli')) { header('WWW-Authenticate: Basic realm="Friendica"'); diff --git a/src/Security/OAuth.php b/src/Security/OAuth.php index d169cb7eab..d00d27b8d3 100644 --- a/src/Security/OAuth.php +++ b/src/Security/OAuth.php @@ -7,10 +7,10 @@ namespace Friendica\Security; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\Database; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Model\Contact; use Friendica\Model\User; use Friendica\Module\BaseApi; @@ -85,10 +85,10 @@ class OAuth $token = DBA::selectFirst('application-view', ['uid', 'id', 'name', 'website', 'created_at', 'read', 'write', 'follow', 'push'], $condition); if (!DBA::isResult($token)) { - Logger::notice('Token not found', $condition); + DI::logger()->notice('Token not found', $condition); return []; } - Logger::debug('Token found', $token); + DI::logger()->debug('Token found', $token); $user = User::getById($token['uid'], ['uid', 'parent-uid', 'last-activity', 'login_date']); if (!empty($user)) { @@ -125,14 +125,14 @@ class OAuth $application = DBA::selectFirst('application', [], $condition); if (!DBA::isResult($application)) { - Logger::warning('Application not found', $condition); + DI::logger()->warning('Application not found', $condition); return []; } // The redirect_uri could contain several URI that are separated by spaces or new lines. $uris = explode(' ', str_replace(["\n", "\r", "\t"], ' ', $application['redirect_uri'])); if (!in_array($redirect_uri, $uris)) { - Logger::warning('Redirection uri does not match', ['redirect_uri' => $redirect_uri, 'application-redirect_uri' => $application['redirect_uri']]); + DI::logger()->warning('Redirection uri does not match', ['redirect_uri' => $redirect_uri, 'application-redirect_uri' => $application['redirect_uri']]); return []; } @@ -191,7 +191,7 @@ class OAuth foreach ([BaseApi::SCOPE_READ, BaseApi::SCOPE_WRITE, BaseApi::SCOPE_FOLLOW, BaseApi::SCOPE_PUSH] as $scope) { if ($fields[$scope] && !$application[$scope]) { - Logger::warning('Requested token scope is not allowed for the application', ['token' => $fields, 'application' => $application]); + DI::logger()->warning('Requested token scope is not allowed for the application', ['token' => $fields, 'application' => $application]); } } diff --git a/src/Security/OpenWebAuth.php b/src/Security/OpenWebAuth.php index 5dd3cf1a27..8ca4baf5d1 100644 --- a/src/Security/OpenWebAuth.php +++ b/src/Security/OpenWebAuth.php @@ -9,7 +9,6 @@ namespace Friendica\Security; use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; @@ -61,31 +60,31 @@ class OpenWebAuth // Try to find the public contact entry of the visitor. $contact = Contact::getByURL($my_url, null, ['id', 'url', 'gsid']); if (empty($contact)) { - Logger::info('No contact record found', ['url' => $my_url]); + DI::logger()->info('No contact record found', ['url' => $my_url]); return; } if (DI::userSession()->getRemoteUserId() && DI::userSession()->getRemoteUserId() == $contact['id']) { - Logger::info('The visitor is already authenticated', ['url' => $my_url]); + DI::logger()->info('The visitor is already authenticated', ['url' => $my_url]); return; } $gserver = DBA::selectFirst('gserver', ['url', 'authredirect'], ['id' => $contact['gsid']]); if (empty($gserver) || empty($gserver['authredirect'])) { - Logger::info('No server record found or magic path not defined for server', ['id' => $contact['gsid'], 'gserver' => $gserver]); + DI::logger()->info('No server record found or magic path not defined for server', ['id' => $contact['gsid'], 'gserver' => $gserver]); return; } // Avoid endless loops $cachekey = 'zrlInit:' . $my_url; if (DI::cache()->get($cachekey)) { - Logger::info('URL ' . $my_url . ' already tried to authenticate.'); + DI::logger()->info('URL ' . $my_url . ' already tried to authenticate.'); return; } else { DI::cache()->set($cachekey, true, Duration::MINUTE); } - Logger::info('Not authenticated. Invoking reverse magic-auth', ['url' => $my_url]); + DI::logger()->info('Not authenticated. Invoking reverse magic-auth', ['url' => $my_url]); // Remove the "addr" parameter from the destination. It is later added as separate parameter again. $addr_request = 'addr=' . urlencode($addr); @@ -97,7 +96,7 @@ class OpenWebAuth if ($gserver['url'] != DI::baseUrl() && !strstr($dest, '/magic')) { $magic_path = $gserver['authredirect'] . '?f=&rev=1&owa=1&dest=' . $dest . '&' . $addr_request; - Logger::info('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path); + DI::logger()->info('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path); System::externalRedirect($magic_path); } } @@ -149,7 +148,7 @@ class OpenWebAuth DI::sysmsg()->addInfo(DI::l10n()->t('OpenWebAuth: %1$s welcomes %2$s', DI::baseUrl()->getHost(), $visitor['name'])); - Logger::info('OpenWebAuth: auth success from ' . $visitor['addr']); + DI::logger()->info('OpenWebAuth: auth success from ' . $visitor['addr']); } /** @@ -166,7 +165,7 @@ class OpenWebAuth // Try to find the public contact entry of the visitor. $cid = Contact::getIdForURL($handle); if (!$cid) { - Logger::info('Handle not found', ['handle' => $handle]); + DI::logger()->info('Handle not found', ['handle' => $handle]); return []; } @@ -186,7 +185,7 @@ class OpenWebAuth $appHelper->setContactId($visitor['id']); - Logger::info('Authenticated visitor', ['url' => $visitor['url']]); + DI::logger()->info('Authenticated visitor', ['url' => $visitor['url']]); return $visitor; } From 0ce0aa4d2c38ebfa94c9c2a4e009ef78030e7eee Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 12:53:09 +0000 Subject: [PATCH 36/91] Replace Logger with DI::logger() in Util classes --- src/Util/Crypto.php | 15 ++++----- src/Util/DateTimeFormat.php | 4 +-- src/Util/HTTPSignature.php | 65 ++++++++++++++++++------------------- src/Util/Images.php | 11 +++---- src/Util/JsonLD.php | 27 ++++++++------- src/Util/LDSignature.php | 4 +-- src/Util/Network.php | 23 +++++++------ src/Util/ParseUrl.php | 39 +++++++++++----------- src/Util/Strings.php | 4 +-- src/Util/XML.php | 16 ++++----- 10 files changed, 101 insertions(+), 107 deletions(-) diff --git a/src/Util/Crypto.php b/src/Util/Crypto.php index 8113697639..da4645ea0e 100644 --- a/src/Util/Crypto.php +++ b/src/Util/Crypto.php @@ -8,7 +8,6 @@ namespace Friendica\Util; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\DI; use phpseclib3\Crypt\PublicKeyLoader; @@ -27,7 +26,7 @@ class Crypto public static function rsaSign($data, $key, $alg = 'sha256') { if (empty($key)) { - Logger::warning('Empty key parameter'); + DI::logger()->warning('Empty key parameter'); } openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg)); return $sig; @@ -43,7 +42,7 @@ class Crypto public static function rsaVerify($data, $sig, $key, $alg = 'sha256') { if (empty($key)) { - Logger::warning('Empty key parameter'); + DI::logger()->warning('Empty key parameter'); } return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg)); } @@ -80,7 +79,7 @@ class Crypto $result = openssl_pkey_new($openssl_options); if (empty($result)) { - Logger::notice('new_keypair: failed'); + DI::logger()->notice('new_keypair: failed'); return false; } @@ -161,7 +160,7 @@ class Crypto private static function encapsulateOther($data, $pubkey, $alg) { if (!$pubkey) { - Logger::notice('no key. data: '.$data); + DI::logger()->notice('no key. data: '.$data); } $fn = 'encrypt' . strtoupper($alg); if (method_exists(__CLASS__, $fn)) { @@ -173,7 +172,7 @@ class Crypto // log the offending call so we can track it down if (!openssl_public_encrypt($key, $k, $pubkey)) { $x = debug_backtrace(); - Logger::notice('RSA failed', ['trace' => $x[0]]); + DI::logger()->notice('RSA failed', ['trace' => $x[0]]); } $result['alg'] = $alg; @@ -203,7 +202,7 @@ class Crypto private static function encapsulateAes($data, $pubkey) { if (!$pubkey) { - Logger::notice('aes_encapsulate: no key. data: ' . $data); + DI::logger()->notice('aes_encapsulate: no key. data: ' . $data); } $key = random_bytes(32); @@ -214,7 +213,7 @@ class Crypto // log the offending call so we can track it down if (!openssl_public_encrypt($key, $k, $pubkey)) { $x = debug_backtrace(); - Logger::notice('aes_encapsulate: RSA failed.', ['data' => $x[0]]); + DI::logger()->notice('aes_encapsulate: RSA failed.', ['data' => $x[0]]); } $result['alg'] = 'aes256cbc'; diff --git a/src/Util/DateTimeFormat.php b/src/Util/DateTimeFormat.php index a8a900fd36..3e10eb1b53 100644 --- a/src/Util/DateTimeFormat.php +++ b/src/Util/DateTimeFormat.php @@ -7,10 +7,10 @@ namespace Friendica\Util; -use Friendica\Core\Logger; use DateTime; use DateTimeZone; use Exception; +use Friendica\DI; /** * Temporal class @@ -140,7 +140,7 @@ class DateTimeFormat try { $d = new DateTime(self::fix($s), $from_obj); } catch (\Throwable $e) { - Logger::warning('DateTimeFormat::convert: exception: ' . $e->getMessage()); + DI::logger()->warning('DateTimeFormat::convert: exception: ' . $e->getMessage()); $d = new DateTime('now', $from_obj); } } diff --git a/src/Util/HTTPSignature.php b/src/Util/HTTPSignature.php index 5f668255ca..a544119616 100644 --- a/src/Util/HTTPSignature.php +++ b/src/Util/HTTPSignature.php @@ -7,7 +7,6 @@ namespace Friendica\Util; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -72,7 +71,7 @@ class HTTPSignature $sig_block = self::parseSigheader($headers['authorization']); if (!$sig_block) { - Logger::notice('no signature provided.'); + DI::logger()->notice('no signature provided.'); return $result; } @@ -102,7 +101,7 @@ class HTTPSignature $key = $key($sig_block['keyId']); } - Logger::info('Got keyID ' . $sig_block['keyId']); + DI::logger()->info('Got keyID ' . $sig_block['keyId']); if (!$key) { return $result; @@ -110,7 +109,7 @@ class HTTPSignature $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm); - Logger::info('verified: ' . $x); + DI::logger()->info('verified: ' . $x); if (!$x) { return $result; @@ -293,7 +292,7 @@ class HTTPSignature $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'), HttpClientRequest::ACTIVITYPUB); $return_code = $postResult->getReturnCode(); - Logger::info('Transmit to ' . $target . ' returned ' . $return_code); + DI::logger()->info('Transmit to ' . $target . ' returned ' . $return_code); self::setInboxStatus($target, ($return_code >= 200) && ($return_code <= 299)); @@ -327,7 +326,7 @@ class HTTPSignature return false; } - Logger::debug('Process directly', ['uid' => $uid, 'target' => $target, 'type' => $type]); + DI::logger()->debug('Process directly', ['uid' => $uid, 'target' => $target, 'type' => $type]); return Receiver::routeActivities($object_data, $type, true, true, $uid); } @@ -371,7 +370,7 @@ class HTTPSignature try { $postResult = self::post($data, $target, $owner); } 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_code = $postResult->getReturnCode(); @@ -402,7 +401,7 @@ class HTTPSignature $status = DBA::selectFirst('inbox-status', [], ['url' => $url]); if (empty($status)) { - Logger::warning('Unable to insert inbox-status row', $insertFields); + DI::logger()->warning('Unable to insert inbox-status row', $insertFields); return; } } @@ -476,12 +475,12 @@ class HTTPSignature try { $curlResult = self::fetchRaw($request, $uid); } catch (\Exception $exception) { - Logger::notice('Error fetching url', ['url' => $request, 'exception' => $exception]); + DI::logger()->notice('Error fetching url', ['url' => $request, 'exception' => $exception]); return []; } if (!$curlResult->isSuccess() || empty($curlResult->getBodyString())) { - Logger::debug('Fetching was unsuccessful', ['url' => $request, 'return-code' => $curlResult->getReturnCode(), 'error-number' => $curlResult->getErrorNumber(), 'error' => $curlResult->getError()]); + DI::logger()->debug('Fetching was unsuccessful', ['url' => $request, 'return-code' => $curlResult->getReturnCode(), 'error-number' => $curlResult->getErrorNumber(), 'error' => $curlResult->getError()]); return []; } @@ -510,7 +509,7 @@ class HTTPSignature } if (current(explode(';', $contentType)) == 'application/json') { - Logger::notice('Unexpected content type, possibly from a remote system that is not standard compliant.', ['content-type' => $contentType, 'url' => $url]); + DI::logger()->notice('Unexpected content type, possibly from a remote system that is not standard compliant.', ['content-type' => $contentType, 'url' => $url]); } return false; } @@ -572,7 +571,7 @@ class HTTPSignature } $return_code = $curlResult->getReturnCode(); - Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code); + DI::logger()->info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code); return $curlResult; } @@ -587,14 +586,14 @@ class HTTPSignature public static function getKeyIdContact(array $http_headers): array { if (empty($http_headers['HTTP_SIGNATURE'])) { - Logger::debug('No HTTP_SIGNATURE header', ['header' => $http_headers]); + DI::logger()->debug('No HTTP_SIGNATURE header', ['header' => $http_headers]); return []; } $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']); if (empty($sig_block['keyId'])) { - Logger::debug('No keyId', ['sig_block' => $sig_block]); + DI::logger()->debug('No keyId', ['sig_block' => $sig_block]); return []; } @@ -614,14 +613,14 @@ class HTTPSignature public static function getSigner(string $content, array $http_headers) { if (empty($http_headers['HTTP_SIGNATURE'])) { - Logger::debug('No HTTP_SIGNATURE header'); + DI::logger()->debug('No HTTP_SIGNATURE header'); return false; } if (!empty($content)) { $object = json_decode($content, true); if (empty($object)) { - Logger::info('No object'); + DI::logger()->info('No object'); return false; } @@ -659,7 +658,7 @@ class HTTPSignature } if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) { - Logger::info('No headers or keyId'); + DI::logger()->info('No headers or keyId'); return false; } @@ -668,13 +667,13 @@ class HTTPSignature if (array_key_exists($h, $headers)) { $signed_data .= $h . ': ' . $headers[$h] . "\n"; } else { - Logger::info('Requested header field not found', ['field' => $h, 'header' => $headers]); + DI::logger()->info('Requested header field not found', ['field' => $h, 'header' => $headers]); } } $signed_data = rtrim($signed_data, "\n"); if (empty($signed_data)) { - Logger::info('Signed data is empty'); + DI::logger()->info('Signed data is empty'); return false; } @@ -697,18 +696,18 @@ class HTTPSignature } if (empty($algorithm)) { - Logger::info('No algorithm'); + DI::logger()->info('No algorithm'); return false; } $key = self::fetchKey($sig_block['keyId'], $actor); if (empty($key)) { - Logger::info('Empty key'); + DI::logger()->info('Empty key'); return false; } if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) { - Logger::info('Actor is a tombstone', ['key' => $key]); + DI::logger()->info('Actor is a tombstone', ['key' => $key]); if (!Contact::isLocal($key['url'])) { // We now delete everything that we possibly knew from this actor @@ -718,12 +717,12 @@ class HTTPSignature } if (empty($key['pubkey'])) { - Logger::info('Empty pubkey'); + DI::logger()->info('Empty pubkey'); return false; } if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) { - Logger::info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]); + DI::logger()->info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]); return false; } @@ -742,7 +741,7 @@ class HTTPSignature /// @todo add all hashes from the rfc if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) { - Logger::info('Digest does not match'); + DI::logger()->info('Digest does not match'); return false; } @@ -769,23 +768,23 @@ class HTTPSignature // Calculate with a grace period of 60 seconds to avoid slight time differences between the servers if (($created - 60) > $current) { - Logger::notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); + DI::logger()->notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); return false; } if ($current > $expired) { - Logger::notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); + DI::logger()->notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); return false; } - Logger::debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); + DI::logger()->debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); $hasGoodSignedContent = true; } // Check the content-length when it is part of the signed data if (in_array('content-length', $sig_block['headers'])) { if (strlen($content) != $headers['content-length']) { - Logger::info('Content length does not match'); + DI::logger()->info('Content length does not match'); return false; } } @@ -793,7 +792,7 @@ class HTTPSignature // Ensure that the authentication had been done with some content // Without this check someone could authenticate with fakeable data if (!$hasGoodSignedContent) { - Logger::info('No good signed content'); + DI::logger()->info('No good signed content'); return false; } @@ -815,17 +814,17 @@ class HTTPSignature $profile = APContact::getByURL($url); if (!empty($profile)) { - Logger::info('Taking key from id', ['id' => $id]); + DI::logger()->info('Taking key from id', ['id' => $id]); return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']]; } elseif ($url != $actor) { $profile = APContact::getByURL($actor); if (!empty($profile)) { - Logger::info('Taking key from actor', ['actor' => $actor]); + DI::logger()->info('Taking key from actor', ['actor' => $actor]); return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']]; } } - Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]); + DI::logger()->notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]); return []; } } diff --git a/src/Util/Images.php b/src/Util/Images.php index f478a0b8b2..804ba73877 100644 --- a/src/Util/Images.php +++ b/src/Util/Images.php @@ -8,7 +8,6 @@ namespace Friendica\Util; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Photo; use Friendica\Network\HTTPClient\Client\HttpClientAccept; @@ -103,7 +102,7 @@ class Images } } - Logger::debug('Undetected mimetype', ['mimetype' => $mimetype]); + DI::logger()->debug('Undetected mimetype', ['mimetype' => $mimetype]); return 0; } @@ -116,7 +115,7 @@ class Images public static function getExtensionByImageType(int $type): string { if (empty($type)) { - Logger::debug('Invalid image type', ['type' => $type]); + DI::logger()->debug('Invalid image type', ['type' => $type]); return ''; } @@ -201,7 +200,7 @@ class Images return $image['mime']; } - Logger::debug('Undetected mime type', ['image' => $image, 'size' => strlen($image_data)]); + DI::logger()->debug('Undetected mime type', ['image' => $image, 'size' => strlen($image_data)]); return ''; } @@ -284,7 +283,7 @@ class Images } } - Logger::debug('Unhandled extension', ['filename' => $filename, 'extension' => $ext]); + DI::logger()->debug('Unhandled extension', ['filename' => $filename, 'extension' => $ext]); return ''; } @@ -345,7 +344,7 @@ class Images try { $img_str = DI::httpClient()->fetch($url, HttpClientAccept::IMAGE, 4, '', HttpClientRequest::MEDIAVERIFIER); } catch (\Exception $exception) { - Logger::notice('Image is invalid', ['url' => $url, 'exception' => $exception]); + DI::logger()->notice('Image is invalid', ['url' => $url, 'exception' => $exception]); return []; } } diff --git a/src/Util/JsonLD.php b/src/Util/JsonLD.php index fc91bcd0b6..833de559d7 100644 --- a/src/Util/JsonLD.php +++ b/src/Util/JsonLD.php @@ -8,7 +8,6 @@ namespace Friendica\Util; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Exception; use Friendica\Core\System; use Friendica\DI; @@ -72,7 +71,7 @@ class JsonLD $url = DI::basePath() . '/static/apschema.jsonld'; break; default: - Logger::info('Got url', ['url' => $url]); + DI::logger()->info('Got url', ['url' => $url]); break; } } @@ -89,7 +88,7 @@ class JsonLD } if ($recursion > 5) { - Logger::error('jsonld bomb detected at: ' . $url); + DI::logger()->error('jsonld bomb detected at: ' . $url); System::exit(); } @@ -127,9 +126,9 @@ class JsonLD $messages[] = $currentException->getMessage(); } while ($currentException = $currentException->getPrevious()); - Logger::notice('JsonLD normalize error', ['messages' => $messages]); - Logger::info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]); - Logger::debug('JsonLD normalize error', ['jsonobj' => $jsonobj]); + DI::logger()->notice('JsonLD normalize error', ['messages' => $messages]); + DI::logger()->info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]); + DI::logger()->debug('JsonLD normalize error', ['jsonobj' => $jsonobj]); } return $normalized; @@ -176,18 +175,18 @@ class JsonLD $compacted = jsonld_compact($jsonobj, $context); } catch (Exception $e) { $compacted = false; - Logger::notice('compacting error', ['msg' => $e->getMessage(), 'previous' => $e->getPrevious(), 'line' => $e->getLine()]); + DI::logger()->notice('compacting error', ['msg' => $e->getMessage(), 'previous' => $e->getPrevious(), 'line' => $e->getLine()]); if ($logfailed && DI::config()->get('debug', 'ap_log_failure')) { $tempfile = tempnam(System::getTempPath(), 'failed-jsonld'); file_put_contents($tempfile, json_encode(['json' => $orig_json, 'msg' => $e->getMessage(), 'previous' => $e->getPrevious()], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); - Logger::notice('Failed message stored', ['file' => $tempfile]); + DI::logger()->notice('Failed message stored', ['file' => $tempfile]); } } $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true); if ($json === false) { - Logger::notice('JSON encode->decode failed', ['orig_json' => $orig_json, 'compacted' => $compacted]); + DI::logger()->notice('JSON encode->decode failed', ['orig_json' => $orig_json, 'compacted' => $compacted]); $json = []; } @@ -212,7 +211,7 @@ class JsonLD // Workaround for servers with missing context // See issue https://github.com/nextcloud/social/issues/330 if (!in_array('https://w3id.org/security/v1', $json['@context'])) { - Logger::debug('Missing security context'); + DI::logger()->debug('Missing security context'); $json['@context'][] = 'https://w3id.org/security/v1'; } } @@ -220,16 +219,16 @@ class JsonLD // Issue 14448: Peertube transmits an unexpected type and schema URL. array_walk_recursive($json['@context'], function (&$value, $key) { if ($key == '@type' && $value == '@json') { - Logger::debug('"@json" converted to "@id"'); + DI::logger()->debug('"@json" converted to "@id"'); $value = '@id'; } if ($key == 'sc' && $value == 'http://schema.org/') { - Logger::debug('schema.org path fixed'); + DI::logger()->debug('schema.org path fixed'); $value = 'http://schema.org#'; } // Issue 14630: Wordpress Event Bridge uses a URL that cannot be retrieved if (is_int($key) && $value == 'https://schema.org/') { - Logger::debug('https schema.org path fixed'); + DI::logger()->debug('https schema.org path fixed'); $value = 'https://schema.org/docs/jsonldcontext.json#'; } }); @@ -237,7 +236,7 @@ class JsonLD // Bookwyrm transmits "id" fields with "null", which isn't allowed. array_walk_recursive($json, function (&$value, $key) { if ($key == 'id' && is_null($value)) { - Logger::debug('Fixed null id'); + DI::logger()->debug('Fixed null id'); $value = ''; } }); diff --git a/src/Util/LDSignature.php b/src/Util/LDSignature.php index 9d0c08d33b..8728915dd0 100644 --- a/src/Util/LDSignature.php +++ b/src/Util/LDSignature.php @@ -7,7 +7,7 @@ namespace Friendica\Util; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Model\APContact; /** @@ -55,7 +55,7 @@ class LDSignature $dhash = self::hash(self::signableData($data)); $x = Crypto::rsaVerify($ohash . $dhash, base64_decode($data['signature']['signatureValue']), $pubkey); - Logger::info('LD-verify', ['verified' => (int)$x, 'actor' => $profile['url']]); + DI::logger()->info('LD-verify', ['verified' => (int)$x, 'actor' => $profile['url']]); if (empty($x)) { return false; diff --git a/src/Util/Network.php b/src/Util/Network.php index 60f4bbab23..a9c14779c7 100644 --- a/src/Util/Network.php +++ b/src/Util/Network.php @@ -8,7 +8,6 @@ namespace Friendica\Util; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Contact; use Friendica\Network\HTTPClient\Client\HttpClientAccept; @@ -79,13 +78,13 @@ class Network try { $curlResult = DI::httpClient()->get($url, HttpClientAccept::DEFAULT, $options); } catch (\Exception $e) { - Logger::notice('Got exception', ['code' => $e->getCode(), 'message' => $e->getMessage()]); + DI::logger()->notice('Got exception', ['code' => $e->getCode(), 'message' => $e->getMessage()]); return false; } } if (!$curlResult->isSuccess()) { - Logger::notice('Url not reachable', ['host' => $host, 'url' => $url]); + DI::logger()->notice('Url not reachable', ['host' => $host, 'url' => $url]); return false; } elseif ($curlResult->isRedirectUrl()) { $url = $curlResult->getRedirectUrl(); @@ -184,7 +183,7 @@ class Network try { return self::isUriBlocked(new Uri($url)); } catch (\Throwable $e) { - Logger::warning('Invalid URL', ['url' => $url]); + DI::logger()->warning('Invalid URL', ['url' => $url]); return false; } } @@ -310,7 +309,7 @@ class Network $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO; } - Logger::info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']); + DI::logger()->info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']); return $avatar['url']; } @@ -508,7 +507,7 @@ class Network private static function idnToAscii(string $uri): string { if (!function_exists('idn_to_ascii')) { - Logger::error('IDN functions are missing.'); + DI::logger()->error('IDN functions are missing.'); return $uri; } return idn_to_ascii($uri); @@ -634,7 +633,7 @@ class Network } if ($sanitized != $url) { - Logger::debug('Link got sanitized', ['url' => $url, 'sanitzed' => $sanitized]); + DI::logger()->debug('Link got sanitized', ['url' => $url, 'sanitzed' => $sanitized]); } return $sanitized; } @@ -654,7 +653,7 @@ class Network try { return new Uri($uri); } catch (\Exception $e) { - Logger::debug('Invalid URI', ['code' => $e->getCode(), 'message' => $e->getMessage(), 'uri' => $uri]); + DI::logger()->debug('Invalid URI', ['code' => $e->getCode(), 'message' => $e->getMessage(), 'uri' => $uri]); return null; } } @@ -662,10 +661,10 @@ class Network /** * Remove an Url parameter * - * @param string $url - * @param string $parameter - * @return string - * @throws MalformedUriException + * @param string $url + * @param string $parameter + * @return string + * @throws MalformedUriException */ public static function removeUrlParameter(string $url, string $parameter): string { diff --git a/src/Util/ParseUrl.php b/src/Util/ParseUrl.php index 97ecdb977b..8e86007695 100644 --- a/src/Util/ParseUrl.php +++ b/src/Util/ParseUrl.php @@ -12,7 +12,6 @@ use DOMXPath; use Friendica\Content\Text\HTML; use Friendica\Protocol\HTTP\MediaType; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\Database\DBA; use Friendica\DI; @@ -68,13 +67,13 @@ class ParseUrl try { $curlResult = DI::httpClient()->get($url, $accept, array_merge([HttpClientOptions::CONTENT_LENGTH => 1000000], $options)); } 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 []; } } if (!$curlResult->isSuccess()) { - Logger::debug('Got HTTP Error', ['http error' => $curlResult->getReturnCode(), 'url' => $url]); + DI::logger()->debug('Got HTTP Error', ['http error' => $curlResult->getReturnCode(), 'url' => $url]); return []; } @@ -210,7 +209,7 @@ class ParseUrl ]; if ($count > 10) { - Logger::warning('Endless loop detected', ['url' => $url]); + DI::logger()->warning('Endless loop detected', ['url' => $url]); return $siteinfo; } @@ -219,25 +218,25 @@ class ParseUrl } else { $type = self::getContentType($url); } - Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]); + DI::logger()->info('Got content-type', ['content-type' => $type, 'url' => $url]); if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) { $siteinfo['type'] = $type[0]; return $siteinfo; } if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) { - Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]); + DI::logger()->info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]); return $siteinfo; } try { $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::REQUEST => HttpClientRequest::SITEINFO]); } catch (\Throwable $th) { - Logger::info('Exception when fetching', ['url' => $url, 'code' => $th->getCode(), 'message' => $th->getMessage()]); + DI::logger()->info('Exception when fetching', ['url' => $url, 'code' => $th->getCode(), 'message' => $th->getMessage()]); return $siteinfo; } if (!$curlResult->isSuccess() || empty($curlResult->getBodyString())) { - Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]); + DI::logger()->info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]); return $siteinfo; } @@ -268,7 +267,7 @@ class ParseUrl // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211 $charset = str_ireplace('latin-1', 'latin1', $charset); - Logger::info('detected charset', ['charset' => $charset]); + DI::logger()->info('detected charset', ['charset' => $charset]); $body = iconv($charset, 'UTF-8//TRANSLIT', $body); } @@ -494,7 +493,7 @@ class ParseUrl } } - Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]); + DI::logger()->info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]); Hook::callAll('getsiteinfo', $siteinfo); @@ -746,7 +745,7 @@ class ParseUrl { $type = JsonLD::fetchElement($jsonld, '@type'); if (empty($type)) { - Logger::info('Empty type', ['url' => $siteinfo['url']]); + DI::logger()->info('Empty type', ['url' => $siteinfo['url']]); return $siteinfo; } @@ -823,7 +822,7 @@ class ParseUrl case 'ImageObject': return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images'); default: - Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]); + DI::logger()->info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]); return $siteinfo; } } @@ -907,7 +906,7 @@ class ParseUrl $jsonldinfo['author_name'] = trim($jsonld['author']); } - Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]); + DI::logger()->info('Fetched Author information', ['fetched' => $jsonldinfo]); return array_merge($siteinfo, $jsonldinfo); } @@ -978,7 +977,7 @@ class ParseUrl $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld); - Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); + DI::logger()->info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); return array_merge($siteinfo, $jsonldinfo); } @@ -1018,7 +1017,7 @@ class ParseUrl $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld); - Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); + DI::logger()->info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); return array_merge($siteinfo, $jsonldinfo); } @@ -1058,7 +1057,7 @@ class ParseUrl $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld); - Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); + DI::logger()->info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); return array_merge($siteinfo, $jsonldinfo); } @@ -1107,7 +1106,7 @@ class ParseUrl $jsonldinfo['publisher_url'] = Network::sanitizeUrl($content); } - Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); + DI::logger()->info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); return array_merge($siteinfo, $jsonldinfo); } @@ -1146,14 +1145,14 @@ class ParseUrl $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject'); if (!empty($content) && !is_string($content)) { - Logger::notice('Unexpected return value for the author image', ['content' => $content]); + DI::logger()->notice('Unexpected return value for the author image', ['content' => $content]); } if (!empty($content) && is_string($content)) { $jsonldinfo['author_img'] = trim($content); } - Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); + DI::logger()->info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); return array_merge($siteinfo, $jsonldinfo); } @@ -1229,7 +1228,7 @@ class ParseUrl } } - Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]); + DI::logger()->info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]); $siteinfo[$name][] = $media; return $siteinfo; } diff --git a/src/Util/Strings.php b/src/Util/Strings.php index fbf691879e..60bb83e0d5 100644 --- a/src/Util/Strings.php +++ b/src/Util/Strings.php @@ -8,7 +8,7 @@ namespace Friendica\Util; use Friendica\Content\ContactSelector; -use Friendica\Core\Logger; +use Friendica\DI; use ParagonIE\ConstantTime\Base64; /** @@ -498,7 +498,7 @@ class Strings ); if (is_null($return)) { - Logger::notice('Received null value from preg_replace_callback', ['text' => $text, 'regex' => $regex, 'blocks' => $blocks, 'executionId' => $executionId]); + DI::logger()->notice('Received null value from preg_replace_callback', ['text' => $text, 'regex' => $regex, 'blocks' => $blocks, 'executionId' => $executionId]); } $text = $callback($return ?? $text) ?? ''; diff --git a/src/Util/XML.php b/src/Util/XML.php index 52a1d9f3bf..8cf0e86b82 100644 --- a/src/Util/XML.php +++ b/src/Util/XML.php @@ -11,7 +11,7 @@ use DOMDocument; use DOMElement; use DOMNode; use DOMXPath; -use Friendica\Core\Logger; +use Friendica\DI; use SimpleXMLElement; /** @@ -256,7 +256,7 @@ class XML } if (!function_exists('xml_parser_create')) { - Logger::error('Xml::toArray: parser function missing'); + DI::logger()->error('Xml::toArray: parser function missing'); return []; } @@ -272,7 +272,7 @@ class XML } if (!$parser) { - Logger::warning('Xml::toArray: xml_parser_create: no resource'); + DI::logger()->warning('Xml::toArray: xml_parser_create: no resource'); return []; } @@ -284,9 +284,9 @@ class XML @xml_parser_free($parser); if (! $xml_values) { - Logger::debug('Xml::toArray: libxml: parse error: ' . $contents); + DI::logger()->debug('Xml::toArray: libxml: parse error: ' . $contents); foreach (libxml_get_errors() as $err) { - Logger::debug('libxml: parse: ' . $err->code . ' at ' . $err->line . ':' . $err->column . ' : ' . $err->message); + DI::logger()->debug('libxml: parse: ' . $err->code . ' at ' . $err->line . ':' . $err->column . ' : ' . $err->message); } libxml_clear_errors(); return []; @@ -436,11 +436,11 @@ class XML $x = @simplexml_load_string($s); if (!$x) { if (!$suppress_log) { - Logger::error('Error(s) while parsing XML string.'); + DI::logger()->error('Error(s) while parsing XML string.'); foreach (libxml_get_errors() as $err) { - Logger::info('libxml error', ['code' => $err->code, 'position' => $err->line . ':' . $err->column, 'message' => $err->message]); + DI::logger()->info('libxml error', ['code' => $err->code, 'position' => $err->line . ':' . $err->column, 'message' => $err->message]); } - Logger::debug('Erroring XML string', ['xml' => $s]); + DI::logger()->debug('Erroring XML string', ['xml' => $s]); } libxml_clear_errors(); } From c2f65af8bf393dc6de6ceecb8ad98105ac0fe807 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:04:29 +0000 Subject: [PATCH 37/91] Replace Logger with DI::logger() in Update Worker classes --- src/Worker/UpdateBlockedServers.php | 9 ++++----- src/Worker/UpdateContact.php | 4 ++-- src/Worker/UpdateContacts.php | 13 ++++++------- src/Worker/UpdateGServer.php | 6 ++---- src/Worker/UpdateGServers.php | 9 ++++----- src/Worker/UpdateScores.php | 8 ++++---- src/Worker/UpdateServerDirectory.php | 17 ++++++++--------- src/Worker/UpdateServerPeers.php | 11 +++++------ 8 files changed, 35 insertions(+), 42 deletions(-) diff --git a/src/Worker/UpdateBlockedServers.php b/src/Worker/UpdateBlockedServers.php index 61ea6ab0eb..ab38a5dd85 100644 --- a/src/Worker/UpdateBlockedServers.php +++ b/src/Worker/UpdateBlockedServers.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Model\GServer; @@ -20,7 +19,7 @@ class UpdateBlockedServers */ public static function execute() { - Logger::info('Update blocked servers - start'); + DI::logger()->info('Update blocked servers - start'); $gservers = DBA::select('gserver', ['id', 'url', 'blocked']); $changed = 0; $unchanged = 0; @@ -39,12 +38,12 @@ class UpdateBlockedServers $changed++; } DBA::close($gservers); - Logger::info('Update blocked servers - done', ['changed' => $changed, 'unchanged' => $unchanged]); + DI::logger()->info('Update blocked servers - done', ['changed' => $changed, 'unchanged' => $unchanged]); if (DI::config()->get('system', 'delete-blocked-servers')) { - Logger::info('Delete blocked servers - start'); + DI::logger()->info('Delete blocked servers - start'); $ret = DBA::delete('gserver', ["`blocked` AND NOT EXISTS(SELECT `gsid` FROM `inbox-status` WHERE `gsid` = `gserver`.`id`) AND NOT EXISTS(SELECT `gsid` FROM `contact` WHERE gsid= `gserver`.`id`) AND NOT EXISTS(SELECT `gsid` FROM `apcontact` WHERE `gsid` = `gserver`.`id`) AND NOT EXISTS(SELECT `gsid` FROM `delivery-queue` WHERE `gsid` = `gserver`.`id`) AND NOT EXISTS(SELECT `gsid` FROM `diaspora-contact` WHERE `gsid` = `gserver`.`id`) AND NOT EXISTS(SELECT `gserver-id` FROM `gserver-tag` WHERE `gserver-id` = `gserver`.`id`)"]); - Logger::info('Delete blocked servers - done', ['ret' => $ret, 'rows' => DBA::affectedRows()]); + DI::logger()->info('Delete blocked servers - done', ['ret' => $ret, 'rows' => DBA::affectedRows()]); } } } diff --git a/src/Worker/UpdateContact.php b/src/Worker/UpdateContact.php index aad6a93db2..059a8134c5 100644 --- a/src/Worker/UpdateContact.php +++ b/src/Worker/UpdateContact.php @@ -7,8 +7,8 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; +use Friendica\DI; use Friendica\Model\Contact; use Friendica\Network\HTTPException\InternalServerErrorException; @@ -31,7 +31,7 @@ class UpdateContact $success = Contact::updateFromProbe($contact_id); - Logger::info('Updated from probe', ['id' => $contact_id, 'success' => $success]); + DI::logger()->info('Updated from probe', ['id' => $contact_id, 'success' => $success]); } /** diff --git a/src/Worker/UpdateContacts.php b/src/Worker/UpdateContacts.php index 92c97beff2..bb7e236661 100644 --- a/src/Worker/UpdateContacts.php +++ b/src/Worker/UpdateContacts.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -30,11 +29,11 @@ class UpdateContacts $updating = Worker::countWorkersByCommand('UpdateContact'); $limit = $update_limit - $updating; if ($limit <= 0) { - Logger::info('The number of currently running jobs exceed the limit'); + DI::logger()->info('The number of currently running jobs exceed the limit'); return; } - Logger::info('Updating contact', ['count' => $limit]); + DI::logger()->info('Updating contact', ['count' => $limit]); $condition = ['self' => false]; @@ -54,20 +53,20 @@ class UpdateContacts if ((!empty($contact['gsid']) || !empty($contact['baseurl'])) && GServer::reachable($contact)) { $stamp = (float)microtime(true); $success = Contact::updateFromProbe($contact['id']); - Logger::debug('Direct update', ['id' => $contact['id'], 'count' => $count, 'duration' => round((float)microtime(true) - $stamp, 3), 'success' => $success]); + DI::logger()->debug('Direct update', ['id' => $contact['id'], 'count' => $count, 'duration' => round((float)microtime(true) - $stamp, 3), 'success' => $success]); ++$count; } elseif (UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id'])) { - Logger::debug('Update by worker', ['id' => $contact['id'], 'count' => $count]); + DI::logger()->debug('Update by worker', ['id' => $contact['id'], 'count' => $count]); ++$count; } } catch (\InvalidArgumentException $e) { - Logger::notice($e->getMessage(), ['contact' => $contact]); + DI::logger()->notice($e->getMessage(), ['contact' => $contact]); } Worker::coolDown(); } DBA::close($contacts); - Logger::info('Initiated update for federated contacts', ['count' => $count]); + DI::logger()->info('Initiated update for federated contacts', ['count' => $count]); } } diff --git a/src/Worker/UpdateGServer.php b/src/Worker/UpdateGServer.php index 7fd6057a92..1c95631da4 100644 --- a/src/Worker/UpdateGServer.php +++ b/src/Worker/UpdateGServer.php @@ -7,15 +7,13 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Model\GServer; use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Util\Network; use Friendica\Util\Strings; -use GuzzleHttp\Psr7\Uri; -use Psr\Http\Message\UriInterface; class UpdateGServer { @@ -62,7 +60,7 @@ class UpdateGServer } $ret = GServer::check($filtered, '', true, $only_nodeinfo); - Logger::info('Updated gserver', ['url' => $filtered, 'result' => $ret]); + DI::logger()->info('Updated gserver', ['url' => $filtered, 'result' => $ret]); } /** diff --git a/src/Worker/UpdateGServers.php b/src/Worker/UpdateGServers.php index d40d86f844..a5eb626dba 100644 --- a/src/Worker/UpdateGServers.php +++ b/src/Worker/UpdateGServers.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -31,14 +30,14 @@ class UpdateGServers $updating = Worker::countWorkersByCommand('UpdateGServer'); $limit = $update_limit - $updating; if ($limit <= 0) { - Logger::info('The number of currently running jobs exceed the limit'); + DI::logger()->info('The number of currently running jobs exceed the limit'); return; } $total = DBA::count('gserver'); $condition = ["NOT `blocked` AND `next_contact` < ? AND (`nurl` != ? OR `url` != ?)", DateTimeFormat::utcNow(), '', '']; $outdated = DBA::count('gserver', $condition); - Logger::info('Server status', ['total' => $total, 'outdated' => $outdated, 'updating' => $limit]); + DI::logger()->info('Server status', ['total' => $total, 'outdated' => $outdated, 'updating' => $limit]); $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'failed', 'created', 'last_contact'], $condition, ['limit' => $limit]); if (!DBA::isResult($gservers)) { @@ -49,7 +48,7 @@ class UpdateGServers while ($gserver = DBA::fetch($gservers)) { if (DI::config()->get('system', 'update_active_contacts') && !Contact::exists(['gsid' => $gserver['id'], 'local-data' => true])) { $next_update = GServer::getNextUpdateDate(!$gserver['failed'], $gserver['created'], $gserver['last_contact']); - Logger::debug('Skip server without contacts with local data', ['url' => $gserver['url'], 'failed' => $gserver['failed'], 'next_update' => $next_update]); + DI::logger()->debug('Skip server without contacts with local data', ['url' => $gserver['url'], 'failed' => $gserver['failed'], 'next_update' => $next_update]); GServer::update(['next_contact' => $next_update], ['nurl' => $gserver['nurl']]); continue; } @@ -70,6 +69,6 @@ class UpdateGServers Worker::coolDown(); } DBA::close($gservers); - Logger::info('Updated servers', ['count' => $count]); + DI::logger()->info('Updated servers', ['count' => $count]); } } diff --git a/src/Worker/UpdateScores.php b/src/Worker/UpdateScores.php index ffba5fd3ac..c2086e8cba 100644 --- a/src/Worker/UpdateScores.php +++ b/src/Worker/UpdateScores.php @@ -7,19 +7,19 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Model\Contact\Relation; use Friendica\Model\Post; /** - * Update the interaction scores + * Update the interaction scores */ class UpdateScores { public static function execute($param = '', $hook_function = '') { - Logger::notice('Start score update'); + DI::logger()->notice('Start score update'); $users = DBA::select('user', ['uid'], ["`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `uid` > ?", 0]); while ($user = DBA::fetch($users)) { @@ -27,7 +27,7 @@ class UpdateScores } DBA::close($users); - Logger::notice('Score update done'); + DI::logger()->notice('Score update done'); Post\Engagement::expire(); diff --git a/src/Worker/UpdateServerDirectory.php b/src/Worker/UpdateServerDirectory.php index cf3634d878..e9482124e8 100644 --- a/src/Worker/UpdateServerDirectory.php +++ b/src/Worker/UpdateServerDirectory.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Contact; use Friendica\Model\GServer; @@ -38,17 +37,17 @@ class UpdateServerDirectory { $result = DI::httpClient()->fetch($gserver['poco'] . '?fields=urls', HttpClientAccept::JSON, 0, '', HttpClientRequest::SERVERDISCOVER); if (empty($result)) { - Logger::info('Empty result', ['url' => $gserver['url']]); + DI::logger()->info('Empty result', ['url' => $gserver['url']]); return; } $contacts = json_decode($result, true); if (empty($contacts['entry'])) { - Logger::info('No contacts', ['url' => $gserver['url']]); + DI::logger()->info('No contacts', ['url' => $gserver['url']]); return; } - Logger::info('PoCo discovery started', ['poco' => $gserver['poco']]); + DI::logger()->info('PoCo discovery started', ['poco' => $gserver['poco']]); $urls = []; foreach (array_column($contacts['entry'], 'urls') as $url_entries) { @@ -64,24 +63,24 @@ class UpdateServerDirectory $result = Contact::addByUrls($urls); - Logger::info('PoCo discovery ended', ['count' => $result['count'], 'added' => $result['added'], 'updated' => $result['updated'], 'unchanged' => $result['unchanged'], 'poco' => $gserver['poco']]); + DI::logger()->info('PoCo discovery ended', ['count' => $result['count'], 'added' => $result['added'], 'updated' => $result['updated'], 'unchanged' => $result['unchanged'], 'poco' => $gserver['poco']]); } private static function discoverMastodonDirectory(array $gserver) { $result = DI::httpClient()->fetch($gserver['url'] . '/api/v1/directory?order=new&local=true&limit=200&offset=0', HttpClientAccept::JSON, 0, '', HttpClientRequest::SERVERDISCOVER); if (empty($result)) { - Logger::info('Empty result', ['url' => $gserver['url']]); + DI::logger()->info('Empty result', ['url' => $gserver['url']]); return; } $accounts = json_decode($result, true); if (!is_array($accounts)) { - Logger::info('No contacts', ['url' => $gserver['url']]); + DI::logger()->info('No contacts', ['url' => $gserver['url']]); return; } - Logger::info('Account discovery started', ['url' => $gserver['url']]); + DI::logger()->info('Account discovery started', ['url' => $gserver['url']]); $urls = []; foreach ($accounts as $account) { @@ -92,6 +91,6 @@ class UpdateServerDirectory $result = Contact::addByUrls($urls); - Logger::info('Account discovery ended', ['count' => $result['count'], 'added' => $result['added'], 'updated' => $result['updated'], 'unchanged' => $result['unchanged'], 'url' => $gserver['url']]); + DI::logger()->info('Account discovery ended', ['count' => $result['count'], 'added' => $result['added'], 'updated' => $result['updated'], 'unchanged' => $result['unchanged'], 'url' => $gserver['url']]); } } diff --git a/src/Worker/UpdateServerPeers.php b/src/Worker/UpdateServerPeers.php index 94e04a240d..4d3846b643 100644 --- a/src/Worker/UpdateServerPeers.php +++ b/src/Worker/UpdateServerPeers.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -35,21 +34,21 @@ class UpdateServerPeers try { $ret = DI::httpClient()->get($url . '/api/v1/instance/peers', HttpClientAccept::JSON, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERDISCOVER]); } 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; } if (!$ret->isSuccess() || empty($ret->getBodyString())) { - Logger::info('Server is not reachable or does not offer the "peers" endpoint', ['url' => $url]); + DI::logger()->info('Server is not reachable or does not offer the "peers" endpoint', ['url' => $url]); return; } $peers = json_decode($ret->getBodyString()); if (empty($peers) || !is_array($peers)) { - Logger::info('Server does not have any peers listed', ['url' => $url]); + DI::logger()->info('Server does not have any peers listed', ['url' => $url]); return; } - Logger::info('Server peer update start', ['url' => $url]); + DI::logger()->info('Server peer update start', ['url' => $url]); $total = 0; $added = 0; @@ -69,6 +68,6 @@ class UpdateServerPeers ++$added; Worker::coolDown(); } - Logger::info('Server peer update ended', ['total' => $total, 'added' => $added, 'url' => $url]); + DI::logger()->info('Server peer update ended', ['total' => $total, 'added' => $added, 'url' => $url]); } } From bcf784254f7c7592027c66e0d40011d0a54f7e3d Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:06:00 +0000 Subject: [PATCH 38/91] Replace Logger with DI::logger() in Expire Worker classes --- src/Worker/Expire.php | 17 ++++--- src/Worker/ExpireAndRemoveUsers.php | 42 ++++++++--------- src/Worker/ExpirePosts.php | 73 ++++++++++++++--------------- 3 files changed, 65 insertions(+), 67 deletions(-) diff --git a/src/Worker/Expire.php b/src/Worker/Expire.php index baaef454ff..77a37e4b5f 100644 --- a/src/Worker/Expire.php +++ b/src/Worker/Expire.php @@ -8,7 +8,6 @@ namespace Friendica\Worker; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -28,39 +27,39 @@ class Expire if (intval($param) > 0) { $user = DBA::selectFirst('user', ['uid', 'username', 'expire'], ['uid' => $param]); if (DBA::isResult($user)) { - Logger::info('Expire items', ['user' => $user['uid'], 'username' => $user['username'], 'interval' => $user['expire']]); + DI::logger()->info('Expire items', ['user' => $user['uid'], 'username' => $user['username'], 'interval' => $user['expire']]); $expired = Item::expire($user['uid'], $user['expire']); - Logger::info('Expire items done', ['user' => $user['uid'], 'username' => $user['username'], 'interval' => $user['expire'], 'expired' => $expired]); + DI::logger()->info('Expire items done', ['user' => $user['uid'], 'username' => $user['username'], 'interval' => $user['expire'], 'expired' => $expired]); } return; } elseif ($param == 'hook' && !empty($hook_function)) { foreach (Hook::getByName('expire') as $hook) { if ($hook[1] == $hook_function) { - Logger::info('Calling expire hook', ['hook' => $hook[1]]); + DI::logger()->info('Calling expire hook', ['hook' => $hook[1]]); Hook::callSingle('expire', $hook, $data); } } return; } - Logger::notice('start expiry'); + DI::logger()->notice('start expiry'); $r = DBA::select('user', ['uid', 'username'], ["`expire` != ?", 0]); while ($row = DBA::fetch($r)) { - Logger::info('Calling expiry', ['user' => $row['uid'], 'username' => $row['username']]); + DI::logger()->info('Calling expiry', ['user' => $row['uid'], 'username' => $row['username']]); Worker::add(['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], 'Expire', (int)$row['uid']); } DBA::close($r); - Logger::notice('calling hooks'); + DI::logger()->notice('calling hooks'); foreach (Hook::getByName('expire') as $hook) { - Logger::info('Calling expire', ['hook' => $hook[1]]); + DI::logger()->info('Calling expire', ['hook' => $hook[1]]); Worker::add(['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], 'Expire', 'hook', $hook[1]); } - Logger::notice('calling hooks done'); + DI::logger()->notice('calling hooks done'); return; } diff --git a/src/Worker/ExpireAndRemoveUsers.php b/src/Worker/ExpireAndRemoveUsers.php index 0679f9fdab..816475e8ee 100644 --- a/src/Worker/ExpireAndRemoveUsers.php +++ b/src/Worker/ExpireAndRemoveUsers.php @@ -7,9 +7,9 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Database\DBStructure; +use Friendica\DI; use Friendica\Model\Contact; use Friendica\Model\Photo; use Friendica\Model\User; @@ -45,21 +45,21 @@ class ExpireAndRemoveUsers while ($user = DBA::fetch($users)) { $pcid = Contact::getPublicIdByUserId($user['uid']); - Logger::info('Removing user - start', ['uid' => $user['uid'], 'pcid' => $pcid]); + DI::logger()->info('Removing user - start', ['uid' => $user['uid'], 'pcid' => $pcid]); // We have to delete photo entries by hand because otherwise the photo data won't be deleted $result = Photo::delete(['uid' => $user['uid']]); if ($result) { - Logger::debug('Deleted user photos', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted user photos', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting user photos', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting user photos', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } if (!empty($pcid)) { $result = DBA::delete('post-tag', ['cid' => $pcid]); if ($result) { - Logger::debug('Deleted post-tag entries', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted post-tag entries', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting post-tag entries', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting post-tag entries', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } $tables = ['post', 'post-user', 'post-thread', 'post-thread-user']; @@ -73,9 +73,9 @@ class ExpireAndRemoveUsers foreach (['owner-id', 'author-id', 'causer-id'] as $field) { $result = DBA::delete($table, [$field => $pcid]); if ($result) { - Logger::debug('Deleted entries', ['table' => $table, 'field' => $field, 'result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted entries', ['table' => $table, 'field' => $field, 'result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting entries', ['table' => $table, 'field' => $field, 'errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting entries', ['table' => $table, 'field' => $field, 'errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } } } @@ -86,18 +86,18 @@ class ExpireAndRemoveUsers if (DBA::isResult($self)) { $result = DBA::delete('contact', ['nurl' => $self['nurl'], 'self' => false]); if ($result) { - Logger::debug('Deleted the user contact for other users', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted the user contact for other users', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting the user contact for other users', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting the user contact for other users', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } } // Delete all contacts of this user $result = DBA::delete('contact', ['uid' => $user['uid']]); if ($result) { - Logger::debug('Deleted user contacts', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted user contacts', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting user contacts', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting user contacts', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } // These tables contain the permissionset which will also be deleted when a user is deleted. @@ -107,33 +107,33 @@ class ExpireAndRemoveUsers if (DBStructure::existsTable('item')) { $result = DBA::delete('item', ['uid' => $user['uid']]); if ($result) { - Logger::debug('Deleted user items', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted user items', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting user items', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting user items', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } } $result = DBA::delete('post-user', ['uid' => $user['uid']]); if ($result) { - Logger::debug('Deleted post-user entries', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted post-user entries', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting post-user entries', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting post-user entries', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } $result = DBA::delete('profile_field', ['uid' => $user['uid']]); if ($result) { - Logger::debug('Deleted profile_field entries', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted profile_field entries', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting profile_field entries', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting profile_field entries', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } $result = DBA::delete('user', ['uid' => $user['uid']]); if ($result) { - Logger::debug('Deleted user record', ['result' => $result, 'rows' => DBA::affectedRows()]); + DI::logger()->debug('Deleted user record', ['result' => $result, 'rows' => DBA::affectedRows()]); } else { - Logger::warning('Error deleting user record', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); + DI::logger()->warning('Error deleting user record', ['errno' => DBA::errorNo(), 'errmsg' => DBA::errorMessage()]); } - Logger::info('Removing user - done', ['uid' => $user['uid']]); + DI::logger()->info('Removing user - done', ['uid' => $user['uid']]); } DBA::close($users); } diff --git a/src/Worker/ExpirePosts.php b/src/Worker/ExpirePosts.php index 74a11687e8..e1c8fe1685 100644 --- a/src/Worker/ExpirePosts.php +++ b/src/Worker/ExpirePosts.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\Database; use Friendica\Database\DBA; @@ -27,36 +26,36 @@ class ExpirePosts */ public static function execute() { - Logger::notice('Expire posts - start'); + DI::logger()->notice('Expire posts - start'); if (!DBA::acquireOptimizeLock()) { - Logger::warning('Lock could not be acquired'); + DI::logger()->warning('Lock could not be acquired'); Worker::defer(); return; } - Logger::notice('Expire posts - Delete expired origin posts'); + DI::logger()->notice('Expire posts - Delete expired origin posts'); self::deleteExpiredOriginPosts(); - Logger::notice('Expire posts - Delete orphaned entries'); + DI::logger()->notice('Expire posts - Delete orphaned entries'); self::deleteOrphanedEntries(); - Logger::notice('Expire posts - delete external posts'); + DI::logger()->notice('Expire posts - delete external posts'); self::deleteExpiredExternalPosts(); if (DI::config()->get('system', 'add_missing_posts')) { - Logger::notice('Expire posts - add missing posts'); + DI::logger()->notice('Expire posts - add missing posts'); self::addMissingEntries(); } - Logger::notice('Expire posts - delete unused attachments'); + DI::logger()->notice('Expire posts - delete unused attachments'); self::deleteUnusedAttachments(); - Logger::notice('Expire posts - delete unused item-uri entries'); + DI::logger()->notice('Expire posts - delete unused item-uri entries'); self::deleteUnusedItemUri(); DBA::releaseOptimizeLock(); - Logger::notice('Expire posts - done'); + DI::logger()->notice('Expire posts - done'); } /** @@ -71,7 +70,7 @@ class ExpirePosts return; } - Logger::notice('Delete expired posts'); + DI::logger()->notice('Delete expired posts'); // physically remove anything that has been deleted for more than two months $condition = ["`gravity` = ? AND `deleted` AND `edited` < ?", Item::GRAVITY_PARENT, DateTimeFormat::utc('now - 60 days')]; $pass = 0; @@ -80,7 +79,7 @@ class ExpirePosts $rows = DBA::select('post-user', ['uri-id', 'uid'], $condition, ['limit' => $limit]); $affected_count = 0; while ($row = Post::fetch($rows)) { - Logger::info('Delete expired item', ['pass' => $pass, 'uri-id' => $row['uri-id']]); + DI::logger()->info('Delete expired item', ['pass' => $pass, 'uri-id' => $row['uri-id']]); Post\User::delete(['parent-uri-id' => $row['uri-id'], 'uid' => $row['uid']]); $affected_count += DBA::affectedRows(); Post\Origin::delete(['parent-uri-id' => $row['uri-id'], 'uid' => $row['uid']]); @@ -88,7 +87,7 @@ class ExpirePosts } DBA::close($rows); DBA::commit(); - Logger::notice('Delete expired posts - done', ['pass' => $pass, 'rows' => $affected_count]); + DI::logger()->notice('Delete expired posts - done', ['pass' => $pass, 'rows' => $affected_count]); } while ($affected_count); } @@ -99,7 +98,7 @@ class ExpirePosts */ private static function deleteOrphanedEntries() { - Logger::notice('Delete orphaned entries'); + DI::logger()->notice('Delete orphaned entries'); // "post-user" is the leading table. So we delete every entry that isn't found there $tables = ['item', 'post', 'post-content', 'post-thread', 'post-thread-user']; @@ -108,10 +107,10 @@ class ExpirePosts continue; } - Logger::notice('Start collecting orphaned entries', ['table' => $table]); + DI::logger()->notice('Start collecting orphaned entries', ['table' => $table]); $uris = DBA::select($table, ['uri-id'], ["NOT `uri-id` IN (SELECT `uri-id` FROM `post-user`)"]); $affected_count = 0; - Logger::notice('Deleting orphaned entries - start', ['table' => $table]); + DI::logger()->notice('Deleting orphaned entries - start', ['table' => $table]); while ($rows = DBA::toArray($uris, false, 100)) { $ids = array_column($rows, 'uri-id'); DBA::delete($table, ['uri-id' => $ids]); @@ -119,9 +118,9 @@ class ExpirePosts } DBA::close($uris); DBA::commit(); - Logger::notice('Orphaned entries deleted', ['table' => $table, 'rows' => $affected_count]); + DI::logger()->notice('Orphaned entries deleted', ['table' => $table, 'rows' => $affected_count]); } - Logger::notice('Delete orphaned entries - done'); + DI::logger()->notice('Delete orphaned entries - done'); } /** @@ -131,7 +130,7 @@ class ExpirePosts */ private static function addMissingEntries() { - Logger::notice('Adding missing entries'); + DI::logger()->notice('Adding missing entries'); $rows = 0; $userposts = DBA::select('post-user', [], ["`uri-id` not in (select `uri-id` from `post`)"]); @@ -142,9 +141,9 @@ class ExpirePosts } DBA::close($userposts); if ($rows > 0) { - Logger::notice('Added post entries', ['rows' => $rows]); + DI::logger()->notice('Added post entries', ['rows' => $rows]); } else { - Logger::notice('No post entries added'); + DI::logger()->notice('No post entries added'); } $rows = 0; @@ -157,9 +156,9 @@ class ExpirePosts } DBA::close($userposts); if ($rows > 0) { - Logger::notice('Added post-thread entries', ['rows' => $rows]); + DI::logger()->notice('Added post-thread entries', ['rows' => $rows]); } else { - Logger::notice('No post-thread entries added'); + DI::logger()->notice('No post-thread entries added'); } $rows = 0; @@ -172,9 +171,9 @@ class ExpirePosts } DBA::close($userposts); if ($rows > 0) { - Logger::notice('Added post-thread-user entries', ['rows' => $rows]); + DI::logger()->notice('Added post-thread-user entries', ['rows' => $rows]); } else { - Logger::notice('No post-thread-user entries added'); + DI::logger()->notice('No post-thread-user entries added'); } } @@ -196,10 +195,10 @@ class ExpirePosts ['order' => ['received' => true]] ); if (empty($item['uri-id'])) { - Logger::warning('No item with uri-id found - we better quit here'); + DI::logger()->warning('No item with uri-id found - we better quit here'); return; } - Logger::notice('Start collecting orphaned URI-ID', ['last-id' => $item['uri-id']]); + DI::logger()->notice('Start collecting orphaned URI-ID', ['last-id' => $item['uri-id']]); $condition = [ "`id` < ? AND NOT EXISTS(SELECT `uri-id` FROM `post-user` WHERE `uri-id` = `item-uri`.`id`) @@ -226,17 +225,17 @@ class ExpirePosts ++$pass; $uris = DBA::select('item-uri', ['id'], $condition, ['limit' => $limit]); $total = DBA::numRows($uris); - Logger::notice('Start deleting orphaned URI-ID', ['pass' => $pass, 'last-id' => $item['uri-id']]); + DI::logger()->notice('Start deleting orphaned URI-ID', ['pass' => $pass, 'last-id' => $item['uri-id']]); $affected_count = 0; while ($rows = DBA::toArray($uris, false, 100)) { $ids = array_column($rows, 'id'); DBA::delete('item-uri', ['id' => $ids]); $affected_count += DBA::affectedRows(); - Logger::debug('Deleted', ['pass' => $pass, 'affected_count' => $affected_count, 'total' => $total]); + DI::logger()->debug('Deleted', ['pass' => $pass, 'affected_count' => $affected_count, 'total' => $total]); } DBA::close($uris); DBA::commit(); - Logger::notice('Orphaned URI-ID entries removed', ['pass' => $pass, 'rows' => $affected_count]); + DI::logger()->notice('Orphaned URI-ID entries removed', ['pass' => $pass, 'rows' => $affected_count]); } while ($affected_count); } @@ -257,7 +256,7 @@ class ExpirePosts } if (!empty($expire_days)) { - Logger::notice('Start collecting expired threads', ['expiry_days' => $expire_days]); + DI::logger()->notice('Start collecting expired threads', ['expiry_days' => $expire_days]); $condition = [ "`received` < ? AND NOT `uri-id` IN (SELECT `uri-id` FROM `post-thread-user` @@ -281,7 +280,7 @@ class ExpirePosts ++$pass; $uris = DBA::select('post-thread', ['uri-id'], $condition, ['limit' => $limit]); - Logger::notice('Start deleting expired threads', ['pass' => $pass]); + DI::logger()->notice('Start deleting expired threads', ['pass' => $pass]); $affected_count = 0; while ($rows = DBA::toArray($uris, false, 100)) { $ids = array_column($rows, 'uri-id'); @@ -290,12 +289,12 @@ class ExpirePosts } DBA::close($uris); DBA::commit(); - Logger::notice('Deleted expired threads', ['pass' => $pass, 'rows' => $affected_count]); + DI::logger()->notice('Deleted expired threads', ['pass' => $pass, 'rows' => $affected_count]); } while ($affected_count); } if (!empty($expire_days_unclaimed)) { - Logger::notice('Start collecting unclaimed public items', ['expiry_days' => $expire_days_unclaimed]); + DI::logger()->notice('Start collecting unclaimed public items', ['expiry_days' => $expire_days_unclaimed]); $condition = [ "`gravity` = ? AND `uid` = ? AND `received` < ? AND NOT `uri-id` IN (SELECT `parent-uri-id` FROM `post-user` AS `i` WHERE `i`.`uid` != ? @@ -309,17 +308,17 @@ class ExpirePosts ++$pass; $uris = DBA::select('post-user', ['uri-id'], $condition, ['limit' => $limit]); $total = DBA::numRows($uris); - Logger::notice('Start deleting unclaimed public items', ['pass' => $pass]); + DI::logger()->notice('Start deleting unclaimed public items', ['pass' => $pass]); $affected_count = 0; while ($rows = DBA::toArray($uris, false, 100)) { $ids = array_column($rows, 'uri-id'); DBA::delete('item-uri', ['id' => $ids]); $affected_count += DBA::affectedRows(); - Logger::debug('Deleted', ['pass' => $pass, 'affected_count' => $affected_count, 'total' => $total]); + DI::logger()->debug('Deleted', ['pass' => $pass, 'affected_count' => $affected_count, 'total' => $total]); } DBA::close($uris); DBA::commit(); - Logger::notice('Deleted unclaimed public items', ['pass' => $pass, 'rows' => $affected_count]); + DI::logger()->notice('Deleted unclaimed public items', ['pass' => $pass, 'rows' => $affected_count]); } while ($affected_count); } } From c90b4850899ffc11dcb801217e63c014e358570c Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:07:14 +0000 Subject: [PATCH 39/91] Replace Logger with DI::logger() in Process Worker classes --- src/Worker/ProcessQueue.php | 6 +++--- src/Worker/ProcessReplyByUri.php | 6 +++--- src/Worker/ProcessUnprocessedEntries.php | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/Worker/ProcessQueue.php b/src/Worker/ProcessQueue.php index e5cfa348e6..bf8b8df1a6 100644 --- a/src/Worker/ProcessQueue.php +++ b/src/Worker/ProcessQueue.php @@ -7,7 +7,7 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Protocol\ActivityPub\Queue; class ProcessQueue @@ -21,8 +21,8 @@ class ProcessQueue */ public static function execute(int $id) { - Logger::info('Start processing queue entry', ['id' => $id]); + DI::logger()->info('Start processing queue entry', ['id' => $id]); $result = Queue::process($id); - Logger::info('Successfully processed queue entry', ['result' => $result, 'id' => $id]); + DI::logger()->info('Successfully processed queue entry', ['result' => $result, 'id' => $id]); } } diff --git a/src/Worker/ProcessReplyByUri.php b/src/Worker/ProcessReplyByUri.php index ad7bc02278..88b00bc1a2 100644 --- a/src/Worker/ProcessReplyByUri.php +++ b/src/Worker/ProcessReplyByUri.php @@ -7,7 +7,7 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Protocol\ActivityPub\Queue; class ProcessReplyByUri @@ -21,8 +21,8 @@ class ProcessReplyByUri */ public static function execute(string $uri) { - Logger::info('Start processing queued replies', ['url' => $uri]); + DI::logger()->info('Start processing queued replies', ['url' => $uri]); $count = Queue::processReplyByUri($uri); - Logger::info('Successfully processed queued replies', ['count' => $count, 'url' => $uri]); + DI::logger()->info('Successfully processed queued replies', ['count' => $count, 'url' => $uri]); } } diff --git a/src/Worker/ProcessUnprocessedEntries.php b/src/Worker/ProcessUnprocessedEntries.php index 2191494275..afde8bb26b 100644 --- a/src/Worker/ProcessUnprocessedEntries.php +++ b/src/Worker/ProcessUnprocessedEntries.php @@ -7,7 +7,7 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Protocol\ActivityPub\Queue; class ProcessUnprocessedEntries @@ -19,8 +19,8 @@ class ProcessUnprocessedEntries */ public static function execute() { - Logger::info('Start processing unprocessed entries'); + DI::logger()->info('Start processing unprocessed entries'); Queue::processAll(); - Logger::info('Successfully processed unprocessed entries'); + DI::logger()->info('Successfully processed unprocessed entries'); } } From 1762d1e72d741b41d64b5884da76dc6f40a84d5a Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:13:50 +0000 Subject: [PATCH 40/91] Replace Logger with DI::logger() in Remove Worker classes --- src/Worker/Contact/Remove.php | 4 ++-- src/Worker/Contact/RemoveContent.php | 3 +-- src/Worker/RemoveUnusedAvatars.php | 24 ++++++++++++------------ src/Worker/RemoveUnusedContacts.php | 17 ++++++++--------- 4 files changed, 23 insertions(+), 25 deletions(-) diff --git a/src/Worker/Contact/Remove.php b/src/Worker/Contact/Remove.php index 870edbb502..d9c4c96a41 100644 --- a/src/Worker/Contact/Remove.php +++ b/src/Worker/Contact/Remove.php @@ -7,8 +7,8 @@ namespace Friendica\Worker\Contact; -use Friendica\Core\Logger; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Model\Contact; /** @@ -29,7 +29,7 @@ class Remove extends RemoveContent } $ret = Contact::deleteById($id); - Logger::info('Deleted contact', ['id' => $id, 'result' => $ret]); + DI::logger()->info('Deleted contact', ['id' => $id, 'result' => $ret]); return true; } diff --git a/src/Worker/Contact/RemoveContent.php b/src/Worker/Contact/RemoveContent.php index 5aea6f8e63..762ff7a6d4 100644 --- a/src/Worker/Contact/RemoveContent.php +++ b/src/Worker/Contact/RemoveContent.php @@ -7,7 +7,6 @@ namespace Friendica\Worker\Contact; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Database\DBStructure; use Friendica\DI; @@ -25,7 +24,7 @@ class RemoveContent return false; } - Logger::info('Start deleting contact content', ['cid' => $id]); + DI::logger()->info('Start deleting contact content', ['cid' => $id]); // Now we delete the contact and all depending tables DBA::delete('post-tag', ['cid' => $id]); diff --git a/src/Worker/RemoveUnusedAvatars.php b/src/Worker/RemoveUnusedAvatars.php index a6426be115..8cebde12d2 100644 --- a/src/Worker/RemoveUnusedAvatars.php +++ b/src/Worker/RemoveUnusedAvatars.php @@ -8,8 +8,8 @@ namespace Friendica\Worker; use Friendica\Contact\Avatar; -use Friendica\Core\Logger; use Friendica\Database\DBA; +use Friendica\DI; use Friendica\Model\Contact; use Friendica\Model\Photo; @@ -32,7 +32,7 @@ class RemoveUnusedAvatars ]; $total = DBA::count('contact', $condition); - Logger::notice('Starting removal', ['total' => $total]); + DI::logger()->notice('Starting removal', ['total' => $total]); $count = 0; $contacts = DBA::select('contact', ['id', 'uri-id', 'uid', 'photo', 'thumb', 'micro'], $condition); while ($contact = DBA::fetch($contacts)) { @@ -40,11 +40,11 @@ class RemoveUnusedAvatars Contact::update(['photo' => '', 'thumb' => '', 'micro' => ''], ['id' => $contact['id']]); } if ((++$count % 1000) == 0) { - Logger::info('In removal', ['count' => $count, 'total' => $total]); + DI::logger()->info('In removal', ['count' => $count, 'total' => $total]); } } DBA::close($contacts); - Logger::notice('Removal done', ['count' => $count, 'total' => $total]); + DI::logger()->notice('Removal done', ['count' => $count, 'total' => $total]); self::fixPhotoContacts(); self::deleteDuplicates(); @@ -56,7 +56,7 @@ class RemoveUnusedAvatars $deleted = 0; $updated1 = 0; $updated2 = 0; - Logger::notice('Starting contact fix'); + DI::logger()->notice('Starting contact fix'); $photos = DBA::select('photo', [], ["`uid` = ? AND `contact-id` IN (SELECT `id` FROM `contact` WHERE `uid` != ?) AND `contact-id` != ? AND `scale` IN (?, ?, ?)", 0, 0, 0, 4, 5, 6]); while ($photo = DBA::fetch($photos)) { $total++; @@ -65,7 +65,7 @@ class RemoveUnusedAvatars if ($photo['resource-id'] == $resource) { $contact = DBA::selectFirst('contact', [], ['nurl' => $photo_contact['nurl'], 'uid' => 0]); if (!empty($contact['photo']) && ($contact['photo'] == $photo_contact['photo'])) { - Logger::notice('Photo updated to public user', ['id' => $photo['id'], 'contact-id' => $contact['id']]); + DI::logger()->notice('Photo updated to public user', ['id' => $photo['id'], 'contact-id' => $contact['id']]); DBA::update('photo', ['contact-id' => $contact['id']], ['id' => $photo['id']]); $updated1++; } @@ -74,7 +74,7 @@ class RemoveUnusedAvatars $contacts = DBA::select('contact', [], ['nurl' => $photo_contact['nurl']]); while ($contact = DBA::fetch($contacts)) { if ($photo['resource-id'] == Photo::ridFromURI($contact['photo'])) { - Logger::notice('Photo updated to given user', ['id' => $photo['id'], 'contact-id' => $contact['id'], 'uid' => $contact['uid']]); + DI::logger()->notice('Photo updated to given user', ['id' => $photo['id'], 'contact-id' => $contact['id'], 'uid' => $contact['uid']]); DBA::update('photo', ['contact-id' => $contact['id'], 'uid' => $contact['uid']], ['id' => $photo['id']]); $updated = true; $updated2++; @@ -82,14 +82,14 @@ class RemoveUnusedAvatars } DBA::close($contacts); if (!$updated) { - Logger::notice('Photo deleted', ['id' => $photo['id']]); + DI::logger()->notice('Photo deleted', ['id' => $photo['id']]); Photo::delete(['id' => $photo['id']]); $deleted++; } } } DBA::close($photos); - Logger::notice('Contact fix done', ['total' => $total, 'updated1' => $updated1, 'updated2' => $updated2, 'deleted' => $deleted]); + DI::logger()->notice('Contact fix done', ['total' => $total, 'updated1' => $updated1, 'updated2' => $updated2, 'deleted' => $deleted]); } private static function deleteDuplicates() @@ -98,20 +98,20 @@ class RemoveUnusedAvatars $total = 0; $deleted = 0; - Logger::notice('Starting duplicate removal'); + DI::logger()->notice('Starting duplicate removal'); $photos = DBA::p("SELECT `photo`.`id`, `photo`.`uid`, `photo`.`scale`, `photo`.`album`, `photo`.`contact-id`, `photo`.`resource-id`, `contact`.`photo`, `contact`.`thumb`, `contact`.`micro` FROM `photo` INNER JOIN `contact` ON `contact`.`id` = `photo`.`contact-id` and `photo`.`contact-id` != ? AND `photo`.`scale` IN (?, ?, ?)", 0, 4, 5, 6); while ($photo = DBA::fetch($photos)) { $resource = Photo::ridFromURI($photo[$size[$photo['scale']]]); if ($resource != $photo['resource-id'] && !empty($resource)) { $total++; if (DBA::exists('photo', ['resource-id' => $resource, 'scale' => $photo['scale']])) { - Logger::notice('Photo deleted', ['id' => $photo['id']]); + DI::logger()->notice('Photo deleted', ['id' => $photo['id']]); Photo::delete(['id' => $photo['id']]); $deleted++; } } } DBA::close($photos); - Logger::notice('Duplicate removal done', ['total' => $total, 'deleted' => $deleted]); + DI::logger()->notice('Duplicate removal done', ['total' => $total, 'deleted' => $deleted]); } } diff --git a/src/Worker/RemoveUnusedContacts.php b/src/Worker/RemoveUnusedContacts.php index 9ee7390ca9..3419b69421 100644 --- a/src/Worker/RemoveUnusedContacts.php +++ b/src/Worker/RemoveUnusedContacts.php @@ -8,7 +8,6 @@ namespace Friendica\Worker; use Friendica\Contact\Avatar; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Worker; use Friendica\Database\DBA; @@ -27,21 +26,21 @@ class RemoveUnusedContacts { $loop = 0; while (self::removeContacts(++$loop)) { - Logger::info('In removal', ['loop' => $loop]); + DI::logger()->info('In removal', ['loop' => $loop]); } - Logger::notice('Remove apcontact entries with no related contact'); + DI::logger()->notice('Remove apcontact entries with no related contact'); DBA::delete('apcontact', ["`uri-id` NOT IN (SELECT `uri-id` FROM `contact`) AND `updated` < ?", DateTimeFormat::utc('now - 30 days')]); - Logger::notice('Removed apcontact entries with no related contact', ['count' => DBA::affectedRows()]); + DI::logger()->notice('Removed apcontact entries with no related contact', ['count' => DBA::affectedRows()]); - Logger::notice('Remove diaspora-contact entries with no related contact'); + DI::logger()->notice('Remove diaspora-contact entries with no related contact'); DBA::delete('diaspora-contact', ["`uri-id` NOT IN (SELECT `uri-id` FROM `contact`) AND `updated` < ?", DateTimeFormat::utc('now - 30 days')]); - Logger::notice('Removed diaspora-contact entries with no related contact', ['count' => DBA::affectedRows()]); + DI::logger()->notice('Removed diaspora-contact entries with no related contact', ['count' => DBA::affectedRows()]); } public static function removeContacts(int $loop): bool { - Logger::notice('Starting removal', ['loop' => $loop]); + DI::logger()->notice('Starting removal', ['loop' => $loop]); $condition = [ "`id` != ? AND `uid` = ? AND NOT `self` AND NOT `uri-id` IN (SELECT `uri-id` FROM `contact` WHERE `uid` != ?) @@ -64,7 +63,7 @@ class RemoveUnusedContacts "(NOT `network` IN (?, ?, ?, ?, ?, ?) OR `archive`)", Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL, Protocol::ACTIVITYPUB ]; - + $condition = DBA::mergeConditions($condition2, $condition); } @@ -102,7 +101,7 @@ class RemoveUnusedContacts Contact::deleteById($contact['id']); } DBA::close($contacts); - Logger::notice('Removal done', ['count' => $count]); + DI::logger()->notice('Removal done', ['count' => $count]); return ($count == 1000 && Worker::isInMaintenanceWindow()); } } From 8fe3383976a60ec4cf53ad8f020b78da2125512a Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:19:24 +0000 Subject: [PATCH 41/91] Replace Logger with DI::logger() in many Worker classes --- src/Worker/APDelivery.php | 6 +++--- src/Worker/BulkDelivery.php | 5 ++--- src/Worker/CheckRelMeProfileLink.php | 17 ++++++++--------- src/Worker/CheckVersion.php | 9 ++++----- src/Worker/Cron.php | 9 ++++----- src/Worker/DelayedPublish.php | 4 ++-- src/Worker/Directory.php | 3 +-- src/Worker/FetchFeaturedPosts.php | 6 +++--- src/Worker/FetchMissingActivity.php | 13 ++++++------- src/Worker/MergeContact.php | 4 ++-- src/Worker/NodeInfo.php | 9 ++++----- src/Worker/OptimizeTables.php | 7 +++---- src/Worker/PollContacts.php | 5 ++--- src/Worker/ProfileUpdate.php | 3 +-- src/Worker/PullDirectory.php | 13 ++++++------- src/Worker/PushSubscription.php | 17 ++++++++--------- src/Worker/SearchDirectory.php | 5 ++--- src/Worker/SetSeen.php | 4 ++-- src/Worker/SpoolPost.php | 14 +++++++------- 19 files changed, 70 insertions(+), 83 deletions(-) diff --git a/src/Worker/APDelivery.php b/src/Worker/APDelivery.php index a3966de8c4..2d1df8cca4 100644 --- a/src/Worker/APDelivery.php +++ b/src/Worker/APDelivery.php @@ -7,8 +7,8 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; +use Friendica\DI; use Friendica\Model\Post; use Friendica\Model\User; use Friendica\Protocol\ActivityPub; @@ -29,7 +29,7 @@ class APDelivery public static function execute(string $cmd, int $item_id, string $inbox, int $uid, array $receivers = [], int $uri_id = 0) { if (ActivityPub\Transmitter::archivedInbox($inbox)) { - Logger::info('Inbox is archived', ['cmd' => $cmd, 'inbox' => $inbox, 'id' => $item_id, 'uri-id' => $uri_id, 'uid' => $uid]); + DI::logger()->info('Inbox is archived', ['cmd' => $cmd, 'inbox' => $inbox, 'id' => $item_id, 'uri-id' => $uri_id, 'uid' => $uid]); if (empty($uri_id) && !empty($item_id)) { $item = Post::selectFirst(['uri-id'], ['id' => $item_id]); $uri_id = $item['uri-id'] ?? 0; @@ -48,7 +48,7 @@ class APDelivery return; } - Logger::debug('Invoked', ['cmd' => $cmd, 'inbox' => $inbox, 'id' => $item_id, 'uri-id' => $uri_id, 'uid' => $uid]); + DI::logger()->debug('Invoked', ['cmd' => $cmd, 'inbox' => $inbox, 'id' => $item_id, 'uri-id' => $uri_id, 'uid' => $uid]); if (empty($uri_id)) { $result = ActivityPub\Delivery::deliver($inbox); diff --git a/src/Worker/BulkDelivery.php b/src/Worker/BulkDelivery.php index 269a04fa58..3d42424a82 100644 --- a/src/Worker/BulkDelivery.php +++ b/src/Worker/BulkDelivery.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\DI; use Friendica\Model\GServer; @@ -24,7 +23,7 @@ class BulkDelivery foreach ($deliveryQueueItems as $deliveryQueueItem) { if (!$server_failure && ProtocolDelivery::deliver($deliveryQueueItem->command, $deliveryQueueItem->postUriId, $deliveryQueueItem->targetContactId, $deliveryQueueItem->senderUserId)) { DI::deliveryQueueItemRepo()->remove($deliveryQueueItem); - Logger::debug('Delivery successful', $deliveryQueueItem->toArray()); + DI::logger()->debug('Delivery successful', $deliveryQueueItem->toArray()); } else { DI::deliveryQueueItemRepo()->incrementFailed($deliveryQueueItem); $delivery_failure = true; @@ -32,7 +31,7 @@ class BulkDelivery if (!$server_failure) { $server_failure = !GServer::isReachableById($gsid); } - Logger::debug('Delivery failed', ['server_failure' => $server_failure, 'post' => $deliveryQueueItem]); + DI::logger()->debug('Delivery failed', ['server_failure' => $server_failure, 'post' => $deliveryQueueItem]); } } diff --git a/src/Worker/CheckRelMeProfileLink.php b/src/Worker/CheckRelMeProfileLink.php index 0aeaf49c2c..3b0f1800e3 100644 --- a/src/Worker/CheckRelMeProfileLink.php +++ b/src/Worker/CheckRelMeProfileLink.php @@ -9,7 +9,6 @@ namespace Friendica\Worker; use DOMDocument; use Friendica\Content\Text\HTML; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Profile; use Friendica\Model\User; @@ -41,12 +40,12 @@ class CheckRelMeProfileLink */ public static function execute(int $uid) { - Logger::notice('Verifying the homepage', ['uid' => $uid]); + DI::logger()->notice('Verifying the homepage', ['uid' => $uid]); Profile::update(['homepage_verified' => false], $uid); $owner = User::getOwnerDataById($uid); if (empty($owner['homepage'])) { - Logger::notice('The user has no homepage link.', ['uid' => $uid]); + DI::logger()->notice('The user has no homepage link.', ['uid' => $uid]); return; } @@ -54,31 +53,31 @@ class CheckRelMeProfileLink try { $curlResult = DI::httpClient()->get($owner['homepage'], HttpClientAccept::HTML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::CONTACTVERIFIER]); } 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; } if (!$curlResult->isSuccess()) { - Logger::notice('Could not cURL the homepage URL', ['owner homepage' => $owner['homepage']]); + DI::logger()->notice('Could not cURL the homepage URL', ['owner homepage' => $owner['homepage']]); return; } $content = $curlResult->getBodyString(); if (!$content) { - Logger::notice('Empty body of the fetched homepage link). Cannot verify the relation to profile of UID %s.', ['uid' => $uid, 'owner homepage' => $owner['homepage']]); + DI::logger()->notice('Empty body of the fetched homepage link). Cannot verify the relation to profile of UID %s.', ['uid' => $uid, 'owner homepage' => $owner['homepage']]); return; } $doc = new DOMDocument(); if (!@$doc->loadHTML($content)) { - Logger::notice('Could not parse the content'); + DI::logger()->notice('Could not parse the content'); return; } if (HTML::checkRelMeLink($doc, new Uri($owner['url']))) { Profile::update(['homepage_verified' => true], $uid); - Logger::notice('Homepage URL verified', ['uid' => $uid, 'owner homepage' => $owner['homepage']]); + DI::logger()->notice('Homepage URL verified', ['uid' => $uid, 'owner homepage' => $owner['homepage']]); } else { - Logger::notice('Homepage URL could not be verified', ['uid' => $uid, 'owner homepage' => $owner['homepage']]); + DI::logger()->notice('Homepage URL could not be verified', ['uid' => $uid, 'owner homepage' => $owner['homepage']]); } } } diff --git a/src/Worker/CheckVersion.php b/src/Worker/CheckVersion.php index c62cc5f182..2a8f7264ae 100644 --- a/src/Worker/CheckVersion.php +++ b/src/Worker/CheckVersion.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Network\HTTPClient\Client\HttpClientAccept; @@ -22,7 +21,7 @@ class CheckVersion { public static function execute() { - Logger::notice('checkversion: start'); + DI::logger()->notice('checkversion: start'); $checkurl = DI::config()->get('system', 'check_new_version_url', 'none'); @@ -38,15 +37,15 @@ class CheckVersion // don't check return; } - Logger::info("Checking VERSION from: ".$checked_url); + DI::logger()->info("Checking VERSION from: ".$checked_url); // fetch the VERSION file $gitversion = DBA::escape(trim(DI::httpClient()->fetch($checked_url, HttpClientAccept::TEXT))); - Logger::notice("Upstream VERSION is: ".$gitversion); + DI::logger()->notice("Upstream VERSION is: ".$gitversion); DI::keyValue()->set('git_friendica_version', $gitversion); - Logger::notice('checkversion: end'); + DI::logger()->notice('checkversion: end'); return; } diff --git a/src/Worker/Cron.php b/src/Worker/Cron.php index c10a548559..3438b9e55a 100644 --- a/src/Worker/Cron.php +++ b/src/Worker/Cron.php @@ -9,7 +9,6 @@ namespace Friendica\Worker; use Friendica\Core\Addon; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\Database\DBA; use Friendica\DI; @@ -30,12 +29,12 @@ class Cron if ($last) { $next = $last + ($poll_interval * 60); if ($next > time()) { - Logger::notice('cron interval not reached'); + DI::logger()->notice('cron interval not reached'); return; } } - Logger::notice('start'); + DI::logger()->notice('start'); // Ensure to have a .htaccess file. // this is a precaution for systems that update automatically @@ -151,7 +150,7 @@ class Cron DI::keyValue()->set('last_cron_daily', time()); } - Logger::notice('end'); + DI::logger()->notice('end'); DI::keyValue()->set('last_cron', time()); } @@ -163,7 +162,7 @@ class Cron */ private static function deleteSleepingProcesses() { - Logger::info('Looking for sleeping processes'); + DI::logger()->info('Looking for sleeping processes'); DBA::deleteSleepingProcesses(); } diff --git a/src/Worker/DelayedPublish.php b/src/Worker/DelayedPublish.php index a484ddbc6a..8020a042d4 100644 --- a/src/Worker/DelayedPublish.php +++ b/src/Worker/DelayedPublish.php @@ -7,7 +7,7 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Model\Post; class DelayedPublish @@ -26,6 +26,6 @@ class DelayedPublish public static function execute(array $item, int $notify = 0, array $taglist = [], array $attachments = [], int $preparation_mode = Post\Delayed::PREPARED, string $uri = '') { $id = Post\Delayed::publish($item, $notify, $taglist, $attachments, $preparation_mode, $uri); - Logger::notice('Post published', ['id' => $id, 'uid' => $item['uid'], 'notify' => $notify, 'unprepared' => $preparation_mode]); + DI::logger()->notice('Post published', ['id' => $id, 'uid' => $item['uid'], 'notify' => $notify, 'unprepared' => $preparation_mode]); } } diff --git a/src/Worker/Directory.php b/src/Worker/Directory.php index b5025d7710..e9a9102277 100644 --- a/src/Worker/Directory.php +++ b/src/Worker/Directory.php @@ -8,7 +8,6 @@ namespace Friendica\Worker; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Search; use Friendica\Core\Worker; use Friendica\Database\DBA; @@ -40,7 +39,7 @@ class Directory Hook::callAll('globaldir_update', $arr); - Logger::info('Updating directory: ' . $arr['url']); + DI::logger()->info('Updating directory: ' . $arr['url']); if (strlen($arr['url'])) { DI::httpClient()->fetch($dir . '?url=' . bin2hex($arr['url']), HttpClientAccept::HTML, 0, '', HttpClientRequest::CONTACTDISCOVER); } diff --git a/src/Worker/FetchFeaturedPosts.php b/src/Worker/FetchFeaturedPosts.php index de8bc96b9a..be314decb7 100644 --- a/src/Worker/FetchFeaturedPosts.php +++ b/src/Worker/FetchFeaturedPosts.php @@ -7,7 +7,7 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Protocol\ActivityPub; class FetchFeaturedPosts @@ -18,8 +18,8 @@ class FetchFeaturedPosts */ public static function execute(string $url) { - Logger::info('Start fetching featured posts', ['url' => $url]); + DI::logger()->info('Start fetching featured posts', ['url' => $url]); ActivityPub\Processor::fetchFeaturedPosts($url); - Logger::info('Finished fetching featured posts', ['url' => $url]); + DI::logger()->info('Finished fetching featured posts', ['url' => $url]); } } diff --git a/src/Worker/FetchMissingActivity.php b/src/Worker/FetchMissingActivity.php index 5b6e8ffd03..4cbc47976d 100644 --- a/src/Worker/FetchMissingActivity.php +++ b/src/Worker/FetchMissingActivity.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\DI; use Friendica\Protocol\ActivityPub; @@ -26,18 +25,18 @@ class FetchMissingActivity */ public static function execute(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL) { - Logger::info('Start fetching missing activity', ['url' => $url]); + DI::logger()->info('Start fetching missing activity', ['url' => $url]); if (ActivityPub\Processor::alreadyKnown($url, $child['id'] ?? '')) { - Logger::info('Activity is already known.', ['url' => $url]); + DI::logger()->info('Activity is already known.', ['url' => $url]); return; } $result = ActivityPub\Processor::fetchMissingActivity($url, $child, $relay_actor, $completion); if ($result) { - Logger::info('Successfully fetched missing activity', ['url' => $url]); + DI::logger()->info('Successfully fetched missing activity', ['url' => $url]); } elseif (is_null($result)) { - Logger::info('Permament error, activity could not be fetched', ['url' => $url]); + DI::logger()->info('Permament error, activity could not be fetched', ['url' => $url]); } elseif (!Worker::defer(self::WORKER_DEFER_LIMIT)) { - Logger::info('Defer limit reached, activity could not be fetched', ['url' => $url]); + DI::logger()->info('Defer limit reached, activity could not be fetched', ['url' => $url]); // recursively delete all entries that belong to this worker task $queue = DI::appHelper()->getQueue(); @@ -45,7 +44,7 @@ class FetchMissingActivity Queue::deleteByWorkerId($queue['id']); } } else { - Logger::info('Fetching deferred', ['url' => $url]); + DI::logger()->info('Fetching deferred', ['url' => $url]); } } } diff --git a/src/Worker/MergeContact.php b/src/Worker/MergeContact.php index 5c32f80fec..cdb464211b 100644 --- a/src/Worker/MergeContact.php +++ b/src/Worker/MergeContact.php @@ -7,9 +7,9 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\Database\DBStructure; +use Friendica\DI; use Friendica\Model\Contact; class MergeContact @@ -28,7 +28,7 @@ class MergeContact return; } - Logger::info('Handling duplicate', ['search' => $old_cid, 'replace' => $new_cid]); + DI::logger()->info('Handling duplicate', ['search' => $old_cid, 'replace' => $new_cid]); foreach (['item', 'thread', 'post-user', 'post-thread-user'] as $table) { if (DBStructure::existsTable($table)) { diff --git a/src/Worker/NodeInfo.php b/src/Worker/NodeInfo.php index 89fca9a1b3..363d2ce1f9 100644 --- a/src/Worker/NodeInfo.php +++ b/src/Worker/NodeInfo.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Model\Nodeinfo as ModelNodeInfo; use Friendica\Network\HTTPClient\Client\HttpClientAccept; @@ -16,13 +15,13 @@ class NodeInfo { public static function execute() { - Logger::info('start'); + DI::logger()->info('start'); ModelNodeInfo::update(); // Now trying to register $url = 'http://the-federation.info/register/' . DI::baseUrl()->getHost(); - Logger::debug('Check registering url', ['url' => $url]); + DI::logger()->debug('Check registering url', ['url' => $url]); $ret = DI::httpClient()->fetch($url, HttpClientAccept::HTML); - Logger::debug('Check registering answer', ['answer' => $ret]); - Logger::info('end'); + DI::logger()->debug('Check registering answer', ['answer' => $ret]); + DI::logger()->info('end'); } } diff --git a/src/Worker/OptimizeTables.php b/src/Worker/OptimizeTables.php index 853abc3c95..85231a0466 100644 --- a/src/Worker/OptimizeTables.php +++ b/src/Worker/OptimizeTables.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; @@ -20,11 +19,11 @@ class OptimizeTables { if (!DI::lock()->acquire('optimize_tables', 0)) { - Logger::warning('Lock could not be acquired'); + DI::logger()->warning('Lock could not be acquired'); return; } - Logger::info('Optimize start'); + DI::logger()->info('Optimize start'); DBA::optimizeTable('cache'); DBA::optimizeTable('locks'); @@ -60,7 +59,7 @@ class OptimizeTables DBA::optimizeTable('tag'); } - Logger::info('Optimize end'); + DI::logger()->info('Optimize end'); DI::lock()->release('optimize_tables'); } diff --git a/src/Worker/PollContacts.php b/src/Worker/PollContacts.php index 66b3cc39da..9a5405bbc5 100644 --- a/src/Worker/PollContacts.php +++ b/src/Worker/PollContacts.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Worker; use Friendica\Database\DBA; @@ -52,7 +51,7 @@ class PollContacts $next_update = DateTimeFormat::utc($contact['last-update'] . ' + ' . $interval . ' minute'); if ($now < $next_update) { - Logger::debug('No update', ['cid' => $contact['id'], 'interval' => $interval, 'next' => $next_update, 'now' => $now]); + DI::logger()->debug('No update', ['cid' => $contact['id'], 'interval' => $interval, 'next' => $next_update, 'now' => $now]); continue; } @@ -64,7 +63,7 @@ class PollContacts $priority = Worker::PRIORITY_LOW; } - Logger::notice("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact['priority'] . " " . $contact["nick"] . " " . $contact["name"]); + DI::logger()->notice("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact['priority'] . " " . $contact["nick"] . " " . $contact["name"]); Worker::add(['priority' => $priority, 'dont_fork' => true, 'force_priority' => true], 'OnePoll', (int)$contact['id']); Worker::coolDown(); diff --git a/src/Worker/ProfileUpdate.php b/src/Worker/ProfileUpdate.php index 685229b3b5..700da98d8e 100644 --- a/src/Worker/ProfileUpdate.php +++ b/src/Worker/ProfileUpdate.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Worker; use Friendica\DI; use Friendica\Protocol\Delivery; @@ -35,7 +34,7 @@ class ProfileUpdate { $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser($uid); foreach ($inboxes as $inbox => $receivers) { - Logger::info('Profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub'); + DI::logger()->info('Profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub'); Worker::add(['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], 'APDelivery', Delivery::PROFILEUPDATE, diff --git a/src/Worker/PullDirectory.php b/src/Worker/PullDirectory.php index 4272b91d68..2410be7d96 100644 --- a/src/Worker/PullDirectory.php +++ b/src/Worker/PullDirectory.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Search; use Friendica\DI; use Friendica\Model\Contact; @@ -22,29 +21,29 @@ class PullDirectory public static function execute() { if (!DI::config()->get('system', 'synchronize_directory')) { - Logger::info('Synchronization deactivated'); + DI::logger()->info('Synchronization deactivated'); return; } $directory = Search::getGlobalDirectory(); if (empty($directory)) { - Logger::info('No directory configured'); + DI::logger()->info('No directory configured'); return; } $now = (int)(DI::keyValue()->get('last-directory-sync') ?? 0); - Logger::info('Synchronization started.', ['now' => $now, 'directory' => $directory]); + DI::logger()->info('Synchronization started.', ['now' => $now, 'directory' => $directory]); $result = DI::httpClient()->fetch($directory . '/sync/pull/since/' . $now, HttpClientAccept::JSON, 0, '', HttpClientRequest::CONTACTDISCOVER); if (empty($result)) { - Logger::info('Directory server return empty result.', ['directory' => $directory]); + DI::logger()->info('Directory server return empty result.', ['directory' => $directory]); return; } $contacts = json_decode($result, true); if (empty($contacts['results'])) { - Logger::info('No results fetched.', ['directory' => $directory]); + DI::logger()->info('No results fetched.', ['directory' => $directory]); return; } @@ -53,6 +52,6 @@ class PullDirectory $now = $contacts['now'] ?? 0; DI::keyValue()->set('last-directory-sync', $now); - Logger::info('Synchronization ended', ['now' => $now, 'count' => $result['count'], 'added' => $result['added'], 'updated' => $result['updated'], 'unchanged' => $result['unchanged'], 'directory' => $directory]); + DI::logger()->info('Synchronization ended', ['now' => $now, 'count' => $result['count'], 'added' => $result['added'], 'updated' => $result['updated'], 'unchanged' => $result['unchanged'], 'directory' => $directory]); } } diff --git a/src/Worker/PushSubscription.php b/src/Worker/PushSubscription.php index 4d47a4b18e..b1c07996f1 100644 --- a/src/Worker/PushSubscription.php +++ b/src/Worker/PushSubscription.php @@ -9,7 +9,6 @@ namespace Friendica\Worker; use Friendica\Content\Text\BBCode; use Friendica\Content\Text\Plaintext; -use Friendica\Core\Logger; use Friendica\Database\DBA; use Friendica\DI; use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory; @@ -32,30 +31,30 @@ class PushSubscription */ public static function execute(int $sid, int $nid) { - Logger::info('Start', ['subscription' => $sid, 'notification' => $nid]); + DI::logger()->info('Start', ['subscription' => $sid, 'notification' => $nid]); $subscription = DBA::selectFirst('subscription', [], ['id' => $sid]); if (empty($subscription)) { - Logger::info('Subscription not found', ['subscription' => $sid]); + DI::logger()->info('Subscription not found', ['subscription' => $sid]); return; } try { $notification = DI::notification()->selectOneById($nid); } catch (NotFoundException $e) { - Logger::info('Notification not found', ['notification' => $nid]); + DI::logger()->info('Notification not found', ['notification' => $nid]); return; } $application_token = DBA::selectFirst('application-token', [], ['application-id' => $subscription['application-id'], 'uid' => $subscription['uid']]); if (empty($application_token)) { - Logger::info('Application token not found', ['application' => $subscription['application-id']]); + DI::logger()->info('Application token not found', ['application' => $subscription['application-id']]); return; } $user = User::getById($notification->uid); if (empty($user)) { - Logger::info('User not found', ['application' => $subscription['uid']]); + DI::logger()->info('User not found', ['application' => $subscription['uid']]); return; } @@ -97,7 +96,7 @@ class PushSubscription 'body' => $body ?: $l10n->t('Empty Post'), ]; - Logger::info('Payload', ['payload' => $payload]); + DI::logger()->info('Payload', ['payload' => $payload]); $auth = [ 'VAPID' => [ @@ -114,9 +113,9 @@ class PushSubscription $endpoint = $report->getRequest()->getUri()->__toString(); if ($report->isSuccess()) { - Logger::info('Message sent successfully for subscription', ['subscription' => $sid, 'notification' => $nid, 'endpoint' => $endpoint]); + DI::logger()->info('Message sent successfully for subscription', ['subscription' => $sid, 'notification' => $nid, 'endpoint' => $endpoint]); } else { - Logger::info('Message failed to sent for subscription', ['subscription' => $sid, 'notification' => $nid, 'endpoint' => $endpoint, 'reason' => $report->getReason()]); + DI::logger()->info('Message failed to sent for subscription', ['subscription' => $sid, 'notification' => $nid, 'endpoint' => $endpoint, 'reason' => $report->getReason()]); } } } diff --git a/src/Worker/SearchDirectory.php b/src/Worker/SearchDirectory.php index 0c83ea2d31..ac7242235f 100644 --- a/src/Worker/SearchDirectory.php +++ b/src/Worker/SearchDirectory.php @@ -8,7 +8,6 @@ namespace Friendica\Worker; use Friendica\Core\Cache\Enum\Duration; -use Friendica\Core\Logger; use Friendica\Core\Search; use Friendica\DI; use Friendica\Model\Contact; @@ -21,7 +20,7 @@ class SearchDirectory public static function execute($search) { if (!DI::config()->get('system', 'poco_local_search')) { - Logger::info('Local search is not enabled'); + DI::logger()->info('Local search is not enabled'); return; } @@ -29,7 +28,7 @@ class SearchDirectory if (!is_null($data)) { // Only search for the same item every 24 hours if (time() < $data + (60 * 60 * 24)) { - Logger::info('Already searched this in the last 24 hours', ['search' => $search]); + DI::logger()->info('Already searched this in the last 24 hours', ['search' => $search]); return; } } diff --git a/src/Worker/SetSeen.php b/src/Worker/SetSeen.php index 2428bd8dec..ea26494abd 100644 --- a/src/Worker/SetSeen.php +++ b/src/Worker/SetSeen.php @@ -7,7 +7,7 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; +use Friendica\DI; use Friendica\Model\Item; /** @@ -18,6 +18,6 @@ class SetSeen public static function execute(int $uid) { $ret = Item::update(['unseen' => false], ['unseen' => true, 'uid' => $uid]); - Logger::debug('Set seen', ['uid' => $uid, 'ret' => $ret]); + DI::logger()->debug('Set seen', ['uid' => $uid, 'ret' => $ret]); } } diff --git a/src/Worker/SpoolPost.php b/src/Worker/SpoolPost.php index 9d0a21f5c3..aab2b7a975 100644 --- a/src/Worker/SpoolPost.php +++ b/src/Worker/SpoolPost.php @@ -7,8 +7,8 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\System; +use Friendica\DI; use Friendica\Model\Item; /** @@ -24,7 +24,7 @@ class SpoolPost { // It is not named like a spool file, so we don't care. if (substr($file, 0, 5) != "item-") { - Logger::info('Spool file does not start with "item-"', ['file' => $file]); + DI::logger()->info('Spool file does not start with "item-"', ['file' => $file]); continue; } @@ -32,13 +32,13 @@ class SpoolPost { // We don't care about directories either if (filetype($fullfile) != "file") { - Logger::info('Spool file is no file', ['file' => $file]); + DI::logger()->info('Spool file is no file', ['file' => $file]); continue; } // We can't read or write the file? So we don't care about it. if (!is_writable($fullfile) || !is_readable($fullfile)) { - Logger::warning('Spool file has insufficent permissions', ['file' => $file, 'writable' => is_writable($fullfile), 'readable' => is_readable($fullfile)]); + DI::logger()->warning('Spool file has insufficent permissions', ['file' => $file, 'writable' => is_writable($fullfile), 'readable' => is_readable($fullfile)]); continue; } @@ -46,19 +46,19 @@ class SpoolPost { // If it isn't an array then it is no spool file if (!is_array($arr)) { - Logger::notice('Spool file is no array', ['file' => $file]); + DI::logger()->notice('Spool file is no array', ['file' => $file]); continue; } // Skip if it doesn't seem to be an item array if (!isset($arr['uid']) && !isset($arr['uri']) && !isset($arr['network'])) { - Logger::warning('Spool file does not contain the needed fields', ['file' => $file]); + DI::logger()->warning('Spool file does not contain the needed fields', ['file' => $file]); continue; } $result = Item::insert($arr); - Logger::info('Spool file is stored', ['file' => $file, 'result' => $result]); + DI::logger()->info('Spool file is stored', ['file' => $file, 'result' => $result]); unlink($fullfile); } closedir($dh); From 90a76ec60b3c221b801c84f4ccb6e173e52c6412 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:20:33 +0000 Subject: [PATCH 42/91] Replace Logger with DI::logger() in Notifier Worker classes --- src/Worker/Notifier.php | 111 ++++++++++++++++++++-------------------- 1 file changed, 55 insertions(+), 56 deletions(-) diff --git a/src/Worker/Notifier.php b/src/Worker/Notifier.php index 35e206bf38..eccb0bb602 100644 --- a/src/Worker/Notifier.php +++ b/src/Worker/Notifier.php @@ -9,7 +9,6 @@ namespace Friendica\Worker; use Exception; use Friendica\Core\Hook; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\Worker; use Friendica\Database\DBA; @@ -46,7 +45,7 @@ class Notifier { $appHelper = DI::appHelper(); - Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]); + DI::logger()->info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]); $target_id = $post_uriid; $recipients = []; @@ -70,7 +69,7 @@ class Notifier $inboxes = ActivityPub\Transmitter::fetchTargetInboxesFromMail($target_id); foreach ($inboxes as $inbox => $receivers) { $ap_contacts = array_merge($ap_contacts, $receivers); - Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'target' => $target_id, 'inbox' => $inbox]); + DI::logger()->info('Delivery via ActivityPub', ['cmd' => $cmd, 'target' => $target_id, 'inbox' => $inbox]); Worker::add(['priority' => Worker::PRIORITY_HIGH, 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], 'APDelivery', $cmd, $target_id, $inbox, $uid, $receivers, $post_uriid); } @@ -88,7 +87,7 @@ class Notifier } else { $post = Post::selectFirst(['id'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]); if (!DBA::isResult($post)) { - Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]); + DI::logger()->warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]); return; } $target_id = $post['id']; @@ -99,7 +98,7 @@ class Notifier $target_item = Post\Media::addHTMLAttachmentToItem($target_item); if (!DBA::isResult($target_item) || !intval($target_item['parent'])) { - Logger::info('No target item', ['cmd' => $cmd, 'target' => $target_id]); + DI::logger()->info('No target item', ['cmd' => $cmd, 'target' => $target_id]); return; } @@ -108,7 +107,7 @@ class Notifier } elseif (!empty($target_item['uid'])) { $uid = $target_item['uid']; } else { - Logger::info('Only public users, quitting', ['target' => $target_id]); + DI::logger()->info('Only public users, quitting', ['target' => $target_id]); return; } @@ -116,7 +115,7 @@ class Notifier $params = ['order' => ['id']]; $items_stmt = Post::select(Item::DELIVER_FIELDLIST, $condition, $params); if (!DBA::isResult($items_stmt)) { - Logger::info('No item found', ['cmd' => $cmd, 'target' => $target_id]); + DI::logger()->info('No item found', ['cmd' => $cmd, 'target' => $target_id]); return; } @@ -132,7 +131,7 @@ class Notifier $owner = User::getOwnerDataById($uid); if (!$owner) { - Logger::info('Owner not found', ['cmd' => $cmd, 'target' => $target_id]); + DI::logger()->info('Owner not found', ['cmd' => $cmd, 'target' => $target_id]); return; } @@ -159,7 +158,7 @@ class Notifier $thr_parent = $parent; } - Logger::info('Got post', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'network' => $target_item['network'], 'parent-network' => $parent['network'], 'thread-parent-network' => $thr_parent['network']]); + DI::logger()->info('Got post', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'network' => $target_item['network'], 'parent-network' => $parent['network'], 'thread-parent-network' => $thr_parent['network']]); // Restrict distribution to AP, when there are no permissions. if (!self::isRemovalActivity($cmd, $owner, Protocol::ACTIVITYPUB) && ($target_item['private'] == Item::PRIVATE) && empty($target_item['allow_cid']) && empty($target_item['allow_gid']) && empty($target_item['deny_cid']) && empty($target_item['deny_gid'])) { @@ -171,7 +170,7 @@ class Notifier if (!$target_item['origin'] && $target_item['network'] == Protocol::ACTIVITYPUB) { $only_ap_delivery = true; $diaspora_delivery = false; - Logger::debug('Remote post arrived via AP', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'network' => $target_item['network'], 'parent-network' => $parent['network'], 'thread-parent-network' => $thr_parent['network']]); + DI::logger()->debug('Remote post arrived via AP', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'network' => $target_item['network'], 'parent-network' => $parent['network'], 'thread-parent-network' => $thr_parent['network']]); } // Only deliver threaded replies (comment to a comment) to Diaspora @@ -179,10 +178,10 @@ class Notifier if ($thr_parent['author-link'] && $target_item['parent-uri'] != $target_item['thr-parent']) { $diaspora_delivery = Diaspora::isSupportedByContactUrl($thr_parent['author-link']); if ($diaspora_delivery && empty($target_item['signed_text'])) { - Logger::debug('Post has got no Diaspora signature, so there will be no Diaspora delivery', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id']]); + DI::logger()->debug('Post has got no Diaspora signature, so there will be no Diaspora delivery', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id']]); $diaspora_delivery = false; } - Logger::info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]); + DI::logger()->info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]); } $unlisted = $target_item['private'] == Item::UNLISTED; @@ -215,11 +214,11 @@ class Notifier $exclusive_targets = Tag::getByURIId($parent['uri-id'], [Tag::EXCLUSIVE_MENTION]); if (!empty($exclusive_targets)) { $exclusive_delivery = true; - Logger::info('Possible Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id']]); + DI::logger()->info('Possible Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id']]); foreach ($exclusive_targets as $target) { if (Strings::compareLink($owner['url'], $target['url'])) { $exclusive_delivery = false; - Logger::info('False Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]); + DI::logger()->info('False Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]); } } } @@ -231,7 +230,7 @@ class Notifier $recipients = [$parent['contact-id']]; $recipients_followup = [$parent['contact-id']]; - Logger::info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]); + DI::logger()->info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]); } elseif ($exclusive_delivery) { $followup = true; @@ -239,18 +238,18 @@ class Notifier $cid = Contact::getIdForURL($target['url'], $uid, false); if ($cid) { $recipients_followup[] = $cid; - Logger::info('Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]); + DI::logger()->info('Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]); } } } else { $followup = false; - Logger::info('Distributing directly', ['target' => $target_id, 'guid' => $target_item['guid']]); + DI::logger()->info('Distributing directly', ['target' => $target_id, 'guid' => $target_item['guid']]); // don't send deletions onward for other people's stuff if ($target_item['deleted'] && !intval($target_item['wall'])) { - Logger::notice('Ignoring delete notification for non-wall item'); + DI::logger()->notice('Ignoring delete notification for non-wall item'); return; } @@ -305,7 +304,7 @@ class Notifier if ($diaspora_delivery) { $networks = [Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL]; if (($parent['network'] == Protocol::DIASPORA) || ($thr_parent['network'] == Protocol::DIASPORA)) { - Logger::info('Add AP contacts', ['target' => $target_id, 'guid' => $target_item['guid']]); + DI::logger()->info('Add AP contacts', ['target' => $target_id, 'guid' => $target_item['guid']]); $networks[] = Protocol::ACTIVITYPUB; } } else { @@ -375,7 +374,7 @@ class Notifier } if (!empty($target_item)) { - Logger::info('Calling hooks for ' . $cmd . ' ' . $target_id); + DI::logger()->info('Calling hooks for ' . $cmd . ' ' . $target_id); Hook::fork($appHelper->getQueueValue('priority'), 'notifier_normal', $target_item); @@ -420,7 +419,7 @@ class Notifier $delivery_queue_count = 0; if (!empty($target_item['verb']) && ($target_item['verb'] == Activity::ANNOUNCE)) { - Logger::notice('Announces are only delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->notice('Announces are only delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); return 0; } @@ -428,40 +427,40 @@ class Notifier // Transmit via Diaspora if the thread had started as Diaspora post. // Also transmit via Diaspora if this is a direct answer to a Diaspora comment. if (($contact['network'] != Protocol::DIASPORA) && in_array(Protocol::DIASPORA, [$parent['network'] ?? '', $thr_parent['network'] ?? '', $target_item['network'] ?? ''])) { - Logger::info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]); + DI::logger()->info('Enforcing the Diaspora protocol', ['id' => $contact['id'], 'network' => $contact['network'], 'parent' => $parent['network'], 'thread-parent' => $thr_parent['network'], 'post' => $target_item['network']]); $contact['network'] = Protocol::DIASPORA; } // Direct delivery of local contacts if (!in_array($cmd, [Delivery::RELOCATION, Delivery::SUGGESTION, Delivery::MAIL]) && $target_uid = User::getIdForURL($contact['url'])) { if ($cmd == Delivery::DELETION) { - Logger::info('No need to deliver deletions internally', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->info('No need to deliver deletions internally', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); continue; } if ($target_item['origin'] || ($target_item['network'] != Protocol::ACTIVITYPUB)) { if ($target_uid != $target_item['uid']) { $fields = ['protocol' => Conversation::PARCEL_LOCAL_DFRN, 'direction' => Conversation::PUSH, 'post-reason' => Item::PR_DIRECT]; Item::storeForUserByUriId($target_item['uri-id'], $target_uid, $fields, $target_item['uid']); - Logger::info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'target' => $target_uid]); + DI::logger()->info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'target' => $target_uid]); } else { - Logger::info('No need to deliver to myself', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->info('No need to deliver to myself', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); } } else { - Logger::info('Remote item does not need to be delivered locally', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->info('Remote item does not need to be delivered locally', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); } continue; } $cdata = Contact::getPublicAndUserContactID($contact['id'], $sender_uid); if (empty($cdata)) { - Logger::info('No contact entry found', ['id' => $contact['id'], 'uid' => $sender_uid]); + DI::logger()->info('No contact entry found', ['id' => $contact['id'], 'uid' => $sender_uid]); continue; } if (in_array($cdata['public'] ?: $contact['id'], $ap_contacts)) { - Logger::info('The public contact is already delivered via AP, so skip delivery via legacy DFRN/Diaspora', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); + DI::logger()->info('The public contact is already delivered via AP, so skip delivery via legacy DFRN/Diaspora', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); continue; } elseif (in_array($cdata['user'] ?: $contact['id'], $ap_contacts)) { - Logger::info('The user contact is already delivered via AP, so skip delivery via legacy DFRN/Diaspora', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); + DI::logger()->info('The user contact is already delivered via AP, so skip delivery via legacy DFRN/Diaspora', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); continue; } @@ -469,29 +468,29 @@ class Notifier // We mark the contact here, since we could have only got here, when the "archived" value on this // specific contact hadn't been set. Contact::markForArchival($contact); - Logger::info('Contact is archived, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); + DI::logger()->info('Contact is archived, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); continue; } if (self::isRemovalActivity($cmd, $owner, $contact['network'])) { - Logger::info('Contact does no supports account removal commands, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); + DI::logger()->info('Contact does no supports account removal commands, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]); continue; } if (self::skipActivityPubForDiaspora($contact, $target_item, $thr_parent)) { - Logger::info('Contact is from Diaspora, but the replied author is from ActivityPub, so skip delivery via Diaspora', ['id' => $post_uriid, 'uid' => $sender_uid, 'url' => $contact['url']]); + DI::logger()->info('Contact is from Diaspora, but the replied author is from ActivityPub, so skip delivery via Diaspora', ['id' => $post_uriid, 'uid' => $sender_uid, 'url' => $contact['url']]); continue; } // Don't deliver to Diaspora if it already had been done as batch delivery if (!$in_batch && $batch_delivery && ($contact['network'] == Protocol::DIASPORA)) { - Logger::info('Diaspora contact is already delivered via batch', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]); + DI::logger()->info('Diaspora contact is already delivered via batch', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]); continue; } // Don't deliver to folks who have already been delivered to if (in_array($contact['id'], $conversants)) { - Logger::info('Already delivery', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]); + DI::logger()->info('Already delivery', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]); continue; } @@ -504,16 +503,16 @@ class Notifier } if (!$reachable) { - Logger::info('Server is not reachable', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]); + DI::logger()->info('Server is not reachable', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]); continue; } if (($contact['network'] == Protocol::ACTIVITYPUB) && !DI::dsprContact()->existsByUriId($contact['uri-id'])) { - Logger::info('The ActivityPub contact does not support Diaspora, so skip delivery via Diaspora', ['id' => $post_uriid, 'uid' => $sender_uid, 'url' => $contact['url']]); + DI::logger()->info('The ActivityPub contact does not support Diaspora, so skip delivery via Diaspora', ['id' => $post_uriid, 'uid' => $sender_uid, 'url' => $contact['url']]); continue; } - Logger::info('Delivery', ['cmd' => $cmd, 'batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'guid' => $target_item['guid'] ?? '', 'to' => $contact]); + DI::logger()->info('Delivery', ['cmd' => $cmd, 'batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'guid' => $target_item['guid'] ?? '', 'to' => $contact]); // Ensure that posts with our own protocol arrives before Diaspora posts arrive. // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first. @@ -617,7 +616,7 @@ class Notifier $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser($self_user_id); foreach ($inboxes as $inbox => $receivers) { - Logger::info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]); + DI::logger()->info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]); Worker::add(['priority' => Worker::PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true], 'APDelivery', Delivery::REMOVAL, 0, $inbox, $self_user_id, $receivers); Worker::coolDown(); @@ -644,25 +643,25 @@ class Notifier { // Don't deliver via AP when the starting post isn't from a federated network if (!in_array($parent['network'] ?? '', Protocol::FEDERATED)) { - Logger::info('Parent network is no federated network, so no AP delivery', ['network' => $parent['network'] ?? '']); + DI::logger()->info('Parent network is no federated network, so no AP delivery', ['network' => $parent['network'] ?? '']); return ['count' => 0, 'contacts' => []]; } // Don't deliver via AP when the starting post is delivered via Diaspora if ($parent['network'] == Protocol::DIASPORA) { - Logger::info('Parent network is Diaspora, so no AP delivery'); + DI::logger()->info('Parent network is Diaspora, so no AP delivery'); return ['count' => 0, 'contacts' => []]; } // Also don't deliver when the direct thread parent was delivered via Diaspora if ($thr_parent['network'] == Protocol::DIASPORA) { - Logger::info('Thread parent network is Diaspora, so no AP delivery'); + DI::logger()->info('Thread parent network is Diaspora, so no AP delivery'); return ['count' => 0, 'contacts' => []]; } // Posts from Diaspora contacts are transmitted via Diaspora if ($target_item['network'] == Protocol::DIASPORA) { - Logger::info('Post network is Diaspora, so no AP delivery'); + DI::logger()->info('Post network is Diaspora, so no AP delivery'); return ['count' => 0, 'contacts' => []]; } @@ -687,10 +686,10 @@ class Notifier $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes(); } - Logger::info('Origin item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); + DI::logger()->info('Origin item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); $check_signature = false; } elseif (!$target_item['deleted'] && !Post\Activity::exists($target_item['uri-id'])) { - Logger::info('Remote activity not found. It will not be distributed.', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); + DI::logger()->info('Remote activity not found. It will not be distributed.', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); return ['count' => 0, 'contacts' => []]; } elseif ($parent['origin'] && ($target_item['private'] != Item::PRIVATE) && (($target_item['gravity'] != Item::GRAVITY_ACTIVITY) || DI::config()->get('system', 'redistribute_activities'))) { $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid); @@ -699,10 +698,10 @@ class Notifier $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($parent['id'], $inboxes); } - Logger::info('Remote item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); + DI::logger()->info('Remote item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); $check_signature = ($target_item['gravity'] == Item::GRAVITY_ACTIVITY); } else { - Logger::info('Remote activity will not be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); + DI::logger()->info('Remote activity will not be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); return ['count' => 0, 'contacts' => []]; } @@ -711,19 +710,19 @@ class Notifier } if (empty($inboxes) && empty($relay_inboxes)) { - Logger::info('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.'); + DI::logger()->info('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.'); return ['count' => 0, 'contacts' => []]; } // Fill the item cache $activity = ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true); if (empty($activity)) { - Logger::info('Item cache was not created. The post will not be distributed.', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); + DI::logger()->info('Item cache was not created. The post will not be distributed.', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); return ['count' => 0, 'contacts' => []]; } if ($check_signature && !LDSignature::isSigned($activity)) { - Logger::info('Unsigned remote activity will not be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); + DI::logger()->info('Unsigned remote activity will not be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]); return ['count' => 0, 'contacts' => []]; } @@ -737,27 +736,27 @@ class Notifier $contact = Contact::getById($receivers[0], ['url']); if (!in_array($cmd, [Delivery::RELOCATION, Delivery::SUGGESTION, Delivery::MAIL]) && ($target_uid = User::getIdForURL($contact['url']))) { if ($cmd == Delivery::DELETION) { - Logger::info('No need to deliver deletions internally', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->info('No need to deliver deletions internally', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); continue; } if ($target_item['origin'] || ($target_item['network'] != Protocol::ACTIVITYPUB)) { if ($target_uid != $target_item['uid']) { $fields = ['protocol' => Conversation::PARCEL_LOCAL_DFRN, 'direction' => Conversation::PUSH, 'post-reason' => Item::PR_BCC]; Item::storeForUserByUriId($target_item['uri-id'], $target_uid, $fields, $target_item['uid']); - Logger::info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]); + DI::logger()->info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]); } else { - Logger::info('No need to deliver to myself', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->info('No need to deliver to myself', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); } } else { - Logger::info('Remote item does not need to be delivered locally', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->info('Remote item does not need to be delivered locally', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); } continue; } } elseif ((count($receivers) >= 1) && DI::baseUrl()->isLocalUrl($inbox)) { - Logger::info('Is this a thing?', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); + DI::logger()->info('Is this a thing?', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]); } - Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]); + DI::logger()->info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]); if (DI::config()->get('system', 'bulk_delivery')) { $delivery_queue_count++; @@ -774,7 +773,7 @@ class Notifier // We deliver posts to relay servers slightly delayed to prioritize the direct delivery foreach ($relay_inboxes as $inbox) { - Logger::info('Delivery to relay servers via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]); + DI::logger()->info('Delivery to relay servers via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]); if (DI::config()->get('system', 'bulk_delivery')) { $delivery_queue_count++; From abe6bf79472a994dbae14064d2d856bc929c8074 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:21:19 +0000 Subject: [PATCH 43/91] Replace Logger with DI::logger() in OnePoll Worker classes --- src/Worker/OnePoll.php | 88 +++++++++++++++++++++--------------------- 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/src/Worker/OnePoll.php b/src/Worker/OnePoll.php index c9b16717b7..5fb4293d84 100644 --- a/src/Worker/OnePoll.php +++ b/src/Worker/OnePoll.php @@ -7,7 +7,6 @@ namespace Friendica\Worker; -use Friendica\Core\Logger; use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; @@ -21,7 +20,6 @@ use Friendica\Network\HTTPClient\Client\HttpClientAccept; use Friendica\Network\HTTPClient\Client\HttpClientOptions; use Friendica\Network\HTTPClient\Client\HttpClientRequest; use Friendica\Protocol\Activity; -use Friendica\Protocol\ActivityPub; use Friendica\Protocol\Email; use Friendica\Protocol\Feed; use Friendica\Util\DateTimeFormat; @@ -32,18 +30,18 @@ class OnePoll { public static function execute(int $contact_id = 0, string $command = '') { - Logger::notice('Start polling/probing contact', ['id' => $contact_id, 'command' => $command]); + DI::logger()->notice('Start polling/probing contact', ['id' => $contact_id, 'command' => $command]); $force = ($command == 'force'); if (empty($contact_id)) { - Logger::notice('no contact provided'); + DI::logger()->notice('no contact provided'); return; } $contact = DBA::selectFirst('contact', [], ['id' => $contact_id]); if (!DBA::isResult($contact)) { - Logger::warning('Contact not found', ['id' => $contact_id]); + DI::logger()->warning('Contact not found', ['id' => $contact_id]); return; } @@ -65,14 +63,14 @@ class OnePoll && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL])) { $importer = User::getOwnerDataById($importer_uid); if (empty($importer)) { - Logger::warning('No self contact for user', ['uid' => $importer_uid]); + DI::logger()->warning('No self contact for user', ['uid' => $importer_uid]); // set the last-update so we don't keep polling Contact::update(['last-update' => $updated], ['id' => $contact['id']]); return; } - Logger::info('Start polling/subscribing', ['protocol' => $contact['network'], 'id' => $contact['id']]); + DI::logger()->info('Start polling/subscribing', ['protocol' => $contact['network'], 'id' => $contact['id']]); if ($contact['network'] === Protocol::FEED) { $success = self::pollFeed($contact, $importer); } elseif ($contact['network'] === Protocol::MAIL) { @@ -81,7 +79,7 @@ class OnePoll $success = self::subscribeToHub($contact['url'], $importer, $contact, $contact['blocked'] ? 'unsubscribe' : 'subscribe'); } if (!$success) { - Logger::notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]); + DI::logger()->notice('Probing had been successful, polling/subscribing failed', ['protocol' => $contact['network'], 'id' => $contact['id'], 'url' => $contact['url']]); } } @@ -93,7 +91,7 @@ class OnePoll Contact::markForArchival($contact); } - Logger::notice('End'); + DI::logger()->notice('End'); return; } @@ -136,12 +134,12 @@ class OnePoll { // Are we allowed to import from this person? if ($contact['rel'] == Contact::FOLLOWER || $contact['blocked']) { - Logger::notice('Contact is blocked or only a follower'); + DI::logger()->notice('Contact is blocked or only a follower'); return false; } if (!Network::isValidHttpUrl($contact['poll'])) { - Logger::warning('Poll address is not valid', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'poll' => $contact['poll']]); + DI::logger()->warning('Poll address is not valid', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'poll' => $contact['poll']]); return false; } @@ -150,25 +148,25 @@ class OnePoll try { $curlResult = DI::httpClient()->get($contact['poll'], HttpClientAccept::FEED_XML, [HttpClientOptions::COOKIEJAR => $cookiejar, HttpClientOptions::REQUEST => HttpClientRequest::FEEDFETCHER]); } 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; } unlink($cookiejar); - Logger::debug('Polled feed', ['url' => $contact['poll'], 'http-code' => $curlResult->getReturnCode(), 'redirect-url' => $curlResult->getRedirectUrl()]); + DI::logger()->debug('Polled feed', ['url' => $contact['poll'], 'http-code' => $curlResult->getReturnCode(), 'redirect-url' => $curlResult->getRedirectUrl()]); if ($curlResult->isTimeout()) { - Logger::notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]); + DI::logger()->notice('Polling timed out', ['id' => $contact['id'], 'url' => $contact['poll']]); return false; } if ($curlResult->isGone()) { - Logger::notice('URL is permanently gone', ['id' => $contact['id'], 'url' => $contact['poll']]); + DI::logger()->notice('URL is permanently gone', ['id' => $contact['id'], 'url' => $contact['poll']]); Contact::remove($contact['id']); return false; } if ($curlResult->redirectIsPermanent()) { - Logger::notice('Poll address permanently changed', [ + DI::logger()->notice('Poll address permanently changed', [ 'id' => $contact['id'], 'uid' => $contact['uid'], 'old' => $contact['poll'], @@ -179,21 +177,21 @@ class OnePoll $xml = $curlResult->getBodyString(); if (empty($xml)) { - Logger::notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]); + DI::logger()->notice('Empty content', ['id' => $contact['id'], 'url' => $contact['poll']]); return false; } if (strpos($curlResult->getContentType(), 'xml') === false) { - Logger::notice('Unexpected content type.', ['id' => $contact['id'], 'url' => $contact['poll'], 'content-type' => $curlResult->getContentType()]); + DI::logger()->notice('Unexpected content type.', ['id' => $contact['id'], 'url' => $contact['poll'], 'content-type' => $curlResult->getContentType()]); return false; } if (!strstr($xml, '<')) { - Logger::notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]); + DI::logger()->notice('response did not contain XML.', ['id' => $contact['id'], 'url' => $contact['poll']]); return false; } - Logger::notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]); + DI::logger()->notice('Consume feed of contact', ['id' => $contact['id'], 'url' => $contact['poll'], 'Content-Type' => $curlResult->getHeader('Content-Type')]); return !empty(Feed::import($xml, $importer, $contact)); } @@ -210,15 +208,15 @@ class OnePoll */ private static function pollMail(array $contact, int $importer_uid, string $updated): bool { - Logger::info('Fetching mails', ['addr' => $contact['addr']]); + DI::logger()->info('Fetching mails', ['addr' => $contact['addr']]); $mail_disabled = ((function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) ? 0 : 1); if ($mail_disabled) { - Logger::notice('Mail is disabled'); + DI::logger()->notice('Mail is disabled'); return false; } - Logger::info('Mail is enabled'); + DI::logger()->info('Mail is enabled'); $mbox = false; $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]); @@ -231,16 +229,16 @@ class OnePoll openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']); $mbox = Email::connect($mailbox, $mailconf['user'], $password); unset($password); - Logger::notice('Connect', ['user' => $mailconf['user']]); + DI::logger()->notice('Connect', ['user' => $mailconf['user']]); if ($mbox === false) { - Logger::notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]); + DI::logger()->notice('Connection error', ['user' => $mailconf['user'], 'error' => imap_errors()]); return false; } $fields = ['last_check' => $updated]; DBA::update('mailacct', $fields, ['id' => $mailconf['id']]); - Logger::notice('Connected', ['user' => $mailconf['user']]); + DI::logger()->notice('Connected', ['user' => $mailconf['user']]); } if ($mbox === false) { @@ -250,12 +248,12 @@ class OnePoll $msgs = Email::poll($mbox, $contact['addr']); if (count($msgs)) { - Logger::info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]); + DI::logger()->info('Parsing mails', ['count' => count($msgs), 'addr' => $contact['addr'], 'user' => $mailconf['user']]); $metas = Email::messageMeta($mbox, implode(',', $msgs)); if (count($metas) != count($msgs)) { - Logger::info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas"); + DI::logger()->info("for " . $mailconf['user'] . " there are ". count($msgs) . " messages but received " . count($metas) . " metas"); } else { $msgs = array_combine($msgs, $metas); @@ -264,7 +262,7 @@ class OnePoll continue; } - Logger::info('Parsing mail', ['message-uid' => $msg_uid]); + DI::logger()->info('Parsing mail', ['message-uid' => $msg_uid]); $datarray = [ 'uid' => $importer_uid, @@ -284,7 +282,7 @@ class OnePoll $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']]; $item = Post::selectFirst($fields, $condition); if (DBA::isResult($item)) { - Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . ' UID: ' . $importer_uid . ' URI: ' . $datarray['uri']); + DI::logger()->info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . ' UID: ' . $importer_uid . ' URI: ' . $datarray['uri']); // Only delete when mails aren't automatically moved or deleted if (($mailconf['action'] != 1) && ($mailconf['action'] != 3)) @@ -295,21 +293,21 @@ class OnePoll switch ($mailconf['action']) { case 0: - Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.'); + DI::logger()->info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.'); break; case 1: - Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']); + DI::logger()->notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']); imap_delete($mbox, $msg_uid, FT_UID); break; case 2: - Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']); + DI::logger()->notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']); imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID); break; case 3: - Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']); + DI::logger()->notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']); imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID); if ($mailconf['movetofolder'] != '') { imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID); @@ -421,31 +419,31 @@ class OnePoll $datarray = Email::getMessage($mbox, $msg_uid, $reply, $datarray); if (empty($datarray['body'])) { - Logger::warning('Cannot fetch mail', ['msg-id' => $msg_uid, 'uid' => $mailconf['user']]); + DI::logger()->warning('Cannot fetch mail', ['msg-id' => $msg_uid, 'uid' => $mailconf['user']]); continue; } - Logger::notice('Mail: Importing ' . $msg_uid . ' for ' . $mailconf['user']); + DI::logger()->notice('Mail: Importing ' . $msg_uid . ' for ' . $mailconf['user']); Item::insert($datarray); switch ($mailconf['action']) { case 0: - Logger::info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.'); + DI::logger()->info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . '. Doing nothing.'); break; case 1: - Logger::notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']); + DI::logger()->notice('Mail: Deleting ' . $msg_uid . ' for ' . $mailconf['user']); imap_delete($mbox, $msg_uid, FT_UID); break; case 2: - Logger::notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']); + DI::logger()->notice('Mail: Mark as seen ' . $msg_uid . ' for ' . $mailconf['user']); imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID); break; case 3: - Logger::notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']); + DI::logger()->notice('Mail: Moving ' . $msg_uid . ' to ' . $mailconf['movetofolder'] . ' for ' . $mailconf['user']); imap_setflag_full($mbox, $msg_uid, "\\Seen", ST_UID); if ($mailconf['movetofolder'] != '') { imap_mail_move($mbox, $msg_uid, $mailconf['movetofolder'], FT_UID); @@ -455,11 +453,11 @@ class OnePoll } } } else { - Logger::notice('No mails', ['user' => $mailconf['user']]); + DI::logger()->notice('No mails', ['user' => $mailconf['user']]); } - Logger::info('Closing connection', ['user' => $mailconf['user']]); + DI::logger()->info('Closing connection', ['user' => $mailconf['user']]); imap_close($mbox); return true; @@ -492,7 +490,7 @@ class OnePoll $params = 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token; - Logger::info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]); + DI::logger()->info('Hub subscription start', ['mode' => $hubmode, 'name' => $contact['name'], 'hub' => $url, 'endpoint' => $push_url, 'verifier' => $verify_token]); if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) { Contact::update(['hub-verify' => $verify_token], ['id' => $contact['id']]); @@ -501,11 +499,11 @@ class OnePoll try { $postResult = DI::httpClient()->post($url, $params, [], 0, HttpClientRequest::PUBSUB); } 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; } - Logger::info('Hub subscription done', ['result' => $postResult->getReturnCode()]); + DI::logger()->info('Hub subscription done', ['result' => $postResult->getReturnCode()]); return $postResult->isSuccess(); } From 5caa3b13e6c6c15e5a5eca6a27ab95c7744c7322 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:24:40 +0000 Subject: [PATCH 44/91] Remove call of non-existing Logger::init() method in tests --- tests/src/Console/AutomaticInstallationConsoleTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/src/Console/AutomaticInstallationConsoleTest.php b/tests/src/Console/AutomaticInstallationConsoleTest.php index 0c2ffe1072..23c2840524 100644 --- a/tests/src/Console/AutomaticInstallationConsoleTest.php +++ b/tests/src/Console/AutomaticInstallationConsoleTest.php @@ -104,7 +104,6 @@ class AutomaticInstallationConsoleTest extends ConsoleTestCase }); $this->mode->shouldReceive('isInstall')->andReturn(true); - Logger::init(new NullLogger()); } /** From d4697a17a37b885ff9d88fe914f4c37d042e5379 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:27:50 +0000 Subject: [PATCH 45/91] Remove unused import statements --- src/App/Page.php | 1 - src/Contact/Avatar.php | 1 - src/Module/Api/Mastodon/Accounts/Relationships.php | 2 -- src/Module/BaseSearch.php | 1 - src/Module/Smilies.php | 2 -- src/Object/Api/Mastodon/Attachment.php | 2 -- src/Util/Proxy.php | 1 - tests/src/Console/AutomaticInstallationConsoleTest.php | 2 -- 8 files changed, 12 deletions(-) diff --git a/src/App/Page.php b/src/App/Page.php index 6470afd6b8..45293b1e05 100644 --- a/src/App/Page.php +++ b/src/App/Page.php @@ -16,7 +16,6 @@ use Friendica\Content\Nav; use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Hook; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues; use Friendica\Core\Renderer; use Friendica\Core\Session\Model\UserSession; diff --git a/src/Contact/Avatar.php b/src/Contact/Avatar.php index 5bafa07e24..b7ec5372a0 100644 --- a/src/Contact/Avatar.php +++ b/src/Contact/Avatar.php @@ -7,7 +7,6 @@ namespace Friendica\Contact; -use Friendica\Core\Logger; use Friendica\DI; use Friendica\Network\HTTPClient\Client\HttpClientAccept; use Friendica\Network\HTTPClient\Client\HttpClientOptions; diff --git a/src/Module/Api/Mastodon/Accounts/Relationships.php b/src/Module/Api/Mastodon/Accounts/Relationships.php index 1d0ec65bcb..4f0c79ebfc 100644 --- a/src/Module/Api/Mastodon/Accounts/Relationships.php +++ b/src/Module/Api/Mastodon/Accounts/Relationships.php @@ -7,8 +7,6 @@ namespace Friendica\Module\Api\Mastodon\Accounts; -use Friendica\Core\Logger; -use Friendica\Core\System; use Friendica\DI; use Friendica\Module\BaseApi; diff --git a/src/Module/BaseSearch.php b/src/Module/BaseSearch.php index 046403ce6a..793787a627 100644 --- a/src/Module/BaseSearch.php +++ b/src/Module/BaseSearch.php @@ -9,7 +9,6 @@ namespace Friendica\Module; use Friendica\BaseModule; use Friendica\Content\Pager; -use Friendica\Core\Logger; use Friendica\Core\Renderer; use Friendica\Core\Search; use Friendica\DI; diff --git a/src/Module/Smilies.php b/src/Module/Smilies.php index 3556696ecc..b923e2ac7b 100644 --- a/src/Module/Smilies.php +++ b/src/Module/Smilies.php @@ -9,9 +9,7 @@ namespace Friendica\Module; use Friendica\BaseModule; use Friendica\Content; -use Friendica\Core\Logger; use Friendica\Core\Renderer; -use Friendica\Core\System; use Friendica\DI; /** diff --git a/src/Object/Api/Mastodon/Attachment.php b/src/Object/Api/Mastodon/Attachment.php index 323e4a77a8..c3871be795 100644 --- a/src/Object/Api/Mastodon/Attachment.php +++ b/src/Object/Api/Mastodon/Attachment.php @@ -8,8 +8,6 @@ namespace Friendica\Object\Api\Mastodon; use Friendica\BaseDataTransferObject; -use Friendica\Core\Logger; -use Friendica\Core\System; /** * Class Attachment diff --git a/src/Util/Proxy.php b/src/Util/Proxy.php index 82e852b6e7..1e49f7bbf5 100644 --- a/src/Util/Proxy.php +++ b/src/Util/Proxy.php @@ -8,7 +8,6 @@ namespace Friendica\Util; use Friendica\Content\Text\BBCode; -use Friendica\Core\Logger; use Friendica\DI; use GuzzleHttp\Psr7\Uri; diff --git a/tests/src/Console/AutomaticInstallationConsoleTest.php b/tests/src/Console/AutomaticInstallationConsoleTest.php index 23c2840524..9bc673ff4f 100644 --- a/tests/src/Console/AutomaticInstallationConsoleTest.php +++ b/tests/src/Console/AutomaticInstallationConsoleTest.php @@ -13,7 +13,6 @@ use Friendica\Console\AutomaticInstallation; use Friendica\Core\Config\ValueObject\Cache; use Friendica\Core\Installer; use Friendica\Core\L10n; -use Friendica\Core\Logger; use Friendica\Database\Database; use Friendica\DI; use Friendica\Test\ConsoleTestCase; @@ -23,7 +22,6 @@ use Mockery; use Mockery\MockInterface; use org\bovigo\vfs\vfsStream; use org\bovigo\vfs\vfsStreamFile; -use Psr\Log\NullLogger; class AutomaticInstallationConsoleTest extends ConsoleTestCase { From 0e59dba914c0411c84caf8d97e12c3a38c7303a7 Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:31:54 +0000 Subject: [PATCH 46/91] Fix code style --- mod/item.php | 22 +- mod/photos.php | 290 +++++++------- src/App/Page.php | 8 +- src/Contact/Avatar.php | 2 +- src/Content/Item.php | 136 +++---- src/Content/PageInfo.php | 11 +- src/Content/Text/BBCode.php | 117 +++--- src/Content/Text/Markdown.php | 13 +- src/Content/Widget/VCard.php | 18 +- src/Core/Addon.php | 28 +- src/Core/Protocol.php | 16 +- src/Core/Search.php | 10 +- src/Core/Theme.php | 24 +- src/Core/Update.php | 31 +- src/Core/Worker/Cron.php | 5 +- src/Database/DBStructure.php | 66 ++-- src/Database/PostUpdate.php | 144 ++++--- src/Factory/Api/Mastodon/Status.php | 6 +- src/Model/APContact.php | 29 +- src/Model/Circle.php | 97 ++--- src/Model/Contact.php | 202 +++++----- src/Model/Contact/Relation.php | 280 +++++++++----- src/Model/Contact/User.php | 8 +- src/Model/Event.php | 63 ++- src/Model/GServer.php | 253 ++++++------ src/Model/Item.php | 360 +++++++++--------- src/Model/Mail.php | 36 +- src/Model/Post.php | 10 +- src/Model/Post/Delayed.php | 14 +- src/Model/Post/Engagement.php | 44 ++- src/Model/Post/Link.php | 6 +- src/Model/Post/UserNotification.php | 2 +- src/Model/Profile.php | 108 +++--- src/Model/Tag.php | 24 +- src/Model/User.php | 191 +++++----- src/Module/ActivityPub/Objects.php | 14 +- src/Module/Api/Mastodon/Accounts/Statuses.php | 6 +- src/Module/Api/Mastodon/Directory.php | 6 +- src/Module/Api/Mastodon/Search.php | 8 +- src/Module/Api/Mastodon/Timelines/Home.php | 4 +- .../Api/Mastodon/Timelines/ListTimeline.php | 6 +- .../Api/Mastodon/Timelines/PublicTimeline.php | 4 +- src/Module/Api/Mastodon/Trends/Statuses.php | 2 +- src/Module/BaseApi.php | 26 +- src/Module/BaseSearch.php | 27 +- src/Module/Contact.php | 210 +++++----- src/Module/OAuth/Token.php | 7 +- src/Module/Owa.php | 2 +- src/Module/Photo.php | 32 +- src/Module/Register.php | 102 ++--- src/Module/Search/Index.php | 40 +- src/Module/Smilies.php | 2 +- src/Network/Probe.php | 98 ++--- src/Object/Api/Mastodon/Attachment.php | 20 +- src/Object/Post.php | 300 +++++++-------- src/Object/Thread.php | 14 +- src/Protocol/ActivityPub.php | 82 ++-- src/Protocol/ActivityPub/ClientToServer.php | 8 +- src/Protocol/ActivityPub/Delivery.php | 4 +- src/Protocol/ActivityPub/Processor.php | 168 ++++---- src/Protocol/ActivityPub/Queue.php | 8 +- src/Protocol/ActivityPub/Transmitter.php | 321 ++++++++-------- src/Protocol/DFRN.php | 291 +++++++------- src/Protocol/Delivery.php | 8 +- src/Protocol/Diaspora.php | 360 +++++++++--------- src/Protocol/Email.php | 80 ++-- src/Protocol/Feed.php | 102 ++--- src/Protocol/Relay.php | 47 +-- src/Security/BasicAuth.php | 16 +- src/Security/OAuth.php | 2 +- src/Util/Crypto.php | 14 +- src/Util/DateTimeFormat.php | 2 +- src/Util/HTTPSignature.php | 56 +-- src/Util/Images.php | 14 +- src/Util/JsonLD.php | 40 +- src/Util/LDSignature.php | 8 +- src/Util/Network.php | 25 +- src/Util/ParseUrl.php | 55 +-- src/Util/Proxy.php | 3 +- src/Util/Strings.php | 14 +- src/Util/XML.php | 34 +- src/Worker/APDelivery.php | 3 +- src/Worker/DelayedPublish.php | 20 +- src/Worker/Directory.php | 3 +- src/Worker/Expire.php | 15 +- src/Worker/ExpireAndRemoveUsers.php | 2 +- src/Worker/ExpirePosts.php | 22 +- src/Worker/Notifier.php | 110 ++++-- src/Worker/OnePoll.php | 35 +- src/Worker/PollContacts.php | 18 +- src/Worker/ProfileUpdate.php | 6 +- src/Worker/PushSubscription.php | 2 +- src/Worker/RemoveUnusedAvatars.php | 12 +- src/Worker/RemoveUnusedContacts.php | 2 +- src/Worker/SpoolPost.php | 8 +- src/Worker/UpdateBlockedServers.php | 4 +- src/Worker/UpdateContacts.php | 8 +- src/Worker/UpdateGServers.php | 6 +- .../AutomaticInstallationConsoleTest.php | 93 ++--- update.php | 48 ++- view/theme/frio/theme.php | 12 +- view/theme/vier/style.php | 7 +- 102 files changed, 3038 insertions(+), 2764 deletions(-) diff --git a/mod/item.php b/mod/item.php index f4dcf187fa..de9a51915a 100644 --- a/mod/item.php +++ b/mod/item.php @@ -131,10 +131,10 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat $post = DI::contentItem()->initializePost($post); $post['edit'] = null; - $post['post-type'] = $request['post_type'] ?? ''; - $post['wall'] = $request['wall'] ?? true; + $post['post-type'] = $request['post_type'] ?? ''; + $post['wall'] = $request['wall'] ?? true; $post['pubmail'] = $request['pubmail_enable'] ?? false; - $post['created'] = $request['created_at'] ?? DateTimeFormat::utcNow(); + $post['created'] = $request['created_at'] ?? DateTimeFormat::utcNow(); $post['edited'] = $post['changed'] = $post['commented'] = $post['created']; $post['app'] = ''; $post['inform'] = ''; @@ -167,15 +167,15 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat 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['gravity'] = Item::GRAVITY_COMMENT; - $post['thr-parent'] = $parent_item['uri']; - $post['wall'] = $toplevel_item['wall']; + $post['parent'] = $toplevel_item['id']; + $post['gravity'] = Item::GRAVITY_COMMENT; + $post['thr-parent'] = $parent_item['uri']; + $post['wall'] = $toplevel_item['wall']; } else { - $parent_item = []; - $post['parent'] = 0; - $post['gravity'] = Item::GRAVITY_PARENT; - $post['thr-parent'] = $post['uri']; + $parent_item = []; + $post['parent'] = 0; + $post['gravity'] = Item::GRAVITY_PARENT; + $post['thr-parent'] = $post['uri']; } $post = DI::contentItem()->getACL($post, $parent_item, $request); diff --git a/mod/photos.php b/mod/photos.php index 779d229000..c2831270ab 100644 --- a/mod/photos.php +++ b/mod/photos.php @@ -114,8 +114,8 @@ function photos_post() throw new HTTPException\NotFoundException(DI::l10n()->t('User not found.')); } - $can_post = false; - $visitor = 0; + $can_post = false; + $visitor = 0; $page_owner_uid = intval($user['uid']); $community_page = in_array($user['page-flags'], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_COMM_MAN]); @@ -124,8 +124,8 @@ function photos_post() $can_post = true; } elseif ($community_page && !empty(DI::userSession()->getRemoteContactID($page_owner_uid))) { $contact_id = DI::userSession()->getRemoteContactID($page_owner_uid); - $can_post = true; - $visitor = $contact_id; + $can_post = true; + $visitor = $contact_id; } if (!$can_post) { @@ -141,7 +141,7 @@ function photos_post() System::exit(); } - $aclFormatter = DI::aclFormatter(); + $aclFormatter = DI::aclFormatter(); $str_contact_allow = isset($_REQUEST['contact_allow']) ? $aclFormatter->toString($_REQUEST['contact_allow']) : $owner_record['allow_cid'] ?? ''; $str_circle_allow = isset($_REQUEST['circle_allow']) ? $aclFormatter->toString($_REQUEST['circle_allow']) : $owner_record['allow_gid'] ?? ''; $str_contact_deny = isset($_REQUEST['contact_deny']) ? $aclFormatter->toString($_REQUEST['contact_deny']) : $owner_record['deny_cid'] ?? ''; @@ -151,7 +151,7 @@ function photos_post() if ($visibility === 'public') { // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected $str_contact_allow = $str_circle_allow = $str_contact_deny = $str_circle_deny = ''; - } else if ($visibility === 'custom') { + } elseif ($visibility === 'custom') { // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL // case that would make it public. So we always append the author's contact id to the allowed contacts. // See https://github.com/friendica/friendica/issues/9672 @@ -317,7 +317,7 @@ function photos_post() if (DBA::isResult($photos)) { $photo = $photos[0]; - $ext = Images::getExtensionByMimeType($photo['type']); + $ext = Images::getExtensionByMimeType($photo['type']); Photo::update( ['desc' => $desc, 'album' => $albname, 'allow_cid' => $str_contact_allow, 'allow_gid' => $str_circle_allow, 'deny_cid' => $str_contact_deny, 'deny_gid' => $str_circle_deny], ['resource-id' => $resource_id, 'uid' => $page_owner_uid] @@ -332,9 +332,9 @@ function photos_post() if (DBA::isResult($photos) && !$item_id) { // Create item container $title = ''; - $uri = Item::newURI(); + $uri = Item::newURI(); - $arr = []; + $arr = []; $arr['guid'] = System::createUUID(); $arr['uid'] = $page_owner_uid; $arr['uri'] = $uri; @@ -356,7 +356,7 @@ function photos_post() $arr['visible'] = 0; $arr['origin'] = 1; - $arr['body'] = Images::getBBCodeByResource($photo['resource-id'], $user['nickname'], $photo['scale'], $ext); + $arr['body'] = Images::getBBCodeByResource($photo['resource-id'], $user['nickname'], $photo['scale'], $ext); $item_id = Item::insert($arr); } @@ -370,7 +370,7 @@ function photos_post() } if (strlen($rawtags)) { - $inform = ''; + $inform = ''; // if the new tag doesn't have a namespace specifier (@foo or #foo) give it a hashtag $x = substr($rawtags, 0, 1); @@ -379,13 +379,13 @@ function photos_post() } $taginfo = []; - $tags = BBCode::getTags($rawtags); + $tags = BBCode::getTags($rawtags); if (count($tags)) { foreach ($tags as $tag) { if (strpos($tag, '@') === 0) { $profile = ''; - $name = substr($tag, 1); + $name = substr($tag, 1); $contact = Contact::getByURL($name); if (empty($contact)) { $newname = $name; @@ -453,7 +453,7 @@ function photos_post() } $newinform .= $inform; - $fields = ['inform' => $newinform, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()]; + $fields = ['inform' => $newinform, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()]; $condition = ['id' => $item_id]; Item::update($fields, $condition); @@ -552,7 +552,7 @@ function photos_content() $datum = null; if (DI::args()->getArgc() > 3) { $datatype = DI::args()->getArgv()[2]; - $datum = DI::args()->getArgv()[3]; + $datum = DI::args()->getArgv()[3]; } elseif ((DI::args()->getArgc() > 2) && (DI::args()->getArgv()[2] === 'upload')) { $datatype = 'upload'; } else { @@ -582,12 +582,12 @@ function photos_content() $can_post = true; } elseif ($community_page && !empty(DI::userSession()->getRemoteContactID($owner_uid))) { $contact_id = DI::userSession()->getRemoteContactID($owner_uid); - $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]); + $contact = DBA::selectFirst('contact', [], ['id' => $contact_id, 'uid' => $owner_uid, 'blocked' => false, 'pending' => false]); if (DBA::isResult($contact)) { - $can_post = true; + $can_post = true; $remote_contact = true; - $visitor = $contact_id; + $visitor = $contact_id; } } @@ -643,14 +643,14 @@ function photos_content() $uploader = ''; $ret = [ - 'post_url' => 'profile/' . $user['nickname'] . '/photos', - 'addon_text' => $uploader, + 'post_url' => 'profile/' . $user['nickname'] . '/photos', + 'addon_text' => $uploader, 'default_upload' => true ]; Hook::callAll('photo_upload_form', $ret); - $default_upload_box = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_box.tpl'), []); + $default_upload_box = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_box.tpl'), []); $default_upload_submit = Renderer::replaceMacros(Renderer::getMarkupTemplate('photos_default_uploader_submit.tpl'), [ '$submit' => DI::l10n()->t('Submit'), ]); @@ -675,22 +675,22 @@ function photos_content() $aclselect_e = ($visitor ? '' : ACL::getFullSelectorHTML(DI::page(), DI::userSession()->getLocalUserId())); $o .= Renderer::replaceMacros($tpl, [ - '$pagename' => DI::l10n()->t('Upload Photos'), - '$sessid' => session_id(), - '$usage' => $usage_message, - '$nickname' => $user['nickname'], - '$newalbum' => DI::l10n()->t('New album name: '), - '$existalbumtext' => DI::l10n()->t('or select existing album:'), - '$nosharetext' => DI::l10n()->t('Do not show a status post for this upload'), - '$albumselect' => $albumselect, - '$selname' => $selname, - '$permissions' => DI::l10n()->t('Permissions'), - '$aclselect' => $aclselect_e, - '$lockstate' => ACL::getLockstateForUserId(DI::userSession()->getLocalUserId()) ? 'lock' : 'unlock', - '$alt_uploader' => $ret['addon_text'], - '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''), + '$pagename' => DI::l10n()->t('Upload Photos'), + '$sessid' => session_id(), + '$usage' => $usage_message, + '$nickname' => $user['nickname'], + '$newalbum' => DI::l10n()->t('New album name: '), + '$existalbumtext' => DI::l10n()->t('or select existing album:'), + '$nosharetext' => DI::l10n()->t('Do not show a status post for this upload'), + '$albumselect' => $albumselect, + '$selname' => $selname, + '$permissions' => DI::l10n()->t('Permissions'), + '$aclselect' => $aclselect_e, + '$lockstate' => ACL::getLockstateForUserId(DI::userSession()->getLocalUserId()) ? 'lock' : 'unlock', + '$alt_uploader' => $ret['addon_text'], + '$default_upload_box' => ($ret['default_upload'] ? $default_upload_box : ''), '$default_upload_submit' => ($ret['default_upload'] ? $default_upload_submit : ''), - '$uploadurl' => $ret['post_url'], + '$uploadurl' => $ret['post_url'], // ACL permissions box '$return_path' => DI::args()->getQueryString(), @@ -712,7 +712,7 @@ function photos_content() } $total = 0; - $r = DBA::toArray(DBA::p( + $r = DBA::toArray(DBA::p( "SELECT `resource-id`, MAX(`scale`) AS `scale` FROM `photo` WHERE `uid` = ? AND `album` = ? AND `scale` <= 4 $sql_extra GROUP BY `resource-id`", $owner_uid, @@ -748,7 +748,7 @@ function photos_content() $drop_url = DI::args()->getQueryString(); return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [ - '$l10n' => [ + '$l10n' => [ 'message' => DI::l10n()->t('Do you really want to delete this photo album and all its photos?'), 'confirm' => DI::l10n()->t('Delete Album'), 'cancel' => DI::l10n()->t('Cancel'), @@ -768,11 +768,11 @@ function photos_content() $album_e = $album; $o .= Renderer::replaceMacros($edit_tpl, [ - '$nametext' => DI::l10n()->t('New album name: '), - '$nickname' => $user['nickname'], - '$album' => $album_e, - '$hexalbum' => bin2hex($album), - '$submit' => DI::l10n()->t('Submit'), + '$nametext' => DI::l10n()->t('New album name: '), + '$nickname' => $user['nickname'], + '$album' => $album_e, + '$hexalbum' => bin2hex($album), + '$submit' => DI::l10n()->t('Submit'), '$dropsubmit' => DI::l10n()->t('Delete Album') ]); } @@ -782,7 +782,7 @@ function photos_content() } if ($order_field === 'created') { - $order = [DI::l10n()->t('Show Newest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album), 'oldest']; + $order = [DI::l10n()->t('Show Newest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album), 'oldest']; } else { $order = [DI::l10n()->t('Show Oldest First'), 'photos/' . $user['nickname'] . '/album/' . bin2hex($album) . '?order=created', 'newest']; } @@ -798,7 +798,7 @@ function photos_content() $ext = Images::getExtensionByMimeType($rr['type']); $imgalt_e = $rr['filename']; - $desc_e = $rr['desc']; + $desc_e = $rr['desc']; $photos[] = [ 'id' => $rr['id'], @@ -817,13 +817,13 @@ function photos_content() $tpl = Renderer::getMarkupTemplate('photo_album.tpl'); $o .= Renderer::replaceMacros($tpl, [ - '$photos' => $photos, - '$album' => $album, + '$photos' => $photos, + '$album' => $album, '$can_post' => $can_post, - '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload/' . bin2hex($album)], - '$order' => $order, - '$edit' => $edit, - '$drop' => $drop, + '$upload' => [DI::l10n()->t('Upload New Photos'), 'photos/' . $user['nickname'] . '/upload/' . bin2hex($album)], + '$order' => $order, + '$edit' => $edit, + '$drop' => $drop, '$paginate' => $pager->renderFull($total), ]); @@ -848,7 +848,7 @@ function photos_content() $drop_url = DI::args()->getQueryString(); return Renderer::replaceMacros(Renderer::getMarkupTemplate('confirm.tpl'), [ - '$l10n' => [ + '$l10n' => [ 'message' => DI::l10n()->t('Do you really want to delete this photo?'), 'confirm' => DI::l10n()->t('Delete Photo'), 'cancel' => DI::l10n()->t('Cancel'), @@ -950,8 +950,8 @@ function photos_content() if ($cmd === 'edit') { $tools['view'] = ['photos/' . $user['nickname'] . '/image/' . $datum, DI::l10n()->t('View photo')]; } else { - $tools['edit'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/edit', DI::l10n()->t('Edit photo')]; - $tools['delete'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/drop', DI::l10n()->t('Delete photo')]; + $tools['edit'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/edit', DI::l10n()->t('Edit photo')]; + $tools['delete'] = ['photos/' . $user['nickname'] . '/image/' . $datum . '/drop', DI::l10n()->t('Delete photo')]; $tools['profile'] = ['settings/profile/photo/crop/' . $ph[0]['resource-id'], DI::l10n()->t('Use as profile photo')]; } @@ -973,9 +973,9 @@ function photos_content() 'filename' => $hires['filename'], ]; - $map = null; + $map = null; $link_item = []; - $total = 0; + $total = 0; // Do we have an item for this photo? @@ -989,12 +989,12 @@ function photos_content() if (!empty($link_item['parent']) && !empty($link_item['uid'])) { $condition = ["`parent` = ? AND `gravity` = ?", $link_item['parent'], Item::GRAVITY_COMMENT]; - $total = Post::count($condition); + $total = Post::count($condition); $pager = new Pager(DI::l10n(), DI::args()->getQueryString()); $params = ['order' => ['id'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]]; - $items = Post::toArray(Post::selectForUser($link_item['uid'], array_merge(Item::ITEM_FIELDLIST, ['author-alias']), $condition, $params)); + $items = Post::toArray(Post::selectForUser($link_item['uid'], array_merge(Item::ITEM_FIELDLIST, ['author-alias']), $condition, $params)); if (DI::userSession()->getLocalUserId() == $link_item['uid']) { Item::update(['unseen' => false], ['parent' => $link_item['parent']]); @@ -1021,51 +1021,51 @@ function photos_content() $tags = ['title' => DI::l10n()->t('Tags: '), 'tags' => $tag_arr]; if ($cmd === 'edit') { $tags['removeanyurl'] = 'post/' . $link_item['id'] . '/tag/remove?return=' . urlencode(DI::args()->getCommand()); - $tags['removetitle'] = DI::l10n()->t('[Select tags to remove]'); + $tags['removetitle'] = DI::l10n()->t('[Select tags to remove]'); } } - $edit = Null; + $edit = null; if ($cmd === 'edit' && $can_post) { $edit_tpl = Renderer::getMarkupTemplate('photo_edit.tpl'); - $album_e = $ph[0]['album']; - $caption_e = $ph[0]['desc']; + $album_e = $ph[0]['album']; + $caption_e = $ph[0]['desc']; $aclselect_e = ACL::getFullSelectorHTML(DI::page(), DI::userSession()->getLocalUserId(), false, ACL::getDefaultUserPermissions($ph[0])); $edit = Renderer::replaceMacros($edit_tpl, [ - '$id' => $ph[0]['id'], - '$album' => ['albname', DI::l10n()->t('New album name'), $album_e, ''], - '$caption' => ['desc', DI::l10n()->t('Caption'), $caption_e, ''], - '$tags' => ['newtag', DI::l10n()->t('Add a Tag'), "", DI::l10n()->t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')], + '$id' => $ph[0]['id'], + '$album' => ['albname', DI::l10n()->t('New album name'), $album_e, ''], + '$caption' => ['desc', DI::l10n()->t('Caption'), $caption_e, ''], + '$tags' => ['newtag', DI::l10n()->t('Add a Tag'), "", DI::l10n()->t('Example: @bob, @Barbara_Jensen, @jim@example.com, #California, #camping')], '$rotate_none' => ['rotate', DI::l10n()->t('Do not rotate'), 0, '', true], - '$rotate_cw' => ['rotate', DI::l10n()->t("Rotate CW \x28right\x29"), 1, ''], - '$rotate_ccw' => ['rotate', DI::l10n()->t("Rotate CCW \x28left\x29"), 2, ''], + '$rotate_cw' => ['rotate', DI::l10n()->t("Rotate CW \x28right\x29"), 1, ''], + '$rotate_ccw' => ['rotate', DI::l10n()->t("Rotate CCW \x28left\x29"), 2, ''], - '$nickname' => $user['nickname'], + '$nickname' => $user['nickname'], '$resource_id' => $ph[0]['resource-id'], '$permissions' => DI::l10n()->t('Permissions'), - '$aclselect' => $aclselect_e, + '$aclselect' => $aclselect_e, '$item_id' => $link_item['id'] ?? 0, - '$submit' => DI::l10n()->t('Submit'), - '$delete' => DI::l10n()->t('Delete Photo'), + '$submit' => DI::l10n()->t('Submit'), + '$delete' => DI::l10n()->t('Delete Photo'), // ACL permissions box '$return_path' => DI::args()->getQueryString(), ]); } - $like = ''; - $dislike = ''; + $like = ''; + $dislike = ''; $likebuttons = ''; - $comments = ''; - $paginate = ''; + $comments = ''; + $paginate = ''; if (!empty($link_item['id']) && !empty($link_item['uri'])) { - $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl'); - $tpl = Renderer::getMarkupTemplate('photo_item.tpl'); + $cmnt_tpl = Renderer::getMarkupTemplate('comment_item.tpl'); + $tpl = Renderer::getMarkupTemplate('photo_item.tpl'); $return_path = DI::args()->getCommand(); if (!DBA::isResult($items)) { @@ -1076,25 +1076,25 @@ function photos_content() */ $qcomment = null; if (Addon::isEnabled('qcomment')) { - $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); + $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); $qcomment = $words ? explode("\n", $words) : []; } $comments .= Renderer::replaceMacros($cmnt_tpl, [ '$return_path' => '', - '$jsreload' => $return_path, - '$id' => $link_item['id'], - '$parent' => $link_item['id'], - '$profile_uid' => $owner_uid, - '$mylink' => $contact['url'], - '$mytitle' => DI::l10n()->t('This is you'), - '$myphoto' => $contact['thumb'], - '$comment' => DI::l10n()->t('Comment'), - '$submit' => DI::l10n()->t('Submit'), - '$preview' => DI::l10n()->t('Preview'), - '$loading' => DI::l10n()->t('Loading...'), - '$qcomment' => $qcomment, - '$rand_num' => Crypto::randomDigits(12), + '$jsreload' => $return_path, + '$id' => $link_item['id'], + '$parent' => $link_item['id'], + '$profile_uid' => $owner_uid, + '$mylink' => $contact['url'], + '$mytitle' => DI::l10n()->t('This is you'), + '$myphoto' => $contact['thumb'], + '$comment' => DI::l10n()->t('Comment'), + '$submit' => DI::l10n()->t('Submit'), + '$preview' => DI::l10n()->t('Preview'), + '$loading' => DI::l10n()->t('Loading...'), + '$qcomment' => $qcomment, + '$rand_num' => Crypto::randomDigits(12), ]); } } @@ -1132,29 +1132,29 @@ function photos_content() */ $qcomment = null; if (Addon::isEnabled('qcomment')) { - $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); + $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); $qcomment = $words ? explode("\n", $words) : []; } $comments .= Renderer::replaceMacros($cmnt_tpl, [ '$return_path' => '', - '$jsreload' => $return_path, - '$id' => $link_item['id'], - '$parent' => $link_item['id'], - '$profile_uid' => $owner_uid, - '$mylink' => $contact['url'], - '$mytitle' => DI::l10n()->t('This is you'), - '$myphoto' => $contact['thumb'], - '$comment' => DI::l10n()->t('Comment'), - '$submit' => DI::l10n()->t('Submit'), - '$preview' => DI::l10n()->t('Preview'), - '$qcomment' => $qcomment, - '$rand_num' => Crypto::randomDigits(12), + '$jsreload' => $return_path, + '$id' => $link_item['id'], + '$parent' => $link_item['id'], + '$profile_uid' => $owner_uid, + '$mylink' => $contact['url'], + '$mytitle' => DI::l10n()->t('This is you'), + '$myphoto' => $contact['thumb'], + '$comment' => DI::l10n()->t('Comment'), + '$submit' => DI::l10n()->t('Submit'), + '$preview' => DI::l10n()->t('Preview'), + '$qcomment' => $qcomment, + '$rand_num' => Crypto::randomDigits(12), ]); } foreach ($items as $item) { - $comment = ''; + $comment = ''; $template = $tpl; $activity = DI::activity(); @@ -1181,7 +1181,7 @@ function photos_content() } $dropping = (($item['contact-id'] == $contact_id) || ($item['uid'] == DI::userSession()->getLocalUserId())); - $drop = [ + $drop = [ 'dropping' => $dropping, 'pagedrop' => false, 'select' => DI::l10n()->t('Select'), @@ -1189,7 +1189,7 @@ function photos_content() ]; $title_e = $item['title']; - $body_e = BBCode::convertForUriId($item['uri-id'], $item['body']); + $body_e = BBCode::convertForUriId($item['uri-id'], $item['body']); $comments .= Renderer::replaceMacros($template, [ '$id' => $item['id'], @@ -1212,24 +1212,24 @@ function photos_content() */ $qcomment = null; if (Addon::isEnabled('qcomment')) { - $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); + $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); $qcomment = $words ? explode("\n", $words) : []; } $comments .= Renderer::replaceMacros($cmnt_tpl, [ '$return_path' => '', - '$jsreload' => $return_path, - '$id' => $item['id'], - '$parent' => $item['parent'], - '$profile_uid' => $owner_uid, - '$mylink' => $contact['url'], - '$mytitle' => DI::l10n()->t('This is you'), - '$myphoto' => $contact['thumb'], - '$comment' => DI::l10n()->t('Comment'), - '$submit' => DI::l10n()->t('Submit'), - '$preview' => DI::l10n()->t('Preview'), - '$qcomment' => $qcomment, - '$rand_num' => Crypto::randomDigits(12), + '$jsreload' => $return_path, + '$id' => $item['id'], + '$parent' => $item['parent'], + '$profile_uid' => $owner_uid, + '$mylink' => $contact['url'], + '$mytitle' => DI::l10n()->t('This is you'), + '$myphoto' => $contact['thumb'], + '$comment' => DI::l10n()->t('Comment'), + '$submit' => DI::l10n()->t('Submit'), + '$preview' => DI::l10n()->t('Preview'), + '$qcomment' => $qcomment, + '$rand_num' => Crypto::randomDigits(12), ]); } } @@ -1243,17 +1243,17 @@ function photos_content() } if ($cmd === 'view' && ($can_post || Security::canWriteToUserWall($owner_uid))) { - $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl'); + $like_tpl = Renderer::getMarkupTemplate('like_noshare.tpl'); $likebuttons = Renderer::replaceMacros($like_tpl, [ - '$id' => $link_item['id'], - '$like' => DI::l10n()->t('Like'), - '$like_title' => DI::l10n()->t('I like this (toggle)'), - '$dislike' => DI::l10n()->t('Dislike'), - '$wait' => DI::l10n()->t('Please wait'), + '$id' => $link_item['id'], + '$like' => DI::l10n()->t('Like'), + '$like_title' => DI::l10n()->t('I like this (toggle)'), + '$dislike' => DI::l10n()->t('Dislike'), + '$wait' => DI::l10n()->t('Please wait'), '$dislike_title' => DI::l10n()->t('I don\'t like this (toggle)'), - '$hide_dislike' => DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike'), - '$responses' => $responses, - '$return_path' => DI::args()->getQueryString(), + '$hide_dislike' => DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'hide_dislike'), + '$responses' => $responses, + '$return_path' => DI::args()->getQueryString(), ]); } @@ -1262,22 +1262,22 @@ function photos_content() $photo_tpl = Renderer::getMarkupTemplate('photo_view.tpl'); $o .= Renderer::replaceMacros($photo_tpl, [ - '$id' => $ph[0]['id'], - '$album' => [$album_link, $ph[0]['album']], - '$tools' => $tools, - '$photo' => $photo, - '$prevlink' => $prevlink, - '$nextlink' => $nextlink, - '$desc' => $ph[0]['desc'], - '$tags' => $tags, - '$edit' => $edit, - '$map' => $map, - '$map_text' => DI::l10n()->t('Map'), + '$id' => $ph[0]['id'], + '$album' => [$album_link, $ph[0]['album']], + '$tools' => $tools, + '$photo' => $photo, + '$prevlink' => $prevlink, + '$nextlink' => $nextlink, + '$desc' => $ph[0]['desc'], + '$tags' => $tags, + '$edit' => $edit, + '$map' => $map, + '$map_text' => DI::l10n()->t('Map'), '$likebuttons' => $likebuttons, - '$like' => $like, - '$dislike' => $dislike, - '$comments' => $comments, - '$paginate' => $paginate, + '$like' => $like, + '$dislike' => $dislike, + '$comments' => $comments, + '$paginate' => $paginate, ]); DI::page()['htmlhead'] .= "\n" . '' . "\n"; diff --git a/src/App/Page.php b/src/App/Page.php index 45293b1e05..87493a67e4 100644 --- a/src/App/Page.php +++ b/src/App/Page.php @@ -81,7 +81,7 @@ class Page implements ArrayAccess public function __construct(string $basepath) { $this->timestamp = microtime(true); - $this->basePath = $basepath; + $this->basePath = $basepath; } public function setLogging(string $method, string $module, string $command) @@ -445,7 +445,7 @@ class Page implements ArrayAccess $this->initContent($response, $mode); // Load current theme info after module has been initialized as theme could have been set in module - $currentTheme = $appHelper->getCurrentTheme(); + $currentTheme = $appHelper->getCurrentTheme(); $theme_info_file = 'view/theme/' . $currentTheme . '/theme.php'; if (file_exists($theme_info_file)) { require_once $theme_info_file; @@ -479,7 +479,7 @@ class Page implements ArrayAccess // Add the navigation (menu) template if ($moduleName != 'install' && $moduleName != 'maintenance') { $this->page['htmlhead'] .= Renderer::replaceMacros(Renderer::getMarkupTemplate('nav_head.tpl'), []); - $this->page['nav'] = $nav->getHtml(); + $this->page['nav'] = $nav->getHtml(); } // Build the page - now that we have all the components @@ -512,7 +512,7 @@ class Page implements ArrayAccess } } - $page = $this->page; + $page = $this->page; // add and escape some common but crucial content for direct "echo" in HTML (security) $page['title'] = htmlspecialchars($page['title'] ?? ''); diff --git a/src/Contact/Avatar.php b/src/Contact/Avatar.php index b7ec5372a0..677ab8e048 100644 --- a/src/Contact/Avatar.php +++ b/src/Contact/Avatar.php @@ -215,7 +215,7 @@ class Avatar } $avatarpath = parse_url(self::baseUrl(), PHP_URL_PATH); - $pos = strpos($parts['path'], $avatarpath); + $pos = strpos($parts['path'], $avatarpath); if ($pos !== 0) { return ''; } diff --git a/src/Content/Item.php b/src/Content/Item.php index d6e4cb7d59..943bda4591 100644 --- a/src/Content/Item.php +++ b/src/Content/Item.php @@ -116,8 +116,8 @@ class Item public function determineCategoriesTerms(array $item, int $uid = 0): array { $categories = []; - $folders = []; - $first = true; + $folders = []; + $first = true; $uid = $item['uid'] ?: $uid; @@ -132,11 +132,11 @@ class Item $url = '#'; } $categories[] = [ - 'name' => $savedFolderName, - 'url' => $url, + 'name' => $savedFolderName, + 'url' => $url, 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '', - 'first' => $first, - 'last' => false + 'first' => $first, + 'last' => false ]; $first = false; } @@ -148,11 +148,11 @@ class Item if ($this->userSession->getLocalUserId() == $uid) { foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) { $folders[] = [ - 'name' => $savedFolderName, - 'url' => "#", + 'name' => $savedFolderName, + 'url' => "#", 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '', - 'first' => $first, - 'last' => false + 'first' => $first, + 'last' => false ]; $first = false; } @@ -197,55 +197,55 @@ class Item // Sometimes the tag detection doesn't seem to work right // This is some workaround $nameparts = explode(' ', $name); - $name = $nameparts[0]; + $name = $nameparts[0]; // Try to detect the contact in various ways if (strpos($name, 'http://') || strpos($name, '@')) { $contact = Contact::getByURLForUser($name, $profile_uid); } else { $contact = false; - $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv']; + $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv']; if (strrpos($name, '+')) { // Is it in format @nick+number? - $tagcid = intval(substr($name, strrpos($name, '+') + 1)); + $tagcid = intval(substr($name, strrpos($name, '+') + 1)); $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]); } // select someone by nick in the current network if (!DBA::isResult($contact) && ($network != '')) { $condition = ['nick' => $name, 'network' => $network, 'uid' => $profile_uid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); } // select someone by attag in the current network if (!DBA::isResult($contact) && ($network != '')) { $condition = ['attag' => $name, 'network' => $network, 'uid' => $profile_uid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); } //select someone by name in the current network if (!DBA::isResult($contact) && ($network != '')) { $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); } // select someone by nick in any network if (!DBA::isResult($contact)) { $condition = ['nick' => $name, 'uid' => $profile_uid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); } // select someone by attag in any network if (!DBA::isResult($contact)) { $condition = ['attag' => $name, 'uid' => $profile_uid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); } // select someone by name in any network if (!DBA::isResult($contact)) { $condition = ['name' => $name, 'uid' => $profile_uid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); } } @@ -262,8 +262,8 @@ class Item $replaced = true; // create profile link $profile = str_replace(',', '%2c', $profile); - $newtag = $tag_type . '[url=' . $profile . ']' . $newname . '[/url]'; - $body = str_replace($tag_type . $name, $newtag, $body); + $newtag = $tag_type . '[url=' . $profile . ']' . $newname . '[/url]'; + $body = str_replace($tag_type . $name, $newtag, $body); } } @@ -303,7 +303,7 @@ class Item 'url' => $item['author-link'], 'alias' => $item['author-alias'], ]; - $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]'; + $author = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]'; $author_arr = [ 'uid' => 0, @@ -312,7 +312,7 @@ class Item 'url' => $obj['author-link'], 'alias' => $obj['author-alias'], ]; - $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]'; + $objauthor = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]'; switch ($obj['verb']) { case Activity::POST: @@ -340,7 +340,7 @@ class Item $parsedobj = XML::parseString($xmlhead . $item['object']); - $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content); + $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content); $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag); } } @@ -358,7 +358,7 @@ class Item public function photoMenu(array $item, string $formSecurityToken): string { $this->profiler->startRecording('rendering'); - $sub_link = $contact_url = $pm_url = $status_link = ''; + $sub_link = $contact_url = $pm_url = $status_link = ''; $photos_link = $posts_link = $block_link = $ignore_link = $collapse_link = $ignoreserver_link = ''; if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) { @@ -379,16 +379,16 @@ class Item $profile_link = $profile_link . '?' . http_build_query(['url' => $item['author-link'] . '/profile']); } - $cid = 0; - $pcid = $item['author-id']; - $network = ''; - $rel = 0; + $cid = 0; + $pcid = $item['author-id']; + $network = ''; + $rel = 0; $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']]; - $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition); + $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition); if (DBA::isResult($contact)) { - $cid = $contact['id']; + $cid = $contact['id']; $network = $contact['network']; - $rel = $contact['rel']; + $rel = $contact['rel']; } if (!empty($pcid)) { @@ -415,16 +415,16 @@ class Item if ($this->userSession->getLocalUserId()) { $menu = [ - $this->l10n->t('Follow Thread') => $sub_link, - $this->l10n->t('View Status') => $status_link, - $this->l10n->t('View Profile') => $profile_link, - $this->l10n->t('View Photos') => $photos_link, - $this->l10n->t('Network Posts') => $posts_link, - $this->l10n->t('View Contact') => $contact_url, - $this->l10n->t('Send PM') => $pm_url, - $this->l10n->t('Block') => $block_link, - $this->l10n->t('Ignore') => $ignore_link, - $this->l10n->t('Collapse') => $collapse_link, + $this->l10n->t('Follow Thread') => $sub_link, + $this->l10n->t('View Status') => $status_link, + $this->l10n->t('View Profile') => $profile_link, + $this->l10n->t('View Photos') => $photos_link, + $this->l10n->t('Network Posts') => $posts_link, + $this->l10n->t('View Contact') => $contact_url, + $this->l10n->t('Send PM') => $pm_url, + $this->l10n->t('Block') => $block_link, + $this->l10n->t('Ignore') => $ignore_link, + $this->l10n->t('Collapse') => $collapse_link, $this->l10n->t("Ignore %s server", $authorBaseUri->getHost()) => $ignoreserver_link, ]; @@ -517,13 +517,13 @@ class Item if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) { $private_group = $contact['prv']; $only_to_group = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]); - $private_id = $contact['id']; + $private_id = $contact['id']; $group_contact = $contact; DI::logger()->info('Private group or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]); } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') { $private_group = false; $only_to_group = true; - $private_id = $contact['id']; + $private_id = $contact['id']; $group_contact = $contact; DI::logger()->info('Public group', ['url' => $tag[2], 'mention' => $tag[1]]); } else { @@ -561,7 +561,7 @@ class Item } elseif ($setPermissions) { if (empty($receivers)) { // For security reasons direct posts without any receiver will be posts to yourself - $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]); + $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]); $receivers[] = $self['id']; } @@ -605,9 +605,9 @@ class Item $owner_updated = ''; $owner_thumb = $item['contact-avatar']; } else { - $owner_avatar = $item['owner-id']; - $owner_updated = $item['owner-updated']; - $owner_thumb = $item['owner-avatar']; + $owner_avatar = $item['owner-id']; + $owner_updated = $item['owner-updated']; + $owner_thumb = $item['owner-avatar']; } if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) { @@ -634,7 +634,7 @@ class Item return $body; } - $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]]); if (!DBA::isResult($shared_item)) { DI::logger()->notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]); @@ -649,7 +649,7 @@ class Item */ private function createSharedPostByGuid(string $guid, bool $add_media): string { - $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network']; + $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network']; $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]); if (!DBA::isResult($shared_item)) { @@ -800,14 +800,14 @@ class Item public function storeAttachmentFromRequest(array $request): string { - $attachment_type = $request['attachment_type'] ?? ''; + $attachment_type = $request['attachment_type'] ?? ''; $attachment_title = $request['attachment_title'] ?? ''; - $attachment_text = $request['attachment_text'] ?? ''; + $attachment_text = $request['attachment_text'] ?? ''; - $attachment_url = hex2bin($request['attachment_url'] ?? ''); + $attachment_url = hex2bin($request['attachment_url'] ?? ''); $attachment_img_src = hex2bin($request['attachment_img_src'] ?? ''); - $attachment_img_width = $request['attachment_img_width'] ?? 0; + $attachment_img_width = $request['attachment_img_width'] ?? 0; $attachment_img_height = $request['attachment_img_height'] ?? 0; // Fetch the basic attachment data @@ -815,10 +815,10 @@ class Item unset($attachment['keywords']); // Overwrite the basic data with possible changes from the frontend - $attachment['type'] = $attachment_type; + $attachment['type'] = $attachment_type; $attachment['title'] = $attachment_title; - $attachment['text'] = $attachment_text; - $attachment['url'] = $attachment_url; + $attachment['text'] = $attachment_text; + $attachment['url'] = $attachment_url; if (!empty($attachment_img_src)) { $attachment['images'] = [ @@ -842,7 +842,7 @@ class Item $filedas = FileTag::fileToArray($post['file']); } - $list_array = explode(',', trim($category)); + $list_array = explode(',', trim($category)); $post['file'] = FileTag::arrayToFile($list_array, 'category'); if (!empty($filedas) && is_array($filedas)) { @@ -858,8 +858,8 @@ class Item if ($toplevel_item) { $post['allow_cid'] = $toplevel_item['allow_cid'] ?? ''; $post['allow_gid'] = $toplevel_item['allow_gid'] ?? ''; - $post['deny_cid'] = $toplevel_item['deny_cid'] ?? ''; - $post['deny_gid'] = $toplevel_item['deny_gid'] ?? ''; + $post['deny_cid'] = $toplevel_item['deny_cid'] ?? ''; + $post['deny_gid'] = $toplevel_item['deny_gid'] ?? ''; $post['private'] = $toplevel_item['private']; return $post; } @@ -878,7 +878,7 @@ class Item if ($visibility === 'public') { // The ACL selector introduced in version 2019.12 sends ACL input data even when the Public visibility is selected $post['allow_cid'] = $post['allow_gid'] = $post['deny_cid'] = $post['deny_gid'] = ''; - } else if ($visibility === 'custom') { + } elseif ($visibility === 'custom') { // Since we know from the visibility parameter the item should be private, we have to prevent the empty ACL // case that would make it public. So we always append the author's contact id to the allowed contacts. // See https://github.com/friendica/friendica/issues/9672 @@ -907,7 +907,7 @@ class Item if ((preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", $post['body'], $match, PREG_SET_ORDER) || !empty($data['type'])) && ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) ) { - $post['post-type'] = ItemModel::PT_PAGE; + $post['post-type'] = ItemModel::PT_PAGE; $post['object-type'] = Activity\ObjectType::BOOKMARK; } @@ -925,10 +925,10 @@ class Item $post['direction'] = Conversation::PUSH; $post['received'] = DateTimeFormat::utcNow(); $post['origin'] = true; - $post['wall'] = $post['wall'] ?? true; - $post['guid'] = $post['guid'] ?? System::createUUID(); - $post['verb'] = $post['verb'] ?? Activity::POST; - $post['uri'] = $post['uri'] ?? ItemModel::newURI($post['guid']); + $post['wall'] = $post['wall'] ?? true; + $post['guid'] = $post['guid'] ?? System::createUUID(); + $post['verb'] = $post['verb'] ?? Activity::POST; + $post['uri'] = $post['uri'] ?? ItemModel::newURI($post['guid']); $post['thr-parent'] = $post['thr-parent'] ?? $post['uri']; if (empty($post['gravity'])) { @@ -989,7 +989,7 @@ class Item // Convert links with empty descriptions to links without an explicit description $post['body'] = trim(preg_replace('#\[url=([^\]]*?)\]\[/url\]#ism', '[url]$1[/url]', $post['body'])); $post['body'] = $this->bbCodeVideo->transform($post['body']); - $post = $this->setObjectType($post); + $post = $this->setObjectType($post); // Personal notes must never be altered to a group post. if ($post['post-type'] != ItemModel::PT_PERSONAL_NOTE) { @@ -1083,7 +1083,7 @@ class Item } if (($expire_interval > 0) && !empty($created)) { - $expire_date = time() - ($expire_interval * 86400); + $expire_date = time() - ($expire_interval * 86400); $created_date = strtotime($created); if ($created_date < $expire_date) { DI::logger()->notice('Item created before expiration interval.', ['created' => date('c', $created_date), 'expired' => date('c', $expire_date)]); diff --git a/src/Content/PageInfo.php b/src/Content/PageInfo.php index 99863b8910..93d2e46750 100644 --- a/src/Content/PageInfo.php +++ b/src/Content/PageInfo.php @@ -59,7 +59,7 @@ class PageInfo $body = substr_replace($body, "\n[bookmark=" . $data['url'] . ']' . $linkTitle . "[/bookmark]\n", $existingAttachmentPos, 0); } else { $footer = self::getFooterFromData($data, $no_photos); - $body = self::stripTrailingUrlFromBody($body, $data['url']); + $body = self::stripTrailingUrlFromBody($body, $data['url']); $body .= "\n" . $footer; } @@ -215,8 +215,11 @@ class PageInfo $taglist = []; foreach ($data['keywords'] as $keyword) { - $hashtag = str_replace([' ', '+', '/', '.', '#', "'"], - ['', '', '', '', '', ''], $keyword); + $hashtag = str_replace( + [' ', '+', '/', '.', '#', "'"], + ['', '', '', '', '', ''], + $keyword + ); $taglist[] = $hashtag; } @@ -270,7 +273,7 @@ class PageInfo protected static function stripTrailingUrlFromBody(string $body, string $url): string { $quotedUrl = preg_quote($url, '#'); - $body = preg_replace_callback("#(?: + $body = preg_replace_callback("#(?: \[url]$quotedUrl\[/url]| \[url=$quotedUrl]$quotedUrl\[/url]| \[url=$quotedUrl]([^[]*?)\[/url]| diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php index 458041f4bc..f03dfa84be 100644 --- a/src/Content/Text/BBCode.php +++ b/src/Content/Text/BBCode.php @@ -130,10 +130,11 @@ class BBCode break; case 'title': - $value = self::toPlaintext(html_entity_decode($value, ENT_QUOTES, 'UTF-8')); - $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8'); + $value = self::toPlaintext(html_entity_decode($value, ENT_QUOTES, 'UTF-8')); + $value = html_entity_decode($value, ENT_QUOTES, 'UTF-8'); $data['title'] = self::escapeContent($value); + // no break default: $data[$field] = html_entity_decode($value, ENT_QUOTES, 'UTF-8'); break; @@ -289,7 +290,7 @@ class BBCode // Remove all unneeded white space do { $oldtext = $text; - $text = str_replace([' ', "\n", "\r", '"'], ' ', $text); + $text = str_replace([' ', "\n", "\r", '"'], ' ', $text); } while ($oldtext != $text); return trim($text); @@ -330,12 +331,12 @@ class BBCode DI::logger()->info('the total body length exceeds the limit', ['maxlen' => $maxlen, 'body_len' => strlen($body)]); $orig_body = $body; - $new_body = ''; - $textlen = 0; + $new_body = ''; + $textlen = 0; - $img_start = strpos($orig_body, '[img'); + $img_start = strpos($orig_body, '[img'); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); - $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); + $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); while (($img_st_close !== false) && ($img_end !== false)) { $img_st_close++; // make it point to AFTER the closing bracket @@ -349,7 +350,7 @@ class BBCode if ($textlen < $maxlen) { DI::logger()->debug('the limit happens before an embedded image'); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); - $textlen = $maxlen; + $textlen = $maxlen; } } else { $new_body = $new_body . substr($orig_body, 0, $img_start); @@ -363,7 +364,7 @@ class BBCode if ($textlen < $maxlen) { DI::logger()->debug('the limit happens before the end of a non-embedded image'); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); - $textlen = $maxlen; + $textlen = $maxlen; } } else { $new_body = $new_body . substr($orig_body, 0, $img_end); @@ -377,9 +378,9 @@ class BBCode $orig_body = ''; } - $img_start = strpos($orig_body, '[img'); + $img_start = strpos($orig_body, '[img'); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); - $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); + $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); } if (($textlen + strlen($orig_body)) > $maxlen) { @@ -433,7 +434,7 @@ class BBCode if (((strpos($data['text'], '[img=') !== false) || (strpos($data['text'], '[img]') !== false) || DI::config()->get('system', 'always_show_preview')) && !empty($data['image'])) { $data['preview'] = $data['image']; - $data['image'] = ''; + $data['image'] = ''; } $return = ''; @@ -506,11 +507,11 @@ class BBCode } $title = htmlentities($data['title'] ?? '', ENT_QUOTES, 'UTF-8', false); - $text = htmlentities($data['text'], ENT_QUOTES, 'UTF-8', false); + $text = htmlentities($data['text'], ENT_QUOTES, 'UTF-8', false); if ($plaintext || (($title != '') && strstr($text, $title))) { $data['title'] = $data['url']; } elseif (($text != '') && strstr($title, $text)) { - $data['text'] = $data['title']; + $data['text'] = $data['title']; $data['title'] = $data['url']; } @@ -584,11 +585,11 @@ class BBCode $res = [ 'start' => [ - 'open' => $start_open, + 'open' => $start_open, 'close' => $start_close ], 'end' => [ - 'open' => $end_open, + 'open' => $end_open, 'close' => $end_open + strlen('[/' . $name . ']') ], ]; @@ -614,17 +615,17 @@ class BBCode { DI::profiler()->startRecording('rendering'); $occurrences = 0; - $pos = self::getTagPosition($text, $name, $occurrences); + $pos = self::getTagPosition($text, $name, $occurrences); while ($pos !== false && $occurrences++ < 1000) { - $start = substr($text, 0, $pos['start']['open']); + $start = substr($text, 0, $pos['start']['open']); $subject = substr($text, $pos['start']['open'], $pos['end']['close'] - $pos['start']['open']); - $end = substr($text, $pos['end']['close']); + $end = substr($text, $pos['end']['close']); if ($end === false) { $end = ''; } $subject = preg_replace($pattern, $replace, $subject); - $text = $start . $subject . $end; + $text = $start . $subject . $end; $pos = self::getTagPosition($text, $name, $occurrences); } @@ -636,13 +637,13 @@ class BBCode private static function extractImagesFromItemBody(string $body): array { $saved_image = []; - $orig_body = $body; - $new_body = ''; + $orig_body = $body; + $new_body = ''; - $cnt = 0; - $img_start = strpos($orig_body, '[img'); + $cnt = 0; + $img_start = strpos($orig_body, '[img'); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); - $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); + $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); while (($img_st_close !== false) && ($img_end !== false)) { $img_st_close++; // make it point to AFTER the closing bracket $img_end += $img_start; @@ -650,7 +651,7 @@ class BBCode if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) { // This is an embedded image $saved_image[$cnt] = substr($orig_body, $img_start + $img_st_close, $img_end - ($img_start + $img_st_close)); - $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]'; + $new_body = $new_body . substr($orig_body, 0, $img_start) . '[$#saved_image' . $cnt . '#$]'; $cnt++; } else { @@ -664,9 +665,9 @@ class BBCode $orig_body = ''; } - $img_start = strpos($orig_body, '[img'); + $img_start = strpos($orig_body, '[img'); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); - $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); + $img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false); } $new_body = $new_body . $orig_body; @@ -736,7 +737,7 @@ class BBCode $attributes = self::extractShareAttributes($matches[2]); $attributes['comment'] = trim($matches[1]); - $attributes['shared'] = trim($matches[3]); + $attributes['shared'] = trim($matches[3]); DI::profiler()->stopRecording(); return $attributes; @@ -796,13 +797,13 @@ class BBCode function ($match) use ($callback, $uriid) { $attributes = self::extractShareAttributes($match[2]); - $author_contact = Contact::getByURL($attributes['profile'], false, ['id', 'url', 'addr', 'name', 'micro']); - $author_contact['url'] = ($author_contact['url'] ?? $attributes['profile']); + $author_contact = Contact::getByURL($attributes['profile'], false, ['id', 'url', 'addr', 'name', 'micro']); + $author_contact['url'] = ($author_contact['url'] ?? $attributes['profile']); $author_contact['addr'] = ($author_contact['addr'] ?? ''); - $attributes['author'] = ($author_contact['name'] ?? '') ?: $attributes['author']; - $attributes['avatar'] = ($author_contact['micro'] ?? '') ?: $attributes['avatar']; - $attributes['profile'] = ($author_contact['url'] ?? '') ?: $attributes['profile']; + $attributes['author'] = ($author_contact['name'] ?? '') ?: $attributes['author']; + $attributes['avatar'] = ($author_contact['micro'] ?? '') ?: $attributes['avatar']; + $attributes['profile'] = ($author_contact['url'] ?? '') ?: $attributes['profile']; if (!empty($author_contact['id'])) { $attributes['avatar'] = Contact::getAvatarUrlForId($author_contact['id'], Proxy::SIZE_THUMB); @@ -831,7 +832,7 @@ class BBCode "/\[[zi]mg(.*?)\]([^\[\]]*)\[\/[zi]mg\]/ism", function ($match) use ($simplehtml, $uriid) { $attribute_string = $match[1]; - $attributes = []; + $attributes = []; foreach (['alt', 'width', 'height'] as $field) { preg_match("/$field=(['\"])(.+?)\\1/ism", $attribute_string, $matches); $attributes[$field] = html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8'); @@ -907,7 +908,7 @@ class BBCode break; case self::ACTIVITYPUB: $author = '@' . $author_contact['addr'] . ':'; - $text = '' . "\n"; + $text = '' . "\n"; break; default: $text = ($is_quote_share ? "\n" : ''); @@ -916,7 +917,7 @@ class BBCode $network = $contact['network'] ?? Protocol::PHANTOM; $gsid = ContactSelector::getServerIdForProfile($attributes['profile']); - $tpl = Renderer::getMarkupTemplate('shared_content.tpl'); + $tpl = Renderer::getMarkupTemplate('shared_content.tpl'); $text .= self::SHARED_ANCHOR . Renderer::replaceMacros($tpl, [ '$profile' => $attributes['profile'], '$avatar' => $attributes['avatar'], @@ -938,7 +939,7 @@ class BBCode private static function removePictureLinksCallback(array $match): string { $cache_key = 'remove:' . $match[1]; - $text = DI::cache()->get($cache_key); + $text = DI::cache()->get($cache_key); if (is_null($text)) { $curlResult = DI::httpClient()->head($match[1], [HttpClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout'), HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]); @@ -963,7 +964,7 @@ class BBCode $doc = new DOMDocument(); @$doc->loadHTML($body); $xpath = new DOMXPath($doc); - $list = $xpath->query('//meta[@name]'); + $list = $xpath->query('//meta[@name]'); foreach ($list as $node) { $attr = []; @@ -1034,7 +1035,7 @@ class BBCode } $cache_key = 'clean:' . $match[1]; - $text = DI::cache()->get($cache_key); + $text = DI::cache()->get($cache_key); if (!is_null($text)) { return $text; } @@ -1066,7 +1067,7 @@ class BBCode $doc = new DOMDocument(); @$doc->loadHTML($body); $xpath = new DOMXPath($doc); - $list = $xpath->query('//meta[@name]'); + $list = $xpath->query('//meta[@name]'); foreach ($list as $node) { $attr = []; if ($node->attributes->length) { @@ -1134,7 +1135,7 @@ class BBCode { DI::profiler()->startRecording('rendering'); $regexp = "/([@!])\[url\=([^\[\]]*)\].*?\[\/url\]/ism"; - $body = preg_replace_callback($regexp, [self::class, 'mentionCallback'], $body); + $body = preg_replace_callback($regexp, [self::class, 'mentionCallback'], $body); DI::profiler()->stopRecording(); return $body; } @@ -1170,7 +1171,7 @@ class BBCode { DI::profiler()->startRecording('rendering'); $regexp = "/([@!])\[url\=([^\[\]]*)\].*?\[\/url\]/ism"; - $body = preg_replace_callback($regexp, [self::class, 'mentionToAddrCallback'], $body); + $body = preg_replace_callback($regexp, [self::class, 'mentionToAddrCallback'], $body); DI::profiler()->stopRecording(); return $body; } @@ -1310,7 +1311,7 @@ class BBCode * $match[2] = $title or absent */ $try_oembed_callback = function (array $match) use ($uriid) { - $url = $match[1]; + $url = $match[1]; $title = $match[2] ?? ''; try { @@ -1325,7 +1326,7 @@ class BBCode // Extract the private images which use data urls since preg has issues with // large data sizes. Stash them away while we do bbcode conversion, and then put them back // in after we've done all the regex matching. We cannot use any preg functions to do this. - $extracted = self::extractImagesFromItemBody($text); + $extracted = self::extractImagesFromItemBody($text); $saved_image = $extracted['images']; // General clean up of the content, for example unneeded blanks and new lines @@ -1474,13 +1475,13 @@ class BBCode ]; do { $oldtext = $text; - $text = str_replace($search, $replace, $text); + $text = str_replace($search, $replace, $text); } while ($oldtext != $text); // Replace these here only once - $search = ["\n[table]", "[/table]\n"]; + $search = ["\n[table]", "[/table]\n"]; $replace = ["[table]", "[/table]"]; - $text = str_replace($search, $replace, $text); + $text = str_replace($search, $replace, $text); // Trim new lines regardless of the system.remove_multiplicated_lines config value $text = trim($text, "\n"); @@ -1497,7 +1498,7 @@ class BBCode ]; do { $oldtext = $text; - $text = str_replace($search, $replace, $text); + $text = str_replace($search, $replace, $text); } while ($oldtext != $text); } @@ -1634,7 +1635,7 @@ class BBCode } $elements = [ - 'del' => 's', 'ins' => 'em', 'kbd' => 'code', 'mark' => 'strong', + 'del' => 's', 'ins' => 'em', 'kbd' => 'code', 'mark' => 'strong', 'samp' => 'code', 'u' => 'em', 'var' => 'em' ]; foreach ($elements as $bbcode => $html) { @@ -1749,7 +1750,7 @@ class BBCode // handle nested quotes $endlessloop = 0; - while ((strpos($text, "[/spoiler]") !== false) && (strpos($text, "[spoiler=") !== false) && (++$endlessloop < 20)) { + while ((strpos($text, "[/spoiler]") !== false) && (strpos($text, "[spoiler=") !== false) && (++$endlessloop < 20)) { $text = preg_replace( "/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism", '
$1$2
', @@ -1795,7 +1796,7 @@ class BBCode // handle nested quotes $endlessloop = 0; - while ((strpos($text, "[/quote]") !== false) && (strpos($text, "[quote=") !== false) && (++$endlessloop < 20)) { + while ((strpos($text, "[/quote]") !== false) && (strpos($text, "[quote=") !== false) && (++$endlessloop < 20)) { $text = preg_replace( "/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism", "

" . $t_wrote . "

$2
", @@ -1829,7 +1830,7 @@ class BBCode "/\[[iz]mg\=(.*?)\](.*?)\[\/[iz]mg\]/ism", function ($matches) use ($simple_html, $uriid) { $matches[1] = self::proxyUrl($matches[1], $simple_html, $uriid); - $alt = htmlspecialchars($matches[2], ENT_COMPAT); + $alt = htmlspecialchars($matches[2], ENT_COMPAT); // Fix for Markdown problems with Diaspora, see issue #12701 if (($simple_html != self::DIASPORA) || strpos($matches[2], '"') === false) { return '' . $alt . ''; @@ -2043,7 +2044,7 @@ class BBCode // Server independent link to posts and comments // See issue: https://github.com/diaspora/diaspora_federation/issues/75 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism"; - $text = preg_replace($expression, DI::baseUrl() . "/display/$1", $text); + $text = preg_replace($expression, DI::baseUrl() . "/display/$1", $text); /* Tag conversion * Supports: @@ -2218,7 +2219,7 @@ class BBCode }); $regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism'; - $text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 data-original-href="$3" class="invalid-href" title="' . DI::l10n()->t('Invalid link protocol') . '">', $text); + $text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 data-original-href="$3" class="invalid-href" title="' . DI::l10n()->t('Invalid link protocol') . '">', $text); return $text; } @@ -2318,7 +2319,7 @@ class BBCode * Transform #tags, strip off the [url] and replace spaces with underscore */ $url_search_string = "^\[\]"; - $text = preg_replace_callback( + $text = preg_replace_callback( "/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/i", function ($matches) { return '#' . str_replace(' ', '_', $matches[2]); @@ -2367,7 +2368,7 @@ class BBCode if ($for_diaspora) { $url_search_string = "^\[\]"; - $text = preg_replace_callback( + $text = preg_replace_callback( "/([@!])\[(.*?)\]\(([$url_search_string]*?)\)/ism", [self::class, 'bbCodeMention2DiasporaCallback'], $text @@ -2571,7 +2572,7 @@ class BBCode $header .= "' message_id='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $uri); } - $header .= "']"; + $header .= "']"; DI::profiler()->stopRecording(); return $header; diff --git a/src/Content/Text/Markdown.php b/src/Content/Text/Markdown.php index f0ac888ab2..8aa9453041 100644 --- a/src/Content/Text/Markdown.php +++ b/src/Content/Text/Markdown.php @@ -24,10 +24,11 @@ class Markdown * @param string $baseuri Optional. Prepend anchor links with this URL * @return string */ - public static function convert($text, $hardwrap = true, $baseuri = null) { + public static function convert($text, $hardwrap = true, $baseuri = null) + { DI::profiler()->startRecording('rendering'); - $MarkdownParser = new MarkdownParser(); + $MarkdownParser = new MarkdownParser(); $MarkdownParser->code_class_prefix = 'language-'; $MarkdownParser->hard_wrap = $hardwrap; $MarkdownParser->hashtag_protection = true; @@ -121,10 +122,10 @@ class Markdown //$s = preg_replace("/([^\]\=]|^)(https?\:\/\/)(vimeo|youtu|www\.youtube|soundcloud)([a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2$3$4]$2$3$4[/url]',$s); $s = BBCode::pregReplaceInTag('/\[url\=?(.*?)\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/url\]/ism', '[youtube]$2[/youtube]', 'url', $s); - $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/www.youtube.com\/watch\?v\=(.*?)\].*?\[\/url\]/ism' , '[youtube]$1[/youtube]', 'url', $s); - $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/www.youtube.com\/shorts\/(.*?)\].*?\[\/url\]/ism' , '[youtube]$1[/youtube]', 'url', $s); - $s = BBCode::pregReplaceInTag('/\[url\=?(.*?)\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/url\]/ism' , '[vimeo]$2[/vimeo]' , 'url', $s); - $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/vimeo.com\/([0-9]+)\](.*?)\[\/url\]/ism' , '[vimeo]$1[/vimeo]' , 'url', $s); + $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/www.youtube.com\/watch\?v\=(.*?)\].*?\[\/url\]/ism', '[youtube]$1[/youtube]', 'url', $s); + $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/www.youtube.com\/shorts\/(.*?)\].*?\[\/url\]/ism', '[youtube]$1[/youtube]', 'url', $s); + $s = BBCode::pregReplaceInTag('/\[url\=?(.*?)\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/url\]/ism', '[vimeo]$2[/vimeo]', 'url', $s); + $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/vimeo.com\/([0-9]+)\](.*?)\[\/url\]/ism', '[vimeo]$1[/vimeo]', 'url', $s); // remove duplicate adjacent code tags $s = preg_replace('/(\[code\])+(.*?)(\[\/code\])+/ism', '[code]$2[/code]', $s); diff --git a/src/Content/Widget/VCard.php b/src/Content/Widget/VCard.php index b3943720d2..173a91d017 100644 --- a/src/Content/Widget/VCard.php +++ b/src/Content/Widget/VCard.php @@ -39,11 +39,11 @@ class VCard $contact_url = Contact::getProfileLink($contact); if ($contact['network'] != '') { - $network_link = Strings::formatNetworkName($contact['network'], $contact_url); - $network_svg = ContactSelector::networkToSVG($contact['network'], $contact['gsid'], '', DI::userSession()->getLocalUserId()); + $network_link = Strings::formatNetworkName($contact['network'], $contact_url); + $network_svg = ContactSelector::networkToSVG($contact['network'], $contact['gsid'], '', DI::userSession()->getLocalUserId()); } else { - $network_link = ''; - $network_svg = ''; + $network_link = ''; + $network_svg = ''; } $follow_link = ''; @@ -53,7 +53,7 @@ class VCard $mention_link = ''; $showgroup_link = ''; - $photo = Contact::getPhoto($contact); + $photo = Contact::getPhoto($contact); if (DI::userSession()->getLocalUserId()) { if (Contact\User::isIsBlocked($contact['id'], DI::userSession()->getLocalUserId())) { @@ -68,8 +68,8 @@ class VCard } else { $pcontact = Contact::selectFirst([], ['uid' => DI::userSession()->getLocalUserId(), 'uri-id' => $contact['uri-id'], 'deleted' => false]); - $id = $pcontact['id'] ?? $contact['id']; - $rel = $pcontact['rel'] ?? Contact::NOTHING; + $id = $pcontact['id'] ?? $contact['id']; + $rel = $pcontact['rel'] ?? Contact::NOTHING; $pending = $pcontact['pending'] ?? false; if (!empty($pcontact) && in_array($pcontact['network'], [Protocol::MAIL, Protocol::FEED])) { @@ -91,8 +91,8 @@ class VCard if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) { if (!$hide_mention) { - $mention_label = DI::l10n()->t('Post to group'); - $mention_link = 'compose/0?body=!' . $contact['addr']; + $mention_label = DI::l10n()->t('Post to group'); + $mention_link = 'compose/0?body=!' . $contact['addr']; } $showgroup_link = 'contact/' . $id . '/conversations'; } elseif (!$hide_mention) { diff --git a/src/Core/Addon.php b/src/Core/Addon.php index 42848da5ff..5b162fd986 100644 --- a/src/Core/Addon.php +++ b/src/Core/Addon.php @@ -40,12 +40,12 @@ class Addon public static function getAvailableList(): array { $addons = []; - $files = glob('addon/*/'); + $files = glob('addon/*/'); if (is_array($files)) { foreach ($files as $file) { if (is_dir($file)) { list($tmp, $addon) = array_map('trim', explode('/', $file)); - $info = self::getInfo($addon); + $info = self::getInfo($addon); if (DI::config()->get('system', 'show_unsupported_addons') || strtolower($info['status']) != 'unsupported' @@ -70,7 +70,7 @@ class Addon public static function getAdminList(): array { $addons_admin = []; - $addons = array_filter(DI::config()->get('addons') ?? []); + $addons = array_filter(DI::config()->get('addons') ?? []); ksort($addons); foreach ($addons as $name => $data) { @@ -79,8 +79,8 @@ class Addon } $addons_admin[$name] = [ - 'url' => 'admin/addons/' . $name, - 'name' => $name, + 'url' => 'admin/addons/' . $name, + 'name' => $name, 'class' => 'addon' ]; } @@ -160,7 +160,7 @@ class Addon DI::config()->set('addons', $addon, [ 'last_update' => $t, - 'admin' => function_exists($addon . '_addon_admin'), + 'admin' => function_exists($addon . '_addon_admin'), ]); if (!self::isEnabled($addon)) { @@ -182,7 +182,7 @@ class Addon $addons = array_filter(DI::config()->get('addons') ?? []); foreach ($addons as $name => $data) { - $addonname = Strings::sanitizeFilePathItem(trim($name)); + $addonname = Strings::sanitizeFilePathItem(trim($name)); $addon_file_path = 'addon/' . $addonname . '/' . $addonname . '.php'; if (file_exists($addon_file_path) && $data['last_update'] == filemtime($addon_file_path)) { // Addon unmodified, skipping @@ -218,12 +218,12 @@ class Addon $addon = Strings::sanitizeFilePathItem($addon); $info = [ - 'name' => $addon, + 'name' => $addon, 'description' => "", - 'author' => [], - 'maintainer' => [], - 'version' => "", - 'status' => "" + 'author' => [], + 'maintainer' => [], + 'version' => "", + 'status' => "" ]; if (!is_file("addon/$addon/$addon.php")) { @@ -247,7 +247,7 @@ class Addon } list($type, $v) = $addon_info; - $type = strtolower($type); + $type = strtolower($type); if ($type == "author" || $type == "maintainer") { $r = preg_match("|([^<]+)<([^>]+)>|", $v, $m); if ($r) { @@ -302,7 +302,7 @@ class Addon public static function getVisibleList(): array { $visible_addons = []; - $addons = array_filter(DI::config()->get('addons') ?? []); + $addons = array_filter(DI::config()->get('addons') ?? []); foreach ($addons as $name => $data) { $visible_addons[] = $name; diff --git a/src/Core/Protocol.php b/src/Core/Protocol.php index b170d4c881..53f69bc509 100644 --- a/src/Core/Protocol.php +++ b/src/Core/Protocol.php @@ -57,7 +57,7 @@ class Protocol const XMPP = 'xmpp'; // XMPP const ZOT = 'zot!'; // Zot! - const PHANTOM = 'unkn'; // Place holder + const PHANTOM = 'unkn'; // Place holder /** * Returns whether the provided protocol supports following @@ -74,7 +74,7 @@ class Protocol $hook_data = [ 'protocol' => $protocol, - 'result' => null + 'result' => null ]; Hook::callAll('support_follow', $hook_data); @@ -96,7 +96,7 @@ class Protocol $hook_data = [ 'protocol' => $protocol, - 'result' => null + 'result' => null ]; Hook::callAll('support_revoke_follow', $hook_data); @@ -242,8 +242,8 @@ class Protocol // Catch-all hook for connector addons $hook_data = [ 'contact' => $contact, - 'uid' => $uid, - 'result' => null, + 'uid' => $uid, + 'result' => null, ]; Hook::callAll('block', $hook_data); @@ -281,8 +281,8 @@ class Protocol // Catch-all hook for connector addons $hook_data = [ 'contact' => $contact, - 'uid' => $uid, - 'result' => null, + 'uid' => $uid, + 'result' => null, ]; Hook::callAll('unblock', $hook_data); @@ -309,7 +309,7 @@ class Protocol $hook_data = [ 'protocol' => $protocol, - 'result' => null + 'result' => null ]; Hook::callAll('support_probe', $hook_data); diff --git a/src/Core/Search.php b/src/Core/Search.php index 56509b3b93..0abd808377 100644 --- a/src/Core/Search.php +++ b/src/Core/Search.php @@ -117,15 +117,15 @@ class Search $results = json_decode($resultJson, true); $resultList = new ResultList( - ($results['page'] ?? 0) ?: 1, - $results['count'] ?? 0, + ($results['page'] ?? 0) ?: 1, + $results['count'] ?? 0, ($results['itemsperpage'] ?? 0) ?: 30 ); $profiles = $results['profiles'] ?? []; foreach ($profiles as $profile) { - $profile_url = $profile['profile_url'] ?? ''; + $profile_url = $profile['profile_url'] ?? ''; $contactDetails = Contact::getByURLForUser($profile_url, DI::userSession()->getLocalUserId()); $result = new ContactResult( @@ -137,7 +137,7 @@ class Search Protocol::DFRN, $contactDetails['cid'] ?? 0, $contactDetails['zid'] ?? 0, - $profile['tags'] ?? '' + $profile['tags'] ?? '' ); $resultList->addResult($result); @@ -231,7 +231,7 @@ class Search // Converting Directory Search results into contact-looking records $return = array_map(function ($result) { static $contactType = [ - 'People' => Contact::TYPE_PERSON, + 'People' => Contact::TYPE_PERSON, // Kept for backward compatibility 'Forum' => Contact::TYPE_COMMUNITY, 'Group' => Contact::TYPE_COMMUNITY, diff --git a/src/Core/Theme.php b/src/Core/Theme.php index dac930ceb1..8cd22a2e1c 100644 --- a/src/Core/Theme.php +++ b/src/Core/Theme.php @@ -20,7 +20,7 @@ class Theme { $allowed_themes_str = DI::config()->get('system', 'allowed_themes'); $allowed_themes_raw = explode(',', str_replace(' ', '', $allowed_themes_str)); - $allowed_themes = []; + $allowed_themes = []; if (count($allowed_themes_raw)) { foreach ($allowed_themes_raw as $theme) { $theme = Strings::sanitizeFilePathItem(trim($theme)); @@ -58,14 +58,14 @@ class Theme $theme = Strings::sanitizeFilePathItem($theme); $info = [ - 'name' => $theme, - 'description' => "", - 'author' => [], - 'maintainer' => [], - 'version' => "", - 'credits' => "", + 'name' => $theme, + 'description' => "", + 'author' => [], + 'maintainer' => [], + 'version' => "", + 'credits' => "", 'experimental' => file_exists("view/theme/$theme/experimental"), - 'unsupported' => file_exists("view/theme/$theme/unsupported") + 'unsupported' => file_exists("view/theme/$theme/unsupported") ]; if (!is_file("view/theme/$theme/theme.php")) { @@ -84,7 +84,7 @@ class Theme $comment_line = trim($comment_line, "\t\n\r */"); if (strpos($comment_line, ':') !== false) { list($key, $value) = array_map("trim", explode(":", $comment_line, 2)); - $key = strtolower($key); + $key = strtolower($key); if ($key == "author") { $result = preg_match("|([^<]+)<([^>]+)>|", $value, $matches); if ($result) { @@ -153,7 +153,7 @@ class Theme } $allowed_themes = Theme::getAllowedList(); - $key = array_search($theme, $allowed_themes); + $key = array_search($theme, $allowed_themes); if ($key !== false) { unset($allowed_themes[$key]); Theme::setAllowedList($allowed_themes); @@ -185,7 +185,7 @@ class Theme $func(); } - $allowed_themes = Theme::getAllowedList(); + $allowed_themes = Theme::getAllowedList(); $allowed_themes[] = $theme; Theme::setAllowedList($allowed_themes); @@ -267,7 +267,7 @@ class Theme { $theme = Strings::sanitizeFilePathItem($theme); - $appHelper = DI::appHelper(); + $appHelper = DI::appHelper(); $base_theme = $appHelper->getThemeInfoValue('extends') ?? ''; if (file_exists("view/theme/$theme/config.php")) { diff --git a/src/Core/Update.php b/src/Core/Update.php index 7a221c38e1..7aeefc3793 100644 --- a/src/Core/Update.php +++ b/src/Core/Update.php @@ -169,7 +169,7 @@ class Update if ($build != DB_UPDATE_VERSION || $force) { require_once 'update.php'; - $stored = intval($build); + $stored = intval($build); $current = intval(DB_UPDATE_VERSION); if ($stored < $current || $force) { DI::config()->reload(); @@ -203,8 +203,11 @@ class Update // run the pre_update_nnnn functions in update.php for ($version = $stored + 1; $version <= $current; $version++) { DI::logger()->notice('Execute pre update.', ['version' => $version]); - DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing pre update %d', - DateTimeFormat::utcNow() . ' ' . date('e'), $version)); + DI::config()->set('system', 'maintenance_reason', DI::l10n()->t( + '%s: executing pre update %d', + DateTimeFormat::utcNow() . ' ' . date('e'), + $version + )); $r = self::runUpdateFunction($version, 'pre_update', $sendMail); if (!$r) { DI::logger()->warning('Pre update failed', ['version' => $version]); @@ -245,8 +248,11 @@ class Update // run the update_nnnn functions in update.php for ($version = $stored + 1; $version <= $current; $version++) { DI::logger()->notice('Execute post update.', ['version' => $version]); - DI::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing post update %d', - DateTimeFormat::utcNow() . ' ' . date('e'), $version)); + DI::config()->set('system', 'maintenance_reason', DI::l10n()->t( + '%s: executing post update %d', + DateTimeFormat::utcNow() . ' ' . date('e'), + $version + )); $r = self::runUpdateFunction($version, 'update', $sendMail); if (!$r) { DI::logger()->warning('Post update failed', ['version' => $version]); @@ -359,13 +365,15 @@ class Update foreach($adminEmails as $admin) { $l10n = DI::l10n()->withLang($admin['language'] ?: 'en'); - $preamble = Strings::deindent($l10n->t(" + $preamble = Strings::deindent($l10n->t( + " The friendica developers released update %s recently, 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 friendica developer if you can not help me on your own. My database might be invalid.", - $update_id)); - $body = $l10n->t('The error message is\n[pre]%s[/pre]', $error_message); + $update_id + )); + $body = $l10n->t('The error message is\n[pre]%s[/pre]', $error_message); $email = DI::emailer() ->newSystemMail() @@ -391,9 +399,12 @@ class Update foreach(User::getAdminListForEmailing(['uid', 'language', 'email']) as $admin) { $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.', - $from_build, $to_build)); + $from_build, + $to_build + )); $email = DI::emailer() ->newSystemMail() diff --git a/src/Core/Worker/Cron.php b/src/Core/Worker/Cron.php index 5e50a9159d..a4184caf70 100644 --- a/src/Core/Worker/Cron.php +++ b/src/Core/Worker/Cron.php @@ -112,7 +112,10 @@ class Cron } elseif ($entry['priority'] != Worker::PRIORITY_CRITICAL) { $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 { DI::logger()->info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]); diff --git a/src/Database/DBStructure.php b/src/Database/DBStructure.php index 2e26453767..6809838b96 100644 --- a/src/Database/DBStructure.php +++ b/src/Database/DBStructure.php @@ -73,8 +73,11 @@ class DBStructure 'deliverq', 'dsprphotoq', 'ffinder', 'sign', 'spam', 'term', 'user-item', 'thread', 'item', 'challenge', 'auth_codes', 'tokens', 'clients', 'profile_check', 'host', 'conversation', 'fcontact', 'addon', 'push_subscriber']; - $tables = DBA::selectToArray('INFORMATION_SCHEMA.TABLES', ['TABLE_NAME'], - ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE']); + $tables = DBA::selectToArray( + 'INFORMATION_SCHEMA.TABLES', + ['TABLE_NAME'], + ['TABLE_SCHEMA' => DBA::databaseName(), 'TABLE_TYPE' => 'BASE TABLE'] + ); if (empty($tables)) { echo DI::l10n()->t('No unused tables found.'); @@ -143,8 +146,11 @@ class DBStructure */ private static function printUpdateError(string $message): string { - echo DI::l10n()->t("\nError %d occurred during database update:\n%s\n", - DBA::errorNo(), DBA::errorMessage()); + echo DI::l10n()->t( + "\nError %d occurred during database update:\n%s\n", + DBA::errorNo(), + DBA::errorMessage() + ); return DI::l10n()->t('Errors encountered performing database changes: ') . $message . '
'; } @@ -522,30 +528,36 @@ class DBStructure // This query doesn't seem to be executable as a prepared statement $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_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'], + 'COLUMN_KEY', 'COLLATION_NAME', 'COLUMN_COMMENT'], ["`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'], ["`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'], ["`TABLE_SCHEMA` = ? AND `TABLE_NAME` = ?", - DBA::databaseName(), $table]); + DBA::databaseName(), $table] + ); - $fielddata = []; - $indexdata = []; + $fielddata = []; + $indexdata = []; $foreigndata = []; if (DBA::isResult($foreign_keys)) { foreach ($foreign_keys as $foreign_key) { - $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]]; - $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters); + $parameters = ['foreign' => [$foreign_key['REFERENCED_TABLE_NAME'] => $foreign_key['REFERENCED_COLUMN_NAME']]]; + $constraint = self::getConstraintName($table, $foreign_key['COLUMN_NAME'], $parameters); $foreigndata[$constraint] = $foreign_key; } } @@ -573,8 +585,8 @@ class DBStructure $fielddata = []; if (DBA::isResult($fields)) { foreach ($fields as $field) { - $search = ['tinyint(1)', 'tinyint(3) unsigned', 'tinyint(4)', 'smallint(5) unsigned', 'smallint(6)', 'mediumint(8) unsigned', 'mediumint(9)', 'bigint(20)', 'int(10) unsigned', 'int(11)']; - $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int']; + $search = ['tinyint(1)', 'tinyint(3) unsigned', 'tinyint(4)', 'smallint(5) unsigned', 'smallint(6)', 'mediumint(8) unsigned', 'mediumint(9)', 'bigint(20)', 'int(10) unsigned', 'int(11)']; + $replace = ['boolean', 'tinyint unsigned', 'tinyint', 'smallint unsigned', 'smallint', 'mediumint unsigned', 'mediumint', 'bigint', 'int unsigned', 'int']; $field['COLUMN_TYPE'] = str_replace($search, $replace, $field['COLUMN_TYPE']); $fielddata[$field['COLUMN_NAME']]['type'] = $field['COLUMN_TYPE']; @@ -596,13 +608,13 @@ class DBStructure } $fielddata[$field['COLUMN_NAME']]['Collation'] = $field['COLLATION_NAME']; - $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT']; + $fielddata[$field['COLUMN_NAME']]['comment'] = $field['COLUMN_COMMENT']; } } return [ - 'fields' => $fielddata, - 'indexes' => $indexdata, + 'fields' => $fielddata, + 'indexes' => $indexdata, 'foreign_keys' => $foreigndata, 'table_status' => $table_status ]; @@ -731,9 +743,11 @@ class DBStructure */ 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", - DBA::databaseName(), $table, $field]); + DBA::databaseName(), $table, $field] + ); } /** @@ -806,8 +820,8 @@ class DBStructure if (self::existsTable('user') && !DBA::exists('user', ['uid' => 0])) { $user = [ - 'verified' => true, - 'page-flags' => User::PAGE_FLAGS_SOAPBOX, + 'verified' => true, + 'page-flags' => User::PAGE_FLAGS_SOAPBOX, 'account-type' => User::ACCOUNT_TYPE_RELAY, ]; DBA::insert('user', $user); @@ -883,7 +897,7 @@ class DBStructure $permission = ''; } $fields = ['id' => $set['psid'], 'uid' => $set['uid'], 'allow_cid' => $permission, - 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']; + 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']; DBA::insert('permissionset', $fields, Database::INSERT_IGNORE); } DBA::close($sets); @@ -913,7 +927,7 @@ class DBStructure $isUpdate = false; $processes = DBA::select('information_schema.processlist', ['info'], [ - 'db' => DBA::databaseName(), + 'db' => DBA::databaseName(), 'command' => ['Query', 'Execute'] ]); diff --git a/src/Database/PostUpdate.php b/src/Database/PostUpdate.php index 4db87bb429..a4db193752 100644 --- a/src/Database/PostUpdate.php +++ b/src/Database/PostUpdate.php @@ -35,7 +35,7 @@ use GuzzleHttp\Psr7\Uri; class PostUpdate { // Needed for the helper function to read from the legacy term table - const OBJECT_TYPE_POST = 1; + const OBJECT_TYPE_POST = 1; const VERSION = 1550; @@ -138,7 +138,7 @@ class PostUpdate } $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; DI::logger()->info('Start update1297 with max iid: ' . $max_iid); @@ -174,12 +174,19 @@ class PostUpdate 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 `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`", - Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, - Protocol::DIASPORA, Protocol::OSTATUS, Protocol::ACTIVITYPUB, 0); + Protocol::DIASPORA, + Protocol::OSTATUS, + Protocol::ACTIVITYPUB, + Protocol::DIASPORA, + Protocol::OSTATUS, + Protocol::ACTIVITYPUB, + 0 + ); while ($contact = DBA::fetch($contacts)) { DI::logger()->info('Remove duplicates', ['nurl' => $contact['nurl'], 'uid' => $contact['uid']]); @@ -216,11 +223,11 @@ class PostUpdate DI::logger()->info('Start', ['item' => $id]); - $start_id = $id; - $rows = 0; + $start_id = $id; + $rows = 0; $condition = ["`id` > ?", $id]; - $params = ['order' => ['id'], 'limit' => 10000]; - $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params); + $params = ['order' => ['id'], 'limit' => 10000]; + $items = DBA::select('item', ['id', 'uri-id', 'uid'], $condition, $params); if (DBA::errorNo() != 0) { DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); @@ -331,12 +338,18 @@ class PostUpdate $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` INNER JOIN `item` ON `item`.`id` = `term`.`oid` INNER JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id` 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) { DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); @@ -345,17 +358,17 @@ class PostUpdate while ($term = DBA::fetch($terms)) { if (($term['type'] == Tag::MENTION) && !empty($term['url']) && !strstr($term['body'], $term['url'])) { - $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false]; - $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]); - if (!DBA::isResult($contact)) { - $ssl_url = str_replace('http://', 'https://', $term['url']); - $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0]; - $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]); - } + $condition = ['nurl' => Strings::normaliseLink($term['url']), 'uid' => 0, 'deleted' => false]; + $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]); + if (!DBA::isResult($contact)) { + $ssl_url = str_replace('http://', 'https://', $term['url']); + $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $term['url'], Strings::normaliseLink($term['url']), $ssl_url, 0]; + $contact = DBA::selectFirst('contact', ['url', 'alias'], $condition, ['order' => ['id']]); + } - if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) { - $term['type'] = Tag::IMPLICIT_MENTION; - } + if (DBA::isResult($contact) && (!strstr($term['body'], $contact['url']) && (empty($contact['alias']) || !strstr($term['body'], $contact['alias'])))) { + $term['type'] = Tag::IMPLICIT_MENTION; + } } Tag::store($term['uri-id'], $term['type'], $term['term'], $term['url']); @@ -454,7 +467,7 @@ class PostUpdate $file_text = ''; $condition = ['otype' => self::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => [Category::FILE, Category::CATEGORY]]; - $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition); + $tags = DBA::selectToArray('term', ['type', 'term', 'url'], $condition); foreach ($tags as $tag) { if ($tag['type'] == Category::CATEGORY) { $file_text .= '<' . $tag['term'] . '>'; @@ -490,9 +503,12 @@ class PostUpdate $rows = 0; - $terms = DBA::select('term', ['oid'], + $terms = DBA::select( + 'term', + ['oid'], ["`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) { DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); @@ -557,7 +573,7 @@ class PostUpdate DI::logger()->info('Start', ['item' => $id]); $start_id = $id; - $rows = 0; + $rows = 0; $items = DBA::p("SELECT `item`.`id`, `item`.`verb` AS `item-verb`, `item-content`.`verb`, `item-activity`.`activity` FROM `item` LEFT JOIN `item-content` ON `item-content`.`uri-id` = `item`.`uri-id` @@ -570,7 +586,7 @@ class PostUpdate } while ($item = DBA::fetch($items)) { - $id = $item['id']; + $id = $item['id']; $verb = $item['item-verb']; if (empty($verb)) { $verb = $item['verb']; @@ -618,11 +634,11 @@ class PostUpdate DI::logger()->info('Start', ['contact' => $id]); - $start_id = $id; - $rows = 0; + $start_id = $id; + $rows = 0; $condition = ["`id` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id]; - $params = ['order' => ['id'], 'limit' => 10000]; - $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params); + $params = ['order' => ['id'], 'limit' => 10000]; + $contacts = DBA::select('contact', ['id', 'baseurl'], $condition, $params); if (DBA::errorNo() != 0) { DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); @@ -632,9 +648,11 @@ class PostUpdate while ($contact = DBA::fetch($contacts)) { $id = $contact['id']; - DBA::update('contact', + DBA::update( + 'contact', ['gsid' => GServer::getID($contact['baseurl'], true), 'baseurl' => GServer::cleanURL($contact['baseurl'])], - ['id' => $contact['id']]); + ['id' => $contact['id']] + ); ++$rows; } @@ -671,10 +689,10 @@ class PostUpdate DI::logger()->info('Start', ['apcontact' => $id]); - $start_id = $id; - $rows = 0; - $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id]; - $params = ['order' => ['url'], 'limit' => 10000]; + $start_id = $id; + $rows = 0; + $condition = ["`url` > ? AND `gsid` IS NULL AND `baseurl` != '' AND NOT `baseurl` IS NULL", $id]; + $params = ['order' => ['url'], 'limit' => 10000]; $apcontacts = DBA::select('apcontact', ['url', 'baseurl'], $condition, $params); if (DBA::errorNo() != 0) { @@ -685,9 +703,11 @@ class PostUpdate while ($apcontact = DBA::fetch($apcontacts)) { $id = $apcontact['url']; - DBA::update('apcontact', + DBA::update( + 'apcontact', ['gsid' => GServer::getID($apcontact['baseurl'], true), 'baseurl' => GServer::cleanURL($apcontact['baseurl'])], - ['url' => $apcontact['url']]); + ['url' => $apcontact['url']] + ); ++$rows; } @@ -723,7 +743,7 @@ class PostUpdate DI::logger()->info('Start'); $deleted = 0; - $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro']; + $avatar = [4 => 'photo', 5 => 'thumb', 6 => 'micro']; $photos = DBA::select('photo', ['id', 'contact-id', 'resource-id', 'scale'], ["`contact-id` != ? AND `album` = ?", 0, Photo::CONTACT_PHOTOS]); while ($photo = DBA::fetch($photos)) { @@ -764,7 +784,7 @@ class PostUpdate $condition = ["`hash` IS NULL"]; DI::logger()->info('Start', ['rest' => DBA::count('photo', $condition)]); - $rows = 0; + $rows = 0; $photos = DBA::select('photo', [], $condition, ['limit' => 100]); if (DBA::errorNo() != 0) { @@ -814,7 +834,7 @@ 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)", '']; 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]); if (DBA::errorNo() != 0) { @@ -856,7 +876,7 @@ class PostUpdate $condition = ["`uri-id` IS NULL"]; DI::logger()->info('Start', ['rest' => DBA::count('contact', $condition)]); - $rows = 0; + $rows = 0; $contacts = DBA::select('contact', ['id', 'url'], $condition, ['limit' => 1000]); if (DBA::errorNo() != 0) { @@ -903,7 +923,7 @@ class PostUpdate $condition = ["`uri-id` IS NULL"]; DI::logger()->info('Start', ['rest' => DBA::count('fcontact', $condition)]); - $rows = 0; + $rows = 0; $fcontacts = DBA::select('fcontact', ['id', 'url', 'guid'], $condition, ['limit' => 1000]); if (DBA::errorNo() != 0) { @@ -950,7 +970,7 @@ class PostUpdate $condition = ["`uri-id` IS NULL"]; DI::logger()->info('Start', ['rest' => DBA::count('apcontact', $condition)]); - $rows = 0; + $rows = 0; $apcontacts = DBA::select('apcontact', ['url', 'uuid'], $condition, ['limit' => 1000]); if (DBA::errorNo() != 0) { @@ -997,7 +1017,7 @@ class PostUpdate $condition = ["`uri-id` IS NULL"]; DI::logger()->info('Start', ['rest' => DBA::count('event', $condition)]); - $rows = 0; + $rows = 0; $events = DBA::select('event', ['id', 'uri', 'guid'], $condition, ['limit' => 1000]); if (DBA::errorNo() != 0) { @@ -1053,10 +1073,14 @@ class PostUpdate $rows = 0; $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` 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) { DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); @@ -1199,11 +1223,11 @@ class PostUpdate DI::logger()->info('Start', ['contact' => $id]); - $start_id = $id; - $rows = 0; + $start_id = $id; + $rows = 0; $condition = ["`id` > ? AND `gsid` IS NULL AND `network` = ?", $id, Protocol::DIASPORA]; - $params = ['order' => ['id'], 'limit' => 10000]; - $contacts = DBA::select('contact', ['id', 'url'], $condition, $params); + $params = ['order' => ['id'], 'limit' => 10000]; + $contacts = DBA::select('contact', ['id', 'url'], $condition, $params); if (DBA::errorNo() != 0) { DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]); @@ -1217,9 +1241,11 @@ class PostUpdate unset($parts['path']); $server = (string)Uri::fromParts($parts); - DBA::update('contact', + DBA::update( + 'contact', ['gsid' => GServer::getID($server, true), 'baseurl' => GServer::cleanURL($server)], - ['id' => $contact['id']]); + ['id' => $contact['id']] + ); ++$rows; } @@ -1256,10 +1282,10 @@ class PostUpdate DI::logger()->info('Start', ['apcontact' => $id]); - $start_id = $id; - $rows = 0; - $condition = ["`url` > ? AND NOT `gsid` IS NULL", $id]; - $params = ['order' => ['url'], 'limit' => 10000]; + $start_id = $id; + $rows = 0; + $condition = ["`url` > ? AND NOT `gsid` IS NULL", $id]; + $params = ['order' => ['url'], 'limit' => 10000]; $apcontacts = DBA::select('apcontact', ['url', 'gsid', 'sharedinbox', 'inbox'], $condition, $params); if (DBA::errorNo() != 0) { @@ -1310,7 +1336,7 @@ class PostUpdate $id = (int)(DI::keyValue()->get('post_update_version_1544_id') ?? 0); if ($id == 0) { $post = Post::selectFirstPost(['uri-id'], [], ['order' => ['uri-id' => true]]); - $id = (int)($post['uri-id'] ?? 0); + $id = (int)($post['uri-id'] ?? 0); } DI::logger()->info('Start', ['uri-id' => $id]); @@ -1375,7 +1401,7 @@ class PostUpdate $id = (int)(DI::keyValue()->get('post_update_version_1550_id') ?? 0); if ($id == 0) { $post = Post::selectFirstPost(['uri-id'], [], ['order' => ['uri-id' => true]]); - $id = (int)($post['uri-id'] ?? 0); + $id = (int)($post['uri-id'] ?? 0); } DI::logger()->info('Start', ['uri-id' => $id]); diff --git a/src/Factory/Api/Mastodon/Status.php b/src/Factory/Api/Mastodon/Status.php index fc1715c1d5..8eba9221e7 100644 --- a/src/Factory/Api/Mastodon/Status.php +++ b/src/Factory/Api/Mastodon/Status.php @@ -221,8 +221,8 @@ class Status extends BaseFactory $application = new \Friendica\Object\Api\Mastodon\Application($item['app'] ?: $platform); - $mentions = $this->mstdnMentionFactory->createFromUriId($uriId)->getArrayCopy(); - $tags = $this->mstdnTagFactory->createFromUriId($uriId); + $mentions = $this->mstdnMentionFactory->createFromUriId($uriId)->getArrayCopy(); + $tags = $this->mstdnTagFactory->createFromUriId($uriId); if ($item['has-media']) { $card = $this->mstdnCardFactory->createFromUriId($uriId); $attachments = $this->mstdnAttachmentFactory->createFromUriId($uriId); @@ -349,7 +349,7 @@ class Status extends BaseFactory $quote_id = $media['media-uri-id']; } else { $shared_item = Post::selectFirst(['uri-id'], ['plink' => $media[0]['url'], 'uid' => [$uid, 0]]); - $quote_id = $shared_item['uri-id'] ?? 0; + $quote_id = $shared_item['uri-id'] ?? 0; } } } else { diff --git a/src/Model/APContact.php b/src/Model/APContact.php index e88cccd619..a364344a51 100644 --- a/src/Model/APContact.php +++ b/src/Model/APContact.php @@ -13,7 +13,6 @@ use Friendica\Core\Protocol; use Friendica\Core\System; use Friendica\Database\DBA; use Friendica\DI; -use Friendica\Model\Item; use Friendica\Network\HTTPException; use Friendica\Network\Probe; use Friendica\Protocol\ActivityNamespace; @@ -153,7 +152,7 @@ class APContact // Detect multiple fast repeating request to the same address // See https://github.com/friendica/friendica/issues/9303 $cachekey = 'apcontact:' . ItemURI::getIdByURI($url); - $result = DI::cache()->get($cachekey); + $result = DI::cache()->get($cachekey); if (!is_null($result)) { DI::logger()->info('Multiple requests for the address', ['url' => $url, 'update' => $update, 'result' => $result]); if (!empty($fetched_contact)) { @@ -165,7 +164,7 @@ class APContact if (DI::baseUrl()->isLocalUrl($url) && ($local_uid = User::getIdForURL($url))) { try { - $data = Transmitter::getProfile($local_uid); + $data = Transmitter::getProfile($local_uid); $local_owner = User::getOwnerDataById($local_uid); } catch(HTTPException\NotFoundException $e) { $data = null; @@ -177,11 +176,11 @@ class APContact try { $curlResult = HTTPSignature::fetchRaw($url); - $failed = empty($curlResult->getBodyString()) || + $failed = empty($curlResult->getBodyString()) || (!$curlResult->isSuccess() && ($curlResult->getReturnCode() != 410)); - if (!$failed) { - $data = json_decode($curlResult->getBodyString(), true); + if (!$failed) { + $data = json_decode($curlResult->getBodyString(), true); $failed = empty($data) || !is_array($data); } @@ -206,13 +205,13 @@ class APContact return $fetched_contact; } - $apcontact['url'] = $compacted['@id']; - $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value'); - $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type')); + $apcontact['url'] = $compacted['@id']; + $apcontact['uuid'] = JsonLD::fetchElement($compacted, 'diaspora:guid', '@value'); + $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type')); $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id'); $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id'); - $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? ''); - $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id'); + $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? ''); + $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id'); $apcontact['sharedinbox'] = ''; if (!empty($compacted['as:endpoints'])) { @@ -303,12 +302,12 @@ class APContact } } - $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers'); + $apcontact['manually-approve'] = (int)JsonLD::fetchElement($compacted, 'as:manuallyApprovesFollowers'); $apcontact['posting-restricted'] = (int)JsonLD::fetchElement($compacted, 'lemmy:postingRestrictedToMods'); - $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended'); + $apcontact['suspended'] = (int)JsonLD::fetchElement($compacted, 'toot:suspended'); if (!empty($compacted['as:generator'])) { - $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id'); + $apcontact['baseurl'] = JsonLD::fetchElement($compacted['as:generator'], 'as:url', '@id'); $apcontact['generator'] = JsonLD::fetchElement($compacted['as:generator'], 'as:name', '@value'); } @@ -348,7 +347,7 @@ class APContact if (!empty($local_owner)) { $statuses_count = self::getStatusesCount($local_owner); } else { - $outbox = HTTPSignature::fetch($apcontact['outbox']); + $outbox = HTTPSignature::fetch($apcontact['outbox']); $statuses_count = $outbox['totalItems'] ?? 0; } if (!empty($statuses_count)) { diff --git a/src/Model/Circle.php b/src/Model/Circle.php index 00b4b16d5d..f9323897e9 100644 --- a/src/Model/Circle.php +++ b/src/Model/Circle.php @@ -23,7 +23,7 @@ use Friendica\Protocol\ActivityPub; class Circle { const FOLLOWERS = '~'; - const MUTUALS = '&'; + const MUTUALS = '&'; /** * Fetches circle record by user id and maybe includes deleted circles as well @@ -163,7 +163,8 @@ class Circle */ 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` WHERE `uid` = ? AND `unseen` @@ -230,15 +231,15 @@ class Circle if ($user['def_gid'] == $gid) { $user['def_gid'] = 0; - $change = true; + $change = true; } if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) { $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']); - $change = true; + $change = true; } if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) { $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']); - $change = true; + $change = true; } if ($change) { @@ -410,13 +411,13 @@ class Circle if ($key !== false) { if ($expand_followers) { $followers = Contact::selectToArray(['id'], [ - 'uid' => $uid, - 'rel' => [Contact::FOLLOWER, Contact::FRIEND], - 'network' => $networks, + 'uid' => $uid, + 'rel' => [Contact::FOLLOWER, Contact::FRIEND], + 'network' => $networks, 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON, Contact::TYPE_NEWS, Contact::TYPE_ORGANISATION], - 'archive' => false, - 'pending' => false, - 'blocked' => false, + 'archive' => false, + 'pending' => false, + 'blocked' => false, ]); foreach ($followers as $follower) { @@ -431,13 +432,13 @@ class Circle $key = array_search(self::MUTUALS, $circle_ids); if ($key !== false) { $mutuals = Contact::selectToArray(['id'], [ - 'uid' => $uid, - 'rel' => [Contact::FRIEND], - 'network' => $networks, + 'uid' => $uid, + 'rel' => [Contact::FRIEND], + 'network' => $networks, 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON], - 'archive' => false, - 'pending' => false, - 'blocked' => false, + 'archive' => false, + 'pending' => false, + 'blocked' => false, ]); foreach ($mutuals as $mutual) { @@ -478,8 +479,8 @@ class Circle { $display_circles = [ [ - 'name' => '', - 'id' => '0', + 'name' => '', + 'id' => '0', 'selected' => '' ] ]; @@ -487,8 +488,8 @@ class Circle $stmt = DBA::select('group', [], ['deleted' => false, 'uid' => $uid, 'cid' => null], ['order' => ['name']]); while ($circle = DBA::fetch($stmt)) { $display_circles[] = [ - 'name' => $circle['name'], - 'id' => $circle['id'], + 'name' => $circle['name'], + 'id' => $circle['id'], 'selected' => $gid == $circle['id'] ? 'true' : '' ]; } @@ -497,8 +498,8 @@ class Circle DI::logger()->info('Got circles', $display_circles); $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('circle_selection.tpl'), [ - '$id' => $id, - '$label' => $label, + '$id' => $id, + '$label' => $label, '$circles' => $display_circles ]); return $o; @@ -526,10 +527,10 @@ class Circle $display_circles = [ [ - 'text' => DI::l10n()->t('Everybody'), - 'id' => 0, + 'text' => DI::l10n()->t('Everybody'), + 'id' => 0, 'selected' => (($circle_id === 'everyone') ? 'circle-selected' : ''), - 'href' => $every, + 'href' => $every, ] ]; @@ -544,7 +545,7 @@ class Circle if ($editmode == 'full') { $circleedit = [ - 'href' => 'circle/' . $circle['id'], + 'href' => 'circle/' . $circle['id'], 'title' => DI::l10n()->t('edit'), ]; } else { @@ -552,23 +553,23 @@ class Circle } if ($each == 'circle') { - $networks = Widget::unavailableNetworks(); + $networks = Widget::unavailableNetworks(); $sql_values = array_merge([$circle['id']], $networks); - $condition = ["`circle-id` = ? AND NOT `contact-network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")"]; - $condition = array_merge($condition, $sql_values); + $condition = ["`circle-id` = ? AND NOT `contact-network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")"]; + $condition = array_merge($condition, $sql_values); - $count = DBA::count('circle-member-view', $condition); + $count = DBA::count('circle-member-view', $condition); $circle_name = sprintf('%s (%d)', $circle['name'], $count); } else { $circle_name = $circle['name']; } $display_circles[] = [ - 'id' => $circle['id'], - 'cid' => $cid, - 'text' => $circle_name, - 'href' => $each . '/' . $circle['id'], - 'edit' => $circleedit, + 'id' => $circle['id'], + 'cid' => $cid, + 'text' => $circle_name, + 'href' => $each . '/' . $circle['id'], + 'edit' => $circleedit, 'selected' => $selected, 'ismember' => in_array($circle['id'], $member_of), ]; @@ -581,18 +582,18 @@ class Circle } $tpl = Renderer::getMarkupTemplate('circle_side.tpl'); - $o = Renderer::replaceMacros($tpl, [ - '$add' => DI::l10n()->t('add'), - '$title' => DI::l10n()->t('Circles'), - '$circles' => $display_circles, - '$new_circle' => $editmode == 'extended' || $editmode == 'full' ? 1 : '', - '$circle_page' => 'circle/', - '$edittext' => DI::l10n()->t('Edit circle'), - '$uncircled' => $every === 'contact' ? DI::l10n()->t('Contacts not in any circle') : '', - '$uncircled_selected' => (($circle_id === 'none') ? 'circle-selected' : ''), - '$createtext' => DI::l10n()->t('Create a new circle'), - '$create_circle' => DI::l10n()->t('Circle Name: '), - '$edit_circles_text' => DI::l10n()->t('Edit circles'), + $o = Renderer::replaceMacros($tpl, [ + '$add' => DI::l10n()->t('add'), + '$title' => DI::l10n()->t('Circles'), + '$circles' => $display_circles, + '$new_circle' => $editmode == 'extended' || $editmode == 'full' ? 1 : '', + '$circle_page' => 'circle/', + '$edittext' => DI::l10n()->t('Edit circle'), + '$uncircled' => $every === 'contact' ? DI::l10n()->t('Contacts not in any circle') : '', + '$uncircled_selected' => (($circle_id === 'none') ? 'circle-selected' : ''), + '$createtext' => DI::l10n()->t('Create a new circle'), + '$create_circle' => DI::l10n()->t('Circle Name: '), + '$edit_circles_text' => DI::l10n()->t('Edit circles'), '$form_security_token' => BaseModule::getFormSecurityToken('circle_edit'), ]); diff --git a/src/Model/Contact.php b/src/Model/Contact.php index 083f66287f..e894dc64ea 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -74,12 +74,12 @@ class Contact * This will only be assigned to contacts, not to user accounts * @{ */ - const TYPE_UNKNOWN = -1; - const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON; + const TYPE_UNKNOWN = -1; + const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON; const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION; - const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS; - const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY; - const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY; + const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS; + const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY; + const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY; /** * @} */ @@ -335,7 +335,7 @@ class Contact if (!empty($fields)) { foreach (['id', 'next-update', 'network', 'local-data'] as $internal) { if (!in_array($internal, $fields)) { - $fields[] = $internal; + $fields[] = $internal; $removal[] = $internal; } } @@ -353,9 +353,9 @@ class Contact // Then the alias (which could be anything) if (!DBA::isResult($contact)) { // The link could be provided as http although we stored it as https - $ssl_url = str_replace('http://', 'https://', $url); + $ssl_url = str_replace('http://', 'https://', $url); $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid]; - $contact = DBA::selectFirst('contact', $fields, $condition, $options); + $contact = DBA::selectFirst('contact', $fields, $condition, $options); } if (!DBA::isResult($contact)) { @@ -837,7 +837,7 @@ class Contact } $fields = ['uid', 'username', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey']; - $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]); + $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]); if (!DBA::isResult($user)) { return false; } @@ -868,11 +868,11 @@ class Contact 'network' => Protocol::DFRN, 'url' => $url, // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine. - 'nurl' => Strings::normaliseLink($url), - 'uri-id' => ItemURI::getIdByURI($url), - 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3), - 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'], - 'poll' => DI::baseUrl() . '/feed/' . $user['nickname'], + 'nurl' => Strings::normaliseLink($url), + 'uri-id' => ItemURI::getIdByURI($url), + 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3), + 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'], + 'poll' => DI::baseUrl() . '/feed/' . $user['nickname'], ]; $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]); @@ -897,14 +897,14 @@ class Contact $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO); } - $fields['avatar'] = User::getAvatarUrl($user); - $fields['header'] = User::getBannerUrl($user); - $fields['forum'] = in_array($user['page-flags'], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_COMM_MAN]); - $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP; - $fields['unsearchable'] = !$profile['net-publish']; + $fields['avatar'] = User::getAvatarUrl($user); + $fields['header'] = User::getBannerUrl($user); + $fields['forum'] = in_array($user['page-flags'], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_COMM_MAN]); + $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP; + $fields['unsearchable'] = !$profile['net-publish']; $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP, User::PAGE_FLAGS_COMM_MAN]); - $fields['baseurl'] = DI::baseUrl(); - $fields['gsid'] = GServer::getID($fields['baseurl'], true); + $fields['baseurl'] = DI::baseUrl(); + $fields['gsid'] = GServer::getID($fields['baseurl'], true); $update = false; @@ -1083,7 +1083,7 @@ class Contact public static function markForArchival(array $contact) { if ((!isset($contact['uri-id']) || !isset($contact['url']) || !isset($contact['archive']) || !isset($contact['self']) || !isset($contact['term-date'])) && !empty($contact['id'])) { - $fields = ['id', 'uri-id', 'url', 'archive', 'self', 'term-date']; + $fields = ['id', 'uri-id', 'url', 'archive', 'self', 'term-date']; $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]); if (!DBA::isResult($contact)) { return; @@ -1135,7 +1135,7 @@ class Contact { // Always unarchive the relay contact entry if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) { - $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false, 'unsearchable' => true]; + $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false, 'unsearchable' => true]; $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY]; if (!DBA::exists('contact', array_merge($condition, $fields))) { self::update($fields, $condition); @@ -1149,7 +1149,7 @@ class Contact } if ((!isset($contact['url']) || !isset($contact['uri-id'])) && !empty($contact['id'])) { - $fields = ['id', 'uri-id', 'url', 'batch', 'term-date']; + $fields = ['id', 'uri-id', 'url', 'batch', 'term-date']; $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]); if (!DBA::isResult($contact)) { return; @@ -1205,11 +1205,11 @@ class Contact if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) { $mention_label = DI::l10n()->t('Post to group'); - $mention_url = 'compose/0?body=!' . $contact['addr']; + $mention_url = 'compose/0?body=!' . $contact['addr']; $network_label = DI::l10n()->t('View group'); } else { $mention_label = DI::l10n()->t('Mention'); - $mention_url = 'compose/0?body=@' . $contact['addr']; + $mention_url = 'compose/0?body=@' . $contact['addr']; $network_label = DI::l10n()->t('Network Posts'); } $network_url = 'contact/' . $contact['id'] . '/conversations'; @@ -1369,10 +1369,10 @@ class Contact if (DBA::isResult($personal_contact) && !Probe::isProbable($personal_contact['network'])) { DI::logger()->info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact]); - $data = $personal_contact; - $data['photo'] = $personal_contact['avatar']; + $data = $personal_contact; + $data['photo'] = $personal_contact['avatar']; $data['account-type'] = $personal_contact['contact-type']; - $data['hide'] = $personal_contact['unsearchable']; + $data['hide'] = $personal_contact['unsearchable']; unset($data['avatar']); unset($data['contact-type']); unset($data['unsearchable']); @@ -1404,17 +1404,17 @@ class Contact if (!$contact_id) { // We only insert the basic data. The rest will be done in "updateFromProbeArray" $fields = [ - 'uid' => $uid, - 'url' => $data['url'], - 'baseurl' => $data['baseurl'] ?? '', - 'nurl' => Strings::normaliseLink($data['url']), - 'network' => $data['network'], - 'created' => DateTimeFormat::utcNow(), - 'rel' => self::SHARING, - 'writable' => 1, - 'blocked' => 0, - 'readonly' => 0, - 'pending' => 0, + 'uid' => $uid, + 'url' => $data['url'], + 'baseurl' => $data['baseurl'] ?? '', + 'nurl' => Strings::normaliseLink($data['url']), + 'network' => $data['network'], + 'created' => DateTimeFormat::utcNow(), + 'rel' => self::SHARING, + 'writable' => 1, + 'blocked' => 0, + 'readonly' => 0, + 'pending' => 0, ]; $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false]; @@ -1627,13 +1627,13 @@ class Contact if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) { $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl'); - $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); + $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); } else { $o = ''; } $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']); - $items = Post::toArray(Post::selectForUser($uid, $fields, $condition, $params)); + $items = Post::toArray(Post::selectForUser($uid, $fields, $condition, $params)); $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACT_POSTS); @@ -1690,7 +1690,7 @@ class Contact if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) { $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl'); - $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); + $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); } else { $o = ''; } @@ -1706,7 +1706,7 @@ class Contact $sql2 = "SELECT `thr-parent-id` AS `uri-id`, `created` FROM `post-user-view` WHERE " . array_shift($condition2); $union = array_merge($condition1, $condition2); - $sql = $sql1 . " UNION " . $sql2; + $sql = $sql1 . " UNION " . $sql2; $sql .= " ORDER BY `created` DESC LIMIT ?, ?"; $union = array_merge($union, [$pager->getStart(), $pager->getItemsPerPage()]); @@ -1715,7 +1715,7 @@ class Contact if (empty($last_created) && ($pager->getStart() == 0)) { $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'created']; $pinned = Post\Collection::selectToArrayForContact($cid, Post\Collection::FEATURED, $fields); - $items = array_merge($items, $pinned); + $items = array_merge($items, $pinned); } $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_created', $uid); @@ -1906,9 +1906,9 @@ class Contact */ private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array { - $update = false; + $update = false; $contact_fields = []; - $fields = ['photo', 'thumb', 'micro']; + $fields = ['photo', 'thumb', 'micro']; foreach ($fields as $field) { if (isset($contact[$field])) { $contact_fields[] = $field; @@ -1964,7 +1964,7 @@ class Contact if (!empty($contact['gsid'])) { // Use default banners for certain platforms - $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]); + $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]); $platform = strtolower($gserver['platform'] ?? ''); } else { $platform = ''; @@ -2009,18 +2009,18 @@ class Contact switch ($size) { case Proxy::SIZE_MICRO: $avatar['size'] = 48; - $default = self::DEFAULT_AVATAR_MICRO; + $default = self::DEFAULT_AVATAR_MICRO; break; case Proxy::SIZE_THUMB: $avatar['size'] = 80; - $default = self::DEFAULT_AVATAR_THUMB; + $default = self::DEFAULT_AVATAR_THUMB; break; case Proxy::SIZE_SMALL: default: $avatar['size'] = 300; - $default = self::DEFAULT_AVATAR_PHOTO; + $default = self::DEFAULT_AVATAR_PHOTO; break; } @@ -2029,14 +2029,14 @@ class Contact $type = Contact::TYPE_PERSON; if (!empty($contact['id'])) { - $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]); - $platform = $account['platform'] ?? ''; + $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]); + $platform = $account['platform'] ?? ''; $type = $account['contact-type'] ?? Contact::TYPE_PERSON; } if (empty($platform) && !empty($contact['uri-id'])) { - $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]); - $platform = $account['platform'] ?? ''; + $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]); + $platform = $account['platform'] ?? ''; $type = $account['contact-type'] ?? Contact::TYPE_PERSON; } @@ -2146,7 +2146,7 @@ class Contact return DI::baseUrl() . $default; } - $avatar['url'] = ''; + $avatar['url'] = ''; $avatar['success'] = false; Hook::callAll('avatar_lookup', $avatar); @@ -2174,7 +2174,7 @@ class Contact if (empty($updated)) { $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]); $updated = $account['updated'] ?? ''; - $guid = $account['guid'] ?? ''; + $guid = $account['guid'] ?? ''; } $guid = urlencode($guid); @@ -2242,7 +2242,7 @@ class Contact if (empty($updated) || empty($guid)) { $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]); $updated = $account['updated'] ?? ''; - $guid = $account['guid'] ?? ''; + $guid = $account['guid'] ?? ''; } $guid = urlencode($guid); @@ -2373,11 +2373,11 @@ class Contact if ($default_avatar && Proxy::isLocalImage($avatar)) { $fields = [ - 'avatar' => $avatar, + 'avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), - 'photo' => $avatar, - 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB), - 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO) + 'photo' => $avatar, + 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB), + 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO) ]; DI::logger()->debug('Use default avatar', ['id' => $cid, 'uid' => $uid]); } @@ -2416,11 +2416,11 @@ class Contact $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true); if ($photos) { $fields = [ - 'avatar' => $avatar, - 'photo' => $photos[0], - 'thumb' => $photos[1], - 'micro' => $photos[2], - 'blurhash' => $photos[3], + 'avatar' => $avatar, + 'photo' => $photos[0], + 'thumb' => $photos[1], + 'micro' => $photos[2], + 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow(), ]; $update = true; @@ -2473,7 +2473,7 @@ class Contact { // Update contact data for all users $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)) { DI::logger()->info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]); self::remove($contact['id']); @@ -2600,7 +2600,7 @@ class Contact public static function removeDuplicates(string $nurl, int $uid) { $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED]; - $count = DBA::count('contact', $condition); + $count = DBA::count('contact', $condition); if ($count <= 1) { return false; } @@ -2615,7 +2615,7 @@ class Contact DI::logger()->info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]); // 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]; $duplicates = DBA::select('contact', ['id', 'network'], $condition); while ($duplicate = DBA::fetch($duplicates)) { if (!in_array($duplicate['network'], Protocol::FEDERATED)) { @@ -2686,7 +2686,7 @@ class Contact $data = Probe::uri($contact['url'], $network, $contact['uid']); if (in_array($data['network'], Protocol::FEDERATED) && (parse_url($data['url'], PHP_URL_SCHEME) == 'http')) { - $ssl_url = str_replace('http://', 'https://', $contact['url']); + $ssl_url = str_replace('http://', 'https://', $contact['url']); $ssl_data = Probe::uri($ssl_url, $network, $contact['uid']); if (($ssl_data['network'] == $data['network']) && (parse_url($ssl_data['url'], PHP_URL_SCHEME) != 'http')) { $data = $ssl_data; @@ -2883,12 +2883,12 @@ class Contact } if (isset($ret['account-type']) && is_int($ret['account-type'])) { - $ret['forum'] = false; - $ret['prv'] = false; + $ret['forum'] = false; + $ret['prv'] = false; $ret['contact-type'] = $ret['account-type']; if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) { $ret['forum'] = (bool)!$ret['manually-approve']; - $ret['prv'] = (bool)!$ret['forum']; + $ret['prv'] = (bool)!$ret['forum']; } } @@ -2907,7 +2907,7 @@ class Contact } $update = false; - $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? ''); + $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? ''); // make sure to not overwrite existing values with blank entries except some technical fields $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl']; @@ -2974,7 +2974,7 @@ class Contact } if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) { - $ret['last-update'] = $updated; + $ret['last-update'] = $updated; $ret['success_update'] = $updated; } @@ -3106,10 +3106,10 @@ class Contact if (!empty($arr['contact']['name'])) { $probed = false; - $ret = $arr['contact']; + $ret = $arr['contact']; } else { $probed = true; - $ret = Probe::uri($url, $network, $uid); + $ret = Probe::uri($url, $network, $uid); // Ensure that the public contact exists if ($ret['network'] != Protocol::PHANTOM) { @@ -3124,7 +3124,7 @@ class Contact // check if we already have a contact $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false]; - $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition); + $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition); $protocol = self::getProtocol($ret['url'], $ret['network']); @@ -3203,7 +3203,7 @@ class Contact 'nick' => $ret['nick'], 'network' => $ret['network'], 'baseurl' => $ret['baseurl'], - 'gsid' => $ret['gsid'] ?? null, + 'gsid' => $ret['gsid'] ?? null, 'contact-type' => $ret['account-type'] ?? self::TYPE_PERSON, 'protocol' => $protocol, 'pubkey' => $ret['pubkey'], @@ -3223,7 +3223,7 @@ class Contact return $result; } - $contact_id = $contact['id']; + $contact_id = $contact['id']; $result['cid'] = $contact_id; if ($contact['contact-type'] == self::TYPE_COMMUNITY) { @@ -3268,7 +3268,7 @@ class Contact return false; } - $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked', 'baseurl']; + $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked', 'baseurl']; $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]); if (!DBA::isResult($pub_contact)) { // Should never happen @@ -3280,10 +3280,10 @@ class Contact return false; } - $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url']; - $name = $pub_contact['name']; - $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"]; - $nick = $pub_contact['nick']; + $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url']; + $name = $pub_contact['name']; + $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"]; + $nick = $pub_contact['nick']; $network = $pub_contact['network']; // Ensure that we don't create a new contact when there already is one @@ -3361,7 +3361,7 @@ class Contact /// @TODO Encapsulate this into a function/method $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language']; - $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]); + $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]); if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) { // create notification if (is_array($contact_record)) { @@ -3395,7 +3395,7 @@ class Contact } $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true]; - $fields = ['pending' => false]; + $fields = ['pending' => false]; if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) { $fields['rel'] = self::FRIEND; } @@ -3500,7 +3500,7 @@ class Contact DBA::update( 'contact', ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd], - ['id' => $contact['id']] + ['id' => $contact['id']] ); } } @@ -3655,9 +3655,9 @@ class Contact */ public static function isGroup(int $contactid): bool { - $fields = ['contact-type']; + $fields = ['contact-type']; $condition = ['id' => $contactid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); if (!DBA::isResult($contact)) { return false; } @@ -3675,7 +3675,7 @@ class Contact public static function canReceivePrivateMessages(array $contact): bool { $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM; - $self = $contact['self'] ?? false; + $self = $contact['self'] ?? false; return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self; } @@ -3706,12 +3706,12 @@ class Contact } $condition = [ - 'network' => $networks, - 'server-failed' => false, - 'failed' => false, - 'deleted' => false, - 'unsearchable' => false, - 'uid' => $uid + 'network' => $networks, + 'server-failed' => false, + 'failed' => false, + 'deleted' => false, + 'unsearchable' => false, + 'uid' => $uid ]; if (!$show_blocked) { @@ -3755,10 +3755,10 @@ class Contact */ public static function addByUrls(array $urls): array { - $added = 0; - $updated = 0; + $added = 0; + $updated = 0; $unchanged = 0; - $count = 0; + $count = 0; foreach ($urls as $url) { if (empty($url) || !is_string($url)) { diff --git a/src/Model/Contact/Relation.php b/src/Model/Contact/Relation.php index 76e0a7ac63..5172d87c70 100644 --- a/src/Model/Contact/Relation.php +++ b/src/Model/Contact/Relation.php @@ -98,7 +98,7 @@ class Relation $uid = User::getIdForURL($url); if (!empty($uid)) { 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]); } elseif (!Contact::isLocal($url)) { DI::logger()->info('Fetch the followers/followings by polling the endpoints', ['url' => $url]); @@ -117,7 +117,7 @@ class Relation } } else { DI::logger()->warning('Contact seems to be local but could not be found here', ['url' => $url]); - $followers = []; + $followers = []; $followings = []; } @@ -158,7 +158,7 @@ class Relation } $contacts = array_unique($contacts); - $follower_counter = 0; + $follower_counter = 0; $following_counter = 0; DI::logger()->info('Discover contacts', ['id' => $target, 'url' => $url, 'contacts' => count($contacts)]); @@ -199,7 +199,7 @@ class Relation */ private static function getContacts(int $uid, array $rel, bool $only_ap = true): array { - $list = []; + $list = []; $profile = Profile::getByUID($uid); if (!empty($profile['hide-friends'])) { return $list; @@ -300,7 +300,7 @@ class Relation * @param integer $uid * @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(); } @@ -311,7 +311,7 @@ class Relation * @param integer $uid * @return void */ - static public function updateCachedSuggestions(int $uid) + public static function updateCachedSuggestions(int $uid) { if (!self::areSuggestionsOutdated($uid)) { return; @@ -334,11 +334,11 @@ class Relation * @param int $limit optional, default 80 * @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]; - $params = ['limit' => [$start, $limit]]; - $cached = DBA::selectToArray('contact', [], $condition, $params); + $params = ['limit' => [$start, $limit]]; + $cached = DBA::selectToArray('contact', [], $condition, $params); if (!empty($cached)) { return $cached; @@ -355,15 +355,15 @@ class Relation * @param int $limit optional, default 80 * @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) { return []; } - $cid = Contact::getPublicIdByUserId($uid); + $cid = Contact::getPublicIdByUserId($uid); $totallimit = $start + $limit; - $contacts = []; + $contacts = []; DI::logger()->info('Collecting suggestions', ['uid' => $uid, 'cid' => $cid, 'start' => $start, 'limit' => $limit]); @@ -371,17 +371,21 @@ class Relation // 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. - $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` = ?) 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`) AND NOT `hidden` AND `network` IN (?, ?, ?) AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)", - $cid, - 0, - $uid, Contact::FRIEND, Contact::SHARING, - Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid - ], [ + $cid, + 0, + $uid, Contact::FRIEND, Contact::SHARING, + Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid + ], + [ 'order' => ['last-item' => true], 'limit' => $totallimit, ] @@ -401,15 +405,17 @@ class Relation // 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. - $results = DBA::select('contact', [], + $results = DBA::select( + 'contact', + [], ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ?) 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`) AND NOT `hidden` AND `network` IN (?, ?, ?) AND NOT `uri-id` IN (SELECT `uri-id` FROM `account-suggestion` WHERE `uri-id` = `contact`.`uri-id` AND `uid` = ?)", - $cid, 0, $uid, Contact::FRIEND, Contact::SHARING, - Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid], + $cid, 0, $uid, Contact::FRIEND, Contact::SHARING, + Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid], ['order' => ['last-item' => true], 'limit' => $totallimit] ); @@ -425,12 +431,14 @@ class Relation } // 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` = ?) 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` = ?)", - $uid, Contact::FOLLOWER, 0, - Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid], + $uid, Contact::FOLLOWER, 0, + Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid], ['order' => ['last-item' => true], 'limit' => $totallimit] ); @@ -446,12 +454,14 @@ class Relation } // 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`) 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` = ?)", - $uid, Contact::FRIEND, Contact::SHARING, 0, - Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid], + $uid, Contact::FRIEND, Contact::SHARING, 0, + Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $uid], ['order' => ['last-item' => true], 'limit' => $totallimit] ); @@ -476,7 +486,7 @@ class Relation public static function countFollows(int $cid, array $condition = []): int { $condition = DBA::mergeConditions($condition, ["`cid` = ? and `follows`", $cid]); - $sql = "SELECT COUNT(*) AS `total` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition); + $sql = "SELECT COUNT(*) AS `total` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition); $result = DBA::fetchFirst($sql, $condition); return $result['total'] ?? 0; @@ -495,7 +505,7 @@ class Relation public static function listFollows(int $cid, array $condition = [], int $count = 30, int $offset = 0) { $condition = DBA::mergeConditions($condition, ["`cid` = ? and `follows`", $cid]); - $sql = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition); + $sql = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition); if ($count > 0) { $sql .= " LIMIT ?, ?"; $condition = array_merge($condition, [$offset, $count]); @@ -514,7 +524,7 @@ class Relation public static function countFollowers(int $cid, array $condition = []) { $condition = DBA::mergeConditions($condition, ["`relation-cid` = ? and `follows`", $cid]); - $sql = "SELECT COUNT(*) AS `total` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition); + $sql = "SELECT COUNT(*) AS `total` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition); $result = DBA::fetchFirst($sql, $condition); return $result['total'] ?? 0; @@ -533,7 +543,7 @@ class Relation public static function listFollowers(int $cid, array $condition = [], int $count = 30, int $offset = 0) { $condition = DBA::mergeConditions($condition, ["`relation-cid` = ? and `follows`", $cid]); - $sql = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition); + $sql = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition); if ($count > 0) { $sql .= " LIMIT ?, ?"; $condition = array_merge($condition, [$offset, $count]); @@ -553,13 +563,13 @@ class Relation { $condition1 = DBA::mergeConditions($condition, ["`cid` = ? and `follows`", $cid]); $condition2 = DBA::mergeConditions($condition, ["`relation-cid` = ? and `follows`", $cid]); - $sql1 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); - $sql2 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition2); - $union = array_merge($condition1, $condition2); - $sql = $sql1 . " INTERSECT " . $sql2; + $sql1 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); + $sql2 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition2); + $union = array_merge($condition1, $condition2); + $sql = $sql1 . " INTERSECT " . $sql2; $contacts = 0; - $query = DBA::p($sql, $union); + $query = DBA::p($sql, $union); while (DBA::fetch($query)) { $contacts++; } @@ -582,10 +592,10 @@ class Relation { $condition1 = DBA::mergeConditions($condition, ["`cid` = ? and `follows`", $cid]); $condition2 = DBA::mergeConditions($condition, ["`relation-cid` = ? and `follows`", $cid]); - $sql1 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); - $sql2 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition2); - $union = array_merge($condition1, $condition2); - $sql = $sql1 . " INTERSECT " . $sql2; + $sql1 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); + $sql2 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition2); + $union = array_merge($condition1, $condition2); + $sql = $sql1 . " INTERSECT " . $sql2; if ($count > 0) { $sql .= " LIMIT ?, ?"; $union = array_merge($union, [$offset, $count]); @@ -605,13 +615,13 @@ class Relation { $condition1 = DBA::mergeConditions($condition, ["`cid` = ? and `follows`", $cid]); $condition2 = DBA::mergeConditions($condition, ["`relation-cid` = ? and `follows`", $cid]); - $sql1 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); - $sql2 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); - $union = array_merge($condition1, $condition2); - $sql = $sql1 . " UNION " . $sql2; + $sql1 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); + $sql2 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); + $union = array_merge($condition1, $condition2); + $sql = $sql1 . " UNION " . $sql2; $contacts = 0; - $query = DBA::p($sql, $union); + $query = DBA::p($sql, $union); while (DBA::fetch($query)) { $contacts++; } @@ -634,10 +644,10 @@ class Relation { $condition1 = DBA::mergeConditions($condition, ["`cid` = ? and `follows`", $cid]); $condition2 = DBA::mergeConditions($condition, ["`relation-cid` = ? and `follows`", $cid]); - $sql1 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); - $sql2 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); - $union = array_merge($condition1, $condition2); - $sql = $sql1 . " UNION " . $sql2; + $sql1 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `relation-cid` WHERE " . array_shift($condition1); + $sql2 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); + $union = array_merge($condition1, $condition2); + $sql = $sql1 . " UNION " . $sql2; if ($count > 0) { $sql .= " LIMIT ?, ?"; $union = array_merge($union, [$offset, $count]); @@ -659,13 +669,13 @@ class Relation { $condition1 = DBA::mergeConditions($condition, ["`relation-cid` = ?", $sourceId]); $condition2 = DBA::mergeConditions($condition, ["`relation-cid` = ?", $targetId]); - $sql1 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition1); - $sql2 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); - $union = array_merge($condition1, $condition2); - $sql = $sql1 . " INTERSECT " . $sql2; + $sql1 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition1); + $sql2 = "SELECT `contact`.`id` FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); + $union = array_merge($condition1, $condition2); + $sql = $sql1 . " INTERSECT " . $sql2; $contacts = 0; - $query = DBA::p($sql, $union); + $query = DBA::p($sql, $union); while (DBA::fetch($query)) { $contacts++; } @@ -690,10 +700,10 @@ class Relation { $condition1 = DBA::mergeConditions($condition, ["`relation-cid` = ?", $sourceId]); $condition2 = DBA::mergeConditions($condition, ["`relation-cid` = ?", $targetId]); - $sql1 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition1); - $sql2 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); - $union = array_merge($condition1, $condition2); - $sql = $sql1 . " INTERSECT " . $sql2; + $sql1 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " . array_shift($condition1); + $sql2 = "SELECT `contact`.* FROM `contact-relation` INNER JOIN `contact` ON `contact`.`id` = `cid` WHERE " .array_shift($condition2); + $union = array_merge($condition1, $condition2); + $sql = $sql1 . " INTERSECT " . $sql2; if ($count > 0) { $sql .= " LIMIT ?, ?"; $union = array_merge($union, [$offset, $count]); @@ -712,10 +722,11 @@ class Relation */ 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`) AND `id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', - $sourceId, $targetId] + $sourceId, $targetId] ); return DI::dba()->count('contact', $condition); @@ -735,13 +746,17 @@ class Relation */ 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`) 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']] ); } @@ -757,10 +772,11 @@ class Relation */ 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`) AND `id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)", - $sourceId, $targetId] + $sourceId, $targetId] ); return DI::dba()->count('contact', $condition); @@ -780,13 +796,17 @@ class Relation */ 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`) 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']] ); } @@ -799,78 +819,156 @@ class Relation */ public static function calculateInteractionScore(int $uid) { - $days = DI::config()->get('channel', 'interaction_score_days'); + $days = DI::config()->get('channel', 'interaction_score_days'); $contact_id = Contact::getPublicIdByUserId($uid); DI::logger()->debug('Calculation - start', ['uid' => $uid, 'cid' => $contact_id, 'days' => $days]); $follow = Verb::getID(Activity::FOLLOW); - $view = Verb::getID(Activity::VIEW); - $read = Verb::getID(Activity::READ); + $view = Verb::getID(Activity::VIEW); + $read = Verb::getID(Activity::READ); 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 (?, ?, ?)", - $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); + $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 (?, ?, ?)", + $contact_id, + DateTimeFormat::utc('now - ' . $days . ' day'), + $uid, + $contact_id, + $follow, + $view, + $read + ); 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`", - $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)) { $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::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 (?, ?, ?)", - $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); + $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 (?, ?, ?)", + $contact_id, + DateTimeFormat::utc('now - ' . $days . ' day'), + $uid, + $contact_id, + $follow, + $view, + $read + ); 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`", - $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)) { $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::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 (?, ?, ?)", - $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); + $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 (?, ?, ?)", + $contact_id, + DateTimeFormat::utc('now - ' . $days . ' day'), + $uid, + $contact_id, + $follow, + $view, + $read + ); 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`", - $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); + $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`", + $contact_id, + DateTimeFormat::utc('now - ' . $days . ' day'), + $uid, + $contact_id, + $follow, + $view, + $read + ); while ($interaction = DBA::fetch($interactions)) { $score = min((int)(($interaction['activity'] / $total['activity']) * 65535), 65535); DBA::update('contact-relation', ['score' => $score], ['relation-cid' => $contact_id, 'cid' => $interaction['author-id']]); } 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 (?, ?, ?)", - $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); + $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 (?, ?, ?)", + $contact_id, + DateTimeFormat::utc('now - ' . $days . ' day'), + $uid, + $contact_id, + $follow, + $view, + $read + ); 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`", - $contact_id, DateTimeFormat::utc('now - ' . $days . ' day'), $uid, $contact_id, $follow, $view, $read); + $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`", + $contact_id, + DateTimeFormat::utc('now - ' . $days . ' day'), + $uid, + $contact_id, + $follow, + $view, + $read + ); while ($interaction = DBA::fetch($interactions)) { $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::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` > ?", - $contact_id, $uid, DateTimeFormat::utc('now - ' . $days . ' day')); + $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` > ?", + $contact_id, + $uid, + DateTimeFormat::utc('now - ' . $days . ' day') + ); 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`", - $contact_id, $uid, DateTimeFormat::utc('now - ' . $days . ' day')); + $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`", + $contact_id, + $uid, + DateTimeFormat::utc('now - ' . $days . ' day') + ); while ($post = DBA::fetch($posts)) { $score = min((int)(($post['posts'] / $total['posts']) * 65535), 65535); DBA::update('contact-relation', ['post-score' => $score], ['relation-cid' => $contact_id, 'cid' => $post['author-id']]); diff --git a/src/Model/Contact/User.php b/src/Model/Contact/User.php index e7f5699556..17663e233b 100644 --- a/src/Model/Contact/User.php +++ b/src/Model/Contact/User.php @@ -56,9 +56,9 @@ class User return false; } - $fields = self::preparedFields($contact); - $fields['cid'] = $pcid; - $fields['uid'] = $contact['uid']; + $fields = self::preparedFields($contact); + $fields['cid'] = $pcid; + $fields['uid'] = $contact['uid']; $fields['uri-id'] = $contact['uri-id']; $ret = DBA::insert('user-contact', $fields, Database::INSERT_UPDATE); @@ -89,7 +89,7 @@ class User continue; } $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); DI::logger()->info('Updated user contact', ['uid' => $contact['uid'], 'id' => $contact['pid'], 'uri-id' => $contact['uri-id'], 'ret' => $ret]); } diff --git a/src/Model/Event.php b/src/Model/Event.php index 86567681e1..6cb73f4c37 100644 --- a/src/Model/Event.php +++ b/src/Model/Event.php @@ -29,7 +29,6 @@ use Friendica\Util\XML; */ class Event { - public static function getHTML(array $event, bool $simple = false, int $uriid = 0): string { if (empty($event)) { @@ -232,28 +231,28 @@ class Event */ public static function store(array $arr): int { - $guid = $arr['guid'] ?? '' ?: System::createUUID(); - $uri = $arr['uri'] ?? '' ?: Item::newURI($guid); + $guid = $arr['guid'] ?? '' ?: System::createUUID(); + $uri = $arr['uri'] ?? '' ?: Item::newURI($guid); $event = [ - 'id' => intval($arr['id'] ?? 0), - 'uid' => intval($arr['uid'] ?? 0), - 'cid' => intval($arr['cid'] ?? 0), + 'id' => intval($arr['id'] ?? 0), + 'uid' => intval($arr['uid'] ?? 0), + 'cid' => intval($arr['cid'] ?? 0), 'guid' => $guid, 'uri' => $uri, 'uri-id' => ItemURI::insert(['uri' => $uri, 'guid' => $guid]), - 'type' => ($arr['type'] ?? '') ?: 'event', - 'summary' => $arr['summary'] ?? '', - 'desc' => $arr['desc'] ?? '', - 'location' => $arr['location'] ?? '', - 'allow_cid' => $arr['allow_cid'] ?? '', - 'allow_gid' => $arr['allow_gid'] ?? '', - 'deny_cid' => $arr['deny_cid'] ?? '', - 'deny_gid' => $arr['deny_gid'] ?? '', + 'type' => ($arr['type'] ?? '') ?: 'event', + 'summary' => $arr['summary'] ?? '', + 'desc' => $arr['desc'] ?? '', + 'location' => $arr['location'] ?? '', + 'allow_cid' => $arr['allow_cid'] ?? '', + 'allow_gid' => $arr['allow_gid'] ?? '', + 'deny_cid' => $arr['deny_cid'] ?? '', + 'deny_gid' => $arr['deny_gid'] ?? '', 'nofinish' => intval($arr['nofinish'] ?? (!empty($arr['start']) && empty($arr['finish']))), 'created' => DateTimeFormat::utc(($arr['created'] ?? '') ?: 'now'), - 'edited' => DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now'), - 'start' => DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME), - 'finish' => DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME), + 'edited' => DateTimeFormat::utc(($arr['edited'] ?? '') ?: 'now'), + 'start' => DateTimeFormat::utc(($arr['start'] ?? '') ?: DBA::NULL_DATETIME), + 'finish' => DateTimeFormat::utc(($arr['finish'] ?? '') ?: DBA::NULL_DATETIME), ]; @@ -357,7 +356,7 @@ class Event $item['body'] = self::getBBCode($event); $item['event-id'] = $event['id']; - $item['object'] = '' . XML::escape(Activity\ObjectType::EVENT) . '' . XML::escape($event['uri']) . ''; + $item['object'] = '' . XML::escape(Activity\ObjectType::EVENT) . '' . XML::escape($event['uri']) . ''; $item['object'] .= '' . XML::escape(self::getBBCode($event)) . ''; $item['object'] .= '' . "\n"; @@ -375,13 +374,13 @@ class Event return $item; } - $item['post-type'] = Item::PT_EVENT; - $item['title'] = ''; - $item['object-type'] = Activity\ObjectType::EVENT; - $item['body'] = self::getBBCode($event); - $item['event-id'] = $event_id; + $item['post-type'] = Item::PT_EVENT; + $item['title'] = ''; + $item['object-type'] = Activity\ObjectType::EVENT; + $item['body'] = self::getBBCode($event); + $item['event-id'] = $event_id; - $item['object'] = '' . XML::escape(Activity\ObjectType::EVENT) . '' . XML::escape($event['uri']) . ''; + $item['object'] = '' . XML::escape(Activity\ObjectType::EVENT) . '' . XML::escape($event['uri']) . ''; $item['object'] .= '' . XML::escape(self::getBBCode($event)) . ''; $item['object'] .= '' . "\n"; @@ -398,7 +397,7 @@ class Event { // First day of the week (0 = Sunday). $firstDay = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'calendar', 'first_day_of_week') ?? 0; - $defaultView = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'calendar', 'defaultView') ?? 'month'; + $defaultView = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'calendar', 'defaultView') ?? 'month'; return [ 'firstDay' => $firstDay, @@ -649,12 +648,12 @@ class Event if (DI::userSession()->getLocalUserId() && DI::userSession()->getLocalUserId() == $event['uid'] && $event['type'] == 'event') { $edit = !$event['cid'] ? ['calendar/event/edit/' . $event['id'], DI::l10n()->t('Edit event'), '', ''] : null; $copy = !$event['cid'] ? ['calendar/event/copy/' . $event['id'], DI::l10n()->t('Duplicate event'), '', ''] : null; - $drop = ['calendar/api/delete/' . $event['id'], DI::l10n()->t('Delete event'), '', '']; + $drop = ['calendar/api/delete/' . $event['id'], DI::l10n()->t('Delete event'), '', '']; } $title = strip_tags(BBCode::convertForUriId($event['uri-id'], $event['summary'])); if (!$title) { - [$title, $_trash] = explode(" 0, 'id' => $item['author-id'], 'network' => $item['author-network'], diff --git a/src/Model/GServer.php b/src/Model/GServer.php index 933ca8d74c..9184997965 100644 --- a/src/Model/GServer.php +++ b/src/Model/GServer.php @@ -39,44 +39,44 @@ use Psr\Http\Message\UriInterface; class GServer { // Directory types - const DT_NONE = 0; - const DT_POCO = 1; + const DT_NONE = 0; + const DT_POCO = 1; const DT_MASTODON = 2; // Methods to detect server types // Non endpoint specific methods - const DETECT_MANUAL = 0; - const DETECT_HEADER = 1; - const DETECT_BODY = 2; - const DETECT_HOST_META = 3; - const DETECT_CONTACTS = 4; - const DETECT_AP_ACTOR = 5; + const DETECT_MANUAL = 0; + const DETECT_HEADER = 1; + const DETECT_BODY = 2; + const DETECT_HOST_META = 3; + const DETECT_CONTACTS = 4; + const DETECT_AP_ACTOR = 5; const DETECT_AP_COLLECTION = 6; const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR]; // Implementation specific endpoints // @todo Possibly add Lemmy detection via the endpoint /api/v3/site - const DETECT_FRIENDIKA = 10; - const DETECT_FRIENDICA = 11; - const DETECT_STATUSNET = 12; - const DETECT_GNUSOCIAL = 13; - const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix + const DETECT_FRIENDIKA = 10; + const DETECT_FRIENDICA = 11; + const DETECT_STATUSNET = 12; + const DETECT_GNUSOCIAL = 13; + const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla - const DETECT_MASTODON_API = 16; - const DETECT_STATUS_PHP = 17; // Nextcloud - const DETECT_V1_CONFIG = 18; - const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap - const DETECT_THREADS = 21; + const DETECT_MASTODON_API = 16; + const DETECT_STATUS_PHP = 17; // Nextcloud + const DETECT_V1_CONFIG = 18; + const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap + const DETECT_THREADS = 21; // Standardized endpoints const DETECT_STATISTICS_JSON = 100; - const DETECT_NODEINFO_10 = 101; // Nodeinfo Version 1.0 - const DETECT_NODEINFO_20 = 102; // Nodeinfo Version 2.0 - const DETECT_NODEINFO2_10 = 103; // Nodeinfo2 Version 1.0 - const DETECT_NODEINFO_21 = 104; // Nodeinfo Version 2.1 - const DETECT_NODEINFO_22 = 105; // Nodeinfo Version 2.2 + const DETECT_NODEINFO_10 = 101; // Nodeinfo Version 1.0 + const DETECT_NODEINFO_20 = 102; // Nodeinfo Version 2.0 + const DETECT_NODEINFO2_10 = 103; // Nodeinfo2 Version 1.0 + const DETECT_NODEINFO_21 = 104; // Nodeinfo Version 2.1 + const DETECT_NODEINFO_22 = 105; // Nodeinfo Version 2.2 /** * Check for the existence of a server and adds it in the background if not existant @@ -343,7 +343,7 @@ class GServer $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]); if (DBA::isResult($gserver)) { if ($gserver['created'] <= DBA::NULL_DATETIME) { - $fields = ['created' => DateTimeFormat::utcNow()]; + $fields = ['created' => DateTimeFormat::utcNow()]; $condition = ['nurl' => Strings::normaliseLink($server_url)]; self::update($fields, $condition); } @@ -450,9 +450,11 @@ class GServer $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]); if (DBA::isResult($gserver)) { $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']); - self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(), - 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null], - ['nurl' => $nurl]); + self::update( + ['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(), + 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null], + ['nurl' => $nurl] + ); DI::logger()->info('Set failed status for existing server', ['url' => $url]); if (self::isDefunct($gserver)) { self::archiveContacts($gserver['id']); @@ -461,8 +463,8 @@ class GServer } self::insert(['url' => $url, 'nurl' => $nurl, - 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(), - 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]); + 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(), + 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]); DI::logger()->info('Set failed status for new server', ['url' => $url]); } @@ -592,7 +594,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)) && (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) { - $url = $valid_url; + $url = $valid_url; } $in_webroot = empty(parse_url($url, PHP_URL_PATH)); @@ -627,10 +629,10 @@ class GServer if ($serverdata['network'] == Protocol::PHANTOM) { if ($in_webroot) { // Fetch the landing page, possibly it reveals some data - $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9'; + $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9'; $curlResult = DI::httpClient()->get($url, $accept, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') { - $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); + $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); $html_fetched = true; } else { $html_fetched = false; @@ -639,8 +641,8 @@ class GServer if ($curlResult->isSuccess()) { $json = json_decode($curlResult->getBodyString(), true); if (!empty($json) && is_array($json)) { - $data = self::fetchDataFromSystemActor($json, $serverdata); - $serverdata = $data['server']; + $data = self::fetchDataFromSystemActor($json, $serverdata); + $serverdata = $data['server']; $systemactor = $data['actor']; if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) { $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); @@ -739,7 +741,7 @@ class GServer return false; } - $serverdata['url'] = $url; + $serverdata['url'] = $url; $serverdata['nurl'] = Strings::normaliseLink($url); // We have to prevent an endless loop here. @@ -803,10 +805,10 @@ class GServer $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]); if (!DBA::isResult($gserver)) { $serverdata['created'] = DateTimeFormat::utcNow(); - $ret = self::insert($serverdata); - $id = DBA::lastInsertId(); + $ret = self::insert($serverdata); + $id = DBA::lastInsertId(); } else { - $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]); + $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]); $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]); if (DBA::isResult($gserver)) { $id = $gserver['id']; @@ -816,8 +818,8 @@ class GServer // Count the number of known contacts from this server if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) { $apcontacts = DBA::count('apcontact', ['gsid' => $id]); - $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]); - $max_users = max($apcontacts, $contacts); + $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]); + $max_users = max($apcontacts, $contacts); if ($max_users > $serverdata['registered-users']) { DI::logger()->info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]); self::update(['registered-users' => $max_users], ['id' => $id]); @@ -846,7 +848,7 @@ class GServer if (!empty($systemactor)) { $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']); - DI::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; @@ -879,9 +881,9 @@ class GServer $data['subscribe'] = (bool)($data['subscribe'] ?? false); if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) { - $data['scope'] = ''; + $data['scope'] = ''; $data['subscribe'] = false; - $data['tags'] = []; + $data['tags'] = []; } $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]); @@ -975,13 +977,13 @@ class GServer return $serverdata; } - $valid = false; + $valid = false; $old_serverdata = $serverdata; $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON; if (!empty($data['version'])) { - $valid = true; + $valid = true; $serverdata['version'] = $data['version']; // 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. @@ -989,12 +991,12 @@ class GServer } if (!empty($data['name'])) { - $valid = true; + $valid = true; $serverdata['site_name'] = $data['name']; } if (!empty($data['network'])) { - $valid = true; + $valid = true; $serverdata['platform'] = strtolower($data['network']); if ($serverdata['platform'] == 'diaspora') { @@ -1009,22 +1011,22 @@ class GServer } if (!empty($data['total_users'])) { - $valid = true; + $valid = true; $serverdata['registered-users'] = max($data['total_users'], 1); } if (!empty($data['active_users_monthly'])) { - $valid = true; + $valid = true; $serverdata['active-month-users'] = max($data['active_users_monthly'], 0); } if (!empty($data['active_users_halfyear'])) { - $valid = true; + $valid = true; $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0); } if (!empty($data['local_posts'])) { - $valid = true; + $valid = true; $serverdata['local-posts'] = max($data['local_posts'], 0); } @@ -1065,8 +1067,8 @@ class GServer return []; } - $nodeinfo1_url = ''; - $nodeinfo2_url = ''; + $nodeinfo1_url = ''; + $nodeinfo2_url = ''; $detection_method = self::DETECT_MANUAL; foreach ($nodeinfo['links'] as $link) { @@ -1078,13 +1080,13 @@ class GServer if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') { $nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl()); } elseif (($detection_method < self::DETECT_NODEINFO_20) && ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0')) { - $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); + $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); $detection_method = self::DETECT_NODEINFO_20; } elseif (($detection_method < self::DETECT_NODEINFO_21) && ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.1')) { - $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); + $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); $detection_method = self::DETECT_NODEINFO_21; } elseif (($detection_method < self::DETECT_NODEINFO_22) && ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.2')) { - $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); + $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); $detection_method = self::DETECT_NODEINFO_22; } } @@ -1132,7 +1134,7 @@ class GServer $server = [ 'detection-method' => self::DETECT_NODEINFO_10, - 'register_policy' => Register::CLOSED + 'register_policy' => Register::CLOSED ]; if (!empty($nodeinfo['openRegistrations'])) { @@ -1232,8 +1234,8 @@ class GServer $server = [ 'detection-method' => $detection_method, - 'register_policy' => Register::CLOSED, - 'platform' => 'unknown', + 'register_policy' => Register::CLOSED, + 'platform' => 'unknown', ]; if (!empty($nodeinfo['openRegistrations'])) { @@ -1363,7 +1365,7 @@ class GServer $server = [ 'detection-method' => self::DETECT_NODEINFO2_10, - 'register_policy' => Register::CLOSED + 'register_policy' => Register::CLOSED ]; if (!empty($nodeinfo['openRegistrations'])) { @@ -1471,7 +1473,7 @@ class GServer if (!empty($data['platform'])) { $serverdata['platform'] = strtolower($data['platform']); - $serverdata['version'] = $data['version'] ?? 'N/A'; + $serverdata['version'] = $data['version'] ?? 'N/A'; } if (!empty($data['plugins'])) { @@ -1547,17 +1549,17 @@ class GServer $actor = JsonLD::compact($data, false); if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) { - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value'); - $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value'); + $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value'); if (self::isNomad($actor)) { - $serverdata['platform'] = self::getNomadName($actor['@id']); - $serverdata['version'] = self::getNomadVersion($actor['@id']); + $serverdata['platform'] = self::getNomadName($actor['@id']); + $serverdata['version'] = self::getNomadVersion($actor['@id']); $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR; } elseif (!empty($actor['as:generator'])) { - $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value')); - $serverdata['platform'] = strtolower(array_shift($generator)); - $serverdata['version'] = self::getNomadVersion($actor['@id']); + $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value')); + $serverdata['platform'] = strtolower(array_shift($generator)); + $serverdata['version'] = self::getNomadVersion($actor['@id']); $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR; } else { $serverdata['detection-method'] = self::DETECT_AP_ACTOR; @@ -1565,8 +1567,8 @@ class GServer return ['server' => $serverdata, 'actor' => $actor['@id']]; } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) { // By now only Ktistec seems to provide collections this way - $serverdata['platform'] = 'ktistec'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['platform'] = 'ktistec'; + $serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['detection-method'] = self::DETECT_AP_COLLECTION; $actors = JsonLD::fetchElementArray($actor, 'as:items'); @@ -1610,7 +1612,7 @@ class GServer */ private static function getNomadName(string $url): string { - $name = 'nomad'; + $name = 'nomad'; $curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json', [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) { if ($curlResult->getReturnCode() == 418) { @@ -1729,7 +1731,7 @@ class GServer private static function validHostMeta(string $url): bool { $xrd_timeout = DI::config()->get('system', 'xrd_timeout'); - $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); + $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess()) { return false; } @@ -1828,10 +1830,10 @@ class GServer } if (!empty($data['totalResults'])) { - $registeredUsers = $serverdata['registered-users'] ?? 0; + $registeredUsers = $serverdata['registered-users'] ?? 0; $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1); - $serverdata['directory-type'] = self::DT_POCO; - $serverdata['poco'] = $url . '/poco'; + $serverdata['directory-type'] = self::DT_POCO; + $serverdata['poco'] = $url . '/poco'; } return $serverdata; @@ -1886,8 +1888,8 @@ class GServer if (!empty($data['instance']) && !empty($data['serverVersion'])) { $serverdata['platform'] = 'peertube'; - $serverdata['version'] = $data['serverVersion']; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['version'] = $data['serverVersion']; + $serverdata['network'] = Protocol::ACTIVITYPUB; if (!empty($data['instance']['name'])) { $serverdata['site_name'] = $data['instance']['name']; @@ -1934,7 +1936,7 @@ class GServer if (!empty($data['version'])) { $serverdata['platform'] = 'nextcloud'; - $serverdata['version'] = $data['version']; + $serverdata['version'] = $data['version']; if ($validHostMeta) { $serverdata['network'] = Protocol::ACTIVITYPUB; @@ -2012,9 +2014,9 @@ class GServer if (!empty($data['version'])) { $serverdata['platform'] = 'mastodon'; - $serverdata['version'] = $data['version'] ?? ''; - $serverdata['network'] = Protocol::ACTIVITYPUB; - $valid = true; + $serverdata['version'] = $data['version'] ?? ''; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $valid = true; } if (!empty($data['title'])) { @@ -2023,8 +2025,8 @@ class GServer if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) { $serverdata['platform'] = 'mastodon'; - $serverdata['network'] = Protocol::ACTIVITYPUB; - $valid = true; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $valid = true; } if (!empty($data['description'])) { @@ -2037,20 +2039,20 @@ class GServer if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) { $serverdata['platform'] = strtolower($matches[1]); - $serverdata['version'] = $matches[2]; - $valid = true; + $serverdata['version'] = $matches[2]; + $valid = true; } if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) { $serverdata['platform'] = 'pleroma'; - $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); - $valid = true; + $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); + $valid = true; } 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'; - $valid = true; + $valid = true; } if ($valid && in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) { @@ -2086,14 +2088,14 @@ class GServer if (!empty($data['site']['platform'])) { $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']); - $serverdata['version'] = $data['site']['platform']['STD_VERSION']; - $serverdata['network'] = Protocol::ZOT; + $serverdata['version'] = $data['site']['platform']['STD_VERSION']; + $serverdata['network'] = Protocol::ZOT; } if (!empty($data['site']['hubzilla'])) { $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']); - $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION']; - $serverdata['network'] = Protocol::ZOT; + $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION']; + $serverdata['network'] = Protocol::ZOT; } if (!empty($data['site']['redmatrix'])) { @@ -2107,9 +2109,9 @@ class GServer $serverdata['network'] = Protocol::ZOT; } - $private = false; + $private = false; $inviteonly = false; - $closed = false; + $closed = false; if (!empty($data['site']['closed'])) { $closed = self::toBoolean($data['site']['closed']); @@ -2196,11 +2198,11 @@ class GServer if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') { $serverdata['platform'] = 'pleroma'; - $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); + $serverdata['network'] = Protocol::ACTIVITYPUB; } else { $serverdata['platform'] = 'statusnet'; - $serverdata['network'] = Protocol::OSTATUS; + $serverdata['network'] = Protocol::OSTATUS; } if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) { @@ -2226,11 +2228,11 @@ class GServer $curlResult = DI::httpClient()->get($url . '/friendica/json', HttpClientAccept::DEFAULT, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess()) { $curlResult = DI::httpClient()->get($url . '/friendika/json', HttpClientAccept::DEFAULT, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); - $friendika = true; - $platform = 'Friendika'; + $friendika = true; + $platform = 'Friendika'; } else { $friendika = false; - $platform = 'Friendica'; + $platform = 'Friendica'; } if (!$curlResult->isSuccess()) { @@ -2316,14 +2318,14 @@ class GServer $doc = new DOMDocument(); @$doc->loadHTML($curlResult->getBodyString()); - $xpath = new DOMXPath($doc); + $xpath = new DOMXPath($doc); $assigned = false; // We can only detect honk via some HTML element on their page if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) { $serverdata['platform'] = 'honk'; - $serverdata['network'] = Protocol::ACTIVITYPUB; - $assigned = true; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $assigned = true; } $title = trim(XML::getFirstNodeValue($xpath, '//head/title/text()')); @@ -2356,11 +2358,11 @@ class GServer if (in_array($attr['name'], ['application-name', 'al:android:app_name', 'al:ios:app_name', '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_replace('/', ' ', $platform); + $platform = str_ireplace(array_keys($platforms), array_values($platforms), $attr['content']); + $platform = str_replace('/', ' ', $platform); $platform_parts = explode(' ', $platform); 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]; } if (in_array($platform, array_values($grouped_platforms['dfrn_platforms']))) { @@ -2372,7 +2374,7 @@ class GServer } if (in_array($platform, array_values($platforms))) { $serverdata['platform'] = $platform; - $assigned = true; + $assigned = true; } } } @@ -2407,7 +2409,7 @@ class GServer if (in_array($attr['property'], ['og:platform', 'generator'])) { if (in_array($attr['content'], array_keys($platforms))) { $serverdata['platform'] = $platforms[$attr['content']]; - $assigned = true; + $assigned = true; } if (in_array($attr['content'], array_keys($grouped_platforms['ap_platforms']))) { @@ -2422,10 +2424,10 @@ class GServer foreach ($list as $node) { foreach ($node->attributes as $attribute) { if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') { - $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); + $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); $serverdata['platform'] = 'microblog'; - $serverdata['network'] = Protocol::ACTIVITYPUB; - $assigned = true; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $assigned = true; } } } @@ -2435,10 +2437,10 @@ class GServer foreach ($list as $node) { foreach ($node->attributes as $attribute) { if (trim($attribute->value) == 'https://micro.blog/micropub') { - $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); + $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); $serverdata['platform'] = 'microblog'; - $serverdata['network'] = Protocol::ACTIVITYPUB; - $assigned = true; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $assigned = true; } } } @@ -2463,15 +2465,15 @@ class GServer { if ($curlResult->getHeader('server') == 'Mastodon') { $serverdata['platform'] = 'mastodon'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; } elseif ($curlResult->inHeader('x-diaspora-version')) { $serverdata['platform'] = 'diaspora'; - $serverdata['network'] = Protocol::DIASPORA; - $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? ''; + $serverdata['network'] = Protocol::DIASPORA; + $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? ''; } elseif ($curlResult->inHeader('x-friendica-version')) { $serverdata['platform'] = 'friendica'; - $serverdata['network'] = Protocol::DFRN; - $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? ''; + $serverdata['network'] = Protocol::DFRN; + $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? ''; } else { return $serverdata; } @@ -2501,9 +2503,12 @@ class GServer $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], - ['order' => ['RAND()']]); + ['order' => ['RAND()']] + ); while ($gserver = DBA::fetch($gservers)) { DI::logger()->info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]); @@ -2541,7 +2546,7 @@ class GServer // Discover federated servers $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus']; foreach ($protocols as $protocol) { - $query = '{nodes(protocol:"' . $protocol . '"){host}}'; + $query = '{nodes(protocol:"' . $protocol . '"){host}}'; $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON, 0, '', HttpClientRequest::SERVERDISCOVER); if (!empty($curlResult)) { $data = json_decode($curlResult, true); @@ -2558,7 +2563,7 @@ class GServer $accesstoken = DI::config()->get('system', 'instances_social_key'); if (!empty($accesstoken)) { - $api = 'https://instances.social/api/1.0/instances/list?count=0'; + $api = 'https://instances.social/api/1.0/instances/list?count=0'; $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken], HttpClientOptions::REQUEST => HttpClientRequest::SERVERDISCOVER]]); if ($curlResult->isSuccess()) { $servers = json_decode($curlResult->getBodyString(), true); diff --git a/src/Model/Item.php b/src/Model/Item.php index 64cf1d7968..10fc41cc23 100644 --- a/src/Model/Item.php +++ b/src/Model/Item.php @@ -45,38 +45,38 @@ use LanguageDetection\Language; class Item { // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types - const PT_ARTICLE = 0; - const PT_NOTE = 1; - const PT_PAGE = 2; - const PT_IMAGE = 16; - const PT_AUDIO = 17; - const PT_VIDEO = 18; - const PT_DOCUMENT = 19; - const PT_EVENT = 32; - const PT_POLL = 33; + const PT_ARTICLE = 0; + const PT_NOTE = 1; + const PT_PAGE = 2; + const PT_IMAGE = 16; + const PT_AUDIO = 17; + const PT_VIDEO = 18; + const PT_DOCUMENT = 19; + const PT_EVENT = 32; + const PT_POLL = 33; const PT_PERSONAL_NOTE = 128; // Posting reasons (Why had a post been stored for a user?) - const PR_NONE = 0; - const PR_TAG = 64; - const PR_TO = 65; - const PR_CC = 66; - const PR_BTO = 67; - const PR_BCC = 68; - const PR_FOLLOWER = 69; + const PR_NONE = 0; + const PR_TAG = 64; + const PR_TO = 65; + const PR_CC = 66; + const PR_BTO = 67; + const PR_BCC = 68; + const PR_FOLLOWER = 69; const PR_ANNOUNCEMENT = 70; - const PR_COMMENT = 71; - const PR_STORED = 72; - const PR_GLOBAL = 73; - const PR_RELAY = 74; - const PR_FETCHED = 75; - const PR_COMPLETION = 76; - const PR_DIRECT = 77; - const PR_ACTIVITY = 78; - const PR_DISTRIBUTE = 79; - const PR_PUSHED = 80; - const PR_LOCAL = 81; - const PR_AUDIENCE = 82; + const PR_COMMENT = 71; + const PR_STORED = 72; + const PR_GLOBAL = 73; + const PR_RELAY = 74; + const PR_FETCHED = 75; + const PR_COMPLETION = 76; + const PR_DIRECT = 77; + const PR_ACTIVITY = 78; + const PR_DISTRIBUTE = 79; + const PR_PUSHED = 80; + const PR_LOCAL = 81; + const PR_AUDIENCE = 82; // system.accept_only_sharer setting values const COMPLETION_NONE = 1; @@ -145,8 +145,8 @@ class Item ]; // Privacy levels - const PUBLIC = 0; - const PRIVATE = 1; + const PUBLIC = 0; + const PRIVATE = 1; const UNLISTED = 2; // Item weight for query ordering @@ -492,7 +492,7 @@ class Item // Is it in the format data@host.tld? - Used for mail contacts if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) { - $mailparts = explode('@', $item['author-link']); + $mailparts = explode('@', $item['author-link']); $prefix_host = array_pop($mailparts); } } @@ -596,7 +596,7 @@ class Item } $condition = [ - 'uri-id' => $item['uri-id'], 'uid' => $item['uid'], + 'uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'network' => [$item['network'], Protocol::DFRN] ]; if (Post::exists($condition)) { @@ -681,7 +681,7 @@ class Item } $condition = [ - 'verb' => Activity::FOLLOW, 'uid' => $item['uid'], + 'verb' => Activity::FOLLOW, 'uid' => $item['uid'], 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id'] ]; if (Post::exists($condition)) { @@ -716,10 +716,10 @@ class Item // We only log the entries with a different user id than 0. Otherwise we would have too many false positives if ($item['uid'] != 0) { DI::logger()->notice('Item already existed for user', [ - 'uri-id' => $item['uri-id'], - 'uid' => $item['uid'], - 'network' => $item['network'], - 'existing_id' => $existing['id'], + 'uri-id' => $item['uri-id'], + 'uid' => $item['uid'], + 'network' => $item['network'], + 'existing_id' => $existing['id'], 'existing_network' => $existing['network'] ]); } @@ -766,8 +766,8 @@ class Item 'wall', 'private', 'origin', 'author-id' ]; $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']]; - $params = ['order' => ['id' => false]]; - $parent = Post::selectFirst($fields, $condition, $params); + $params = ['order' => ['id' => false]]; + $parent = Post::selectFirst($fields, $condition, $params); if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) { $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]); @@ -795,11 +795,11 @@ class Item } $condition = [ - 'uri-id' => $parent['parent-uri-id'], + 'uri-id' => $parent['parent-uri-id'], 'parent-uri-id' => $parent['parent-uri-id'], - 'uid' => $parent['uid'] + 'uid' => $parent['uid'] ]; - $params = ['order' => ['id' => false]]; + $params = ['order' => ['id' => false]]; $toplevel_parent = Post::selectFirst($fields, $condition, $params); if (!DBA::isResult($toplevel_parent) && $item['origin']) { @@ -884,7 +884,7 @@ class Item $uid = intval($item['uid']); $item['guid'] = self::guid($item, $notify); - $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255); + $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255); // Store URI data $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]); @@ -990,13 +990,13 @@ class Item $item['gravity'] = self::getGravity($item); $default = [ - 'url' => $item['author-link'], 'name' => $item['author-name'], + 'url' => $item['author-link'], 'name' => $item['author-name'], 'photo' => $item['author-avatar'], 'network' => $item['network'] ]; $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default); $default = [ - 'url' => $item['owner-link'], 'name' => $item['owner-name'], + 'url' => $item['owner-link'], 'name' => $item['owner-name'], 'photo' => $item['owner-avatar'], 'network' => $item['network'] ]; $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default); @@ -1072,7 +1072,7 @@ class Item // Update the contact relations Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']); } else { - $parent_id = 0; + $parent_id = 0; $parent_origin = $item['origin']; if ($item['wall'] && empty($item['context'])) { @@ -1120,7 +1120,7 @@ class Item } if ($notify && $post_local) { - $item['edit'] = false; + $item['edit'] = false; $item['parent'] = $parent_id; // Trigger automatic reactions for addons @@ -1131,8 +1131,8 @@ class Item // We have to tell the hooks who we are - this really should be improved if (!DI::userSession()->getLocalUserId()) { $_SESSION['authenticated'] = true; - $_SESSION['uid'] = $uid; - $dummy_session = true; + $_SESSION['uid'] = $uid; + $dummy_session = true; } else { $dummy_session = false; } @@ -1250,9 +1250,9 @@ class Item $ev['guid'] = $item['guid']; $ev['plink'] = $item['plink']; $ev['network'] = $item['network']; - $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN; + $ev['protocol'] = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN; $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN; - $ev['source'] = $item['source'] ?? ''; + $ev['source'] = $item['source'] ?? ''; $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]); if (DBA::isResult($event)) { @@ -1260,7 +1260,7 @@ class Item } $event_id = Event::store($ev); - $item = Event::getItemArrayForImportedId($event_id, $item); + $item = Event::getItemArrayForImportedId($event_id, $item); DI::logger()->info('Event was stored', ['id' => $event_id]); } @@ -1542,7 +1542,7 @@ class Item $count = 0; foreach (DI::userDefinedChannel()->getMatchingChannelUsers($engagement['searchtext'], $language, $tags, $engagement['media-type'], $item['owner-id'], $reshare_id) as $uid) { $condition = [ - 'verb' => Activity::ANNOUNCE, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY, + 'verb' => Activity::ANNOUNCE, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY, 'author-id' => Contact::getPublicIdByUserId($uid), 'uid' => $uid, 'thr-parent-id' => $uri_id ]; if (!Post::exists($condition)) { @@ -1632,7 +1632,7 @@ class Item } $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]); - $self = !empty($self_contact) ? $self_contact['id'] : 0; + $self = !empty($self_contact) ? $self_contact['id'] : 0; $cid = Contact::getIdForURL($author['url'], $item['uid']); if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) { @@ -1671,7 +1671,7 @@ class Item foreach (Tag::getUIDListByURIId($item['uri-id']) as $uid => $tags) { if (!empty($languages)) { - $keep = false; + $keep = false; $user_languages = User::getWantedLanguages($uid); foreach ($user_languages as $language) { if (in_array($language, $languages)) { @@ -1705,7 +1705,7 @@ class Item public static function distribute(int $itemid, string $signed_text = '') { $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)) { DI::logger()->warning('Item not found', ['condition' => $condition]); return; @@ -1713,7 +1713,7 @@ class Item // Only distribute public items from native networks $condition = [ - 'id' => $itemid, 'uid' => 0, + 'id' => $itemid, 'uid' => 0, 'network' => array_merge(Protocol::FEDERATED, ['']), 'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED] ]; @@ -1734,7 +1734,7 @@ class Item } $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]]; - $contacts = DBA::select('contact', ['uid'], $condition); + $contacts = DBA::select('contact', ['uid'], $condition); while ($contact = DBA::fetch($contacts)) { if ($contact['uid'] == 0) { continue; @@ -1745,7 +1745,7 @@ class Item DBA::close($contacts); $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]]; - $contacts = DBA::select('contact', ['uid'], $condition); + $contacts = DBA::select('contact', ['uid'], $condition); while ($contact = DBA::fetch($contacts)) { if ($contact['uid'] == 0) { continue; @@ -1757,7 +1757,7 @@ class Item if (!empty($owner['alias'])) { $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]]; - $contacts = DBA::select('contact', ['uid'], $condition); + $contacts = DBA::select('contact', ['uid'], $condition); while ($contact = DBA::fetch($contacts)) { if ($contact['uid'] == 0) { continue; @@ -1979,21 +1979,21 @@ class Item unset($item['postopts']); unset($item['inform']); - $item['uid'] = $uid; + $item['uid'] = $uid; $item['origin'] = 0; - $item['wall'] = 0; + $item['wall'] = 0; $notify = false; if ($item['gravity'] == self::GRAVITY_PARENT) { $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]); if (DBA::isResult($contact)) { - $notify = self::isRemoteSelf($contact, $item); + $notify = self::isRemoteSelf($contact, $item); $item['wall'] = (bool)$notify; } } $item['contact-id'] = self::contactId($item); - $distributed = self::insert($item, $notify); + $distributed = self::insert($item, $notify); if (!$distributed) { DI::logger()->info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]); @@ -2015,9 +2015,9 @@ class Item */ private static function addShadow(int $itemid) { - $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id']; + $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id']; $condition = ['id' => $itemid, 'gravity' => self::GRAVITY_PARENT]; - $item = Post::selectFirst($fields, $condition); + $item = Post::selectFirst($fields, $condition); if (!DBA::isResult($item)) { return; @@ -2029,7 +2029,7 @@ class Item } // Is it a visible public post? - if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) { + if (!$item["visible"] || $item["deleted"] || ($item["private"] == self::PRIVATE)) { return; } @@ -2146,7 +2146,7 @@ class Item } $transmitted = []; - foreach ($item['transmitted-languages'] ?? [] as $language) { + foreach ($item['transmitted-languages'] ?? [] as $language) { $transmitted[$language] = 0; } @@ -2279,10 +2279,10 @@ class Item $previous_block = self::getBlockCode($previous); } - $block = (($next != '') && \IntlChar::isalpha($next)) ? self::getBlockCode($next) : $previous_block; + $block = (($next != '') && \IntlChar::isalpha($next)) ? self::getBlockCode($next) : $previous_block; $blocks[$block] = ($blocks[$block] ?? '') . $character; } else { - $block = self::getBlockCode($character); + $block = self::getBlockCode($character); $blocks[$block] = ($blocks[$block] ?? '') . $character; } } @@ -2329,7 +2329,7 @@ class Item public static function getLanguageMessage(array $item): string { - $iso639 = new \Matriphe\ISO639\ISO639; + $iso639 = new \Matriphe\ISO639\ISO639(); $used_languages = ''; foreach (json_decode($item['language'], true) as $language => $reliability) { @@ -2532,7 +2532,7 @@ class Item } $basetag = str_replace('_', ' ', substr($tag, 1)); - $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($basetag) . ']' . $basetag . '[/url]'; + $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($basetag) . ']' . $basetag . '[/url]'; $body = str_replace($tag, $newtag, $body); } @@ -2694,8 +2694,8 @@ class Item $datarray['contact-id'] = $self['id']; - $datarray['author-name'] = $datarray['owner-name'] = $self['name']; - $datarray['author-link'] = $datarray['owner-link'] = $self['url']; + $datarray['author-name'] = $datarray['owner-name'] = $self['name']; + $datarray['author-link'] = $datarray['owner-link'] = $self['url']; $datarray['author-avatar'] = $datarray['owner-avatar'] = $self['thumb']; unset($datarray['edited']); @@ -2705,14 +2705,14 @@ class Item unset($datarray['author-id']); if ($contact['network'] != Protocol::FEED) { - $old_uri_id = $datarray['uri-id'] ?? 0; + $old_uri_id = $datarray['uri-id'] ?? 0; $datarray['guid'] = System::createUUID(); unset($datarray['plink']); - $datarray['uri'] = self::newURI($datarray['guid']); + $datarray['uri'] = self::newURI($datarray['guid']); $datarray['uri-id'] = ItemURI::getIdByURI($datarray['uri']); - $datarray['extid'] = Protocol::DFRN; - $urlpart = parse_url($datarray2['author-link']); - $datarray['app'] = $urlpart['host']; + $datarray['extid'] = Protocol::DFRN; + $urlpart = parse_url($datarray2['author-link']); + $datarray['app'] = $urlpart['host']; if (!empty($old_uri_id)) { Post\Media::copy($old_uri_id, $datarray['uri-id']); } @@ -2725,7 +2725,7 @@ class Item DI::logger()->info('remote-self post original item', ['contact' => $contact['url'], 'result' => $result, 'item' => $datarray2]); } else { $datarray['app'] = 'Feed'; - $result = true; + $result = true; } if ($result) { @@ -2755,11 +2755,11 @@ class Item $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://')); $orig_body = $s; - $new_body = ''; + $new_body = ''; - $img_start = strpos($orig_body, '[img'); + $img_start = strpos($orig_body, '[img'); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); - $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false); + $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false); while (($img_st_close !== false) && ($img_len !== false)) { $img_st_close++; // make it point to AFTER the closing bracket @@ -2770,13 +2770,13 @@ class Item if (stristr($image, $site . '/photo/')) { // Only embed locally hosted photos $replace = false; - $i = basename($image); - $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i); - $x = strpos($i, '-'); + $i = basename($image); + $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i); + $x = strpos($i, '-'); if ($x) { - $res = substr($i, $x + 1); - $i = substr($i, 0, $x); + $res = substr($i, $x + 1); + $i = substr($i, 0, $x); $photo = Photo::getPhotoForUser($uid, $i, $res); if (DBA::isResult($photo)) { /* @@ -2806,7 +2806,7 @@ class Item if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) { DI::logger()->info('scaling photo'); - $width = intval($match[1]); + $width = intval($match[1]); $height = intval($match[2]); $photo_img->scaleDown(max($width, $height)); @@ -2823,15 +2823,15 @@ class Item } } - $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]'; + $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]'; $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]')); if ($orig_body === false) { $orig_body = ''; } - $img_start = strpos($orig_body, '[img'); + $img_start = strpos($orig_body, '[img'); $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false); - $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false); + $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false); } $new_body = $new_body . $orig_body; @@ -2936,9 +2936,9 @@ class Item $expire_items = true; } - $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true); + $expire_notes = (bool)DI::pConfig()->get($uid, 'expire', 'notes', true); $expire_starred = (bool)DI::pConfig()->get($uid, 'expire', 'starred', true); - $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false); + $expire_photos = (bool)DI::pConfig()->get($uid, 'expire', 'photos', false); $expired = 0; @@ -3114,7 +3114,7 @@ class Item } $condition = [ - 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY, + 'vid' => $vids, 'deleted' => false, 'gravity' => self::GRAVITY_ACTIVITY, 'author-id' => $author_id, 'uid' => $uid, 'thr-parent-id' => $uri_id ]; $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition); @@ -3160,29 +3160,29 @@ class Item $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE; $new_item = [ - 'guid' => System::createUUID(), - 'uri' => self::newURI(), - 'uid' => $uid, - 'contact-id' => $owner['id'], - 'wall' => $item['wall'], - 'origin' => 1, - 'network' => Protocol::DFRN, - 'protocol' => Conversation::PARCEL_DIRECT, - 'direction' => Conversation::PUSH, - 'gravity' => self::GRAVITY_ACTIVITY, - 'parent' => $item['id'], - 'thr-parent' => $item['uri'], - 'owner-id' => $author_id, - 'author-id' => $author_id, - 'body' => $activity, - 'verb' => $activity, - 'object-type' => $objtype, - 'allow_cid' => $allow_cid ?? $item['allow_cid'], - 'allow_gid' => $allow_gid ?? $item['allow_gid'], - 'deny_cid' => $deny_cid ?? $item['deny_cid'], - 'deny_gid' => $deny_gid ?? $item['deny_gid'], - 'visible' => 1, - 'unseen' => 1, + 'guid' => System::createUUID(), + 'uri' => self::newURI(), + 'uid' => $uid, + 'contact-id' => $owner['id'], + 'wall' => $item['wall'], + 'origin' => 1, + 'network' => Protocol::DFRN, + 'protocol' => Conversation::PARCEL_DIRECT, + 'direction' => Conversation::PUSH, + 'gravity' => self::GRAVITY_ACTIVITY, + 'parent' => $item['id'], + 'thr-parent' => $item['uri'], + 'owner-id' => $author_id, + 'author-id' => $author_id, + 'body' => $activity, + 'verb' => $activity, + 'object-type' => $objtype, + 'allow_cid' => $allow_cid ?? $item['allow_cid'], + 'allow_gid' => $allow_gid ?? $item['allow_gid'], + 'deny_cid' => $deny_cid ?? $item['deny_cid'], + 'deny_gid' => $deny_gid ?? $item['deny_gid'], + 'visible' => 1, + 'unseen' => 1, ]; if (in_array($activity, [Activity::LIKE, Activity::DISLIKE])) { @@ -3210,7 +3210,7 @@ class Item */ public static function getPermissionsConditionArrayByUserId(int $owner_id): array { - $local_user = DI::userSession()->getLocalUserId(); + $local_user = DI::userSession()->getLocalUserId(); $remote_user = DI::userSession()->getRemoteContactID($owner_id); // default permissions - anonymous user @@ -3244,7 +3244,7 @@ class Item */ public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string { - $local_user = DI::userSession()->getLocalUserId(); + $local_user = DI::userSession()->getLocalUserId(); $remote_user = DI::userSession()->getRemoteContactID($owner_id); if (!empty($table)) { @@ -3372,7 +3372,7 @@ class Item public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string { $appHelper = DI::appHelper(); - $uid = DI::userSession()->getLocalUserId(); + $uid = DI::userSession()->getLocalUserId(); Hook::callAll('prepare_body_init', $item); // In order to provide theme developers more possibilities, event items @@ -3384,7 +3384,7 @@ class Item $tags = Tag::populateFromItem($item); - $item['tags'] = $tags['tags']; + $item['tags'] = $tags['tags']; $item['hashtags'] = $tags['hashtags']; $item['mentions'] = $tags['mentions']; @@ -3408,12 +3408,12 @@ class Item $shared = DI::contentItem()->getSharedPost($item, $fields); if (!empty($shared['post'])) { - $shared_item = $shared['post']; + $shared_item = $shared['post']; $shared_item['body'] = Post\Media::removeFromEndOfBody($shared_item['body']); $shared_item['body'] = Post\Media::replaceImage($shared_item['body']); - $quote_uri_id = $shared['post']['uri-id']; - $shared_links[] = strtolower($shared['post']['uri']); - $item['body'] = BBCode::removeSharedData($item['body']); + $quote_uri_id = $shared['post']['uri-id']; + $shared_links[] = strtolower($shared['post']['uri']); + $item['body'] = BBCode::removeSharedData($item['body']); } elseif (empty($shared_item['uri-id']) && empty($item['quote-uri-id']) && ($item['network'] != Protocol::DIASPORA)) { $media = Post\Media::getByURIId($item['uri-id'], [Post\Media::ACTIVITY]); if (!empty($media) && ($media[0]['media-uri-id'] != $item['uri-id'])) { @@ -3425,7 +3425,7 @@ class Item } if (empty($shared_item['uri-id'])) { - $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]); + $shared_item = Post::selectFirst($fields, ['uri' => $media[0]['url'], 'uid' => [$item['uid'], 0]]); $shared_links[] = strtolower($media[0]['url']); } @@ -3451,21 +3451,21 @@ class Item $sharedSplitAttachments = []; if (!empty($shared_item['uri-id'])) { - $shared_uri_id = $shared_item['uri-id']; - $shared_links[] = strtolower($shared_item['plink']); + $shared_uri_id = $shared_item['uri-id']; + $shared_links[] = strtolower($shared_item['plink']); $sharedSplitAttachments = DI::postMediaRepository()->splitAttachments($shared_uri_id, [], $shared_item['has-media']); - $shared_links = array_merge($shared_links, $sharedSplitAttachments['visual']->column('url')); - $shared_links = array_merge($shared_links, $sharedSplitAttachments['link']->column('url')); - $shared_links = array_merge($shared_links, $sharedSplitAttachments['additional']->column('url')); - $item['body'] = self::replaceVisualAttachments($sharedSplitAttachments['visual'], $item['body']); + $shared_links = array_merge($shared_links, $sharedSplitAttachments['visual']->column('url')); + $shared_links = array_merge($shared_links, $sharedSplitAttachments['link']->column('url')); + $shared_links = array_merge($shared_links, $sharedSplitAttachments['additional']->column('url')); + $item['body'] = self::replaceVisualAttachments($sharedSplitAttachments['visual'], $item['body']); } $itemSplitAttachments = DI::postMediaRepository()->splitAttachments($item['uri-id'], $shared_links, $item['has-media'] ?? false); - $item['body'] = self::replaceVisualAttachments($itemSplitAttachments['visual'], $item['body'] ?? ''); + $item['body'] = self::replaceVisualAttachments($itemSplitAttachments['visual'], $item['body'] ?? ''); self::putInCache($item); $item['body'] = $body; - $s = $item["rendered-html"]; + $s = $item["rendered-html"]; if ($only_cache) { return ''; @@ -3489,7 +3489,7 @@ class Item $item['attachments'] = $itemSplitAttachments; $hook_data = [ - 'item' => $item, + 'item' => $item, 'filter_reasons' => $filter_reasons ]; Hook::callAll('prepare_body_content_filter', $hook_data); @@ -3502,9 +3502,9 @@ class Item } $hook_data = [ - 'item' => $item, - 'html' => $s, - 'preview' => $is_preview, + 'item' => $item, + 'html' => $s, + 'preview' => $is_preview, 'filter_reasons' => $filter_reasons ]; Hook::callAll('prepare_body', $hook_data); @@ -3515,22 +3515,22 @@ class Item if (!$attach) { // Replace the blockquotes with quotes that are used in mails. $mailquote = '
'; - $s = str_replace(['
', '
', '
'], [$mailquote, $mailquote, $mailquote], $s); + $s = str_replace(['
', '
', '
'], [$mailquote, $mailquote, $mailquote], $s); return $s; } if (!empty($sharedSplitAttachments)) { - $s = self::addGallery($s, $sharedSplitAttachments['visual']); - $s = self::addVisualAttachments($sharedSplitAttachments['visual'], $shared_item, $s, true); - $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $sharedSplitAttachments, $body, $s, true, $quote_shared_links); - $s = self::addNonVisualAttachments($sharedSplitAttachments['additional'], $item, $s); + $s = self::addGallery($s, $sharedSplitAttachments['visual']); + $s = self::addVisualAttachments($sharedSplitAttachments['visual'], $shared_item, $s, true); + $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $sharedSplitAttachments, $body, $s, true, $quote_shared_links); + $s = self::addNonVisualAttachments($sharedSplitAttachments['additional'], $item, $s); $body = BBCode::removeSharedData($body); } $pos = strpos($s, BBCode::SHARED_ANCHOR); if ($pos) { $shared_html = substr($s, $pos + strlen(BBCode::SHARED_ANCHOR)); - $s = substr($s, 0, $pos); + $s = substr($s, 0, $pos); } $s = self::addGallery($s, $itemSplitAttachments['visual']); @@ -3550,7 +3550,7 @@ class Item // Replace friendica image url size with theme preference. if (!empty($appHelper->getThemeInfoValue('item_image_size'))) { $ps = $appHelper->getThemeInfoValue('item_image_size'); - $s = preg_replace('|(]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s); + $s = preg_replace('|(]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s); } if (!empty($shared_html)) { @@ -3592,7 +3592,7 @@ class Item continue; } $element_html = $element->ownerDocument->saveHTML($element); - $html = str_replace($element_html, str_replace($src, $svg, $element_html), $html); + $html = str_replace($element_html, str_replace($src, $svg, $element_html), $html); } return $html; } @@ -3616,8 +3616,8 @@ class Item $s = preg_replace_callback($pattern, function () use ($PostMedia) { return Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image/single_with_height_allocation.tpl'), [ - '$image' => $PostMedia, - '$allocated_height' => $PostMedia->getAllocatedHeight(), + '$image' => $PostMedia, + '$allocated_height' => $PostMedia->getAllocatedHeight(), '$allocated_max_width' => ($PostMedia->previewWidth ?? $PostMedia->width) . 'px', ]); }, $s); @@ -3741,10 +3741,10 @@ class Item if ($PostMedia->mimetype->type == 'image' || $PostMedia->preview) { $preview_size = Proxy::SIZE_MEDIUM; - $preview_url = DI::baseUrl() . $PostMedia->getPreviewPath($preview_size); + $preview_url = DI::baseUrl() . $PostMedia->getPreviewPath($preview_size); } else { $preview_size = 0; - $preview_url = ''; + $preview_url = ''; } if ($preview_url && self::containsLink($item['body'], $preview_url)) { @@ -3780,10 +3780,10 @@ class Item } elseif ($PostMedia->mimetype->type == 'audio') { $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [ '$audio' => [ - 'id' => $PostMedia->id, - 'src' => (string)$PostMedia->url, - 'name' => $PostMedia->name ?: $PostMedia->url, - 'mime' => (string)$PostMedia->mimetype, + 'id' => $PostMedia->id, + 'src' => (string)$PostMedia->url, + 'name' => $PostMedia->name ?: $PostMedia->url, + 'mime' => (string)$PostMedia->mimetype, ], ]); if (($item['post-type'] ?? null) == Item::PT_AUDIO) { @@ -3847,7 +3847,7 @@ class Item { DI::profiler()->startRecording('rendering'); // Don't show a preview when there is a visual attachment (audio or video) - $types = $attachments['visual']->column('type'); + $types = $attachments['visual']->column('type'); $preview = !in_array(PostMedia::TYPE_IMAGE, $types) && !in_array(PostMedia::TYPE_VIDEO, $types); /** @var ?PostMedia $attachment */ @@ -3870,18 +3870,18 @@ class Item if (!empty($attachment)) { $data = [ - 'after' => '', - 'author_name' => $attachment->authorName ?? '', - 'author_url' => (string)($attachment->authorUrl ?? ''), - 'description' => $attachment->description ?? '', - 'image' => '', - 'preview' => '', + 'after' => '', + 'author_name' => $attachment->authorName ?? '', + 'author_url' => (string)($attachment->authorUrl ?? ''), + 'description' => $attachment->description ?? '', + 'image' => '', + 'preview' => '', 'provider_name' => $attachment->publisherName ?? '', - 'provider_url' => (string)($attachment->publisherUrl ?? ''), - 'text' => '', - 'title' => $attachment->name ?? '', - 'type' => 'link', - 'url' => (string)$attachment->url, + 'provider_url' => (string)($attachment->publisherUrl ?? ''), + 'text' => '', + 'title' => $attachment->name ?? '', + 'type' => 'link', + 'url' => (string)$attachment->url, ]; if ($preview && $attachment->preview) { @@ -4022,7 +4022,7 @@ class Item $options = Post\QuestionOption::getByURIId($item['uri-id']); foreach ($options as $key => $option) { if ($question['voters'] > 0) { - $percent = $option['replies'] / $question['voters'] * 100; + $percent = $option['replies'] / $question['voters'] * 100; $options[$key]['vote'] = DI::l10n()->tt('%2$s (%3$d%%, %1$d vote)', '%2$s (%3$d%%, %1$d votes)', $option['replies'] ?? 0, $option['name'], round($percent, 1)); } else { $options[$key]['vote'] = DI::l10n()->tt('%2$s (%1$d vote)', '%2$s (%1$d votes)', $option['replies'] ?? 0, $option['name']); @@ -4073,9 +4073,9 @@ class Item if (DI::userSession()->getLocalUserId()) { $ret = [ - 'href' => "display/" . $item['guid'], - 'orig' => "display/" . $item['guid'], - 'title' => DI::l10n()->t('View on separate page'), + 'href' => "display/" . $item['guid'], + 'orig' => "display/" . $item['guid'], + 'title' => DI::l10n()->t('View on separate page'), 'orig_title' => DI::l10n()->t('View on separate page'), ]; @@ -4091,14 +4091,14 @@ class Item } if (!empty($plink)) { - $ret['href'] = DI::baseUrl()->remove($plink); + $ret['href'] = DI::baseUrl()->remove($plink); $ret['title'] = DI::l10n()->t('Link to source'); } } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) { $ret = [ - 'href' => $plink, - 'orig' => $plink, - 'title' => DI::l10n()->t('Link to source'), + 'href' => $plink, + 'orig' => $plink, + 'title' => DI::l10n()->t('Link to source'), 'orig_title' => DI::l10n()->t('Link to source'), ]; } else { @@ -4143,7 +4143,7 @@ class Item public static function searchByLink(string $uri, int $uid = 0): int { $ssl_uri = str_replace('http://', 'https://', $uri); - $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)]; + $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)]; $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]); if (DBA::isResult($item)) { @@ -4168,7 +4168,7 @@ class Item public static function getURIByLink(string $uri): string { $ssl_uri = str_replace('http://', 'https://', $uri); - $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)]; + $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)]; $item = Post::selectFirst(['uri'], ['uri' => $uris]); if (DBA::isResult($item)) { @@ -4222,7 +4222,7 @@ class Item if (!$mimetype) { try { $curlResult = DI::httpClient()->head($uri, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::JSON_AS, HttpClientOptions::REQUEST => HttpClientRequest::ACTIVITYPUB]); - $mimetype = $curlResult->getContentType(); + $mimetype = $curlResult->getContentType(); } catch (\Throwable $th) { DI::logger()->info('Error while fetching HTTP link via HEAD', ['uid' => $uid, 'uri' => $uri, 'code' => $th->getCode(), 'message' => $th->getMessage()]); return 0; @@ -4233,7 +4233,7 @@ class Item try { // Issue 14126: Workaround for Mastodon servers that return "application/json" on a "head" request. $curlResult = HTTPSignature::fetchRaw($uri, $uid); - $mimetype = $curlResult->getContentType(); + $mimetype = $curlResult->getContentType(); } catch (\Throwable $th) { DI::logger()->info('Error while fetching HTTP link via signed GET', ['uid' => $uid, 'uri' => $uri, 'code' => $th->getCode(), 'message' => $th->getMessage()]); return 0; @@ -4305,7 +4305,7 @@ class Item } $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) { DI::logger()->notice('Post could not be fetched.', ['url' => $url, 'uid' => $uid]); return 0; diff --git a/src/Model/Mail.php b/src/Model/Mail.php index 84542d33e2..8366e91654 100644 --- a/src/Model/Mail.php +++ b/src/Model/Mail.php @@ -137,15 +137,15 @@ class Mail Photo::setPermissionFromBody($body, $sender_uid, $me['id'], '<' . $contact['id'] . '>', '', '', ''); $guid = System::createUUID(); - $uri = Item::newURI($guid); + $uri = Item::newURI($guid); $convid = 0; - $reply = false; + $reply = false; // look for any existing conversation structure if (strlen($replyto)) { - $reply = true; + $reply = true; $condition = ["`uid` = ? AND (`uri` = ? OR `parent-uri` = ?)", $sender_uid, $replyto, $replyto]; $mail = DBA::selectFirst('mail', ['convid'], $condition); @@ -158,11 +158,11 @@ class Mail if (!$convid) { // create a new conversation $conv_guid = System::createUUID(); - $convuri = $contact['addr'] . ':' . $conv_guid; + $convuri = $contact['addr'] . ':' . $conv_guid; $fields = ['uid' => $sender_uid, 'guid' => $conv_guid, 'creator' => $me['addr'], - 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), - 'subject' => $subject, 'recips' => $contact['addr'] . ';' . $me['addr']]; + 'created' => DateTimeFormat::utcNow(), 'updated' => DateTimeFormat::utcNow(), + 'subject' => $subject, 'recips' => $contact['addr'] . ';' . $me['addr']]; if (DBA::insert('conv', $fields)) { $convid = DBA::lastInsertId(); } @@ -179,21 +179,21 @@ class Mail $post_id = self::insert( [ - 'uid' => $sender_uid, - 'guid' => $guid, - 'convid' => $convid, - 'from-name' => $me['name'], + 'uid' => $sender_uid, + 'guid' => $guid, + 'convid' => $convid, + 'from-name' => $me['name'], 'from-photo' => $me['thumb'], - 'from-url' => $me['url'], + 'from-url' => $me['url'], 'contact-id' => $recipient, - 'title' => $subject, - 'body' => $body, - 'seen' => 1, - 'reply' => $reply, - 'replied' => 0, - 'uri' => $uri, + 'title' => $subject, + 'body' => $body, + 'seen' => 1, + 'reply' => $reply, + 'replied' => 0, + 'uri' => $uri, 'parent-uri' => $replyto, - 'created' => DateTimeFormat::utcNow() + 'created' => DateTimeFormat::utcNow() ], false ); diff --git a/src/Model/Post.php b/src/Model/Post.php index 765ad023ac..f4ab71eac6 100644 --- a/src/Model/Post.php +++ b/src/Model/Post.php @@ -212,7 +212,7 @@ class Post public static function selectOriginal(array $fields = [], array $condition = [], array $params = []) { $original_fields = $fields; - $remove = []; + $remove = []; if (!empty($fields)) { foreach (['gravity', 'verb', 'thr-parent-id', 'uid'] as $field) { if (!in_array($field, $fields)) { @@ -447,7 +447,8 @@ class Post $selected = Item::DISPLAY_FIELDLIST; } - $condition = DBA::mergeConditions($condition, + $condition = DBA::mergeConditions( + $condition, ["`visible` AND NOT `deleted` AND NOT `author-blocked` AND NOT `owner-blocked` AND (NOT `causer-blocked` OR `causer-id` = ? OR `causer-id` IS NULL) AND NOT `contact-blocked` @@ -456,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 `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`)", - 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)); @@ -581,7 +583,7 @@ class Post public static function selectOriginalForUser(int $uid, array $selected = [], array $condition = [], array $params = []) { $original_selected = $selected; - $remove = []; + $remove = []; if (!empty($selected)) { foreach (['gravity', 'verb', 'thr-parent-id'] as $field) { if (!in_array($field, $selected)) { diff --git a/src/Model/Post/Delayed.php b/src/Model/Post/Delayed.php index 2e30ba1a59..e4862c27c2 100644 --- a/src/Model/Post/Delayed.php +++ b/src/Model/Post/Delayed.php @@ -53,7 +53,7 @@ class Delayed $last_publish = DI::pConfig()->get($item['uid'], 'system', 'last_publish', 0, true); $next_publish = max($last_publish + (60 * $min_posting), time()); - $delayed = date(DateTimeFormat::MYSQL, $next_publish); + $delayed = date(DateTimeFormat::MYSQL, $next_publish); DI::pConfig()->set($item['uid'], 'system', 'last_publish', $next_publish); } @@ -151,13 +151,13 @@ class Delayed } return [ - 'parameters' => $delayed, - 'item' => $parameters[0], - 'notify' => $parameters[1], - 'taglist' => $parameters[2], + 'parameters' => $delayed, + 'item' => $parameters[0], + 'notify' => $parameters[1], + 'taglist' => $parameters[2], 'attachments' => $parameters[3], - 'unprepared' => $parameters[4], - 'uri' => $parameters[5], + 'unprepared' => $parameters[4], + 'uri' => $parameters[5], ]; } diff --git a/src/Model/Post/Engagement.php b/src/Model/Post/Engagement.php index 621d3ee9ec..7c8a302ac5 100644 --- a/src/Model/Post/Engagement.php +++ b/src/Model/Post/Engagement.php @@ -27,16 +27,16 @@ class Engagement const KEYWORDS = ['source', 'server', 'from', 'to', 'group', 'application', 'tag', 'network', 'platform', 'visibility', 'language', 'media']; const SHORTCUTS = ['lang' => 'language', 'net' => 'network', 'relay' => 'application']; const ALTERNATIVES = ['source:news' => 'source:service', 'source:relay' => 'source:application', - 'media:picture' => 'media:image', 'media:photo' => 'media:image', - 'network:activitypub' => 'network:apub', 'network:friendica' => 'network:dfrn', - 'network:diaspora' => 'network:dspr', 'network:discourse' => 'network:dscs', - 'network:tumblr' => 'network:tmbl', 'network:bluesky' => 'network:bsky']; - const MEDIA_NONE = 0; + 'media:picture' => 'media:image', 'media:photo' => 'media:image', + 'network:activitypub' => 'network:apub', 'network:friendica' => 'network:dfrn', + 'network:diaspora' => 'network:dspr', 'network:discourse' => 'network:dscs', + 'network:tumblr' => 'network:tmbl', 'network:bluesky' => 'network:bsky']; + const MEDIA_NONE = 0; const MEDIA_IMAGE = 1; const MEDIA_VIDEO = 2; const MEDIA_AUDIO = 4; - const MEDIA_CARD = 8; - const MEDIA_POST = 16; + const MEDIA_CARD = 8; + const MEDIA_POST = 16; /** * Store engagement data from an item array @@ -51,11 +51,13 @@ class Engagement return 0; } - $parent = Post::selectFirst(['uri-id', 'created', 'uid', 'private', 'quote-uri-id', - 'contact-contact-type', 'network', 'title', 'content-warning', 'body', 'language', - 'author-id', 'author-contact-type', 'author-nick', 'author-addr', 'author-gsid', - 'owner-id', 'owner-contact-type', 'owner-nick', 'owner-addr', 'owner-gsid'], - ['uri-id' => $item['parent-uri-id']]); + $parent = Post::selectFirst( + ['uri-id', 'created', 'uid', 'private', 'quote-uri-id', + 'contact-contact-type', 'network', 'title', 'content-warning', 'body', 'language', + 'author-id', 'author-contact-type', 'author-nick', 'author-addr', 'author-gsid', + 'owner-id', 'owner-contact-type', 'owner-nick', 'owner-addr', 'owner-gsid'], + ['uri-id' => $item['parent-uri-id']] + ); if ($parent['created'] < self::getCreationDateLimit(false)) { DI::logger()->debug('Post is too old', ['uri-id' => $item['uri-id'], 'parent-uri-id' => $item['parent-uri-id'], 'created' => $parent['created']]); @@ -134,7 +136,7 @@ class Engagement $body = BBCode::removeSharedData($body); $body = preg_replace('/[^@!#]\[url\=.*?\].*?\[\/url\]/ism', '', $body); $body = BBCode::removeLinks($body); - $msg = BBCode::toPlaintext($body, false); + $msg = BBCode::toPlaintext($body, false); return mb_strlen($msg); } @@ -203,7 +205,7 @@ class Engagement $body = '[nosmile]network_' . $item['network']; if (!empty($item['author-gsid'])) { - $gserver = DBA::selectFirst('gserver', ['platform', 'nurl'], ['id' => $item['author-gsid']]); + $gserver = DBA::selectFirst('gserver', ['platform', 'nurl'], ['id' => $item['author-gsid']]); $platform = preg_replace('/[\W]/', '', $gserver['platform'] ?? ''); if (!empty($platform)) { $body .= ' platform_' . $platform; @@ -212,7 +214,7 @@ class Engagement } if (($item['owner-contact-type'] == Contact::TYPE_COMMUNITY) && !empty($item['owner-gsid']) && ($item['owner-gsid'] != ($item['author-gsid'] ?? 0))) { - $gserver = DBA::selectFirst('gserver', ['platform', 'nurl'], ['id' => $item['owner-gsid']]); + $gserver = DBA::selectFirst('gserver', ['platform', 'nurl'], ['id' => $item['owner-gsid']]); $platform = preg_replace('/[\W]/', '', $gserver['platform'] ?? ''); if (!empty($platform) && !strpos($body, 'platform_' . $platform)) { $body .= ' platform_' . $platform; @@ -252,7 +254,7 @@ class Engagement $body .= ' from_' . $item['author-nick'] . ' from_' . $item['author-addr']; } - if ($item['author-id'] != $item['owner-id']) { + if ($item['author-id'] != $item['owner-id']) { if ($item['owner-contact-type'] == Contact::TYPE_COMMUNITY) { $body .= ' group_' . $item['owner-nick'] . ' group_' . $item['owner-addr']; } elseif (in_array($item['owner-contact-type'], [Contact::TYPE_PERSON, Contact::TYPE_NEWS, Contact::TYPE_ORGANISATION])) { @@ -314,8 +316,10 @@ class Engagement private static function addResharers(string $text, int $uri_id): string { - $result = Post::selectPosts(['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]]); + $result = Post::selectPosts( + ['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)) { $prefix = ''; @@ -392,11 +396,11 @@ class Engagement 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); } - foreach (SELF::ALTERNATIVES as $search => $replace) { + foreach (self::ALTERNATIVES as $search => $replace) { $fullTextSearch = str_replace($search, $replace, $fullTextSearch); } diff --git a/src/Model/Post/Link.php b/src/Model/Post/Link.php index 2315928186..4dec537ccd 100644 --- a/src/Model/Post/Link.php +++ b/src/Model/Post/Link.php @@ -61,9 +61,9 @@ class Link $id = $link['id']; DI::logger()->info('Found', ['id' => $id, 'uri-id' => $uriId, 'url' => $url]); } else { - $fields = self::fetchMimeType($url); + $fields = self::fetchMimeType($url); $fields['uri-id'] = $uriId; - $fields['url'] = Network::sanitizeUrl($url); + $fields['url'] = Network::sanitizeUrl($url); DBA::insert('post-link', $fields, Database::INSERT_IGNORE); $id = DBA::lastInsertId(); @@ -126,7 +126,7 @@ class Link if (Images::isSupportedMimeType($fields['mimetype'])) { $img_str = $curlResult->getBodyString(); - $image = new Image($img_str, $fields['mimetype'], $url, false); + $image = new Image($img_str, $fields['mimetype'], $url, false); if ($image->isValid()) { $fields['mimetype'] = $image->getType(); $fields['width'] = $image->getWidth(); diff --git a/src/Model/Post/UserNotification.php b/src/Model/Post/UserNotification.php index e72d3ac353..95c578f486 100644 --- a/src/Model/Post/UserNotification.php +++ b/src/Model/Post/UserNotification.php @@ -118,7 +118,7 @@ class UserNotification $fields = ['id', 'uri-id', 'parent-uri-id', 'uid', 'body', 'parent', 'gravity', 'vid', 'gravity', 'contact-id', 'author-id', 'author-gsid', 'owner-id', 'owner-gsid', 'causer-id', 'causer-gsid', 'private', 'thr-parent', 'thr-parent-id', 'parent-uri-id', 'parent-uri', 'verb']; - $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]); + $item = Post::selectFirst($fields, ['uri-id' => $uri_id, 'uid' => $uid, 'origin' => false]); if (!DBA::isResult($item)) { return; } diff --git a/src/Model/Profile.php b/src/Model/Profile.php index 3732d0d696..8217b2a96a 100644 --- a/src/Model/Profile.php +++ b/src/Model/Profile.php @@ -266,7 +266,7 @@ class Profile */ public static function getVCardHtml(array $profile, bool $block, bool $show_contacts): string { - $o = ''; + $o = ''; $location = false; $profile_contact = []; @@ -293,8 +293,8 @@ class Profile $cid = $contact['id']; - $follow_link = null; - $unfollow_link = null; + $follow_link = null; + $unfollow_link = null; $wallmessage_link = null; // Who is the logged-in user to this profile? @@ -303,13 +303,11 @@ class Profile $visitor_contact = Contact::selectFirst(['rel'], ['uid' => $profile['uid'], 'nurl' => Strings::normaliseLink(DI::userSession()->getMyUrl())]); } - $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_following = - in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]) + $visitor_is_following = in_array($visitor_contact['rel'] ?? 0, [Contact::FOLLOWER, Contact::FRIEND]) || in_array($profile_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]); - $visitor_is_followed = - in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, Contact::FRIEND]) + $visitor_is_followed = in_array($visitor_contact['rel'] ?? 0, [Contact::SHARING, 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()) : ''; @@ -341,15 +339,15 @@ class Profile $profile['edit'] = [DI::baseUrl() . '/settings/profile', DI::l10n()->t('Edit profile'), '', DI::l10n()->t('Edit profile')]; $profile['menu'] = [ 'chg_photo' => DI::l10n()->t('Change profile photo'), - 'cr_new' => null, - 'entries' => [], + 'cr_new' => null, + 'entries' => [], ]; } // Fetch the account type $account_type = Contact::getAccountType($profile['account-type']); - if (!empty($profile['address']) || !empty($profile['location'])) { + if (!empty($profile['address']) || !empty($profile['location'])) { $location = DI::l10n()->t('Location:'); } @@ -363,8 +361,8 @@ class Profile } $split_name = Diaspora::splitName($profile['name']); - $firstname = $split_name['first']; - $lastname = $split_name['last']; + $firstname = $split_name['first']; + $lastname = $split_name['last']; if (!empty($profile['guid'])) { $diaspora = [ @@ -384,7 +382,7 @@ class Profile } $contact_block = ''; - $updated = ''; + $updated = ''; $contact_count = 0; if (!empty($profile['last-item'])) { @@ -415,7 +413,7 @@ class Profile 'upubkey' => null, ]; foreach ($profile as $k => $v) { - $k = str_replace('-', '_', $k); + $k = str_replace('-', '_', $k); $p[$k] = $v; } @@ -444,35 +442,35 @@ class Profile $mention_url = 'compose/0?body=@' . $profile['addr']; $network_label = DI::l10n()->t('Network Posts'); } - $network_url = 'contact/' . $cid . '/conversations'; + $network_url = 'contact/' . $cid . '/conversations'; $tpl = Renderer::getMarkupTemplate('profile/vcard.tpl'); $o .= Renderer::replaceMacros($tpl, [ - '$profile' => $p, - '$xmpp' => $xmpp, - '$matrix' => $matrix, - '$follow' => DI::l10n()->t('Follow'), - '$follow_link' => $follow_link, - '$unfollow' => DI::l10n()->t('Unfollow'), - '$unfollow_link' => $unfollow_link, - '$subscribe_feed' => DI::l10n()->t('Atom feed'), + '$profile' => $p, + '$xmpp' => $xmpp, + '$matrix' => $matrix, + '$follow' => DI::l10n()->t('Follow'), + '$follow_link' => $follow_link, + '$unfollow' => DI::l10n()->t('Unfollow'), + '$unfollow_link' => $unfollow_link, + '$subscribe_feed' => DI::l10n()->t('Atom feed'), '$subscribe_feed_link' => $profile['hidewall'] ?? 0 ? '' : $profile['poll'], - '$wallmessage' => DI::l10n()->t('Message'), - '$wallmessage_link' => $wallmessage_link, - '$account_type' => $account_type, - '$location' => $location, - '$homepage' => $homepage, - '$homepage_verified' => DI::l10n()->t('This website has been verified to belong to the same person.'), - '$about' => $about, - '$network' => DI::l10n()->t('Network:'), - '$contacts' => $contact_count, - '$updated' => $updated, - '$diaspora' => $diaspora, - '$contact_block' => $contact_block, - '$mention_label' => $mention_label, - '$mention_url' => $mention_url, - '$network_label' => $network_label, - '$network_url' => $network_url, + '$wallmessage' => DI::l10n()->t('Message'), + '$wallmessage_link' => $wallmessage_link, + '$account_type' => $account_type, + '$location' => $location, + '$homepage' => $homepage, + '$homepage_verified' => DI::l10n()->t('This website has been verified to belong to the same person.'), + '$about' => $about, + '$network' => DI::l10n()->t('Network:'), + '$contacts' => $contact_count, + '$updated' => $updated, + '$diaspora' => $diaspora, + '$contact_block' => $contact_block, + '$mention_label' => $mention_label, + '$mention_url' => $mention_url, + '$network_label' => $network_label, + '$network_url' => $network_url, ]); $arr = ['profile' => &$profile, 'entry' => &$o]; @@ -603,7 +601,7 @@ class Profile */ public static function getEventsReminderHTML(int $uid, int $pcid): string { - $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18 + $bd_format = DI::l10n()->t('g A l F d'); // 8 AM Friday January 18 $classtoday = ''; $condition = [ @@ -616,13 +614,13 @@ class Profile if (DBA::isResult($s)) { $istoday = false; - $total = 0; + $total = 0; while ($rr = DBA::fetch($s)) { $condition = [ 'parent-uri' => $rr['uri'], 'uid' => $rr['uid'], 'author-id' => $pcid, - 'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)], - 'visible' => true, 'deleted' => false + 'vid' => [Verb::getID(Activity::ATTEND), Verb::getID(Activity::ATTENDMAYBE)], + 'visible' => true, 'deleted' => false ]; if (!Post::exists($condition)) { continue; @@ -656,11 +654,11 @@ class Profile $today = substr($strt, 0, 10) === DateTimeFormat::localNow('Y-m-d'); - $rr['title'] = $title; + $rr['title'] = $title; $rr['description'] = $description; - $rr['date'] = DI::l10n()->getDay(DateTimeFormat::local($rr['start'], $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : ''); - $rr['startime'] = $strt; - $rr['today'] = $today; + $rr['date'] = DI::l10n()->getDay(DateTimeFormat::local($rr['start'], $bd_format)) . (($today) ? ' ' . DI::l10n()->t('[today]') : ''); + $rr['startime'] = $strt; + $rr['today'] = $today; $r[] = $rr; } @@ -669,11 +667,11 @@ class Profile } $tpl = Renderer::getMarkupTemplate('events_reminder.tpl'); return Renderer::replaceMacros($tpl, [ - '$classtoday' => $classtoday, - '$count' => count($r), + '$classtoday' => $classtoday, + '$count' => count($r), '$event_reminders' => DI::l10n()->t('Event Reminders'), - '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'), - '$events' => $r, + '$event_title' => DI::l10n()->t('Upcoming events the next 7 days:'), + '$events' => $r, ]); } @@ -708,9 +706,9 @@ class Profile public static function searchProfiles(int $start = 0, int $count = 100, string $search = null): array { if (!empty($search)) { - $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` "); + $publish = (DI::config()->get('system', 'publish_all') ? '' : "AND `publish` "); $searchTerm = '%' . $search . '%'; - $condition = [ + $condition = [ "`verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` $publish AND ((`name` LIKE ?) OR @@ -822,7 +820,7 @@ class Profile $profile['profile-name'] = null; $profile['is-default'] = null; DBA::update('profile', $profile, ['id' => $profile['id']]); - } else if (!empty($profile['id'])) { + } elseif (!empty($profile['id'])) { DBA::delete('profile', ['id' => $profile['id']]); } } diff --git a/src/Model/Tag.php b/src/Model/Tag.php index e5182a5379..de4beb08ec 100644 --- a/src/Model/Tag.php +++ b/src/Model/Tag.php @@ -26,13 +26,13 @@ use Friendica\Util\Strings; */ class Tag { - const UNKNOWN = 0; - const HASHTAG = 1; - const MENTION = 2; + const UNKNOWN = 0; + const HASHTAG = 1; + const MENTION = 2; /** * An implicit mention is a mention in a comment body that is redundant with the threading information. */ - const IMPLICIT_MENTION = 8; + const IMPLICIT_MENTION = 8; /** * An exclusive mention transmits the post only to the target account without transmitting it to the followers, usually a group. */ @@ -90,7 +90,7 @@ class Tag return; } - $cid = 0; + $cid = 0; $tagid = 0; if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION, self::TO, self::CC, self::BTO, self::BCC, self::AUDIENCE, self::ATTRIBUTED])) { @@ -137,7 +137,7 @@ class Tag $fields = ['uri-id' => $uriId, 'type' => $type, 'tid' => $tagid, 'cid' => $cid]; if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) { - $condition = $fields; + $condition = $fields; $condition['type'] = [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]; if (DBA::exists('post-tag', $condition)) { DI::logger()->info('Tag already exists', $fields); @@ -528,9 +528,9 @@ class Tag public static function populateFromItem(array &$item): array { $return = [ - 'tags' => [], - 'hashtags' => [], - 'mentions' => [], + 'tags' => [], + 'hashtags' => [], + 'mentions' => [], 'implicit_mentions' => [], ]; @@ -556,7 +556,7 @@ class Tag } $return['hashtags'][] = '' . $prefix . '' . htmlspecialchars($tag['name']) . ''; - $return['tags'][] = '' . $prefix . '' . htmlspecialchars($tag['name']) . ''; + $return['tags'][] = '' . $prefix . '' . htmlspecialchars($tag['name']) . ''; break; case self::MENTION: @@ -567,7 +567,7 @@ class Tag $tag['url'] = Contact::magicLink($tag['url']); } $return['mentions'][] = '' . $prefix . '' . htmlspecialchars($tag['name']) . ''; - $return['tags'][] = '' . $prefix . '' . htmlspecialchars($tag['name']) . ''; + $return['tags'][] = '' . $prefix . '' . htmlspecialchars($tag['name']) . ''; break; case self::IMPLICIT_MENTION: @@ -808,7 +808,7 @@ class Tag */ private static function getUIDListByTag(string $tag): array { - $uids = []; + $uids = []; $searches = DBA::select('search', ['uid'], ['term' => $tag]); while ($search = DBA::fetch($searches)) { $uids[] = $search['uid']; diff --git a/src/Model/User.php b/src/Model/User.php index e8b3060b2a..e41db72f7b 100644 --- a/src/Model/User.php +++ b/src/Model/User.php @@ -84,12 +84,12 @@ class User * This will only be assigned to contacts, not to user accounts * @{ */ - const ACCOUNT_TYPE_PERSON = 0; + const ACCOUNT_TYPE_PERSON = 0; const ACCOUNT_TYPE_ORGANISATION = 1; - const ACCOUNT_TYPE_NEWS = 2; - const ACCOUNT_TYPE_COMMUNITY = 3; - const ACCOUNT_TYPE_RELAY = 4; - const ACCOUNT_TYPE_DELETED = 127; + const ACCOUNT_TYPE_NEWS = 2; + const ACCOUNT_TYPE_COMMUNITY = 3; + const ACCOUNT_TYPE_RELAY = 4; + const ACCOUNT_TYPE_DELETED = 127; /** * @} */ @@ -150,42 +150,42 @@ class User } } - $system['name'] = App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION; - $system['uprvkey'] = $system['prvkey']; - $system['upubkey'] = $system['pubkey']; - $system['nickname'] = $system['nick']; - $system['page-flags'] = self::PAGE_FLAGS_SOAPBOX; + $system['name'] = App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION; + $system['uprvkey'] = $system['prvkey']; + $system['upubkey'] = $system['pubkey']; + $system['nickname'] = $system['nick']; + $system['page-flags'] = self::PAGE_FLAGS_SOAPBOX; $system['account-type'] = $system['contact-type']; - $system['guid'] = ''; - $system['picdate'] = ''; - $system['theme'] = ''; - $system['publish'] = false; - $system['net-publish'] = false; + $system['guid'] = ''; + $system['picdate'] = ''; + $system['theme'] = ''; + $system['publish'] = false; + $system['net-publish'] = false; $system['hide-friends'] = true; - $system['hidewall'] = true; + $system['hidewall'] = true; $system['prv_keywords'] = ''; $system['pub_keywords'] = ''; - $system['address'] = ''; - $system['locality'] = ''; - $system['region'] = ''; - $system['postal-code'] = ''; + $system['address'] = ''; + $system['locality'] = ''; + $system['region'] = ''; + $system['postal-code'] = ''; $system['country-name'] = ''; - $system['homepage'] = (string)DI::baseUrl(); - $system['dob'] = '0000-00-00'; + $system['homepage'] = (string)DI::baseUrl(); + $system['dob'] = '0000-00-00'; // Ensure that the user contains data $user = DBA::selectFirst('user', ['prvkey', 'guid', 'language'], ['uid' => 0]); if (empty($user['prvkey']) || empty($user['guid'])) { $fields = [ - 'username' => $system['name'], - 'nickname' => $system['nick'], + 'username' => $system['name'], + 'nickname' => $system['nick'], 'register_date' => $system['created'], - 'pubkey' => $system['pubkey'], - 'prvkey' => $system['prvkey'], - 'guid' => System::createUUID(), - 'verified' => true, - 'page-flags' => self::PAGE_FLAGS_SOAPBOX, - 'account-type' => self::ACCOUNT_TYPE_RELAY, + 'pubkey' => $system['pubkey'], + 'prvkey' => $system['prvkey'], + 'guid' => System::createUUID(), + 'verified' => true, + 'page-flags' => self::PAGE_FLAGS_SOAPBOX, + 'account-type' => self::ACCOUNT_TYPE_RELAY, ]; DBA::update('user', $fields, ['uid' => 0]); @@ -349,12 +349,12 @@ class User DI::pConfig()->set($uid, 'system', 'unlisted', true); $fields = [ - 'allow_cid' => '', - 'allow_gid' => $user['page-flags'] == self::PAGE_FLAGS_PRVGROUP ? '<' . Circle::FOLLOWERS . '>' : '', - 'deny_cid' => '', - 'deny_gid' => '', - 'blockwall' => true, - 'blocktags' => true, + 'allow_cid' => '', + 'allow_gid' => $user['page-flags'] == self::PAGE_FLAGS_PRVGROUP ? '<' . Circle::FOLLOWERS . '>' : '', + 'deny_cid' => '', + 'deny_gid' => '', + 'blockwall' => true, + 'blocktags' => true, ]; self::update($fields, $uid); @@ -490,12 +490,12 @@ class User // Check if the returned data is valid, otherwise fix it. See issue #6122 // Check for correct url and normalised nurl - $url = DI::baseUrl() . '/profile/' . $owner['nickname']; + $url = DI::baseUrl() . '/profile/' . $owner['nickname']; $repair = empty($owner['baseurl']) || empty($owner['network']) || ($owner['url'] != $url) || ($owner['nurl'] != Strings::normaliseLink($owner['url'])); if (!$repair) { // Check if "addr" is present and correct - $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3); + $addr = $owner['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3); $repair = ($addr != $owner['addr']) || empty($owner['prvkey']) || empty($owner['pubkey']); } @@ -628,7 +628,7 @@ class User $users = DBA::select('user', ['uid', 'language'], $condition); while ($user = DBA::fetch($users)) { $uids[] = $user['uid']; - $code = DI::l10n()->toISO6391($user['language']); + $code = DI::l10n()->toISO6391($user['language']); if (!in_array($code, $supported)) { continue; } @@ -644,7 +644,7 @@ class User $values = unserialize($channel['v']); if (!empty($values) && is_array($values)) { foreach ($values as $language) { - $language = DI::l10n()->toISO6391($language); + $language = DI::l10n()->toISO6391($language); $languages[$language] = $language; } } @@ -807,11 +807,11 @@ class User } elseif (is_int($user_info) || is_string($user_info)) { $fields = ['uid', 'nickname', 'password', 'legacy_password']; if (is_int($user_info)) { - $condition = [ - 'uid' => $user_info, + $condition = [ + 'uid' => $user_info, 'account_expired' => false, 'account_removed' => false, - 'verified' => true + 'verified' => true ]; if (!$with_blocked) { $condition = DBA::mergeConditions($condition, ['blocked' => false]); @@ -898,9 +898,9 @@ class User return $passwordExposedChecker->passwordExposed($password) === PasswordExposed\Enums\PasswordStatus::EXPOSED; } catch (Exception $e) { DI::logger()->error('Password Exposed Exception: ' . $e->getMessage(), [ - 'code' => $e->getCode(), - 'file' => $e->getFile(), - 'line' => $e->getLine(), + 'code' => $e->getCode(), + 'file' => $e->getFile(), + 'line' => $e->getLine(), 'trace' => $e->getTraceAsString() ]); @@ -1001,9 +1001,9 @@ class User private static function updatePasswordHashed(int $uid, string $password_hashed): bool { $fields = [ - 'password' => $password_hashed, - 'pwdreset' => null, - 'pwdreset_time' => null, + 'password' => $password_hashed, + 'pwdreset' => null, + 'pwdreset_time' => null, 'legacy_password' => false ]; return DBA::update('user', $fields, ['uid' => $uid]); @@ -1109,7 +1109,7 @@ class User break; } - $updated = ''; + $updated = ''; $mimetype = ''; $photo = Photo::selectFirst(['type', 'created', 'edited', 'updated'], ["scale" => $scale, 'uid' => $user['uid'], 'profile' => true]); @@ -1214,14 +1214,14 @@ class User throw new Exception(DI::l10n()->t('Invalid OpenID url')); } $_SESSION['register'] = 1; - $_SESSION['openid'] = $openid_url; + $_SESSION['openid'] = $openid_url; $openid = new LightOpenID(DI::baseUrl()->getHost()); /** @phpstan-ignore-next-line $openid->identity is private, but will be set via magic setter */ - $openid->identity = $openid_url; + $openid->identity = $openid_url; $openid->returnUrl = DI::baseUrl() . '/openid'; - $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson']; - $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default']; + $openid->required = ['namePerson/friendly', 'contact/email', 'namePerson']; + $openid->optional = ['namePerson/first', 'media/image/aspect11', 'media/image/default']; try { $authurl = $openid->authUrl(); } catch (Exception $e) { @@ -1246,7 +1246,7 @@ class User if ($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_max_length = $tmp; } @@ -1303,7 +1303,7 @@ class User throw new Exception(DI::l10n()->t('Nickname is already registered. Please choose another.')); } - $new_password = strlen($password) ? $password : self::generateNewPassword(); + $new_password = strlen($password) ? $password : self::generateNewPassword(); $new_password_encoded = self::hashPassword($new_password); $return['password'] = $new_password; @@ -1317,24 +1317,24 @@ class User $pubkey = $keys['pubkey']; $insert_result = DBA::insert('user', [ - 'guid' => System::createUUID(), - 'username' => $username, - 'password' => $new_password_encoded, - 'email' => $email, - 'openid' => $openid_url, - 'nickname' => $nickname, - 'pubkey' => $pubkey, - 'prvkey' => $prvkey, - 'verified' => $verified, - 'blocked' => $blocked, - 'language' => $language, - 'timezone' => 'UTC', - 'register_date' => DateTimeFormat::utcNow(), + 'guid' => System::createUUID(), + 'username' => $username, + 'password' => $new_password_encoded, + 'email' => $email, + 'openid' => $openid_url, + 'nickname' => $nickname, + 'pubkey' => $pubkey, + 'prvkey' => $prvkey, + 'verified' => $verified, + 'blocked' => $blocked, + 'language' => $language, + 'timezone' => 'UTC', + 'register_date' => DateTimeFormat::utcNow(), 'default-location' => '' ]); if ($insert_result) { - $uid = DBA::lastInsertId(); + $uid = DBA::lastInsertId(); $user = DBA::selectFirst('user', [], ['uid' => $uid]); } else { throw new Exception(DI::l10n()->t('An error occurred during registration. Please try again.')); @@ -1354,11 +1354,11 @@ class User } $insert_result = DBA::insert('profile', [ - 'uid' => $uid, - 'name' => $username, - 'photo' => self::getAvatarUrl($user), - 'thumb' => self::getAvatarUrl($user, Proxy::SIZE_THUMB), - 'publish' => $publish, + 'uid' => $uid, + 'name' => $username, + 'photo' => self::getAvatarUrl($user), + 'thumb' => self::getAvatarUrl($user, Proxy::SIZE_THUMB), + 'publish' => $publish, 'net-publish' => $netpublish, ]); if (!$insert_result) { @@ -1410,15 +1410,15 @@ class User if ($curlResult->isSuccess()) { DI::logger()->debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $photo]); $img_str = $curlResult->getBodyString(); - $type = $curlResult->getContentType(); + $type = $curlResult->getContentType(); } else { $img_str = ''; - $type = ''; + $type = ''; } } catch (\Throwable $th) { DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); $img_str = ''; - $type = ''; + $type = ''; } $image = new Image($img_str, $type, $photo); @@ -1496,7 +1496,7 @@ class User * @param bool $block Block state (default is true) * * @return bool True, if successfully blocked - + * * @throws Exception */ public static function block(int $uid, bool $block = true): bool @@ -1601,21 +1601,21 @@ class User public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT, string $avatar = ''): bool { if (empty($name) || - empty($email) || - empty($nick)) { + empty($email) || + empty($nick)) { throw new HTTPException\InternalServerErrorException('Invalid arguments.'); } $result = self::create([ 'username' => $name, - 'email' => $email, + 'email' => $email, 'nickname' => $nick, 'verified' => 1, 'language' => $lang, - 'photo' => $avatar + 'photo' => $avatar ]); - $user = $result['user']; + $user = $result['user']; $preamble = Strings::deindent(DI::l10n()->t(' Dear %1$s, the administrator of %2$s has set up an account for you.')); @@ -1647,7 +1647,7 @@ class User Thank you and welcome to %4$s.')); $preamble = sprintf($preamble, $user['username'], DI::config()->get('config', 'sitename')); - $body = sprintf($body, DI::baseUrl(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename')); + $body = sprintf($body, DI::baseUrl(), $user['nickname'], $result['password'], DI::config()->get('config', 'sitename')); $email = DI::emailer() ->newSystemMail() @@ -1848,7 +1848,7 @@ class User if (!$user['parent-uid']) { // First add our own entry $identities = [[ - 'uid' => $user['uid'], + 'uid' => $user['uid'], 'username' => $user['username'], 'nickname' => $user['nickname'] ]]; @@ -1946,17 +1946,20 @@ class User '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` AND NOT `account_removed` AND NOT `account_expired`", - DBA::NULL_DATETIME]); + DBA::NULL_DATETIME] + ); if (!DBA::isResult($userStmt)) { return $statistics; } $halfyear = time() - (180 * 24 * 60 * 60); - $month = time() - (30 * 24 * 60 * 60); - $week = time() - (7 * 24 * 60 * 60); + $month = time() - (30 * 24 * 60 * 60); + $week = time() - (7 * 24 * 60 * 60); while ($user = DBA::fetch($userStmt)) { $statistics['total_users']++; @@ -1994,18 +1997,18 @@ class User */ public static function getList(int $start = 0, int $count = Pager::ITEMS_PER_PAGE, string $type = 'all', string $order = 'name', bool $descending = false) { - $param = ['limit' => [$start, $count], 'order' => [$order => $descending]]; + $param = ['limit' => [$start, $count], 'order' => [$order => $descending]]; $condition = []; switch ($type) { case 'active': $condition['account_removed'] = false; - $condition['blocked'] = false; + $condition['blocked'] = false; break; case 'blocked': $condition['account_removed'] = false; - $condition['blocked'] = true; - $condition['verified'] = true; + $condition['blocked'] = true; + $condition['verified'] = true; break; case 'removed': diff --git a/src/Module/ActivityPub/Objects.php b/src/Module/ActivityPub/Objects.php index 1fa7b2fec5..4ebfe2724d 100644 --- a/src/Module/ActivityPub/Objects.php +++ b/src/Module/ActivityPub/Objects.php @@ -40,8 +40,8 @@ class Objects extends BaseModule $this->logger->info('Provided GUID found.', ['guid' => $this->parameters['guid'], 'uri-id' => $itemuri['id']]); } else { // 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(); - $nurl = Strings::normaliseLink($url); + $url = DI::baseUrl() . '/' . DI::args()->getQueryString(); + $nurl = Strings::normaliseLink($url); $ssl_url = str_replace('http://', 'https://', $nurl); $itemuri = DBA::selectFirst('item-uri', ['guid', 'id'], ['uri' => [$url, $nurl, $ssl_url]]); @@ -63,7 +63,7 @@ class Objects extends BaseModule if (!$validated) { $requester = HTTPSignature::getSigner('', $_SERVER); if (!empty($requester)) { - $receivers = Item::enumeratePermissions($item, false); + $receivers = Item::enumeratePermissions($item, false); $receivers[] = $item['contact-id']; $validated = in_array(Contact::getIdForURL($requester, $item['uid']), $receivers); @@ -96,16 +96,18 @@ class Objects extends BaseModule $data = ['@context' => ActivityPub::CONTEXT]; $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', - 'TentativeAccept', 'Follow', 'Add'])) { + 'TentativeAccept', 'Follow', 'Add'] + )) { $data = ActivityPub\Transmitter::createCachedActivityFromItem($item['id']); if (empty($data)) { throw new HTTPException\NotFoundException(); } if (!empty($this->parameters['activity']) && ($this->parameters['activity'] != 'Create')) { $data['type'] = $this->parameters['activity']; - $data['id'] = str_replace('/Create', '/' . $this->parameters['activity'], $data['id']); + $data['id'] = str_replace('/Create', '/' . $this->parameters['activity'], $data['id']); } } else { throw new HTTPException\NotFoundException(); diff --git a/src/Module/Api/Mastodon/Accounts/Statuses.php b/src/Module/Api/Mastodon/Accounts/Statuses.php index 679e6e8c3d..5e4b3402b4 100644 --- a/src/Module/Api/Mastodon/Accounts/Statuses.php +++ b/src/Module/Api/Mastodon/Accounts/Statuses.php @@ -60,14 +60,14 @@ class Statuses extends BaseApi } elseif (!$uid) { $condition = [ 'author-id' => $id, 'private' => [Item::PUBLIC, Item::UNLISTED], - 'uid' => 0, 'network' => Protocol::FEDERATED + 'uid' => 0, 'network' => Protocol::FEDERATED ]; } else { $condition = ["`author-id` = ? AND (`uid` = 0 OR (`uid` = ? AND NOT `global`))", $id, $uid]; } $condition = $this->addPagingConditions($request, $condition); - $params = $this->buildOrderAndLimitParams($request); + $params = $this->buildOrderAndLimitParams($request); if (!$request['pinned'] && !$request['only_media']) { if ($request['exclude_replies']) { @@ -98,7 +98,7 @@ class Statuses extends BaseApi $statuses = []; while ($item = Post::fetch($items)) { try { - $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); + $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } catch (\Throwable $th) { diff --git a/src/Module/Api/Mastodon/Directory.php b/src/Module/Api/Mastodon/Directory.php index bc6f84c084..b83341d00b 100644 --- a/src/Module/Api/Mastodon/Directory.php +++ b/src/Module/Api/Mastodon/Directory.php @@ -35,15 +35,15 @@ class Directory extends BaseApi $this->logger->info('directory', ['offset' => $request['offset'], 'limit' => $request['limit'], 'order' => $request['order'], 'local' => $request['local']]); if ($request['local']) { - $table = 'owner-view'; + $table = 'owner-view'; $condition = ['net-publish' => true]; } else { - $table = 'contact'; + $table = 'contact'; $condition = ['uid' => 0, 'hidden' => false, 'network' => Protocol::FEDERATED]; } $params = ['limit' => [$request['offset'], $request['limit']], - 'order' => [($request['order'] == 'active') ? 'last-item' : 'created' => true]]; + 'order' => [($request['order'] == 'active') ? 'last-item' : 'created' => true]]; $accounts = []; $contacts = DBA::select($table, ['id', 'uid'], $condition, $params); diff --git a/src/Module/Api/Mastodon/Search.php b/src/Module/Api/Mastodon/Search.php index 532b45dd99..9301c60cdc 100644 --- a/src/Module/Api/Mastodon/Search.php +++ b/src/Module/Api/Mastodon/Search.php @@ -57,7 +57,7 @@ class Search extends BaseApi if (!is_array($result['accounts'])) { // Curbing the search if we got an exact result - $request['type'] = 'accounts'; + $request['type'] = 'accounts'; $result['accounts'] = [$result['accounts']]; } } @@ -67,7 +67,7 @@ class Search extends BaseApi if (!is_array($result['statuses'])) { // Curbing the search if we got an exact result - $request['type'] = 'statuses'; + $request['type'] = 'statuses'; $result['statuses'] = [$result['statuses']]; } } @@ -143,9 +143,9 @@ class Search extends BaseApi substr($q, 1), 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, $uid, 0]; $table = 'tag-search-view'; } else { - $q = Post\Engagement::escapeKeywords($q); + $q = Post\Engagement::escapeKeywords($q); $condition = ["MATCH (`searchtext`) AGAINST (? IN BOOLEAN MODE) AND (NOT `restricted` OR `uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `uid` = ?))", $q, $uid]; - $table = SearchIndex::getSearchTable(); + $table = SearchIndex::getSearchTable(); } if (!empty($account_id)) { diff --git a/src/Module/Api/Mastodon/Timelines/Home.php b/src/Module/Api/Mastodon/Timelines/Home.php index c798a05ae7..10de19a78d 100644 --- a/src/Module/Api/Mastodon/Timelines/Home.php +++ b/src/Module/Api/Mastodon/Timelines/Home.php @@ -44,7 +44,7 @@ class Home extends BaseApi $condition = ['gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT], 'uid' => $uid]; $condition = $this->addPagingConditions($request, $condition); - $params = $this->buildOrderAndLimitParams($request); + $params = $this->buildOrderAndLimitParams($request); if ($request['local']) { $condition = DBA::mergeConditions($condition, ["`uri-id` IN (SELECT `uri-id` FROM `post-user` WHERE `origin`)"]); @@ -74,7 +74,7 @@ class Home extends BaseApi $statuses = []; while ($item = Post::fetch($items)) { try { - $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); + $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } catch (\Throwable $th) { diff --git a/src/Module/Api/Mastodon/Timelines/ListTimeline.php b/src/Module/Api/Mastodon/Timelines/ListTimeline.php index 88ae013012..e5ca2a5c5c 100644 --- a/src/Module/Api/Mastodon/Timelines/ListTimeline.php +++ b/src/Module/Api/Mastodon/Timelines/ListTimeline.php @@ -72,14 +72,14 @@ class ListTimeline extends BaseApi $items = $this->getStatusesForGroup($uid, $request); } elseif (substr($this->parameters['id'], 0, 8) == 'channel:') { $items = $this->getStatusesForChannel($uid, $request); - } else{ + } else { $items = $this->getStatusesForCircle($uid, $request); } $statuses = []; foreach ($items as $item) { try { - $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); + $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } catch (\Throwable $th) { @@ -135,7 +135,7 @@ class ListTimeline extends BaseApi ]; $condition = $this->addPagingConditions($request, $condition); - $params = $this->buildOrderAndLimitParams($request); + $params = $this->buildOrderAndLimitParams($request); if ($request['only_media']) { $condition = DBA::mergeConditions($condition, [ diff --git a/src/Module/Api/Mastodon/Timelines/PublicTimeline.php b/src/Module/Api/Mastodon/Timelines/PublicTimeline.php index 3327757c11..b5539cd55c 100644 --- a/src/Module/Api/Mastodon/Timelines/PublicTimeline.php +++ b/src/Module/Api/Mastodon/Timelines/PublicTimeline.php @@ -74,7 +74,7 @@ class PublicTimeline extends BaseApi ]; $condition = $this->addPagingConditions($request, $condition); - $params = $this->buildOrderAndLimitParams($request); + $params = $this->buildOrderAndLimitParams($request); if ($request['local']) { $condition = DBA::mergeConditions($condition, ['origin' => true]); @@ -108,7 +108,7 @@ class PublicTimeline extends BaseApi $statuses = []; while ($item = Post::fetch($items)) { try { - $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); + $status = DI::mstdnStatus()->createFromUriId($item['uri-id'], $uid, $display_quotes); $this->updateBoundaries($status, $item, $request['friendica_order']); $statuses[] = $status; } catch (\Throwable $th) { diff --git a/src/Module/Api/Mastodon/Trends/Statuses.php b/src/Module/Api/Mastodon/Trends/Statuses.php index ea28647395..a64b83e130 100644 --- a/src/Module/Api/Mastodon/Trends/Statuses.php +++ b/src/Module/Api/Mastodon/Trends/Statuses.php @@ -51,7 +51,7 @@ class Statuses extends BaseApi $uid = self::getCurrentUserID(); $request = $this->getRequest([ - 'limit' => 10, // Maximum number of results to return. Defaults to 10. + 'limit' => 10, // Maximum number of results to return. Defaults to 10. 'offset' => 0, // Offset in set, Defaults to 0. ], $request); diff --git a/src/Module/BaseApi.php b/src/Module/BaseApi.php index 1176143ce8..77d7628061 100644 --- a/src/Module/BaseApi.php +++ b/src/Module/BaseApi.php @@ -287,8 +287,8 @@ class BaseApi extends BaseModule $prev_request = $next_request = $request; if ($asDate) { - $max_date = self::$boundaries['max']; - $min_date = self::$boundaries['min']; + $max_date = self::$boundaries['max']; + $min_date = self::$boundaries['min']; $prev_request['min_id'] = $max_date->format(DateTimeFormat::JSON); $next_request['max_id'] = $min_date->format(DateTimeFormat::JSON); } else { @@ -432,48 +432,48 @@ class BaseApi extends BaseModule // Check for throttling (maximum posts per day, week and month) $throttle_day = DI::config()->get('system', 'throttle_limit_day'); if ($throttle_day > 0) { - $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60); + $datefrom = date(DateTimeFormat::MYSQL, time() - 24 * 60 * 60); $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom]; $posts_day = Post::countThread($condition); if ($posts_day > $throttle_day) { $this->logger->notice('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]); - $error = $this->t('Too Many Requests'); + $error = $this->t('Too Many Requests'); $error_description = $this->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day); - $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); + $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); $this->jsonError(429, $errorobj->toArray()); } } $throttle_week = DI::config()->get('system', 'throttle_limit_week'); if ($throttle_week > 0) { - $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7); + $datefrom = date(DateTimeFormat::MYSQL, time() - 24 * 60 * 60 * 7); - $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom]; + $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom]; $posts_week = Post::countThread($condition); if ($posts_week > $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); - $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); + $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); $this->jsonError(429, $errorobj->toArray()); } } $throttle_month = DI::config()->get('system', 'throttle_limit_month'); if ($throttle_month > 0) { - $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30); + $datefrom = date(DateTimeFormat::MYSQL, time() - 24 * 60 * 60 * 30); - $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom]; + $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom]; $posts_month = Post::countThread($condition); if ($posts_month > $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); - $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); + $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description); $this->jsonError(429, $errorobj->toArray()); } } diff --git a/src/Module/BaseSearch.php b/src/Module/BaseSearch.php index 793787a627..2a3bc8af02 100644 --- a/src/Module/BaseSearch.php +++ b/src/Module/BaseSearch.php @@ -47,13 +47,13 @@ class BaseSearch extends BaseModule return ''; } - $header = ''; + $header = ''; $results = new ResultList(); if (strpos($search, '@') === 0) { - $search = trim(substr($search, 1)); - $type = Search::TYPE_PEOPLE; - $header = DI::l10n()->t('People Search - %s', $search); + $search = trim(substr($search, 1)); + $type = Search::TYPE_PEOPLE; + $header = DI::l10n()->t('People Search - %s', $search); } elseif (strpos($search, '!') === 0) { $search = trim(substr($search, 1)); $type = Search::TYPE_GROUP; @@ -63,11 +63,19 @@ class BaseSearch extends BaseModule $search = Network::convertToIdn($search); if (DI::mode()->isMobile()) { - $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network', - DI::config()->get('system', 'itemspage_network_mobile')); + $itemsPerPage = DI::pConfig()->get( + DI::userSession()->getLocalUserId(), + 'system', + 'itemspage_mobile_network', + DI::config()->get('system', 'itemspage_network_mobile') + ); } else { - $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network', - DI::config()->get('system', 'itemspage_network')); + $itemsPerPage = DI::pConfig()->get( + DI::userSession()->getLocalUserId(), + 'system', + 'itemspage_network', + DI::config()->get('system', 'itemspage_network') + ); } $pager = new Pager(DI::l10n(), DI::args()->getQueryString(), $itemsPerPage); @@ -131,7 +139,8 @@ class BaseSearch extends BaseModule '$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 About page.', '%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 About page.', - $filtered) : '', + $filtered + ) : '', '$contacts' => $entries, '$paginate' => $pager->renderFull($results->getTotal()), ]); diff --git a/src/Module/Contact.php b/src/Module/Contact.php index 293b082618..b352648df7 100644 --- a/src/Module/Contact.php +++ b/src/Module/Contact.php @@ -31,11 +31,11 @@ use Friendica\Worker\UpdateContact; class Contact extends BaseModule { const TAB_CONVERSATIONS = 1; - const TAB_POSTS = 2; - const TAB_PROFILE = 3; - const TAB_CONTACTS = 4; - const TAB_ADVANCED = 5; - const TAB_MEDIA = 6; + const TAB_POSTS = 2; + const TAB_PROFILE = 3; + const TAB_CONTACTS = 4; + const TAB_ADVANCED = 5; + const TAB_MEDIA = 6; private static function batchActions() { @@ -168,11 +168,11 @@ class Contact extends BaseModule } $search = trim($_GET['search'] ?? ''); - $nets = trim($_GET['nets'] ?? ''); - $rel = trim($_GET['rel'] ?? ''); + $nets = trim($_GET['nets'] ?? ''); + $rel = trim($_GET['rel'] ?? ''); $circle = trim($_GET['circle'] ?? ''); - $accounttype = $_GET['accounttype'] ?? ''; + $accounttype = $_GET['accounttype'] ?? ''; $accounttypeid = User::getAccountTypeByString($accounttype); $page = DI::page(); @@ -182,7 +182,7 @@ class Contact extends BaseModule $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css')); $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css')); - $vcard_widget = ''; + $vcard_widget = ''; $findpeople_widget = Widget::findPeople(); if (isset($_GET['add'])) { $follow_widget = Widget::follow($_GET['add']); @@ -248,10 +248,10 @@ class Contact extends BaseModule $sql_values[] = $accounttypeid; } - $searching = false; + $searching = false; $search_hdr = null; if ($search) { - $searching = true; + $searching = true; $search_hdr = $search; $search_txt = preg_quote(trim($search, ' @!')); $sql_extra .= " AND (`name` REGEXP ? OR `url` REGEXP ? OR `nick` REGEXP ? OR `addr` REGEXP ? OR `alias` REGEXP ?)"; @@ -313,80 +313,80 @@ class Contact extends BaseModule $stmt = DBA::select('contact', [], $condition, ['order' => ['name'], 'limit' => [$pager->getStart(), $pager->getItemsPerPage()]]); while ($contact = DBA::fetch($stmt)) { - $contact['blocked'] = Model\Contact\User::isBlocked($contact['id'], DI::userSession()->getLocalUserId()); + $contact['blocked'] = Model\Contact\User::isBlocked($contact['id'], DI::userSession()->getLocalUserId()); $contact['readonly'] = Model\Contact\User::isIgnored($contact['id'], DI::userSession()->getLocalUserId()); - $contacts[] = self::getContactTemplateVars($contact); + $contacts[] = self::getContactTemplateVars($contact); } DBA::close($stmt); $tabs = [ [ - 'label' => DI::l10n()->t('All Contacts'), - 'url' => 'contact', - 'sel' => !$type ? 'active' : '', - 'title' => DI::l10n()->t('Show all contacts'), - 'id' => 'showall-tab', + 'label' => DI::l10n()->t('All Contacts'), + 'url' => 'contact', + 'sel' => !$type ? 'active' : '', + 'title' => DI::l10n()->t('Show all contacts'), + 'id' => 'showall-tab', 'accesskey' => 'l', ], [ - 'label' => DI::l10n()->t('Pending'), - 'url' => 'contact/pending', - 'sel' => $type == 'pending' ? 'active' : '', - 'title' => DI::l10n()->t('Only show pending contacts'), - 'id' => 'showpending-tab', + 'label' => DI::l10n()->t('Pending'), + 'url' => 'contact/pending', + 'sel' => $type == 'pending' ? 'active' : '', + 'title' => DI::l10n()->t('Only show pending contacts'), + 'id' => 'showpending-tab', 'accesskey' => 'p', ], [ - 'label' => DI::l10n()->t('Blocked'), - 'url' => 'contact/blocked', - 'sel' => $type == 'blocked' ? 'active' : '', - 'title' => DI::l10n()->t('Only show blocked contacts'), - 'id' => 'showblocked-tab', + 'label' => DI::l10n()->t('Blocked'), + 'url' => 'contact/blocked', + 'sel' => $type == 'blocked' ? 'active' : '', + 'title' => DI::l10n()->t('Only show blocked contacts'), + 'id' => 'showblocked-tab', 'accesskey' => 'b', ], [ - 'label' => DI::l10n()->t('Ignored'), - 'url' => 'contact/ignored', - 'sel' => $type == 'ignored' ? 'active' : '', - 'title' => DI::l10n()->t('Only show ignored contacts'), - 'id' => 'showignored-tab', + 'label' => DI::l10n()->t('Ignored'), + 'url' => 'contact/ignored', + 'sel' => $type == 'ignored' ? 'active' : '', + 'title' => DI::l10n()->t('Only show ignored contacts'), + 'id' => 'showignored-tab', 'accesskey' => 'i', ], [ - 'label' => DI::l10n()->t('Collapsed'), - 'url' => 'contact/collapsed', - 'sel' => $type == 'collapsed' ? 'active' : '', - 'title' => DI::l10n()->t('Only show collapsed contacts'), - 'id' => 'showcollapsed-tab', + 'label' => DI::l10n()->t('Collapsed'), + 'url' => 'contact/collapsed', + 'sel' => $type == 'collapsed' ? 'active' : '', + 'title' => DI::l10n()->t('Only show collapsed contacts'), + 'id' => 'showcollapsed-tab', 'accesskey' => 'c', ], [ - 'label' => DI::l10n()->t('Archived'), - 'url' => 'contact/archived', - 'sel' => $type == 'archived' ? 'active' : '', - 'title' => DI::l10n()->t('Only show archived contacts'), - 'id' => 'showarchived-tab', + 'label' => DI::l10n()->t('Archived'), + 'url' => 'contact/archived', + 'sel' => $type == 'archived' ? 'active' : '', + 'title' => DI::l10n()->t('Only show archived contacts'), + 'id' => 'showarchived-tab', 'accesskey' => 'y', ], [ - 'label' => DI::l10n()->t('Hidden'), - 'url' => 'contact/hidden', - 'sel' => $type == 'hidden' ? 'active' : '', - 'title' => DI::l10n()->t('Only show hidden contacts'), - 'id' => 'showhidden-tab', + 'label' => DI::l10n()->t('Hidden'), + 'url' => 'contact/hidden', + 'sel' => $type == 'hidden' ? 'active' : '', + 'title' => DI::l10n()->t('Only show hidden contacts'), + 'id' => 'showhidden-tab', 'accesskey' => 'h', ], [ - 'label' => DI::l10n()->t('Circles'), - 'url' => 'circle', - 'sel' => '', - 'title' => DI::l10n()->t('Organize your contact circles'), - 'id' => 'contactcircles-tab', + 'label' => DI::l10n()->t('Circles'), + 'url' => 'circle', + 'sel' => '', + 'title' => DI::l10n()->t('Organize your contact circles'), + 'id' => 'contactcircles-tab', 'accesskey' => 'e', ], ]; - $tabs_tpl = Renderer::getMarkupTemplate('common_tabs.tpl'); + $tabs_tpl = Renderer::getMarkupTemplate('common_tabs.tpl'); $tabs_html = Renderer::replaceMacros($tabs_tpl, ['$tabs' => $tabs]); switch ($rel) { @@ -431,26 +431,26 @@ class Contact extends BaseModule $tpl = Renderer::getMarkupTemplate('contacts-template.tpl'); $o .= Renderer::replaceMacros($tpl, [ - '$header' => $header, - '$tabs' => $tabs_html, - '$total' => $total, - '$search' => $search_hdr, - '$desc' => DI::l10n()->t('Search your contacts'), - '$finding' => $searching ? DI::l10n()->t('Results for: %s', $search) : '', - '$submit' => DI::l10n()->t('Find'), - '$cmd' => DI::args()->getCommand(), - '$parameter' => http_build_query($request), - '$contacts' => $contacts, - '$form_security_token' => BaseModule::getFormSecurityToken('contact_batch_actions'), - 'multiselect' => 1, - '$batch_actions' => [ - 'contacts_batch_update' => DI::l10n()->t('Update'), - 'contacts_batch_block' => DI::l10n()->t('Block') . '/' . DI::l10n()->t('Unblock'), - 'contacts_batch_ignore' => DI::l10n()->t('Ignore') . '/' . DI::l10n()->t('Unignore'), - 'contacts_batch_collapse' => DI::l10n()->t('Collapse') . '/' . DI::l10n()->t('Uncollapse'), + '$header' => $header, + '$tabs' => $tabs_html, + '$total' => $total, + '$search' => $search_hdr, + '$desc' => DI::l10n()->t('Search your contacts'), + '$finding' => $searching ? DI::l10n()->t('Results for: %s', $search) : '', + '$submit' => DI::l10n()->t('Find'), + '$cmd' => DI::args()->getCommand(), + '$parameter' => http_build_query($request), + '$contacts' => $contacts, + '$form_security_token' => BaseModule::getFormSecurityToken('contact_batch_actions'), + 'multiselect' => 1, + '$batch_actions' => [ + 'contacts_batch_update' => DI::l10n()->t('Update'), + 'contacts_batch_block' => DI::l10n()->t('Block') . '/' . DI::l10n()->t('Unblock'), + 'contacts_batch_ignore' => DI::l10n()->t('Ignore') . '/' . DI::l10n()->t('Unignore'), + 'contacts_batch_collapse' => DI::l10n()->t('Collapse') . '/' . DI::l10n()->t('Uncollapse'), ], '$h_batch_actions' => DI::l10n()->t('Batch Actions'), - '$paginate' => $pager->renderFull($total), + '$paginate' => $pager->renderFull($total), ]); return $o; @@ -470,7 +470,7 @@ class Contact extends BaseModule */ public static function getTabsHTML(array $contact, int $active_tab) { - $cid = $pcid = $contact['id']; + $cid = $pcid = $contact['id']; $data = Model\Contact::getPublicAndUserContactID($contact['id'], DI::userSession()->getLocalUserId()); if (!empty($data['user']) && ($contact['id'] == $data['public'])) { $cid = $data['user']; @@ -481,54 +481,54 @@ class Contact extends BaseModule // tabs $tabs = [ [ - 'label' => DI::l10n()->t('Profile'), - 'url' => 'contact/' . $cid, - 'sel' => (($active_tab == self::TAB_PROFILE) ? 'active' : ''), - 'title' => DI::l10n()->t('Profile Details'), - 'id' => 'profile-tab', + 'label' => DI::l10n()->t('Profile'), + 'url' => 'contact/' . $cid, + 'sel' => (($active_tab == self::TAB_PROFILE) ? 'active' : ''), + 'title' => DI::l10n()->t('Profile Details'), + 'id' => 'profile-tab', 'accesskey' => 'o', ], [ - 'label' => DI::l10n()->t('Conversations'), - 'url' => 'contact/' . $pcid . '/conversations', - 'sel' => (($active_tab == self::TAB_CONVERSATIONS) ? 'active' : ''), - 'title' => DI::l10n()->t('Conversations started by this contact'), - 'id' => 'status-tab', + 'label' => DI::l10n()->t('Conversations'), + 'url' => 'contact/' . $pcid . '/conversations', + 'sel' => (($active_tab == self::TAB_CONVERSATIONS) ? 'active' : ''), + 'title' => DI::l10n()->t('Conversations started by this contact'), + 'id' => 'status-tab', 'accesskey' => 'm', ], [ - 'label' => DI::l10n()->t('Posts and Comments'), - 'url' => 'contact/' . $pcid . '/posts', - 'sel' => (($active_tab == self::TAB_POSTS) ? 'active' : ''), - 'title' => DI::l10n()->t('Individual Posts and Replies'), - 'id' => 'posts-tab', + 'label' => DI::l10n()->t('Posts and Comments'), + 'url' => 'contact/' . $pcid . '/posts', + 'sel' => (($active_tab == self::TAB_POSTS) ? 'active' : ''), + 'title' => DI::l10n()->t('Individual Posts and Replies'), + 'id' => 'posts-tab', 'accesskey' => 'p', ], [ - 'label' => DI::l10n()->t('Media'), - 'url' => 'contact/' . $pcid . '/media', - 'sel' => (($active_tab == self::TAB_MEDIA) ? 'active' : ''), - 'title' => DI::l10n()->t('Posts containing media objects'), - 'id' => 'media-tab', + 'label' => DI::l10n()->t('Media'), + 'url' => 'contact/' . $pcid . '/media', + 'sel' => (($active_tab == self::TAB_MEDIA) ? 'active' : ''), + 'title' => DI::l10n()->t('Posts containing media objects'), + 'id' => 'media-tab', 'accesskey' => 'd', ], [ - 'label' => DI::l10n()->t('Contacts'), - 'url' => 'contact/' . $pcid . '/contacts', - 'sel' => (($active_tab == self::TAB_CONTACTS) ? 'active' : ''), - 'title' => DI::l10n()->t('View all known contacts'), - 'id' => 'contacts-tab', + 'label' => DI::l10n()->t('Contacts'), + 'url' => 'contact/' . $pcid . '/contacts', + 'sel' => (($active_tab == self::TAB_CONTACTS) ? 'active' : ''), + 'title' => DI::l10n()->t('View all known contacts'), + 'id' => 'contacts-tab', 'accesskey' => 't' ], ]; if (!empty($contact['network']) && in_array($contact['network'], [Protocol::FEED, Protocol::MAIL]) && ($cid != $pcid)) { $tabs[] = [ - 'label' => DI::l10n()->t('Advanced'), - 'url' => 'contact/' . $cid . '/advanced/', - 'sel' => (($active_tab == self::TAB_ADVANCED) ? 'active' : ''), - 'title' => DI::l10n()->t('Advanced Contact Settings'), - 'id' => 'advanced-tab', + 'label' => DI::l10n()->t('Advanced'), + 'url' => 'contact/' . $cid . '/advanced/', + 'sel' => (($active_tab == self::TAB_ADVANCED) ? 'active' : ''), + 'title' => DI::l10n()->t('Advanced Contact Settings'), + 'id' => 'advanced-tab', 'accesskey' => 'r' ]; } @@ -566,11 +566,11 @@ class Contact extends BaseModule $alt_text = DI::l10n()->t('Mutual Friendship'); break; - case Model\Contact::FOLLOWER; + case Model\Contact::FOLLOWER: $alt_text = DI::l10n()->t('is a fan of yours'); break; - case Model\Contact::SHARING; + case Model\Contact::SHARING: $alt_text = DI::l10n()->t('you are a fan of'); break; diff --git a/src/Module/OAuth/Token.php b/src/Module/OAuth/Token.php index 6d7f1a3507..51648983e1 100644 --- a/src/Module/OAuth/Token.php +++ b/src/Module/OAuth/Token.php @@ -57,7 +57,8 @@ class Token extends BaseApi if (empty($request['client_id']) || empty($request['client_secret'])) { $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']); @@ -90,8 +91,8 @@ class Token extends BaseApi // now check for $grant_type === 'authorization_code' // For security reasons only allow freshly created tokens - $redirect_uri = strtok($request['redirect_uri'],'?'); - $condition = [ + $redirect_uri = strtok($request['redirect_uri'], '?'); + $condition = [ "`redirect_uri` LIKE ? AND `id` = ? AND `code` = ? AND `created_at` > ?", $redirect_uri, $application['id'], $request['code'], DateTimeFormat::utc('now - 5 minutes') ]; diff --git a/src/Module/Owa.php b/src/Module/Owa.php index d7599a82c0..55f9e1c875 100644 --- a/src/Module/Owa.php +++ b/src/Module/Owa.php @@ -62,7 +62,7 @@ class Owa extends BaseModule $this->logger->debug('OWA header', ['addr' => $contact['addr'], 'data' => $verified]); $ret['success'] = true; - $token = Strings::getRandomHex(32); + $token = Strings::getRandomHex(32); // Store the generated token in the database. OpenWebAuthToken::create('owt', 0, $token, $contact['addr']); diff --git a/src/Module/Photo.php b/src/Module/Photo.php index e176efbddf..d2b42811ce 100644 --- a/src/Module/Photo.php +++ b/src/Module/Photo.php @@ -63,19 +63,19 @@ class Photo extends BaseApi OpenWebAuth::addVisitorCookieForHTTPSigner($this->server); - $customsize = 0; + $customsize = 0; $square_resize = true; - $scale = null; - $stamp = microtime(true); + $scale = null; + $stamp = microtime(true); // User avatar if (!empty($this->parameters['type'])) { if (!empty($this->parameters['customsize'])) { - $customsize = intval($this->parameters['customsize']); + $customsize = intval($this->parameters['customsize']); $square_resize = !in_array($this->parameters['type'], ['media', 'preview']); } if (!empty($this->parameters['guid'])) { - $guid = $this->parameters['guid']; + $guid = $this->parameters['guid']; $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]); if (empty($account)) { throw new HTTPException\NotFoundException(); @@ -90,7 +90,7 @@ class Photo extends BaseApi if (!empty($this->parameters['nickname_ext'])) { $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME); - $user = User::getByNickname($nickname, ['uid']); + $user = User::getByNickname($nickname, ['uid']); if (empty($user)) { throw new HTTPException\NotFoundException(); } @@ -110,9 +110,9 @@ class Photo extends BaseApi $photo = $this->getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL); } else { $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME); - $scale = 0; + $scale = 0; if (substr($photoid, -2, 1) == '-') { - $scale = intval(substr($photoid, -1, 1)); + $scale = intval(substr($photoid, -1, 1)); $photoid = substr($photoid, 0, -2); } @@ -174,7 +174,7 @@ class Photo extends BaseApi $this->logger->warning('Invalid photo', ['id' => $photo['id']]); if (in_array($photo['backend-class'], [ExternalResource::NAME])) { $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']); } else { $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']); } @@ -228,13 +228,13 @@ class Photo extends BaseApi $output = microtime(true) - $stamp; $total = microtime(true) - $totalstamp; - $rest = $total - ($fetch + $data + $checksum + $output); + $rest = $total - ($fetch + $data + $checksum + $output); if (!is_null($scale) && ($scale < 4)) { $this->logger->debug('Performance:', [ - 'scale' => $scale, 'resource' => $photo['resource-id'], - 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3), - 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3), + 'scale' => $scale, 'resource' => $photo['resource-id'], + 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3), + 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3), 'output' => number_format($output, 3), 'rest' => number_format($rest, 3) ]); } @@ -296,7 +296,7 @@ class Photo extends BaseApi return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0); 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']; $contact = Contact::getById($id, $fields); if (empty($contact)) { return false; @@ -357,7 +357,7 @@ class Photo extends BaseApi && ((time() - strtotime($contact['updated']) > 86400)); if ($update) { $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); $this->logger->debug('Got return code for avatar', ['return code' => $curlResult->getReturnCode(), 'cid' => $id, 'url' => $contact['url'], 'avatar' => $url]); } if ($update) { @@ -400,7 +400,7 @@ class Photo extends BaseApi } return MPhoto::createPhotoForExternalResource($url, 0, $mimetext, $contact['blurhash'] ?? null, $customsize, $customsize); case 'header': - $fields = ['uid', 'url', 'header', 'network', 'gsid']; + $fields = ['uid', 'url', 'header', 'network', 'gsid']; $contact = Contact::getById($id, $fields); if (empty($contact)) { return false; diff --git a/src/Module/Register.php b/src/Module/Register.php index 575301f777..683d4e0ea6 100644 --- a/src/Module/Register.php +++ b/src/Module/Register.php @@ -114,7 +114,7 @@ class Register extends BaseModule if (DI::config()->get('system', 'publish_all')) { $profile_publish = ''; } else { - $publish_tpl = Renderer::getMarkupTemplate('profile/publish.tpl'); + $publish_tpl = Renderer::getMarkupTemplate('profile/publish.tpl'); $profile_publish = Renderer::replaceMacros($publish_tpl, [ '$instance' => 'reg', '$pubdesc' => DI::l10n()->t('Include your profile in member directory?'), @@ -136,44 +136,44 @@ class Register extends BaseModule $tpl = $arr['template']; $o = Renderer::replaceMacros($tpl, [ - '$invitations' => DI::config()->get('system', 'invitation_only'), - '$permonly' => self::getPolicy() === self::APPROVE, - '$permonlybox' => ['permonlybox', DI::l10n()->t('Note for the admin'), '', DI::l10n()->t('Leave a message for the admin, why you want to join this node'), DI::l10n()->t('Required')], - '$invite_desc' => DI::l10n()->t('Membership on this site is by invitation only.'), - '$invite_label' => DI::l10n()->t('Your invitation code: '), - '$invite_id' => $invite_id, - '$regtitle' => DI::l10n()->t('Registration'), - '$registertext' => BBCode::convertForUriId(User::getSystemUriId(), DI::config()->get('config', 'register_text', '')), - '$fillwith' => $fillwith, - '$fillext' => $fillext, - '$oidlabel' => $oidlabel, - '$openid' => $openid_url, - '$namelabel' => DI::l10n()->t('Your Display Name (as you would like it to be displayed on this system'), - '$addrlabel' => DI::l10n()->t('Your Email Address: (Initial information will be send there, so this has to be an existing address.)'), - '$addrlabel2' => DI::l10n()->t('Please repeat your e-mail address:'), - '$ask_password' => $ask_password, - '$password1' => ['password1', DI::l10n()->t('New Password:'), '', DI::l10n()->t('Leave empty for an auto generated password.')], - '$password2' => ['confirm', DI::l10n()->t('Confirm:'), '', ''], - '$nickdesc' => DI::l10n()->t('Choose a profile nickname. This must begin with a text character. Your profile address on this site will then be "nickname@%s".', DI::baseUrl()->getHost()), - '$nicklabel' => DI::l10n()->t('Choose a nickname: '), - '$photo' => $photo, - '$publish' => $profile_publish, - '$regbutt' => DI::l10n()->t('Register'), - '$username' => $username, - '$email' => $email, - '$nickname' => $nickname, - '$sitename' => DI::baseUrl()->getHost(), - '$importh' => DI::l10n()->t('Import'), - '$importt' => DI::l10n()->t('Import your profile to this friendica instance'), - '$showtoslink' => DI::config()->get('system', 'tosdisplay'), - '$tostext' => DI::l10n()->t('Terms of Service'), - '$showprivstatement' => DI::config()->get('system', 'tosprivstatement'), - '$privstatement'=> $this->tos->privacy_complete, - '$form_security_token' => BaseModule::getFormSecurityToken('register'), - '$explicit_content' => DI::config()->get('system', 'explicit_content', false), + '$invitations' => DI::config()->get('system', 'invitation_only'), + '$permonly' => self::getPolicy() === self::APPROVE, + '$permonlybox' => ['permonlybox', DI::l10n()->t('Note for the admin'), '', DI::l10n()->t('Leave a message for the admin, why you want to join this node'), DI::l10n()->t('Required')], + '$invite_desc' => DI::l10n()->t('Membership on this site is by invitation only.'), + '$invite_label' => DI::l10n()->t('Your invitation code: '), + '$invite_id' => $invite_id, + '$regtitle' => DI::l10n()->t('Registration'), + '$registertext' => BBCode::convertForUriId(User::getSystemUriId(), DI::config()->get('config', 'register_text', '')), + '$fillwith' => $fillwith, + '$fillext' => $fillext, + '$oidlabel' => $oidlabel, + '$openid' => $openid_url, + '$namelabel' => DI::l10n()->t('Your Display Name (as you would like it to be displayed on this system'), + '$addrlabel' => DI::l10n()->t('Your Email Address: (Initial information will be send there, so this has to be an existing address.)'), + '$addrlabel2' => DI::l10n()->t('Please repeat your e-mail address:'), + '$ask_password' => $ask_password, + '$password1' => ['password1', DI::l10n()->t('New Password:'), '', DI::l10n()->t('Leave empty for an auto generated password.')], + '$password2' => ['confirm', DI::l10n()->t('Confirm:'), '', ''], + '$nickdesc' => DI::l10n()->t('Choose a profile nickname. This must begin with a text character. Your profile address on this site will then be "nickname@%s".', DI::baseUrl()->getHost()), + '$nicklabel' => DI::l10n()->t('Choose a nickname: '), + '$photo' => $photo, + '$publish' => $profile_publish, + '$regbutt' => DI::l10n()->t('Register'), + '$username' => $username, + '$email' => $email, + '$nickname' => $nickname, + '$sitename' => DI::baseUrl()->getHost(), + '$importh' => DI::l10n()->t('Import'), + '$importt' => DI::l10n()->t('Import your profile to this friendica instance'), + '$showtoslink' => DI::config()->get('system', 'tosdisplay'), + '$tostext' => DI::l10n()->t('Terms of Service'), + '$showprivstatement' => DI::config()->get('system', 'tosprivstatement'), + '$privstatement' => $this->tos->privacy_complete, + '$form_security_token' => BaseModule::getFormSecurityToken('register'), + '$explicit_content' => DI::config()->get('system', 'explicit_content', false), '$explicit_content_note' => DI::l10n()->t('Note: This node explicitly contains adult content'), - '$additional' => !empty(DI::userSession()->getLocalUserId()), - '$parent_password' => ['parent_password', DI::l10n()->t('Parent Password:'), '', DI::l10n()->t('Please enter the password of the parent account to legitimize your request.')] + '$additional' => !empty(DI::userSession()->getLocalUserId()), + '$parent_password' => ['parent_password', DI::l10n()->t('Parent Password:'), '', DI::l10n()->t('Please enter the password of the parent account to legitimize your request.')] ]); @@ -223,12 +223,12 @@ class Register extends BaseModule switch (self::getPolicy()) { case self::OPEN: - $blocked = 0; + $blocked = 0; $verified = 1; break; case self::APPROVE: - $blocked = 1; + $blocked = 1; $verified = 0; break; @@ -238,7 +238,7 @@ class Register extends BaseModule DI::sysmsg()->addNotice(DI::l10n()->t('Permission denied.')); return; } - $blocked = 1; + $blocked = 1; $verified = 0; break; } @@ -261,11 +261,11 @@ class Register extends BaseModule DI::baseUrl()->redirect('register'); } - $blocked = 0; + $blocked = 0; $verified = 1; $arr['password1'] = $arr['confirm'] = $arr['parent_password']; - $arr['repeat'] = $arr['email'] = $user['email']; + $arr['repeat'] = $arr['email'] = $user['email']; } else { // Overwriting the "tar pit" field with the real one $arr['email'] = $arr['field1']; @@ -280,9 +280,9 @@ class Register extends BaseModule //Check if nickname contains only US-ASCII and do not start with a digit if (!preg_match('/^[a-zA-Z][a-zA-Z0-9]*$/', $arr['nickname'])) { - if (is_numeric(substr($arr['nickname'], 0, 1))) { + if (is_numeric(substr($arr['nickname'], 0, 1))) { DI::sysmsg()->addNotice(DI::l10n()->t("Nickname cannot start with a digit.")); - } else { + } else { DI::sysmsg()->addNotice(DI::l10n()->t("Nickname can only contain US-ASCII characters.")); } $regdata = ['email' => $arr['email'], 'nickname' => $arr['nickname'], 'username' => $arr['username']]; @@ -290,7 +290,7 @@ class Register extends BaseModule return; } - $arr['blocked'] = $blocked; + $arr['blocked'] = $blocked; $arr['verified'] = $verified; $arr['language'] = L10n::detectLanguage($_SERVER, $_GET, DI::config()->get('system', 'language')); @@ -318,7 +318,7 @@ class Register extends BaseModule $using_invites = DI::config()->get('system', 'invitation_only'); $num_invites = DI::config()->get('system', 'number_invites'); - $invite_id = (!empty($_POST['invite_id']) ? trim($_POST['invite_id']) : ''); + $invite_id = (!empty($_POST['invite_id']) ? trim($_POST['invite_id']) : ''); if (self::getPolicy() === self::OPEN) { if ($using_invites && $invite_id) { @@ -344,9 +344,11 @@ class Register extends BaseModule DI::baseUrl()->redirect(); } else { DI::sysmsg()->addNotice( - DI::l10n()->t('Failed to send email message. Here your accout details:
login: %s
password: %s

You can change your password after login.', + DI::l10n()->t( + 'Failed to send email message. Here your accout details:
login: %s
password: %s

You can change your password after login.', $user['email'], - $result['password']) + $result['password'] + ) ); } } else { @@ -422,7 +424,7 @@ class Register extends BaseModule public static function getPolicy(): int { $admins = User::getAdminList(['login_date']); - $days = DI::config()->get('system', 'admin_inactivity_limit'); + $days = DI::config()->get('system', 'admin_inactivity_limit'); if ($days == 0 || empty($admins)) { return intval(DI::config()->get('config', 'register_policy')); } diff --git a/src/Module/Search/Index.php b/src/Module/Search/Index.php index eecd195169..8d395ba880 100644 --- a/src/Module/Search/Index.php +++ b/src/Module/Search/Index.php @@ -59,12 +59,14 @@ class Index extends BaseSearch // 10 requests are "free", after the 11th only a call per minute is allowed $free_crawls = intval(DI::config()->get('system', 'free_crawls')); - if ($free_crawls == 0) + if ($free_crawls == 0) { $free_crawls = 10; + } $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; + } $remote = $this->remoteAddress; $result = DI::cache()->get('remote_search:' . $remote); @@ -87,16 +89,16 @@ class Index extends BaseSearch $tag = false; if (!empty($_GET['tag'])) { - $tag = true; + $tag = true; $search = '#' . trim(rawurldecode($_GET['tag'])); } // construct a wrapper for the search header $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('content_wrapper.tpl'), [ - 'name' => 'search-header', - '$title' => DI::l10n()->t('Search'), + 'name' => 'search-header', + '$title' => DI::l10n()->t('Search'), '$title_size' => 3, - '$content' => HTML::search($search, 'search-box', false) + '$content' => HTML::search($search, 'search-box', false) ]); if (!$search) { @@ -104,7 +106,7 @@ class Index extends BaseSearch } if (strpos($search, '#') === 0) { - $tag = true; + $tag = true; $search = substr($search, 1); } else { if (strpos($search, '@') === 0 || strpos($search, '!') === 0) { @@ -146,11 +148,19 @@ class Index extends BaseSearch // No items will be shown if the member has a blocked profile wall. if (DI::mode()->isMobile()) { - $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_mobile_network', - DI::config()->get('system', 'itemspage_network_mobile')); + $itemsPerPage = DI::pConfig()->get( + DI::userSession()->getLocalUserId(), + 'system', + 'itemspage_mobile_network', + DI::config()->get('system', 'itemspage_network_mobile') + ); } else { - $itemsPerPage = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'system', 'itemspage_network', - DI::config()->get('system', 'itemspage_network')); + $itemsPerPage = DI::pConfig()->get( + DI::userSession()->getLocalUserId(), + 'system', + 'itemspage_network', + DI::config()->get('system', 'itemspage_network') + ); } $last_uriid = isset($_GET['last_uriid']) ? intval($_GET['last_uriid']) : 0; @@ -160,18 +170,18 @@ class Index extends BaseSearch if ($tag) { $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); - $count = Tag::countByTag($search, DI::userSession()->getLocalUserId()); + $count = Tag::countByTag($search, DI::userSession()->getLocalUserId()); } else { $this->logger->info('Start fulltext search.', ['q' => $search]); $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()); } if (!empty($uriids)) { $condition = ["(`uid` = ? OR (`uid` = ? AND NOT `global`))", 0, DI::userSession()->getLocalUserId()]; $condition = DBA::mergeConditions($condition, ['uri-id' => $uriids]); - $params = ['order' => ['uri-id' => true]]; - $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), Item::DISPLAY_FIELDLIST, $condition, $params)); + $params = ['order' => ['uri-id' => true]]; + $items = Post::toArray(Post::selectForUser(DI::userSession()->getLocalUserId(), Item::DISPLAY_FIELDLIST, $condition, $params)); } if (empty($items)) { diff --git a/src/Module/Smilies.php b/src/Module/Smilies.php index b923e2ac7b..fe577ed575 100644 --- a/src/Module/Smilies.php +++ b/src/Module/Smilies.php @@ -32,7 +32,7 @@ class Smilies extends BaseModule protected function content(array $request = []): string { $smilies = Content\Smilies::getList(); - $count = count($smilies['texts'] ?? []); + $count = count($smilies['texts'] ?? []); $tpl = Renderer::getMarkupTemplate('smilies.tpl'); return Renderer::replaceMacros($tpl, [ diff --git a/src/Network/Probe.php b/src/Network/Probe.php index fc064b0f9e..a573790f49 100644 --- a/src/Network/Probe.php +++ b/src/Network/Probe.php @@ -204,10 +204,10 @@ class Probe // Handles the case when the hostname contains the scheme if (!parse_url($host, PHP_URL_SCHEME)) { $ssl_url = 'https://' . $host . self::HOST_META; - $url = 'http://' . $host . self::HOST_META; + $url = 'http://' . $host . self::HOST_META; } else { $ssl_url = $host . self::HOST_META; - $url = ''; + $url = ''; } $xrd_timeout = DI::config()->get('system', 'xrd_timeout', 20); @@ -255,8 +255,8 @@ class Probe return []; } - $xml = $curlResult->getBodyString(); - $xrd = XML::parseString($xml, true); + $xml = $curlResult->getBodyString(); + $xrd = XML::parseString($xml, true); $host_url = 'http://' . $host; } if (!is_object($xrd)) { @@ -330,7 +330,7 @@ class Probe foreach ($webfinger['aliases'] as $alias) { $data[] = [ '@attributes' => [ - 'rel' => 'alias', + 'rel' => 'alias', 'href' => $alias, ] ]; @@ -383,18 +383,18 @@ class Probe unset($data['networks']); if (!empty($data['network'])) { $networks[$data['network']] = $data; - $ap_profile['guid'] = $ap_profile['guid'] ?? $data['guid'] ?? null; - $ap_profile['about'] = $ap_profile['about'] ?? $data['about'] ?? null; - $ap_profile['keywords'] = $data['keywords'] ?? null; - $ap_profile['location'] = $data['location'] ?? null; - $ap_profile['poco'] = $data['poco'] ?? null; - $ap_profile['openwebauth'] = $data['openwebauth'] ?? null; + $ap_profile['guid'] = $ap_profile['guid'] ?? $data['guid'] ?? null; + $ap_profile['about'] = $ap_profile['about'] ?? $data['about'] ?? null; + $ap_profile['keywords'] = $data['keywords'] ?? null; + $ap_profile['location'] = $data['location'] ?? null; + $ap_profile['poco'] = $data['poco'] ?? null; + $ap_profile['openwebauth'] = $data['openwebauth'] ?? null; } - $data = $ap_profile; + $data = $ap_profile; $data['networks'] = $networks; } elseif (!empty($ap_profile)) { $ap_profile['batch'] = ''; - $data = array_merge($ap_profile, $data); + $data = array_merge($ap_profile, $data); } } else { $data = $ap_profile; @@ -582,7 +582,7 @@ class Probe if (empty($webfinger) && empty($lrdd)) { while (empty($lrdd) && empty($webfinger) && (count($path_parts) > 1)) { - $host .= '/' . array_shift($path_parts); + $host .= '/' . array_shift($path_parts); $baseurl = $parts['scheme'] . '://' . $host; if (!empty($nick)) { @@ -679,8 +679,8 @@ class Probe // First try the address because this is the primary purpose of webfinger if ($addr !== '') { - $detected = $addr; - $path = str_replace('{uri}', urlencode('acct:' . $addr), $template); + $detected = $addr; + $path = str_replace('{uri}', urlencode('acct:' . $addr), $template); $webfinger = self::webfinger($path, $type); if (is_null($webfinger)) { return null; @@ -689,8 +689,8 @@ class Probe // Then try the URI if (empty($webfinger) && $uri != $addr) { - $detected = $uri; - $path = str_replace('{uri}', urlencode($uri), $template); + $detected = $uri; + $path = str_replace('{uri}', urlencode($uri), $template); $webfinger = self::webfinger($path, $type); if (is_null($webfinger)) { return null; @@ -772,9 +772,9 @@ class Probe } $webfinger = $data['webfinger']; - $nick = $data['nick'] ?? ''; - $addr = $data['addr'] ?? ''; - $baseurl = $data['baseurl'] ?? ''; + $nick = $data['nick'] ?? ''; + $addr = $data['addr'] ?? ''; + $baseurl = $data['baseurl'] ?? ''; $result = []; @@ -962,7 +962,7 @@ class Probe $data['hide'] = !$json['searchable']; } if (!empty($json['public_forum'])) { - $data['community'] = $json['public_forum']; + $data['community'] = $json['public_forum']; $data['account-type'] = User::ACCOUNT_TYPE_COMMUNITY; } elseif (($json['channel_type'] ?? '') == 'normal') { $data['account-type'] = User::ACCOUNT_TYPE_PERSON; @@ -1189,7 +1189,7 @@ class Probe private static function dfrn(array $webfinger): array { $hcard_url = ''; - $data = []; + $data = []; // The array is reversed to take into account the order of preference for same-rel links // See: https://tools.ietf.org/html/rfc7033#section-4.4.4 foreach (array_reverse($webfinger['links']) as $link) { @@ -1380,7 +1380,7 @@ class Probe private static function diaspora(array $webfinger): array { $hcard_url = ''; - $data = []; + $data = []; // The array is reversed to take into account the order of preference for same-rel links // See: https://tools.ietf.org/html/rfc7033#section-4.4.4 @@ -1446,7 +1446,7 @@ class Probe && !empty($data['pubkey']) && $hcard_url !== '' ) { - $data['network'] = Protocol::DIASPORA; + $data['network'] = Protocol::DIASPORA; $data['manually-approve'] = false; // The Diaspora handle must always be lowercase @@ -1537,7 +1537,7 @@ class Probe && isset($data['poll']) && isset($data['url']) ) { - $data['network'] = Protocol::OSTATUS; + $data['network'] = Protocol::OSTATUS; $data['manually-approve'] = false; } else { return $short ? false : []; @@ -1558,7 +1558,7 @@ class Probe self::$isTimeout = true; return []; } - $feed = $curlResult->getBodyString(); + $feed = $curlResult->getBodyString(); $feed_data = Feed::import($feed); if (!$feed_data) { return []; @@ -1668,10 +1668,12 @@ class Probe // Resolve arbitrary relative path // Lifted from https://www.php.net/manual/en/function.realpath.php#84012 - $parts = array_filter(explode('/', $path), 'strlen'); + $parts = array_filter(explode('/', $path), 'strlen'); $absolutes = []; foreach ($parts as $part) { - if ('.' == $part) continue; + if ('.' == $part) { + continue; + } if ('..' == $part) { array_pop($absolutes); } else { @@ -1721,18 +1723,18 @@ class Probe return []; } - $nick = $profile->handle ?? $profile->did; + $nick = $profile->handle ?? $profile->did; $name = $profile->displayName ?? $nick; $data = [ - 'network' => Protocol::BLUESKY, - 'url' => $profile->did, - 'alias' => ATProtocol::WEB . '/profile/' . $nick, - 'name' => $name ?: $nick, - 'nick' => $nick, - 'addr' => $nick, - 'poll' => ATProtocol::WEB . '/profile/' . $profile->did . '/rss', - 'photo' => $profile->avatar ?? '', + 'network' => Protocol::BLUESKY, + 'url' => $profile->did, + 'alias' => ATProtocol::WEB . '/profile/' . $nick, + 'name' => $name ?: $nick, + 'nick' => $nick, + 'addr' => $nick, + 'poll' => ATProtocol::WEB . '/profile/' . $profile->did . '/rss', + 'photo' => $profile->avatar ?? '', ]; if (!empty($profile->description)) { @@ -1819,7 +1821,7 @@ class Probe $data['alias'] = $feed_data['header']['author-id']; } - $data['url'] = $url; + $data['url'] = $url; $data['poll'] = $url; $data['network'] = Protocol::FEED; @@ -1849,14 +1851,14 @@ class Probe $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $uid]); $condition = ["`uid` = ? AND `server` != ''", $uid]; - $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox']; - $mailacct = DBA::selectFirst('mailacct', $fields, $condition); + $fields = ['pass', 'user', 'server', 'port', 'ssltype', 'mailbox']; + $mailacct = DBA::selectFirst('mailacct', $fields, $condition); if (!DBA::isResult($user) || !DBA::isResult($mailacct)) { return []; } - $mailbox = Email::constructMailboxName($mailacct); + $mailbox = Email::constructMailboxName($mailacct); $password = ''; openssl_private_decrypt(hex2bin($mailacct['pass']), $password, $user['prvkey']); $mbox = Email::connect($mailbox, $mailacct['user'], $password); @@ -1883,7 +1885,7 @@ class Probe 'poll' => 'email ' . Strings::getRandomHex(), ]; - $data['nick'] = $data['name']; + $data['nick'] = $data['name']; $x = Email::messageMeta($mbox, $msgs[0]); @@ -1899,7 +1901,7 @@ class Probe && (strcasecmp($feadr->host, $phost) == 0) && !empty($feadr->personal) ) { - $personal = imap_mime_header_decode($feadr->personal); + $personal = imap_mime_header_decode($feadr->personal); $data['name'] = ''; foreach ($personal as $perspart) { if ($perspart->charset != 'default') { @@ -2064,9 +2066,9 @@ class Probe $last_updated = ''; foreach ($items as $activity) { if (!empty($activity['published'])) { - $published = DateTimeFormat::utc($activity['published']); + $published = DateTimeFormat::utc($activity['published']); } elseif (!empty($activity['object']['published'])) { - $published = DateTimeFormat::utc($activity['object']['published']); + $published = DateTimeFormat::utc($activity['object']['published']); } else { continue; } @@ -2182,7 +2184,7 @@ class Probe 'sharedinbox' => $approfile['endpoints']['sharedInbox'], 'network' => Protocol::DFRN, 'pubkey' => $owner['upubkey'], 'baseurl' => $approfile['generator']['url'], 'gsid' => $owner['gsid'], 'manually-approve' => in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP, User::PAGE_FLAGS_COMM_MAN]), - 'networks' => [ + 'networks' => [ Protocol::DIASPORA => [ 'name' => $owner['name'], 'given_name' => $split_name['first'], @@ -2207,7 +2209,7 @@ class Probe } catch (Exception $e) { // Default values for nonexistent targets $data = [ - 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM, + 'name' => $url, 'nick' => $url, 'url' => $url, 'network' => Protocol::PHANTOM, 'photo' => DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO ]; } diff --git a/src/Object/Api/Mastodon/Attachment.php b/src/Object/Api/Mastodon/Attachment.php index c3871be795..e3d7600f16 100644 --- a/src/Object/Api/Mastodon/Attachment.php +++ b/src/Object/Api/Mastodon/Attachment.php @@ -47,26 +47,26 @@ class Attachment extends BaseDataTransferObject */ public function __construct(array $attachment, string $type, string $url, string $preview, string $remote) { - $this->id = (string)$attachment['id']; - $this->type = $type; - $this->url = $url; + $this->id = (string)$attachment['id']; + $this->type = $type; + $this->url = $url; $this->preview_url = $preview; - $this->remote_url = $remote; - $this->text_url = $this->remote_url ?? $this->url; + $this->remote_url = $remote; + $this->text_url = $this->remote_url ?? $this->url; $this->description = $attachment['description']; - $this->blurhash = $attachment['blurhash']; + $this->blurhash = $attachment['blurhash']; if ($type === 'image') { if ((int) $attachment['width'] > 0 && (int) $attachment['height'] > 0) { - $this->meta['original']['width'] = (int) $attachment['width']; + $this->meta['original']['width'] = (int) $attachment['width']; $this->meta['original']['height'] = (int) $attachment['height']; - $this->meta['original']['size'] = (int) $attachment['width'] . 'x' . (int) $attachment['height']; + $this->meta['original']['size'] = (int) $attachment['width'] . 'x' . (int) $attachment['height']; $this->meta['original']['aspect'] = (float) ((int) $attachment['width'] / (int) $attachment['height']); } if (isset($attachment['preview-width']) && (int) $attachment['preview-width'] > 0 && (int) $attachment['preview-height'] > 0) { - $this->meta['small']['width'] = (int) $attachment['preview-width']; + $this->meta['small']['width'] = (int) $attachment['preview-width']; $this->meta['small']['height'] = (int) $attachment['preview-height']; - $this->meta['small']['size'] = (int) $attachment['preview-width'] . 'x' . (int) $attachment['preview-height']; + $this->meta['small']['size'] = (int) $attachment['preview-width'] . 'x' . (int) $attachment['preview-height']; $this->meta['small']['aspect'] = (float) ((int) $attachment['preview-width'] / (int) $attachment['preview-height']); } } diff --git a/src/Object/Post.php b/src/Object/Post.php index 37b530b679..aafe1b305b 100644 --- a/src/Object/Post.php +++ b/src/Object/Post.php @@ -33,31 +33,31 @@ use InvalidArgumentException; */ class Post { - private $data = []; - private $template = null; + private $data = []; + private $template = null; private $available_templates = [ - 'wall' => 'wall_thread.tpl', + 'wall' => 'wall_thread.tpl', 'wall2wall' => 'wallwall_thread.tpl' ]; private $comment_box_template = 'comment_item.tpl'; - private $toplevel = false; - private $writable = false; + private $toplevel = false; + private $writable = false; /** * @var Post[] */ private $children = []; - private $parent = null; + private $parent = null; /** * @var Thread */ - private $thread = null; + private $thread = null; private $redirect_url = null; - private $owner_url = ''; - private $owner_name = ''; + private $owner_url = ''; + private $owner_name = ''; private $wall_to_wall = false; - private $threaded = false; - private $visiting = false; + private $threaded = false; + private $visiting = false; /** * Constructor @@ -76,7 +76,7 @@ class Post } $this->writable = $this->getDataValue('writable') || $this->getDataValue('self'); - $author = [ + $author = [ 'uid' => 0, 'id' => $this->getDataValue('author-id'), 'network' => $this->getDataValue('author-network'), @@ -104,7 +104,7 @@ class Post } $item['pagedrop'] = $data['pagedrop']; - $child = new Post($item); + $child = new Post($item); $this->addChild($child); } } @@ -153,7 +153,7 @@ class Post */ public function getTemplateData(array $conv_responses, string $formSecurityToken, int $thread_level = 1, array $thread_parent = []) { - $item = $this->getData(); + $item = $this->getData(); $edited = false; /* @@ -177,16 +177,16 @@ class Post 'share' => null, 'announce' => null, ]; - $dropping = false; - $pinned = ''; - $pin = false; - $star = false; - $ignore_thread = false; - $ispinned = 'unpinned'; - $isstarred = 'unstarred'; - $indent = ''; - $shiny = ''; - $osparkle = ''; + $dropping = false; + $pinned = ''; + $pin = false; + $star = false; + $ignore_thread = false; + $ispinned = 'unpinned'; + $isstarred = 'unstarred'; + $indent = ''; + $shiny = ''; + $osparkle = ''; $total_children = $item['counts'] ?? $this->countDescendants(); $conv = $this->getThread(); @@ -257,8 +257,8 @@ class Post $drop = [ 'dropping' => $dropping, 'pagedrop' => $item['pagedrop'], - 'select' => DI::l10n()->t('Select'), - 'label' => $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally'), + 'select' => DI::l10n()->t('Select'), + 'label' => $origin ? DI::l10n()->t('Delete globally') : DI::l10n()->t('Remove locally'), ]; } @@ -322,7 +322,7 @@ class Post $response_verbs = ['like', 'dislike', 'announce', 'comment']; $isevent = false; - $attend = []; + $attend = []; if ($item['object-type'] === Activity\ObjectType::EVENT) { $response_verbs[] = 'attendyes'; $response_verbs[] = 'attendno'; @@ -330,7 +330,7 @@ class Post if ($conv->isWritable()) { $isevent = true; - $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')]; + $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')]; } } @@ -407,7 +407,7 @@ class Post 'toggle' => DI::l10n()->t('Toggle pin status'), 'classdo' => $item['featured'] ? 'hidden' : '', 'classundo' => $item['featured'] ? '' : 'hidden', - 'pinned' => DI::l10n()->t('Pinned'), + 'pinned' => DI::l10n()->t('Pinned'), ]; } @@ -430,7 +430,7 @@ class Post $buttons['share'] = [DI::l10n()->t('Quote share this'), DI::l10n()->t('Quote Share')]; } if ($announceable) { - $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')]; + $buttons['announce'] = [DI::l10n()->t('Reshare this'), DI::l10n()->t('Reshare')]; $buttons['unannounce'] = [DI::l10n()->t('Cancel your Reshare'), DI::l10n()->t('Unshare')]; } } @@ -463,7 +463,7 @@ class Post } $isevent = false; - $tagger = ''; + $tagger = ''; } if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) { @@ -472,7 +472,7 @@ class Post $tags = Tag::populateFromItem($item); - $ago = Temporal::getRelativeDate($item['created']); + $ago = Temporal::getRelativeDate($item['created']); $ago_received = Temporal::getRelativeDate($item['received']); if (DI::config()->get('system', 'show_received') && (abs(strtotime($item['created']) - strtotime($item['received'])) > DI::config()->get('system', 'show_received_seconds')) && ($ago != $ago_received)) { $ago = DI::l10n()->t('%s (Received %s)', $ago, $ago_received); @@ -486,7 +486,7 @@ class Post ]; // Ensure to either display the remote comment or the local activities - $buttons = []; + $buttons = []; $comment_html = ''; } else { $remote_comment = ''; @@ -513,109 +513,109 @@ class Post $parent_unknown = $parent_username ? '' : DI::l10n()->t('Unknown parent'); $tmp_item = [ - 'parentguid' => $parent_guid, - 'inreplyto' => DI::l10n()->t('in reply to %s', $parent_username), - 'isunknown' => $parent_unknown, - 'isunknown_label' => DI::l10n()->t('Parent is probably private or not federated.'), - 'template' => $this->getTemplate(), - 'type' => implode('', array_slice(explode('/', $item['verb']), -1)), + 'parentguid' => $parent_guid, + 'inreplyto' => DI::l10n()->t('in reply to %s', $parent_username), + 'isunknown' => $parent_unknown, + 'isunknown_label' => DI::l10n()->t('Parent is probably private or not federated.'), + 'template' => $this->getTemplate(), + 'type' => implode('', array_slice(explode('/', $item['verb']), -1)), 'comment_firstcollapsed' => false, - 'comment_lastcollapsed' => false, - 'suppress_tags' => DI::config()->get('system', 'suppress_tags'), - 'tags' => $tags['tags'], - 'hashtags' => $tags['hashtags'], - 'mentions' => $tags['mentions'], - 'implicit_mentions' => $tags['implicit_mentions'], - 'txt_cats' => DI::l10n()->t('Categories:'), - 'txt_folders' => DI::l10n()->t('Filed under:'), - 'has_cats' => ((count($categories)) ? 'true' : ''), - 'has_folders' => ((count($folders)) ? 'true' : ''), - 'categories' => $categories, - 'folders' => $folders, - 'body_html' => $body_html, - 'text' => strip_tags($body_html), - 'id' => $this->getId(), - 'guid' => urlencode($item['guid']), - 'isevent' => $isevent, - 'attend' => $attend, - 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']), - 'olinktitle' => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']), - 'to' => DI::l10n()->t('to'), - 'via' => DI::l10n()->t('via'), - 'wall' => DI::l10n()->t('Wall-to-Wall'), - 'vwall' => DI::l10n()->t('via Wall-To-Wall:'), - 'profile_url' => $profile_link, - 'name' => $profile_name, - 'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken), - 'thumb' => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)), - 'osparkle' => $osparkle, - 'sparkle' => $sparkle, - 'title' => $item['title'], - 'summary' => $item['content-warning'], - 'localtime' => DateTimeFormat::local($item['created'], 'r'), - 'ago' => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago, - 'app' => $item['app'], - 'created' => $ago, - 'lock' => $lock, - 'private' => $item['private'], - 'privacy' => $privacy, - 'connector' => $connector, - 'location_html' => $location_html, - 'indent' => $indent, - 'shiny' => $shiny, - 'owner_self' => $item['author-link'] == DI::session()->get('my_url'), - 'owner_url' => $this->getOwnerUrl(), - 'owner_photo' => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)), - 'owner_name' => $this->getOwnerName(), - 'plink' => Item::getPlink($item), - 'browsershare' => $browsershare, - 'edpost' => $edpost, - 'ispinned' => $ispinned, - 'pin' => $pin, - 'pinned' => $pinned, - 'isstarred' => $isstarred, - 'star' => $star, - 'ignore' => $ignore_thread, - 'tagger' => $tagger, - 'filer' => $filer, - 'language' => $languages, - 'searchtext' => DI::l10n()->t('Search Text'), - 'drop' => $drop, - 'block' => $block, - 'ignore_author' => $ignore, - 'collapse' => $collapse, - 'report' => $report, - 'ignore_server' => $ignoreServer, - 'vote' => $buttons, - 'like_html' => $responses['like']['output'], - 'dislike_html' => $responses['dislike']['output'], - 'hide_dislike' => $hide_dislike, - 'emojis' => $emojis, - 'quoteshares' => $this->getQuoteShares($item['quoteshares']), - 'reactions' => $reactions, - 'responses' => $responses, - 'legacy_activities' => DI::config()->get('system', 'legacy_activities'), - 'switchcomment' => DI::l10n()->t('Comment'), - 'reply_label' => DI::l10n()->t('Reply to %s', $profile_name), - 'comment_html' => $comment_html, - 'remote_comment' => $remote_comment, - 'menu' => DI::l10n()->t('More'), - 'previewing' => $conv->isPreview() ? ' preview ' : '', - 'wait' => DI::l10n()->t('Please wait'), - 'thread_level' => $thread_level, - 'edited' => $edited, - 'author_gsid' => $item['author-gsid'], - 'network' => $item['network'], - 'network_name' => ContactSelector::networkToName($item['author-network'], $item['network'], $item['author-gsid']), - 'network_svg' => ContactSelector::networkToSVG($item['network'], $item['author-gsid'], '', DI::userSession()->getLocalUserId()), - 'received' => $item['received'], - 'commented' => $item['commented'], - 'created_date' => $item['created'], - 'uriid' => $item['uri-id'], - 'return' => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '', - 'direction' => $direction, - 'reshared' => $item['reshared'] ?? '', - 'delivery' => [ + 'comment_lastcollapsed' => false, + 'suppress_tags' => DI::config()->get('system', 'suppress_tags'), + 'tags' => $tags['tags'], + 'hashtags' => $tags['hashtags'], + 'mentions' => $tags['mentions'], + 'implicit_mentions' => $tags['implicit_mentions'], + 'txt_cats' => DI::l10n()->t('Categories:'), + 'txt_folders' => DI::l10n()->t('Filed under:'), + 'has_cats' => ((count($categories)) ? 'true' : ''), + 'has_folders' => ((count($folders)) ? 'true' : ''), + 'categories' => $categories, + 'folders' => $folders, + 'body_html' => $body_html, + 'text' => strip_tags($body_html), + 'id' => $this->getId(), + 'guid' => urlencode($item['guid']), + 'isevent' => $isevent, + 'attend' => $attend, + 'linktitle' => DI::l10n()->t('View %s\'s profile @ %s', $profile_name, $item['author-link']), + 'olinktitle' => DI::l10n()->t('View %s\'s profile @ %s', $this->getOwnerName(), $item['owner-link']), + 'to' => DI::l10n()->t('to'), + 'via' => DI::l10n()->t('via'), + 'wall' => DI::l10n()->t('Wall-to-Wall'), + 'vwall' => DI::l10n()->t('via Wall-To-Wall:'), + 'profile_url' => $profile_link, + 'name' => $profile_name, + 'item_photo_menu_html' => DI::contentItem()->photoMenu($item, $formSecurityToken), + 'thumb' => DI::baseUrl()->remove(DI::contentItem()->getAuthorAvatar($item)), + 'osparkle' => $osparkle, + 'sparkle' => $sparkle, + 'title' => $item['title'], + 'summary' => $item['content-warning'], + 'localtime' => DateTimeFormat::local($item['created'], 'r'), + 'ago' => $item['app'] ? DI::l10n()->t('%s from %s', $ago, $item['app']) : $ago, + 'app' => $item['app'], + 'created' => $ago, + 'lock' => $lock, + 'private' => $item['private'], + 'privacy' => $privacy, + 'connector' => $connector, + 'location_html' => $location_html, + 'indent' => $indent, + 'shiny' => $shiny, + 'owner_self' => $item['author-link'] == DI::session()->get('my_url'), + 'owner_url' => $this->getOwnerUrl(), + 'owner_photo' => DI::baseUrl()->remove(DI::contentItem()->getOwnerAvatar($item)), + 'owner_name' => $this->getOwnerName(), + 'plink' => Item::getPlink($item), + 'browsershare' => $browsershare, + 'edpost' => $edpost, + 'ispinned' => $ispinned, + 'pin' => $pin, + 'pinned' => $pinned, + 'isstarred' => $isstarred, + 'star' => $star, + 'ignore' => $ignore_thread, + 'tagger' => $tagger, + 'filer' => $filer, + 'language' => $languages, + 'searchtext' => DI::l10n()->t('Search Text'), + 'drop' => $drop, + 'block' => $block, + 'ignore_author' => $ignore, + 'collapse' => $collapse, + 'report' => $report, + 'ignore_server' => $ignoreServer, + 'vote' => $buttons, + 'like_html' => $responses['like']['output'], + 'dislike_html' => $responses['dislike']['output'], + 'hide_dislike' => $hide_dislike, + 'emojis' => $emojis, + 'quoteshares' => $this->getQuoteShares($item['quoteshares']), + 'reactions' => $reactions, + 'responses' => $responses, + 'legacy_activities' => DI::config()->get('system', 'legacy_activities'), + 'switchcomment' => DI::l10n()->t('Comment'), + 'reply_label' => DI::l10n()->t('Reply to %s', $profile_name), + 'comment_html' => $comment_html, + 'remote_comment' => $remote_comment, + 'menu' => DI::l10n()->t('More'), + 'previewing' => $conv->isPreview() ? ' preview ' : '', + 'wait' => DI::l10n()->t('Please wait'), + 'thread_level' => $thread_level, + 'edited' => $edited, + 'author_gsid' => $item['author-gsid'], + 'network' => $item['network'], + 'network_name' => ContactSelector::networkToName($item['author-network'], $item['network'], $item['author-gsid']), + 'network_svg' => ContactSelector::networkToSVG($item['network'], $item['author-gsid'], '', DI::userSession()->getLocalUserId()), + 'received' => $item['received'], + 'commented' => $item['commented'], + 'created_date' => $item['created'], + 'uriid' => $item['uri-id'], + 'return' => (DI::args()->getCommand()) ? bin2hex(DI::args()->getCommand()) : '', + 'direction' => $direction, + 'reshared' => $item['reshared'] ?? '', + 'delivery' => [ 'queue_count' => $item['delivery_queue_count'], 'queue_done' => $item['delivery_queue_done'] + $item['delivery_queue_failed'], /// @todo Possibly display it separately in the future 'notifier_pending' => DI::l10n()->t('Notifier task is pending'), @@ -632,21 +632,21 @@ class Post $result = $arr['output']; $result['children'] = []; - $children = $this->getChildren(); - $nb_children = count($children); + $children = $this->getChildren(); + $nb_children = count($children); if ($nb_children > 0) { $thread_parent[$item['uri-id']] = ['guid' => $item['guid'], 'name' => $item['author-name']]; foreach ($children as $child) { $thread_parent[$child->getDataValue('uri-id')] = ['guid' => $child->getDataValue('guid'), 'name' => $child->getDataValue('author-name')]; - $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1, $thread_parent); + $result['children'][] = $child->getTemplateData($conv_responses, $formSecurityToken, $thread_level + 1, $thread_parent); } // Collapse if (($nb_children > 2) || ($thread_level > 1)) { $result['children'][0]['comment_firstcollapsed'] = true; - $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children); - $result['children'][0]['show_text'] = DI::l10n()->t('Show more'); - $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer'); + $result['children'][0]['num_comments'] = DI::l10n()->tt('%d comment', '%d comments', $total_children); + $result['children'][0]['show_text'] = DI::l10n()->t('Show more'); + $result['children'][0]['hide_text'] = DI::l10n()->t('Show fewer'); if ($thread_level > 1) { $result['children'][$nb_children - 1]['comment_lastcollapsed'] = true; } else { @@ -1022,7 +1022,7 @@ class Post private function countDescendants(): int { $children = $this->getChildren(); - $total = count($children); + $total = count($children); if ($total > 0) { foreach ($children as $child) { $total += $child->countDescendants(); @@ -1055,7 +1055,7 @@ class Post } $owner = User::getOwnerDataById(DI::userSession()->getLocalUserId()); - $item = $this->getData(); + $item = $this->getData(); if (!empty($item['content-warning']) && Feature::isEnabled(DI::userSession()->getLocalUserId(), Feature::ADD_ABSTRACT)) { $text = '[abstract=' . Protocol::ACTIVITYPUB . ']' . $item['content-warning'] . "[/abstract]\n"; @@ -1102,7 +1102,7 @@ class Post private function getCommentBox(string $indent) { $comment_box = ''; - $conv = $this->getThread(); + $conv = $this->getThread(); if ($conv->isWritable() && $this->isWritable()) { /* @@ -1111,12 +1111,12 @@ class Post */ $qcomment = null; if (Addon::isEnabled('qcomment')) { - $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); + $words = DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'qcomment', 'words'); $qcomment = $words ? explode("\n", $words) : []; } // Fetch the user id from the parent when the owner user is empty - $uid = $conv->getProfileOwner(); + $uid = $conv->getProfileOwner(); $parent_uid = $this->getDataValue('uid'); $owner = User::getOwnerDataById(DI::userSession()->getLocalUserId()); @@ -1127,7 +1127,7 @@ class Post $uid = $parent_uid; } - $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate()); + $template = Renderer::getMarkupTemplate($this->getCommentBoxTemplate()); $comment_box = Renderer::replaceMacros($template, [ '$return_path' => DI::args()->getQueryString(), '$threaded' => $this->isThreaded(), @@ -1180,7 +1180,7 @@ class Post */ protected function checkWallToWall() { - $conv = $this->getThread(); + $conv = $this->getThread(); $this->wall_to_wall = false; if ($this->isToplevel()) { @@ -1200,7 +1200,7 @@ class Post * well that it's the same Bob Smith. * But it could be somebody else with the same name. It just isn't highly likely. */ - $this->owner_name = $this->getDataValue('owner-name'); + $this->owner_name = $this->getDataValue('owner-name'); $this->wall_to_wall = true; $owner = [ @@ -1218,7 +1218,7 @@ class Post if (!$this->wall_to_wall) { $this->setTemplate('wall'); - $this->owner_url = ''; + $this->owner_url = ''; $this->owner_name = ''; } } diff --git a/src/Object/Thread.php b/src/Object/Thread.php index 88534f2918..453e4c3421 100644 --- a/src/Object/Thread.php +++ b/src/Object/Thread.php @@ -21,11 +21,11 @@ use Friendica\Security\Security; class Thread { /** @var Post[] */ - private $parents = []; - private $mode = null; - private $writable = false; + private $parents = []; + private $mode = null; + private $writable = false; private $profile_owner = 0; - private $preview = false; + private $preview = false; /** * Constructor @@ -62,18 +62,18 @@ class Thread case Conversation::MODE_NETWORK: case Conversation::MODE_NOTES: $this->profile_owner = DI::userSession()->getLocalUserId(); - $this->writable = true; + $this->writable = true; break; case Conversation::MODE_PROFILE: case Conversation::MODE_DISPLAY: $this->profile_owner = $appHelper->getProfileOwner(); - $this->writable = Security::canWriteToUserWall($this->profile_owner) || $writable; + $this->writable = Security::canWriteToUserWall($this->profile_owner) || $writable; break; case Conversation::MODE_CHANNEL: case Conversation::MODE_COMMUNITY: case Conversation::MODE_CONTACTS: $this->profile_owner = 0; - $this->writable = $writable; + $this->writable = $writable; break; default: DI::logger()->info('[ERROR] Conversation::setMode : Unhandled mode ('. $mode .').'); diff --git a/src/Protocol/ActivityPub.php b/src/Protocol/ActivityPub.php index 9bef5479cd..405d230341 100644 --- a/src/Protocol/ActivityPub.php +++ b/src/Protocol/ActivityPub.php @@ -47,28 +47,28 @@ use Friendica\Util\JsonLD; class ActivityPub { const PUBLIC_COLLECTION = 'https://www.w3.org/ns/activitystreams#Public'; - const CONTEXT = [ + const CONTEXT = [ 'https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1', [ - 'ostatus' => 'http://ostatus.org#', - 'vcard' => 'http://www.w3.org/2006/vcard/ns#', - 'dfrn' => 'http://purl.org/macgirvin/dfrn/1.0/', + 'ostatus' => 'http://ostatus.org#', + 'vcard' => 'http://www.w3.org/2006/vcard/ns#', + 'dfrn' => 'http://purl.org/macgirvin/dfrn/1.0/', 'diaspora' => 'https://diasporafoundation.org/ns/', - 'litepub' => 'http://litepub.social/ns#', - 'toot' => 'http://joinmastodon.org/ns#', + 'litepub' => 'http://litepub.social/ns#', + 'toot' => 'http://joinmastodon.org/ns#', 'featured' => [ - "@id" => "toot:featured", + "@id" => "toot:featured", "@type" => "@id", ], - 'schema' => 'http://schema.org#', + 'schema' => 'http://schema.org#', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers', - 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag', - 'quoteUrl' => 'as:quoteUrl', - 'conversation' => 'ostatus:conversation', - 'directMessage' => 'litepub:directMessage', - 'discoverable' => 'toot:discoverable', - 'PropertyValue' => 'schema:PropertyValue', - 'value' => 'schema:value', + 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag', + 'quoteUrl' => 'as:quoteUrl', + 'conversation' => 'ostatus:conversation', + 'directMessage' => 'litepub:directMessage', + 'discoverable' => 'toot:discoverable', + 'PropertyValue' => 'schema:PropertyValue', + 'value' => 'schema:value', ] ]; const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application', 'Tombstone']; @@ -142,35 +142,35 @@ class ActivityPub return []; } - $profile = ['network' => Protocol::ACTIVITYPUB]; - $profile['nick'] = $apcontact['nick']; - $profile['name'] = $apcontact['name']; - $profile['guid'] = $apcontact['uuid']; - $profile['url'] = $apcontact['url']; - $profile['addr'] = $apcontact['addr']; - $profile['alias'] = $apcontact['alias']; - $profile['following'] = $apcontact['following']; - $profile['followers'] = $apcontact['followers']; - $profile['inbox'] = $apcontact['inbox']; - $profile['outbox'] = $apcontact['outbox']; - $profile['sharedinbox'] = $apcontact['sharedinbox']; - $profile['photo'] = $apcontact['photo']; - $profile['header'] = $apcontact['header']; + $profile = ['network' => Protocol::ACTIVITYPUB]; + $profile['nick'] = $apcontact['nick']; + $profile['name'] = $apcontact['name']; + $profile['guid'] = $apcontact['uuid']; + $profile['url'] = $apcontact['url']; + $profile['addr'] = $apcontact['addr']; + $profile['alias'] = $apcontact['alias']; + $profile['following'] = $apcontact['following']; + $profile['followers'] = $apcontact['followers']; + $profile['inbox'] = $apcontact['inbox']; + $profile['outbox'] = $apcontact['outbox']; + $profile['sharedinbox'] = $apcontact['sharedinbox']; + $profile['photo'] = $apcontact['photo']; + $profile['header'] = $apcontact['header']; $profile['account-type'] = self::getAccountType($apcontact); - $profile['community'] = ($profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY); + $profile['community'] = ($profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY); // $profile['keywords'] // $profile['location'] - $profile['about'] = $apcontact['about']; - $profile['xmpp'] = $apcontact['xmpp']; - $profile['matrix'] = $apcontact['matrix']; - $profile['batch'] = $apcontact['sharedinbox']; - $profile['notify'] = $apcontact['inbox']; - $profile['poll'] = $apcontact['outbox']; - $profile['pubkey'] = $apcontact['pubkey']; - $profile['subscribe'] = $apcontact['subscribe']; + $profile['about'] = $apcontact['about']; + $profile['xmpp'] = $apcontact['xmpp']; + $profile['matrix'] = $apcontact['matrix']; + $profile['batch'] = $apcontact['sharedinbox']; + $profile['notify'] = $apcontact['inbox']; + $profile['poll'] = $apcontact['outbox']; + $profile['pubkey'] = $apcontact['pubkey']; + $profile['subscribe'] = $apcontact['subscribe']; $profile['manually-approve'] = $apcontact['manually-approve']; - $profile['baseurl'] = $apcontact['baseurl']; - $profile['gsid'] = $apcontact['gsid']; + $profile['baseurl'] = $apcontact['baseurl']; + $profile['gsid'] = $apcontact['gsid']; if (!is_null($apcontact['discoverable'])) { $profile['hide'] = !$apcontact['discoverable']; @@ -307,7 +307,7 @@ class ActivityPub $limited = DI::config()->get('system', 'limited_servers'); if (!empty($limited)) { $servers = explode(',', str_replace(' ', '', $limited)); - $host = parse_url($apcontact['baseurl'], PHP_URL_HOST); + $host = parse_url($apcontact['baseurl'], PHP_URL_HOST); if (!empty($host) && in_array($host, $servers)) { return false; } diff --git a/src/Protocol/ActivityPub/ClientToServer.php b/src/Protocol/ActivityPub/ClientToServer.php index c95732d3b9..cab58075f0 100644 --- a/src/Protocol/ActivityPub/ClientToServer.php +++ b/src/Protocol/ActivityPub/ClientToServer.php @@ -250,7 +250,7 @@ class ClientToServer $item['uid'] = $uid; $item['verb'] = Activity::POST; $item['contact-id'] = $owner['id']; - $item['author-id'] = $item['owner-id'] = Contact::getPublicIdByUserId($uid); + $item['author-id'] = $item['owner-id'] = Contact::getPublicIdByUserId($uid); $item['title'] = $object_data['name']; $item['body'] = Markdown::toBBCode($object_data['content'] ?? ''); $item['app'] = $application['name'] ?? 'API'; @@ -322,8 +322,10 @@ class ClientToServer if (!empty($requester_id)) { $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']); if (count($permissionSets) > 0) { - $condition = ['psid' => array_merge($permissionSets->column('id'), - [DI::permissionSet()->selectPublicForUser($owner['uid'])])]; + $condition = ['psid' => array_merge( + $permissionSets->column('id'), + [DI::permissionSet()->selectPublicForUser($owner['uid'])] + )]; } } } diff --git a/src/Protocol/ActivityPub/Delivery.php b/src/Protocol/ActivityPub/Delivery.php index 865d962d4a..9e243ed1c6 100644 --- a/src/Protocol/ActivityPub/Delivery.php +++ b/src/Protocol/ActivityPub/Delivery.php @@ -115,7 +115,7 @@ class Delivery } else { $data = ActivityPub\Transmitter::createCachedActivityFromItem($item_id); if (!empty($data)) { - $timestamp = microtime(true); + $timestamp = microtime(true); try { $response = HTTPSignature::post($data, $inbox, $owner); $success = $response->isSuccess(); @@ -150,7 +150,7 @@ class Delivery // Resubscribe to relay server upon client error if (!$serverfail && ($response->getReturnCode() >= 400) && ($response->getReturnCode() <= 499)) { - $actor = self:: fetchActorForRelayInbox($inbox); + $actor = self::fetchActorForRelayInbox($inbox); if (!empty($actor)) { $drop = !ActivityPub\Transmitter::sendRelayFollow($actor); DI::logger()->notice('Resubscribed to relay', ['url' => $actor, 'success' => !$drop]); diff --git a/src/Protocol/ActivityPub/Processor.php b/src/Protocol/ActivityPub/Processor.php index 6cc401f05e..cc5fa584aa 100644 --- a/src/Protocol/ActivityPub/Processor.php +++ b/src/Protocol/ActivityPub/Processor.php @@ -93,7 +93,7 @@ class Processor private static function processLanguages(array $languages): string { $codes = array_keys($languages); - $lang = []; + $lang = []; foreach ($codes as $code) { $lang[$code] = 1; } @@ -145,15 +145,15 @@ class Processor return; } - $data = ['uri-id' => $uriid]; - $data['type'] = Post\Media::UNKNOWN; - $data['url'] = $attachment['url']; - $data['mimetype'] = $attachment['mediaType'] ?? null; - $data['height'] = $attachment['height'] ?? null; - $data['width'] = $attachment['width'] ?? null; - $data['size'] = $attachment['size'] ?? null; - $data['preview'] = $attachment['image'] ?? null; - $data['description'] = $attachment['name'] ?? null; + $data = ['uri-id' => $uriid]; + $data['type'] = Post\Media::UNKNOWN; + $data['url'] = $attachment['url']; + $data['mimetype'] = $attachment['mediaType'] ?? null; + $data['height'] = $attachment['height'] ?? null; + $data['width'] = $attachment['width'] ?? null; + $data['size'] = $attachment['size'] ?? null; + $data['preview'] = $attachment['image'] ?? null; + $data['description'] = $attachment['name'] ?? null; Post\Media::insert($data); } @@ -229,7 +229,7 @@ class Processor } $item['changed'] = DateTimeFormat::utcNow(); - $item['edited'] = DateTimeFormat::utc($activity['updated']); + $item['edited'] = DateTimeFormat::utc($activity['updated']); Post\Media::deleteByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE, Post\Media::HTML]); $item = self::processContent($activity, $item); @@ -265,11 +265,11 @@ class Processor { $event = DBA::selectFirst('event', [], ['id' => $event_id]); - $event['edited'] = DateTimeFormat::utc($activity['updated']); - $event['summary'] = HTML::toBBCode($activity['name']); - $event['desc'] = HTML::toBBCode($activity['content']); + $event['edited'] = DateTimeFormat::utc($activity['updated']); + $event['summary'] = HTML::toBBCode($activity['name']); + $event['desc'] = HTML::toBBCode($activity['content']); if (!empty($activity['start-time'])) { - $event['start'] = DateTimeFormat::utc($activity['start-time']); + $event['start'] = DateTimeFormat::utc($activity['start-time']); } if (!empty($activity['end-time'])) { $event['finish'] = DateTimeFormat::utc($activity['end-time']); @@ -294,15 +294,15 @@ class Processor */ public static function createItem(array $activity, bool $fetch_parents): array { - $item = []; - $item['verb'] = Activity::POST; + $item = []; + $item['verb'] = Activity::POST; $item['thr-parent'] = $activity['reply-to-id']; if ($activity['reply-to-id'] == $activity['id']) { - $item['gravity'] = Item::GRAVITY_PARENT; + $item['gravity'] = Item::GRAVITY_PARENT; $item['object-type'] = Activity\ObjectType::NOTE; } else { - $item['gravity'] = Item::GRAVITY_COMMENT; + $item['gravity'] = Item::GRAVITY_COMMENT; $item['object-type'] = Activity\ObjectType::COMMENT; } @@ -318,14 +318,14 @@ class Processor $conversation = Post::selectFirstThread(['uri'], ['context' => $item['context']]); if (!empty($conversation)) { DI::logger()->debug('Got context', ['context' => $item['context'], 'parent' => $conversation]); - $item['parent-uri'] = $conversation['uri']; + $item['parent-uri'] = $conversation['uri']; $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']); } } elseif (!empty($item['conversation'])) { $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]); if (!empty($conversation)) { DI::logger()->debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]); - $item['parent-uri'] = $conversation['uri']; + $item['parent-uri'] = $conversation['uri']; $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']); } } else { @@ -360,11 +360,11 @@ class Processor return []; } - $item['network'] = Protocol::ACTIVITYPUB; + $item['network'] = Protocol::ACTIVITYPUB; $item['author-link'] = $activity['author']; - $item['author-id'] = Contact::getIdForURL($activity['author']); - $item['owner-link'] = $activity['actor']; - $item['owner-id'] = Contact::getIdForURL($activity['actor']); + $item['author-id'] = Contact::getIdForURL($activity['author']); + $item['owner-link'] = $activity['actor']; + $item['owner-id'] = Contact::getIdForURL($activity['actor']); if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) { $item['private'] = Item::UNLISTED; @@ -412,7 +412,7 @@ class Processor if (!empty($activity['thread-completion'])) { if ($activity['thread-completion'] != $item['owner-id']) { - $actor = Contact::getById($activity['thread-completion'], ['url']); + $actor = Contact::getById($activity['thread-completion'], ['url']); $item['causer-link'] = $actor['url']; $item['causer-id'] = $activity['thread-completion']; DI::logger()->info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]); @@ -461,7 +461,7 @@ class Processor $item['causer-id'] = Contact::getIdForURL($item['causer-link']); } - $item['uri'] = $activity['id']; + $item['uri'] = $activity['id']; $item['sensitive'] = $activity['sensitive']; if (empty($activity['published']) || empty($activity['updated'])) { @@ -469,9 +469,9 @@ class Processor } $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now'); - $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now'); - $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']); - $item['guid'] = $activity['diaspora:guid'] ?: $guid; + $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now'); + $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']); + $item['guid'] = $activity['diaspora:guid'] ?: $guid; $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]); if (empty($item['uri-id'])) { @@ -525,7 +525,7 @@ class Processor $replies[] = $item['parent-uri']; } $condition = DBA::mergeConditions(['uri' => $replies], ["`replies-id` IS NOT NULL"]); - $posts = Post::select(['replies', 'replies-id'], $condition); + $posts = Post::select(['replies', 'replies-id'], $condition); while ($post = Post::fetch($posts)) { $cachekey = 'Processor-CreateItem-Replies-' . $post['replies-id']; if (!DI::cache()->get($cachekey)) { @@ -614,7 +614,7 @@ class Processor DI::logger()->notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]); Fetch::add($activity['reply-to-id']); $activity['recursion-depth'] = 0; - $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC); + $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC); Fetch::setWorkerId($activity['reply-to-id'], $wid); } else { DI::logger()->debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]); @@ -676,7 +676,7 @@ class Processor { $owner = Contact::getIdForURL($activity['actor']); - DI::logger()->info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]); + DI::logger()->info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]); Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]); Queue::remove($activity); } @@ -722,15 +722,15 @@ class Processor public static function createActivity(array $activity, string $verb) { $activity['reply-to-id'] = $activity['object_id']; - $item = self::createItem($activity, false); + $item = self::createItem($activity, false); if (empty($item)) { DI::logger()->debug('Activity was not prepared', ['id' => $activity['object_id']]); return; } - $item['verb'] = $verb; + $item['verb'] = $verb; $item['thr-parent'] = $activity['object_id']; - $item['gravity'] = Item::GRAVITY_ACTIVITY; + $item['gravity'] = Item::GRAVITY_ACTIVITY; unset($item['post-type']); $item['object-type'] = Activity\ObjectType::NOTE; @@ -830,10 +830,10 @@ class Processor */ public static function createEvent(array $activity, array $item): int { - $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']); - $event['desc'] = HTML::toBBCode($activity['content'] ?? ''); + $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']); + $event['desc'] = HTML::toBBCode($activity['content'] ?? ''); if (!empty($activity['start-time'])) { - $event['start'] = DateTimeFormat::utc($activity['start-time']); + $event['start'] = DateTimeFormat::utc($activity['start-time']); } if (!empty($activity['end-time'])) { $event['finish'] = DateTimeFormat::utc($activity['end-time']); @@ -876,17 +876,17 @@ class Processor { if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) { $item['title'] = strip_tags($activity['name'] ?? ''); - $content = Markdown::toBBCode($activity['content'] ?? ''); + $content = Markdown::toBBCode($activity['content'] ?? ''); } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) { - $item['title'] = $activity['name'] ?? ''; - $content = $activity['content'] ?? ''; + $item['title'] = $activity['name'] ?? ''; + $content = $activity['content'] ?? ''; } else { // By default assume "text/html" $item['title'] = HTML::toBBCode($activity['name'] ?? ''); - $content = HTML::toBBCode($activity['content'] ?? ''); + $content = HTML::toBBCode($activity['content'] ?? ''); } - $item['title'] = trim(BBCode::toPlaintext($item['title'])); + $item['title'] = trim(BBCode::toPlaintext($item['title'])); $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? ''); if (!empty($activity['languages'])) { @@ -904,7 +904,7 @@ class Processor if (!empty($activity['quote-url'])) { $id = Item::fetchByLink($activity['quote-url'], 0, ActivityPub\Receiver::COMPLETION_ASYNC); if ($id) { - $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]); + $shared_item = Post::selectFirst(['uri-id'], ['id' => $id]); $item['quote-uri-id'] = $shared_item['uri-id']; DI::logger()->debug('Quote is found', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'quote' => $activity['quote-url'], 'quote-uri-id' => $item['quote-uri-id']]); } elseif ($uri_id = ItemURI::getIdByURI($activity['quote-url'], false)) { @@ -919,7 +919,7 @@ class Processor } if (!empty($activity['source'])) { - $item['body'] = $activity['source']; + $item['body'] = $activity['source']; $item['raw-body'] = $content; $quote_uri_id = Item::getQuoteUriId($item['body']); @@ -1093,7 +1093,7 @@ class Processor return; } - $stored = false; + $stored = false; $success = false; ksort($activity['receiver']); @@ -1194,14 +1194,16 @@ class Processor if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE) && in_array($activity['thread-children-type'] ?? '', Receiver::ACTIVITY_TYPES)) { - DI::logger()->info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring', - ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]); + DI::logger()->info( + 'Top level post from thread completion from a non sharer had been initiated via an activity, ignoring', + ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']] + ); continue; } } $isGroup = false; - $user = User::getById($receiver, ['account-type']); + $user = User::getById($receiver, ['account-type']); if (!empty($user['account-type'])) { $isGroup = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY); } @@ -1310,7 +1312,7 @@ class Processor if (Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $receiver])) { $has_parents = true; } elseif ($add_parent && Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) { - $stored = Item::storeForUserByUriId($item['parent-uri-id'], $receiver, $fields); + $stored = Item::storeForUserByUriId($item['parent-uri-id'], $receiver, $fields); $has_parents = (bool)$stored; if ($stored) { DI::logger()->notice('Inserted missing parent post', ['stored' => $stored, 'uid' => $receiver, 'parent' => $item['parent-uri']]); @@ -1329,7 +1331,7 @@ class Processor if (Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $receiver])) { $has_parents = true; } elseif (($has_parents || $add_parent) && Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => 0])) { - $stored = Item::storeForUserByUriId($item['thr-parent-id'], $receiver, $fields); + $stored = Item::storeForUserByUriId($item['thr-parent-id'], $receiver, $fields); $has_parents = $has_parents || (bool)$stored; if ($stored) { DI::logger()->notice('Inserted missing thread parent post', ['stored' => $stored, 'uid' => $receiver, 'thread-parent' => $item['thr-parent']]); @@ -1462,23 +1464,23 @@ class Processor DI::logger()->info('Direct Message', $item); - $msg = []; + $msg = []; $msg['uid'] = $item['uid']; $msg['contact-id'] = $item['contact-id']; - $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']); - $msg['from-name'] = $contact['name']; - $msg['from-url'] = $contact['url']; + $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']); + $msg['from-name'] = $contact['name']; + $msg['from-url'] = $contact['url']; $msg['from-photo'] = $contact['photo']; - $msg['uri'] = $item['uri']; + $msg['uri'] = $item['uri']; $msg['created'] = $item['created']; $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]); if (DBA::isResult($parent)) { $msg['parent-uri'] = $parent['parent-uri']; - $msg['title'] = $parent['title']; + $msg['title'] = $parent['title']; } else { $msg['parent-uri'] = $item['thr-parent']; @@ -1587,7 +1589,7 @@ class Processor public static function fetchCachedActivity(string $url, int $uid): array { $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . hash('sha256', $url); - $object = DI::cache()->get($cachekey); + $object = DI::cache()->get($cachekey); if (!is_null($object)) { if (!empty($object)) { @@ -1709,7 +1711,7 @@ class Processor $signer[] = $object_actor; if (!empty($child['author'])) { - $actor = $child['author']; + $actor = $child['author']; $signer[] = $actor; } else { $actor = $object_actor; @@ -1740,7 +1742,7 @@ class Processor } $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 0; - $ldactivity['children'] = $child['children'] ?? []; + $ldactivity['children'] = $child['children'] ?? []; $ldactivity['callstack'] = $child['callstack'] ?? []; // This check is mostly superfluous, since there are similar checks before. This covers the case, when the fetched id doesn't match the url if (in_array($activity['id'], $ldactivity['children'])) { @@ -1801,7 +1803,7 @@ class Processor } } - $callstack = array_slice(array_column(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 'function'), 1); + $callstack = array_slice(array_column(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS), 'function'), 1); $system_count = 0; foreach ($callstack as $function) { if ($function == __FUNCTION__) { @@ -1829,7 +1831,7 @@ class Processor if (is_array($reply)) { $ldobject = JsonLD::compact($reply); - $id = JsonLD::fetchElement($ldobject, '@id'); + $id = JsonLD::fetchElement($ldobject, '@id'); if (Processor::alreadyKnown($id, $child['id'] ?? '')) { continue; } @@ -1915,7 +1917,7 @@ class Processor $actor = JsonLD::fetchElement($ldobject, 'as:actor', '@id'); $attributed_to = JsonLD::fetchElement($ldobject, 'as:attributedTo', '@id'); - $id_host = parse_url($id, PHP_URL_HOST); + $id_host = parse_url($id, PHP_URL_HOST); if (!empty($actor) && !in_array($type, Receiver::CONTENT_TYPES) && !empty($object_id)) { $actor_host = parse_url($actor, PHP_URL_HOST); @@ -1951,17 +1953,17 @@ class Processor $published = DateTimeFormat::utcNow(); } - $activity = []; + $activity = []; $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT; unset($object['@context']); - $activity['id'] = $object['id']; - $activity['to'] = $object['to'] ?? []; - $activity['cc'] = $object['cc'] ?? []; - $activity['audience'] = $object['audience'] ?? []; - $activity['actor'] = $actor; - $activity['object'] = $object; + $activity['id'] = $object['id']; + $activity['to'] = $object['to'] ?? []; + $activity['cc'] = $object['cc'] ?? []; + $activity['audience'] = $object['audience'] ?? []; + $activity['actor'] = $actor; + $activity['object'] = $object; $activity['published'] = $published; - $activity['type'] = 'Create'; + $activity['type'] = 'Create'; return $activity; } @@ -1983,16 +1985,16 @@ class Processor $id = JsonLD::fetchElement($activity, 'as:object', '@id'); $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id'); - $uriid = ItemURI::getIdByURI($replyto ?? ''); + $uriid = ItemURI::getIdByURI($replyto ?? ''); if (Post::exists(['uri-id' => $uriid])) { DI::logger()->info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]); return true; } $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id'); - $authorid = Contact::getIdForURL($attributed_to); + $authorid = Contact::getIdForURL($attributed_to); - $content = JsonLD::fetchElement($activity['as:object'], 'as:name', '@value') ?? ''; + $content = JsonLD::fetchElement($activity['as:object'], 'as:name', '@value') ?? ''; $content .= ' ' . JsonLD::fetchElement($activity['as:object'], 'as:summary', '@value') ?? ''; $content .= ' ' . HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? ''); @@ -2007,7 +2009,7 @@ class Processor } $messageTags = []; - $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []); + $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []); if (!empty($tags)) { foreach ($tags as $tag) { if (($tag['type'] != 'Hashtag') && !strpos($tag['type'], ':Hashtag') || empty($tag['name'])) { @@ -2047,13 +2049,13 @@ class Processor */ public static function getPostLanguages(array $activity): array { - $content = JsonLD::fetchElement($activity, 'as:content') ?? ''; + $content = JsonLD::fetchElement($activity, 'as:content') ?? ''; $languages = JsonLD::fetchElementArray($activity, 'as:content', '@language') ?? []; if (empty($languages)) { return []; } - $iso639 = new \Matriphe\ISO639\ISO639; + $iso639 = new \Matriphe\ISO639\ISO639(); $result = []; foreach ($languages as $language) { @@ -2097,7 +2099,7 @@ class Processor } $item = [ - 'author-id' => Contact::getIdForURL($activity['actor']), + 'author-id' => Contact::getIdForURL($activity['actor']), 'author-link' => $activity['actor'], ]; @@ -2134,7 +2136,7 @@ class Processor private static function transmitPendingEvents(int $cid, int $uid) { $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]); - $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox']; + $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox']; $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']); while ($event = DBA::fetch($events)) { @@ -2334,7 +2336,7 @@ class Processor $check_id = false; if (!empty($activity['object_actor'])) { - $uid = User::getIdForURL($activity['object_actor']); + $uid = User::getIdForURL($activity['object_actor']); } elseif (!empty($activity['receiver']) && (count($activity['receiver']) == 1)) { $uid = array_shift($activity['receiver']); $check_id = true; @@ -2610,9 +2612,9 @@ class Processor */ public static function addToCallstack(array $callstack): array { - $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $functions = array_slice(array_column($trace, 'function'), 1); - $function = array_shift($functions); + $function = array_shift($functions); if (in_array($function, $callstack)) { DI::logger()->notice('Callstack already contains "' . $function . '"', ['callstack' => $callstack]); diff --git a/src/Protocol/ActivityPub/Queue.php b/src/Protocol/ActivityPub/Queue.php index bf89363de7..ca6b692659 100644 --- a/src/Protocol/ActivityPub/Queue.php +++ b/src/Protocol/ActivityPub/Queue.php @@ -192,7 +192,7 @@ class Queue if (!empty($entry['wid'])) { $worker = DI::appHelper()->getQueue(); - $wid = $worker['id'] ?? 0; + $wid = $worker['id'] ?? 0; if ($entry['wid'] != $wid) { $workerqueue = DBA::selectFirst('workerqueue', ['pid'], ['id' => $entry['wid'], 'done' => false]); if (!empty($workerqueue['pid']) && posix_kill($workerqueue['pid'], 0)) { @@ -327,8 +327,8 @@ class Queue return false; } $activity['recursion-depth'] = 0; - $activity['callstack'] = Processor::addToCallstack($activity['callstack'] ?? []); - $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $entry['in-reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC); + $activity['callstack'] = Processor::addToCallstack($activity['callstack'] ?? []); + $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $entry['in-reply-to-id'], $activity, '', Receiver::COMPLETION_ASYNC); Fetch::setWorkerId($entry['in-reply-to-id'], $wid); DI::logger()->debug('Fetch missing activity', ['wid' => $wid, 'id' => $entry['activity-id'], 'reply-to-id' => $entry['in-reply-to-id']]); self::retrial($id); @@ -348,7 +348,7 @@ class Queue */ public static function processReplyByUri(string $uri, array $parent = []): int { - $count = 0; + $count = 0; $entries = DBA::select('inbox-entry', ['id'], ["`in-reply-to-id` = ? AND `object-id` != ?", $uri, $uri]); while ($entry = DBA::fetch($entries)) { $count += 1; diff --git a/src/Protocol/ActivityPub/Transmitter.php b/src/Protocol/ActivityPub/Transmitter.php index c183b5313b..a4446e5978 100644 --- a/src/Protocol/ActivityPub/Transmitter.php +++ b/src/Protocol/ActivityPub/Transmitter.php @@ -80,7 +80,7 @@ class Transmitter } foreach ($relays as $relay) { - $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']); + $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']); $inboxes[$relay['batch']][] = $contact['id'] ?? 0; } return $inboxes; @@ -100,7 +100,7 @@ class Transmitter } $activity_id = self::activityIDFromContact($contact['id']); - $success = self::sendActivity('Follow', $url, 0, $activity_id); + $success = self::sendActivity('Follow', $url, 0, $activity_id); if ($success) { Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]); } @@ -147,18 +147,18 @@ class Transmitter { if (empty($page)) { $cachekey = self::CACHEKEY_CONTACTS . $module . ':' . $owner['uid']; - $result = DI::cache()->get($cachekey); + $result = DI::cache()->get($cachekey); if (!$nocache && !is_null($result)) { return $result; } } $parameters = [ - 'rel' => $rel, - 'uid' => $owner['uid'], - 'self' => false, + 'rel' => $rel, + 'uid' => $owner['uid'], + 'self' => false, 'deleted' => false, - 'hidden' => false, + 'hidden' => false, 'archive' => false, 'pending' => false, 'blocked' => false, @@ -170,9 +170,9 @@ class Transmitter $modulePath = '/' . $module . '/'; - $data = ['@context' => ActivityPub::CONTEXT]; - $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname']; - $data['type'] = 'OrderedCollection'; + $data = ['@context' => ActivityPub::CONTEXT]; + $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname']; + $data['type'] = 'OrderedCollection'; $data['totalItems'] = $total; if (!empty($page)) { @@ -199,7 +199,7 @@ class Transmitter $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1'; } else { $data['type'] = 'OrderedCollectionPage'; - $list = []; + $list = []; $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]); while ($contact = DBA::fetch($contacts)) { @@ -238,7 +238,7 @@ class Transmitter { if (empty($page)) { $cachekey = self::CACHEKEY_FEATURED . $owner['uid']; - $result = DI::cache()->get($cachekey); + $result = DI::cache()->get($cachekey); if (!$nocache && !is_null($result)) { return $result; } @@ -252,7 +252,7 @@ class Transmitter ]; $condition = DBA::mergeConditions($condition, [ - 'uid' => $owner['uid'], + 'uid' => $owner['uid'], 'author-id' => $owner_cid, 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT], @@ -265,9 +265,9 @@ class Transmitter $count = Post::count($condition); - $data = ['@context' => ActivityPub::CONTEXT]; - $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname']; - $data['type'] = 'OrderedCollection'; + $data = ['@context' => ActivityPub::CONTEXT]; + $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname']; + $data['type'] = 'OrderedCollection'; $data['totalItems'] = $count; if (!empty($page)) { @@ -278,7 +278,7 @@ class Transmitter $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]); } else { $data['type'] = 'OrderedCollectionPage'; - $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]); + $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]); } $list = []; @@ -317,7 +317,7 @@ class Transmitter return [ 'id' => (string)DI::baseUrl() . '/friendica', 'type' => 'Application', - 'name' => App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION, + 'name' => App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION, 'url' => (string)DI::baseUrl(), ]; } @@ -339,7 +339,7 @@ class Transmitter throw new HTTPException\NotFoundException('User not found.'); } - $data = ['@context' => ActivityPub::CONTEXT]; + $data = ['@context' => ActivityPub::CONTEXT]; $data['id'] = $owner['url']; if (!empty($owner['guid'])) { @@ -360,11 +360,11 @@ class Transmitter } $data['preferredUsername'] = $owner['nick']; - $data['name'] = $full ? $owner['name'] : $owner['nick']; + $data['name'] = $full ? $owner['name'] : $owner['nick']; if ($full && !empty($owner['country-name'] . $owner['region'] . $owner['locality'])) { $data['vcard:hasAddress'] = [ - '@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'], + '@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'], 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality'] ]; } @@ -384,12 +384,12 @@ class Transmitter } } - $data['url'] = $owner['url']; + $data['url'] = $owner['url']; $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]); - $data['discoverable'] = (bool)$owner['net-publish'] && $full; - $data['publicKey'] = [ - 'id' => $owner['url'] . '#main-key', - 'owner' => $owner['url'], + $data['discoverable'] = (bool)$owner['net-publish'] && $full; + $data['publicKey'] = [ + 'id' => $owner['url'] . '#main-key', + 'owner' => $owner['url'], 'publicKeyPem' => $owner['pubkey'] ]; $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox']; @@ -420,8 +420,8 @@ class Transmitter foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) { $custom_fields[] = [ - 'type' => 'PropertyValue', - 'name' => $profile_field->label, + 'type' => 'PropertyValue', + 'name' => $profile_field->label, 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value) ]; }; @@ -446,7 +446,7 @@ class Transmitter private static function getActorArrayByCid(int $cid): array { $contact = Contact::getById($cid); - $data = [ + $data = [ 'id' => $contact['url'], 'type' => $data['type'] = ActivityPub::ACCOUNT_TYPES[$contact['contact-type']], 'url' => $contact['alias'], @@ -473,12 +473,12 @@ class Transmitter public static function getDeletedUser(string $username): array { return [ - '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/profile/' . $username, - 'type' => 'Tombstone', + '@context' => ActivityPub::CONTEXT, + 'id' => DI::baseUrl() . '/profile/' . $username, + 'type' => 'Tombstone', 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), - 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), - 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), + 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), + 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), ]; } @@ -513,7 +513,7 @@ class Transmitter $parent_profile = APContact::getByURL($parent['author-link']); $item_profile = APContact::getByURL($item['author-link']); - $exclude[] = $item['author-link']; + $exclude[] = $item['author-link']; if ($item['gravity'] == Item::GRAVITY_PARENT) { $exclude[] = $item['owner-link']; @@ -591,7 +591,7 @@ class Transmitter $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]); if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) { - $profile = APContact::getByURL($parent['causer-link'], false); + $profile = APContact::getByURL($parent['causer-link'], false); $is_group_thread = isset($profile['type']) && $profile['type'] == 'Group'; } else { $is_group_thread = false; @@ -607,7 +607,7 @@ class Transmitter } $profile = APContact::getByURL($tag['url'], false); if (!empty($profile) && ($profile['type'] == 'Group')) { - $audience[] = $tag['url']; + $audience[] = $tag['url']; $is_group_thread = true; } } @@ -798,7 +798,7 @@ class Transmitter } if (!empty($item['quote-uri-id']) && in_array($item['private'], [Item::PUBLIC, Item::UNLISTED])) { - $quoted = Post::selectFirst(['author-link'], ['uri-id' => $item['quote-uri-id']]); + $quoted = Post::selectFirst(['author-link'], ['uri-id' => $item['quote-uri-id']]); $profile = APContact::getByURL($quoted['author-link'], false); if (!empty($profile)) { $data['cc'][] = $profile['url']; @@ -982,12 +982,12 @@ class Transmitter public static function fetchTargetInboxesforUser(int $uid): array { $condition = [ - 'uid' => $uid, - 'self' => false, - 'archive' => false, - 'pending' => false, - 'blocked' => false, - 'network' => Protocol::FEDERATED, + 'uid' => $uid, + 'self' => false, + 'archive' => false, + 'pending' => false, + 'blocked' => false, + 'network' => Protocol::FEDERATED, ]; if (!empty($uid)) { @@ -1149,7 +1149,7 @@ class Transmitter $mail['content-warning'] = $mail['title']; $mail['title'] = ''; } else { - $mail['content-warning'] = ''; + $mail['content-warning'] = ''; } $mail['sensitive'] = false; $mail['author-link'] = $mail['owner-link'] = $mail['from-url']; @@ -1196,12 +1196,12 @@ class Transmitter $data = []; } - $data['id'] = $mail['uri'] . '/Create'; - $data['type'] = 'Create'; - $data['actor'] = $mail['author-link']; - $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM); + $data['id'] = $mail['uri'] . '/Create'; + $data['type'] = 'Create'; + $data['actor'] = $mail['author-link']; + $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM); $data['instrument'] = self::getService(); - $data = array_merge($data, self::createPermissionBlockForItem($mail, true)); + $data = array_merge($data, self::createPermissionBlockForItem($mail, true)); if (empty($data['to']) && !empty($data['cc'])) { $data['to'] = $data['cc']; @@ -1215,7 +1215,7 @@ class Transmitter unset($data['bcc']); unset($data['audience']); - $object['to'] = $data['to']; + $object['to'] = $data['to']; $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']]; unset($object['cc']); @@ -1403,7 +1403,8 @@ class Transmitter } if ($type == 'Delete') { - $data['id'] = Item::newURI($item['guid']) . '/' . $type;; + $data['id'] = Item::newURI($item['guid']) . '/' . $type; + ; } elseif (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($type != 'Undo')) { $data['id'] = $item['uri']; } else { @@ -1439,7 +1440,7 @@ class Transmitter } elseif ($data['type'] == 'Announce') { if ($item['verb'] == ACTIVITY::ANNOUNCE) { if ($announce_activity) { - $anounced_item = Post::selectFirst(['uid'], ['uri-id' => $item['thr-parent-id'], 'origin' => true]); + $anounced_item = Post::selectFirst(['uid'], ['uri-id' => $item['thr-parent-id'], 'origin' => true]); $data['object'] = self::createActivityFromUriId($item['thr-parent-id'], $anounced_item['uid'] ?? 0); unset($data['object']['@context']); } else { @@ -1505,7 +1506,7 @@ class Transmitter } if (!empty($coord['lat']) && !empty($coord['lon'])) { - $location['latitude'] = $coord['lat']; + $location['latitude'] = $coord['lat']; $location['longitude'] = $coord['lon']; } @@ -1528,7 +1529,7 @@ class Transmitter 'name' => $name, 'icon' => [ 'type' => 'Image', - 'url' => $url, + 'url' => $url, ], ]; } @@ -1550,7 +1551,7 @@ class Transmitter $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]); foreach ($terms as $term) { if ($term['type'] == Tag::HASHTAG) { - $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']); + $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']); $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']]; } else { $contact = Contact::getByURL($term['url'], false, ['addr']); @@ -1606,10 +1607,10 @@ class Transmitter $urls[] = $attachment['url']; $attach = [ - 'type' => 'Document', + 'type' => 'Document', 'mediaType' => $attachment['mimetype'], - 'url' => $attachment['url'], - 'name' => $attachment['description'] + 'url' => $attachment['url'], + 'name' => $attachment['description'] ]; if (!empty($attachment['height'])) { @@ -1692,9 +1693,9 @@ class Transmitter */ private static function createEvent(array $item): array { - $event = []; - $event['name'] = $item['event-summary']; - $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB); + $event = []; + $event['name'] = $item['event-summary']; + $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB); $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c'); if (!$item['event-nofinish']) { @@ -1702,7 +1703,7 @@ class Transmitter } if (!empty($item['event-location'])) { - $item['location'] = $item['event-location']; + $item['location'] = $item['event-location']; $event['location'] = self::createLocation($item); } @@ -1732,7 +1733,7 @@ class Transmitter // But to not risk compatibility issues we currently perform the changes only for communities. if ($item['gravity'] == Item::GRAVITY_PARENT) { $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION])); - $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]); + $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]); if ($isCommunityPost && (count($links) == 1)) { $link = $links[0]['url']; } @@ -1763,10 +1764,10 @@ class Transmitter $title = ''; break; case ActivityPub::ARTICLE_EMBED_TITLE: - $type = 'Note'; + $type = 'Note'; $item['raw-body'] = '[b]' . $title . "[/b]\n\n" . $item['raw-body']; $item['body'] = '[b]' . $title . "[/b]\n\n" . $item['body']; - $title = ''; + $title = ''; break; } } else { @@ -1781,8 +1782,8 @@ class Transmitter $type = 'Tombstone'; } - $data = []; - $data['id'] = $item['uri']; + $data = []; + $data['id'] = $item['uri']; $data['type'] = $type; if ($item['deleted']) { @@ -1796,7 +1797,7 @@ class Transmitter } $data['diaspora:guid'] = $item['guid']; - $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM); + $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM); if ($item['created'] != $item['edited']) { $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM); @@ -1832,7 +1833,7 @@ class Transmitter $item = Post\Media::addHTMLAttachmentToItem($item); - $body = $item['body']; + $body = $item['body']; $emojis = []; if ($type == 'Note') { $body = $item['raw-body'] ?? self::removePictures($body); @@ -1876,10 +1877,10 @@ class Transmitter if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] != $item['uri-id'])) { if (Post::exists(['uri-id' => $item['quote-uri-id'], 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN]])) { - $real_quote = true; + $real_quote = true; $data['_misskey_content'] = BBCode::removeSharedData($body); - $data['quoteUrl'] = $item['quote-uri']; - $body = DI::contentItem()->addShareLink($body, $item['quote-uri-id']); + $data['quoteUrl'] = $item['quote-uri']; + $body = DI::contentItem()->addShareLink($body, $item['quote-uri-id']); } else { $body = DI::contentItem()->addSharedPost($item, $body); } @@ -1920,7 +1921,7 @@ class Transmitter } $data['attachment'] = self::createAttachmentList($item); - $data['tag'] = array_merge(self::createTagList($item, $data['quoteUrl'] ?? ''), $emojis); + $data['tag'] = array_merge(self::createTagList($item, $data['quoteUrl'] ?? ''), $emojis); if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) { $data['location'] = self::createLocation($item); @@ -1978,10 +1979,10 @@ class Transmitter $target = XML::parseString($item['target']); $activity['diaspora:guid'] = $item['guid']; - $activity['actor'] = $item['author-link']; - $activity['target'] = (string)$target->id; - $activity['summary'] = BBCode::toPlaintext($item['body']); - $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content]; + $activity['actor'] = $item['author-link']; + $activity['target'] = (string)$target->id; + $activity['summary'] = BBCode::toPlaintext($item['body']); + $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content]; return $activity; } @@ -1999,23 +2000,23 @@ class Transmitter private static function createAnnounce(array $item, array $activity, bool $api_mode = false): array { $orig_body = $item['body']; - $announce = self::getAnnounceArray($item); + $announce = self::getAnnounceArray($item); if (empty($announce)) { - $activity['type'] = 'Create'; + $activity['type'] = 'Create'; $activity['object'] = self::createNote($item, $api_mode); return $activity; } if (empty($announce['comment'])) { // Pure announce, without a quote - $activity['type'] = 'Announce'; + $activity['type'] = 'Announce'; $activity['object'] = $announce['object']['uri']; return $activity; } // Quote - $activity['type'] = 'Create'; - $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink']; + $activity['type'] = 'Create'; + $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink']; $activity['object'] = self::createNote($item, $api_mode); /// @todo Finally decide how to implement this in AP. This is a possible way: @@ -2104,15 +2105,15 @@ class Transmitter $suggestion = DI::fsuggest()->selectOneById($suggestion_id); $data = [ - '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), - 'type' => 'Announce', - 'actor' => $owner['url'], - 'object' => $suggestion->url, - 'content' => $suggestion->note, + '@context' => ActivityPub::CONTEXT, + 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), + 'type' => 'Announce', + 'actor' => $owner['url'], + 'object' => $suggestion->url, + 'content' => $suggestion->note, 'instrument' => self::getService(), - 'to' => [ActivityPub::PUBLIC_COLLECTION], - 'cc' => [] + 'to' => [ActivityPub::PUBLIC_COLLECTION], + 'cc' => [] ]; $signed = LDSignature::sign($data, $owner); @@ -2132,15 +2133,15 @@ class Transmitter public static function sendProfileRelocation(array $owner, string $inbox): bool { $data = [ - '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), - 'type' => 'dfrn:relocate', - 'actor' => $owner['url'], - 'object' => $owner['url'], - 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), + '@context' => ActivityPub::CONTEXT, + 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), + 'type' => 'dfrn:relocate', + 'actor' => $owner['url'], + 'object' => $owner['url'], + 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), 'instrument' => self::getService(), - 'to' => [ActivityPub::PUBLIC_COLLECTION], - 'cc' => [] + 'to' => [ActivityPub::PUBLIC_COLLECTION], + 'cc' => [] ]; $signed = LDSignature::sign($data, $owner); @@ -2165,15 +2166,15 @@ class Transmitter } $data = [ - '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), - 'type' => 'Delete', - 'actor' => $owner['url'], - 'object' => $owner['url'], - 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), + '@context' => ActivityPub::CONTEXT, + 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), + 'type' => 'Delete', + 'actor' => $owner['url'], + 'object' => $owner['url'], + 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), 'instrument' => self::getService(), - 'to' => [ActivityPub::PUBLIC_COLLECTION], - 'cc' => [] + 'to' => [ActivityPub::PUBLIC_COLLECTION], + 'cc' => [] ]; $signed = LDSignature::sign($data, $owner); @@ -2197,15 +2198,15 @@ class Transmitter $profile = APContact::getByURL($owner['url']); $data = [ - '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), - 'type' => 'Update', - 'actor' => $owner['url'], - 'object' => self::getProfile($owner['uid']), - 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), + '@context' => ActivityPub::CONTEXT, + 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), + 'type' => 'Update', + 'actor' => $owner['url'], + 'object' => self::getProfile($owner['uid']), + 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), 'instrument' => self::getService(), - 'to' => [$profile['followers']], - 'cc' => [] + 'to' => [$profile['followers']], + 'cc' => [] ]; $signed = LDSignature::sign($data, $owner); @@ -2245,13 +2246,13 @@ class Transmitter } $data = [ - '@context' => ActivityPub::CONTEXT, - 'id' => $id, - 'type' => $activity, - 'actor' => $owner['url'], - 'object' => $profile['url'], + '@context' => ActivityPub::CONTEXT, + 'id' => $id, + 'type' => $activity, + 'actor' => $owner['url'], + 'object' => $profile['url'], 'instrument' => self::getService(), - 'to' => [$profile['url']], + 'to' => [$profile['url']], ]; DI::logger()->info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid); @@ -2292,7 +2293,7 @@ class Transmitter } $condition = [ - 'verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object, + 'verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object, 'author-id' => Contact::getPublicIdByUserId($uid) ]; if (Post::exists($condition)) { @@ -2303,13 +2304,13 @@ class Transmitter $owner = User::getOwnerDataById($uid); $data = [ - '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), - 'type' => 'Follow', - 'actor' => $owner['url'], - 'object' => $object, + '@context' => ActivityPub::CONTEXT, + 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), + 'type' => 'Follow', + 'actor' => $owner['url'], + 'object' => $object, 'instrument' => self::getService(), - 'to' => [$profile['url']], + 'to' => [$profile['url']], ]; DI::logger()->info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid); @@ -2344,17 +2345,17 @@ class Transmitter $data = [ '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), - 'type' => 'Accept', - 'actor' => $owner['url'], - 'object' => [ - 'id' => $id, - 'type' => 'Follow', - 'actor' => $profile['url'], + 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), + 'type' => 'Accept', + 'actor' => $owner['url'], + 'object' => [ + 'id' => $id, + 'type' => 'Follow', + 'actor' => $profile['url'], 'object' => $owner['url'] ], 'instrument' => self::getService(), - 'to' => [$profile['url']], + 'to' => [$profile['url']], ]; DI::logger()->debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id); @@ -2383,17 +2384,17 @@ class Transmitter $data = [ '@context' => ActivityPub::CONTEXT, - 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), - 'type' => 'Reject', - 'actor' => $owner['url'], - 'object' => [ - 'id' => $objectId, - 'type' => 'Follow', - 'actor' => $profile['url'], + 'id' => DI::baseUrl() . '/activity/' . System::createGUID(), + 'type' => 'Reject', + 'actor' => $owner['url'], + 'object' => [ + 'id' => $objectId, + 'type' => 'Follow', + 'actor' => $profile['url'], 'object' => $owner['url'] ], 'instrument' => self::getService(), - 'to' => [$profile['url']], + 'to' => [$profile['url']], ]; DI::logger()->debug('Sending reject to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); @@ -2430,17 +2431,17 @@ class Transmitter $data = [ '@context' => ActivityPub::CONTEXT, - 'id' => $objectId, - 'type' => 'Undo', - 'actor' => $owner['url'], - 'object' => [ - 'id' => $object_id, - 'type' => 'Follow', - 'actor' => $owner['url'], + 'id' => $objectId, + 'type' => 'Undo', + 'actor' => $owner['url'], + 'object' => [ + 'id' => $object_id, + 'type' => 'Follow', + 'actor' => $owner['url'], 'object' => $profile['url'] ], 'instrument' => self::getService(), - 'to' => [$profile['url']], + 'to' => [$profile['url']], ]; DI::logger()->info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); @@ -2477,17 +2478,17 @@ class Transmitter $data = [ '@context' => ActivityPub::CONTEXT, - 'id' => $objectId, - 'type' => 'Undo', - 'actor' => $owner['url'], - 'object' => [ - 'id' => $object_id, - 'type' => 'Block', - 'actor' => $owner['url'], + 'id' => $objectId, + 'type' => 'Undo', + 'actor' => $owner['url'], + 'object' => [ + 'id' => $object_id, + 'type' => 'Block', + 'actor' => $owner['url'], 'object' => $profile['url'] ], 'instrument' => self::getService(), - 'to' => [$profile['url']], + 'to' => [$profile['url']], ]; DI::logger()->info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId); diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index 3e28fe53f3..a2c60cd27c 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -45,7 +45,6 @@ use GuzzleHttp\Psr7\Uri; */ class DFRN { - const TOP_LEVEL = 0; // Top level posting const REPLY = 1; // Regular reply that is stored locally const REPLY_RC = 2; // Reply that will be relayed @@ -64,27 +63,27 @@ class DFRN public static function getImporter(int $cid, int $uid = 0): array { $condition = ['id' => $cid, 'blocked' => false, 'pending' => false]; - $contact = DBA::selectFirst('contact', [], $condition); + $contact = DBA::selectFirst('contact', [], $condition); if (!DBA::isResult($contact)) { return []; } - $contact['cpubkey'] = $contact['pubkey']; - $contact['cprvkey'] = $contact['prvkey']; + $contact['cpubkey'] = $contact['pubkey']; + $contact['cprvkey'] = $contact['prvkey']; $contact['senderName'] = $contact['name']; if ($uid != 0) { $condition = ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]; - $user = DBA::selectFirst('user', [], $condition); + $user = DBA::selectFirst('user', [], $condition); if (!DBA::isResult($user)) { return []; } $user['importer_uid'] = $user['uid']; - $user['uprvkey'] = $user['prvkey']; + $user['uprvkey'] = $user['prvkey']; } else { $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC', - 'nickname' => '', 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0]; + 'nickname' => '', 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0]; } return array_merge($contact, $user); @@ -105,7 +104,7 @@ class DFRN */ public static function entries(array $items, array $owner): string { - $doc = new DOMDocument('1.0', 'utf-8'); + $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = self::addHeader($doc, $owner, 'dfrn:owner', '', false); @@ -118,7 +117,7 @@ class DFRN // These values aren't sent when sending from the queue. /// @todo Check if we can set these values from the queue or if they are needed at all. $item['entry:comment-allow'] = ($item['entry:comment-allow'] ?? '') ?: true; - $item['entry:cid'] = $item['entry:cid'] ?? 0; + $item['entry:cid'] = $item['entry:cid'] ?? 0; $entry = self::entry($doc, 'text', $item, $owner, $item['entry:comment-allow'], $item['entry:cid']); if (isset($entry)) { @@ -166,9 +165,9 @@ class DFRN $owner = ['uid' => 0, 'nick' => 'feed-item']; } - $doc = new DOMDocument('1.0', 'utf-8'); + $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; - $type = 'html'; + $type = 'html'; if ($conversation) { $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed'); @@ -210,12 +209,12 @@ class DFRN */ public static function mail(array $mail, array $owner): string { - $doc = new DOMDocument('1.0', 'utf-8'); + $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = self::addHeader($doc, $owner, 'dfrn:owner', '', false); - $mailElement = $doc->createElement('dfrn:mail'); + $mailElement = $doc->createElement('dfrn:mail'); $senderElement = $doc->createElement('dfrn:sender'); XML::addElement($doc, $senderElement, 'dfrn:name', $owner['name']); @@ -247,7 +246,7 @@ class DFRN */ public static function fsuggest(array $item, array $owner): string { - $doc = new DOMDocument('1.0', 'utf-8'); + $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = self::addHeader($doc, $owner, 'dfrn:owner', '', false); @@ -293,7 +292,7 @@ class DFRN $photos[$p['scale']] = DI::baseUrl() . '/photo/' . $p['resource-id'] . '-' . $p['scale'] . Images::getExtensionByMimeType($p['type']); } - $doc = new DOMDocument('1.0', 'utf-8'); + $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = self::addHeader($doc, $owner, 'dfrn:owner', '', false); @@ -411,10 +410,10 @@ class DFRN if (DBA::isResult($profile)) { $tmp_dob = substr($profile['dob'], 5); if (intval($tmp_dob)) { - $y = DateTimeFormat::timezoneNow($tz, 'Y'); - $bd = $y . '-' . $tmp_dob . ' 00:00'; + $y = DateTimeFormat::timezoneNow($tz, 'Y'); + $bd = $y . '-' . $tmp_dob . ' 00:00'; $t_dob = strtotime($bd); - $now = strtotime(DateTimeFormat::timezoneNow($tz)); + $now = strtotime(DateTimeFormat::timezoneNow($tz)); if ($t_dob < $now) { $bd = (int) $y + 1 . '-' . $tmp_dob . ' 00:00'; } @@ -457,11 +456,11 @@ class DFRN XML::addElement($doc, $author, 'dfrn:handle', $owner['addr'], $attributes); $attributes = [ - 'rel' => 'photo', - 'type' => 'image/jpeg', - 'media:width' => Proxy::PIXEL_SMALL, + 'rel' => 'photo', + 'type' => 'image/jpeg', + 'media:width' => Proxy::PIXEL_SMALL, 'media:height' => Proxy::PIXEL_SMALL, - 'href' => User::getAvatarUrl($owner, Proxy::SIZE_SMALL), + 'href' => User::getAvatarUrl($owner, Proxy::SIZE_SMALL), ]; if (!$public || !$hide) { @@ -489,9 +488,11 @@ class DFRN } // Only show contact details when we are allowed to - $profile = DBA::selectFirst('owner-view', + $profile = DBA::selectFirst( + 'owner-view', ['about', 'name', 'homepage', 'nickname', 'timezone', 'locality', 'region', 'country-name', 'pub_keywords', 'xmpp', 'dob'], - ['uid' => $owner['uid'], 'hidewall' => false]); + ['uid' => $owner['uid'], 'hidewall' => false] + ); if (DBA::isResult($profile)) { XML::addElement($doc, $author, 'poco:displayName', $profile['name']); XML::addElement($doc, $author, 'poco:updated', $namdate); @@ -578,20 +579,20 @@ class DFRN /// - Check real image type and image size /// - Check which of these elements we should use $attributes = [ - 'rel' => 'photo', - 'type' => 'image/jpeg', - 'media:width' => 80, + 'rel' => 'photo', + 'type' => 'image/jpeg', + 'media:width' => 80, 'media:height' => 80, - 'href' => $contact['photo'], + 'href' => $contact['photo'], ]; XML::addElement($doc, $author, 'link', '', $attributes); $attributes = [ - 'rel' => 'avatar', - 'type' => 'image/jpeg', - 'media:width' => 80, + 'rel' => 'avatar', + 'type' => 'image/jpeg', + 'media:width' => 80, 'media:height' => 80, - 'href' => $contact['photo'], + 'href' => $contact['photo'], ]; XML::addElement($doc, $author, 'link', '', $attributes); } @@ -680,8 +681,8 @@ class DFRN { foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) { $attributes = ['rel' => 'enclosure', - 'href' => $attachment['url'], - 'type' => $attachment['mimetype']]; + 'href' => $attachment['url'], + 'type' => $attachment['mimetype']]; if (!empty($attachment['size'])) { $attributes['length'] = intval($attachment['size']); @@ -771,8 +772,8 @@ class DFRN if ($item['gravity'] != Item::GRAVITY_PARENT) { $parent = Post::selectFirst(['guid', 'plink'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]); if (DBA::isResult($parent)) { - $attributes = ["ref" => $item['thr-parent'], "type" => "text/html", - "href" => $parent['plink'], + $attributes = ["ref" => $item['thr-parent'], "type" => "text/html", + "href" => $parent['plink'], "dfrn:diaspora_guid" => $parent['guid']]; XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes); } @@ -781,7 +782,7 @@ class DFRN // Add conversation data. This is used for OStatus $attributes = [ 'href' => $item['conversation'], - 'ref' => $item['conversation'], + 'ref' => $item['conversation'], ]; XML::addElement($doc, $entry, 'ostatus:conversation', $item['conversation'], $attributes); @@ -806,7 +807,7 @@ class DFRN 'link', '', [ - 'rel' => 'alternate', + 'rel' => 'alternate', 'type' => 'text/html', 'href' => DI::baseUrl() . '/display/' . $item['guid'] ], @@ -888,7 +889,7 @@ class DFRN foreach ($mentioned as $mention) { $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)]; - $contact = DBA::selectFirst('contact', ['contact-type'], $condition); + $contact = DBA::selectFirst('contact', ['contact-type'], $condition); if (DBA::isResult($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) { XML::addElement( @@ -897,9 +898,9 @@ class DFRN 'link', '', [ - 'rel' => 'mentioned', + 'rel' => 'mentioned', 'ostatus:object-type' => Activity\ObjectType::GROUP, - 'href' => $mention, + 'href' => $mention, ], ); } else { @@ -909,9 +910,9 @@ class DFRN 'link', '', [ - 'rel' => 'mentioned', + 'rel' => 'mentioned', 'ostatus:object-type' => Activity\ObjectType::PERSON, - 'href' => $mention, + 'href' => $mention, ], ); } @@ -939,7 +940,7 @@ class DFRN if (empty($contact['addr'])) { DI::logger()->notice('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.'); if (Contact::updateFromProbe($contact['id'])) { - $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]); + $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]); $contact['addr'] = $new_contact['addr']; } @@ -963,10 +964,10 @@ class DFRN // Create the endpoint for public posts. This is some WIP and should later be added to the probing if ($public_batch && empty($contact['batch'])) { - $parts = parse_url($contact['notify']); + $parts = parse_url($contact['notify']); $path_parts = explode('/', $parts['path']); array_pop($path_parts); - $parts['path'] = implode('/', $path_parts); + $parts['path'] = implode('/', $path_parts); $contact['batch'] = (string)Uri::fromParts($parts); } @@ -1043,7 +1044,7 @@ class DFRN */ private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, array $importer, string $element, bool $onlyfetch, string $xml = ''): array { - $author = []; + $author = []; $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context); $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context); @@ -1060,15 +1061,15 @@ class DFRN if (DBA::isResult($contact_old)) { $author["contact-id"] = $contact_old["id"]; - $author["network"] = $contact_old["network"]; + $author["network"] = $contact_old["network"]; } else { DI::logger()->info('Contact not found', ['condition' => $condition]); $author["contact-unknown"] = true; - $contact = Contact::getByURL($author["link"], null, ["id", "network"]); - $author["contact-id"] = $contact["id"] ?? $importer["id"]; - $author["network"] = $contact["network"] ?? $importer["network"]; - $onlyfetch = true; + $contact = Contact::getByURL($author["link"], null, ["id", "network"]); + $author["contact-id"] = $contact["id"] ?? $importer["id"]; + $author["network"] = $contact["network"] ?? $importer["network"]; + $onlyfetch = true; } // Until now we aren't serving different sizes - but maybe later @@ -1076,7 +1077,7 @@ class DFRN /// @todo check if "avatar" or "photo" would be the best field in the specification $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context); foreach ($avatars as $avatar) { - $href = ""; + $href = ""; $width = 0; foreach ($avatar->attributes as $attributes) { /// @TODO Rewrite these similar if() to one switch @@ -1186,7 +1187,7 @@ class DFRN } // Save the keywords into the contact table - $tags = []; + $tags = []; $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context); foreach ($tagelements as $tag) { $tags[$tag->nodeValue] = $tag->nodeValue; @@ -1212,7 +1213,7 @@ class DFRN if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) { $bdyear = date("Y"); - $value = str_replace(["0000", "0001"], $bdyear, $value); + $value = str_replace(["0000", "0001"], $bdyear, $value); if (strtotime($value) < time()) { $value = str_replace($bdyear, $bdyear + 1, $value); @@ -1228,10 +1229,10 @@ class DFRN } $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'], - 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'], - 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'], - 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']), - 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])]; + 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'], + 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'], + 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']), + 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])]; Contact::update($fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old); @@ -1267,7 +1268,7 @@ class DFRN return ""; } - $obj_doc = new DOMDocument("1.0", "utf-8"); + $obj_doc = new DOMDocument("1.0", "utf-8"); $obj_doc->formatOutput = true; $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element); @@ -1319,17 +1320,17 @@ class DFRN { DI::logger()->info("Processing mails"); - $msg = []; - $msg['uid'] = $importer['importer_uid']; - $msg['from-name'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:name/text()', $mail); - $msg['from-url'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:uri/text()', $mail); + $msg = []; + $msg['uid'] = $importer['importer_uid']; + $msg['from-name'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:name/text()', $mail); + $msg['from-url'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:uri/text()', $mail); $msg['from-photo'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:avatar/text()', $mail); $msg['contact-id'] = $importer['id']; - $msg['uri'] = XML::getFirstValue($xpath, 'dfrn:id/text()', $mail); + $msg['uri'] = XML::getFirstValue($xpath, 'dfrn:id/text()', $mail); $msg['parent-uri'] = XML::getFirstValue($xpath, 'dfrn:in-reply-to/text()', $mail); - $msg['created'] = DateTimeFormat::utc(XML::getFirstValue($xpath, 'dfrn:sentdate/text()', $mail)); - $msg['title'] = XML::getFirstValue($xpath, 'dfrn:subject/text()', $mail); - $msg['body'] = XML::getFirstValue($xpath, 'dfrn:content/text()', $mail); + $msg['created'] = DateTimeFormat::utc(XML::getFirstValue($xpath, 'dfrn:sentdate/text()', $mail)); + $msg['title'] = XML::getFirstValue($xpath, 'dfrn:subject/text()', $mail); + $msg['body'] = XML::getFirstValue($xpath, 'dfrn:content/text()', $mail); Mail::insert($msg); } @@ -1347,8 +1348,8 @@ class DFRN { DI::logger()->info('Processing suggestions'); - $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion); - $cid = Contact::getIdForURL($url); + $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion); + $cid = Contact::getIdForURL($url); $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion); return self::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note); @@ -1364,8 +1365,8 @@ class DFRN */ private static function addSuggestion(int $uid, int $cid, int $from_cid, string $note = ''): bool { - $owner = User::getOwnerDataById($uid); - $contact = Contact::getById($cid); + $owner = User::getOwnerDataById($uid); + $contact = Contact::getById($cid); $from_contact = Contact::getById($from_cid); if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($contact['url']), 'uid' => $uid])) { @@ -1377,15 +1378,15 @@ class DFRN return false; } - $suggest = []; - $suggest['uid'] = $uid; - $suggest['cid'] = $from_cid; - $suggest['url'] = $contact['url']; - $suggest['name'] = $contact['name']; - $suggest['photo'] = $contact['photo']; + $suggest = []; + $suggest['uid'] = $uid; + $suggest['cid'] = $from_cid; + $suggest['url'] = $contact['url']; + $suggest['name'] = $contact['name']; + $suggest['photo'] = $contact['photo']; $suggest['request'] = $contact['request']; - $suggest['title'] = ''; - $suggest['body'] = $note; + $suggest['title'] = ''; + $suggest['body'] = $note; DI::intro()->save(DI::introFactory()->createNew( $suggest['uid'], @@ -1424,20 +1425,20 @@ class DFRN DI::logger()->info("Processing relocations"); /// @TODO Rewrite this to one statement - $relocate = []; - $relocate['uid'] = $importer['importer_uid']; - $relocate['cid'] = $importer['id']; - $relocate['url'] = $xpath->query('dfrn:url/text()', $relocation)->item(0)->nodeValue; - $relocate['addr'] = $xpath->query('dfrn:addr/text()', $relocation)->item(0)->nodeValue; - $relocate['name'] = $xpath->query('dfrn:name/text()', $relocation)->item(0)->nodeValue; - $relocate['avatar'] = $xpath->query('dfrn:avatar/text()', $relocation)->item(0)->nodeValue; - $relocate['photo'] = $xpath->query('dfrn:photo/text()', $relocation)->item(0)->nodeValue; - $relocate['thumb'] = $xpath->query('dfrn:thumb/text()', $relocation)->item(0)->nodeValue; - $relocate['micro'] = $xpath->query('dfrn:micro/text()', $relocation)->item(0)->nodeValue; - $relocate['request'] = $xpath->query('dfrn:request/text()', $relocation)->item(0)->nodeValue; - $relocate['confirm'] = $xpath->query('dfrn:confirm/text()', $relocation)->item(0)->nodeValue; - $relocate['notify'] = $xpath->query('dfrn:notify/text()', $relocation)->item(0)->nodeValue; - $relocate['poll'] = $xpath->query('dfrn:poll/text()', $relocation)->item(0)->nodeValue; + $relocate = []; + $relocate['uid'] = $importer['importer_uid']; + $relocate['cid'] = $importer['id']; + $relocate['url'] = $xpath->query('dfrn:url/text()', $relocation)->item(0)->nodeValue; + $relocate['addr'] = $xpath->query('dfrn:addr/text()', $relocation)->item(0)->nodeValue; + $relocate['name'] = $xpath->query('dfrn:name/text()', $relocation)->item(0)->nodeValue; + $relocate['avatar'] = $xpath->query('dfrn:avatar/text()', $relocation)->item(0)->nodeValue; + $relocate['photo'] = $xpath->query('dfrn:photo/text()', $relocation)->item(0)->nodeValue; + $relocate['thumb'] = $xpath->query('dfrn:thumb/text()', $relocation)->item(0)->nodeValue; + $relocate['micro'] = $xpath->query('dfrn:micro/text()', $relocation)->item(0)->nodeValue; + $relocate['request'] = $xpath->query('dfrn:request/text()', $relocation)->item(0)->nodeValue; + $relocate['confirm'] = $xpath->query('dfrn:confirm/text()', $relocation)->item(0)->nodeValue; + $relocate['notify'] = $xpath->query('dfrn:notify/text()', $relocation)->item(0)->nodeValue; + $relocate['poll'] = $xpath->query('dfrn:poll/text()', $relocation)->item(0)->nodeValue; $relocate['sitepubkey'] = $xpath->query('dfrn:sitepubkey/text()', $relocation)->item(0)->nodeValue; if (($relocate['avatar'] == '') && ($relocate['photo'] != '')) { @@ -1457,15 +1458,15 @@ class DFRN // Update the contact table. We try to find every entry. $fields = [ - 'name' => $relocate['name'], - 'avatar' => $relocate['avatar'], - 'url' => $relocate['url'], - 'nurl' => Strings::normaliseLink($relocate['url']), - 'addr' => $relocate['addr'], - 'request' => $relocate['request'], - 'confirm' => $relocate['confirm'], - 'notify' => $relocate['notify'], - 'poll' => $relocate['poll'], + 'name' => $relocate['name'], + 'avatar' => $relocate['avatar'], + 'url' => $relocate['url'], + 'nurl' => Strings::normaliseLink($relocate['url']), + 'addr' => $relocate['addr'], + 'request' => $relocate['request'], + 'confirm' => $relocate['confirm'], + 'notify' => $relocate['notify'], + 'poll' => $relocate['poll'], 'site-pubkey' => $relocate['sitepubkey'], ]; $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer['id'], Strings::normaliseLink($old['url'])]; @@ -1506,10 +1507,10 @@ class DFRN } $fields = [ - 'title' => $item['title'] ?? '', - 'body' => $item['body'] ?? '', + 'title' => $item['title'] ?? '', + 'body' => $item['body'] ?? '', 'changed' => DateTimeFormat::utcNow(), - 'edited' => DateTimeFormat::utc($item['edited']), + 'edited' => DateTimeFormat::utc($item['edited']), ]; $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item['uri'], $importer['importer_uid']]; @@ -1611,16 +1612,16 @@ class DFRN } $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'gravity' => Item::GRAVITY_ACTIVITY, - 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']]; + 'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']]; if (Post::exists($condition)) { return false; } // The owner of an activity must be the author - $item['owner-name'] = $item['author-name']; - $item['owner-link'] = $item['author-link']; + $item['owner-name'] = $item['author-name']; + $item['owner-link'] = $item['author-link']; $item['owner-avatar'] = $item['author-avatar']; - $item['owner-id'] = $item['author-id']; + $item['owner-id'] = $item['author-id']; } if (($item['verb'] == Activity::TAG) && ($item['object-type'] == Activity\ObjectType::TAGTERM)) { @@ -1654,19 +1655,24 @@ class DFRN */ private static function parseLinks($links, array &$item) { - $rel = ''; - $href = ''; - $type = null; + $rel = ''; + $href = ''; + $type = null; $length = null; - $title = null; + $title = null; foreach ($links as $link) { foreach ($link->attributes as $attributes) { switch ($attributes->name) { - case 'href' : $href = $attributes->textContent; break; - case 'rel' : $rel = $attributes->textContent; break; - case 'type' : $type = $attributes->textContent; break; - case 'length': $length = $attributes->textContent; break; - case 'title' : $title = $attributes->textContent; break; + case 'href': $href = $attributes->textContent; + break; + case 'rel': $rel = $attributes->textContent; + break; + case 'type': $type = $attributes->textContent; + break; + case 'length': $length = $attributes->textContent; + break; + case 'title': $title = $attributes->textContent; + break; } } if (($rel != '') && ($href != '')) { @@ -1677,7 +1683,7 @@ class DFRN case 'enclosure': Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT, - 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]); + 'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]); break; } } @@ -1745,7 +1751,8 @@ class DFRN $item['edited'] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry); - $current = Post::selectFirst(['id', 'uid', 'edited', 'body'], + $current = Post::selectFirst( + ['id', 'uid', 'edited', 'body'], ['uri' => $item['uri'], 'uid' => $importer['importer_uid']] ); // Is there an existing item? @@ -1759,18 +1766,18 @@ class DFRN $owner_unknown = (isset($owner['contact-unknown']) && $owner['contact-unknown']); - $item['owner-name'] = $owner['name']; - $item['owner-link'] = $owner['link']; + $item['owner-name'] = $owner['name']; + $item['owner-link'] = $owner['link']; $item['owner-avatar'] = $owner['avatar']; - $item['owner-id'] = Contact::getIdForURL($owner['link'], 0); + $item['owner-id'] = Contact::getIdForURL($owner['link'], 0); // fetch the author $author = self::fetchauthor($xpath, $entry, $importer, 'atom:author', true, $xml); - $item['author-name'] = $author['name']; - $item['author-link'] = $author['link']; + $item['author-name'] = $author['name']; + $item['author-link'] = $author['link']; $item['author-avatar'] = $author['avatar']; - $item['author-id'] = Contact::getIdForURL($author['link'], 0); + $item['author-id'] = Contact::getIdForURL($author['link'], 0); $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry); @@ -1794,8 +1801,8 @@ class DFRN // We don't need the content element since "dfrn:env" is always present //$item['body'] = $xpath->query('atom:content/text()', $entry)->item(0)->nodeValue; $item['location'] = XML::getFirstNodeValue($xpath, 'dfrn:location/text()', $entry); - $item['coord'] = XML::getFirstNodeValue($xpath, 'georss:point', $entry); - $item['private'] = XML::getFirstNodeValue($xpath, 'dfrn:private/text()', $entry); + $item['coord'] = XML::getFirstNodeValue($xpath, 'georss:point', $entry); + $item['private'] = XML::getFirstNodeValue($xpath, 'dfrn:private/text()', $entry); $unlisted = XML::getFirstNodeValue($xpath, 'dfrn:unlisted/text()', $entry); if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) { @@ -1845,7 +1852,7 @@ class DFRN $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry); } - $object = $xpath->query('activity:object', $entry)->item(0); + $object = $xpath->query('activity:object', $entry)->item(0); $item['object'] = self::transformActivity($xpath, $object, 'object'); if (trim($item['object']) != '') { @@ -1855,13 +1862,13 @@ class DFRN } } - $target = $xpath->query('activity:target', $entry)->item(0); + $target = $xpath->query('activity:target', $entry)->item(0); $item['target'] = self::transformActivity($xpath, $target, 'target'); $categories = $xpath->query('atom:category', $entry); if ($categories) { foreach ($categories as $category) { - $term = ''; + $term = ''; $scheme = ''; foreach ($category->attributes as $attributes) { if ($attributes->name == 'term') { @@ -1977,7 +1984,7 @@ class DFRN $ev['source'] = $item['source']; $condition = ['uri' => $item['uri'], 'uid' => $importer['importer_uid']]; - $event = DBA::selectFirst('event', ['id'], $condition); + $event = DBA::selectFirst('event', ['id'], $condition); if (DBA::isResult($event)) { $ev['id'] = $event['id']; } @@ -2054,7 +2061,7 @@ class DFRN // This is my contact on another system, but it's really me. // Turn this into a wall post. - $notify = Item::isRemoteSelf($importer, $item); + $notify = Item::isRemoteSelf($importer, $item); $item['wall'] = (bool)$notify; $posted_id = Item::insert($item, $notify); @@ -2096,7 +2103,7 @@ class DFRN } $condition = ['uri' => $uri, 'uid' => $importer['importer_uid']]; - $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition); + $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition); if (!DBA::isResult($item)) { DI::logger()->info('Item with URI ' . $uri . ' for user ' . $importer['importer_uid'] . ' was not found.'); return; @@ -2163,12 +2170,12 @@ class DFRN $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS); $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET); - $header = []; - $header['uid'] = $importer['importer_uid']; - $header['network'] = Protocol::DFRN; - $header['protocol'] = $protocol; - $header['wall'] = 0; - $header['origin'] = 0; + $header = []; + $header['uid'] = $importer['importer_uid']; + $header['network'] = Protocol::DFRN; + $header['protocol'] = $protocol; + $header['wall'] = 0; + $header['origin'] = 0; $header['contact-id'] = $importer['id']; $header = Diaspora::setDirection($header, $direction); @@ -2314,7 +2321,7 @@ class DFRN } $existing_edited = DateTimeFormat::utc($existing['edited']); - $update_edited = DateTimeFormat::utc($update['edited']); + $update_edited = DateTimeFormat::utc($update['edited']); return (strcmp($existing_edited, $update_edited) < 0); } diff --git a/src/Protocol/Delivery.php b/src/Protocol/Delivery.php index d13b106aeb..6755f645d6 100644 --- a/src/Protocol/Delivery.php +++ b/src/Protocol/Delivery.php @@ -185,7 +185,9 @@ class Delivery } // We don't deliver our items to blocked, archived or pending contacts, and not to ourselves either - $contact = DBA::selectFirst('contact', [], + $contact = DBA::selectFirst( + 'contact', + [], ['id' => $contact_id, 'archive' => false, 'blocked' => false, 'pending' => false, 'self' => false] ); if (!DBA::isResult($contact)) { @@ -533,10 +535,10 @@ class Delivery if (($contact['rel'] == Contact::FRIEND) && !$contact['blocked']) { if ($reply_to) { - $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $reply_to . '>' . "\n"; + $headers = 'From: ' . Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $reply_to . '>' . "\n"; $headers .= 'Sender: ' . $local_user['email'] . "\n"; } else { - $headers = 'From: ' . Email::encodeHeader($local_user['username'],'UTF-8') . ' <' . $local_user['email'] . '>' . "\n"; + $headers = 'From: ' . Email::encodeHeader($local_user['username'], 'UTF-8') . ' <' . $local_user['email'] . '>' . "\n"; } } else { $sender = DI::config()->get('config', 'sender_email', 'noreply@' . DI::baseUrl()->getHost()); diff --git a/src/Protocol/Diaspora.php b/src/Protocol/Diaspora.php index 952f6f3b96..0235cb2f3f 100644 --- a/src/Protocol/Diaspora.php +++ b/src/Protocol/Diaspora.php @@ -31,7 +31,6 @@ use Friendica\Network\HTTPException; use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\NotFoundException; use Friendica\Network\Probe; -use Friendica\Protocol\Delivery; use Friendica\Util\Crypto; use Friendica\Util\DateTimeFormat; use Friendica\Util\Map; @@ -141,14 +140,14 @@ class Diaspora $alg = $children->alg; - $sig = Strings::base64UrlDecode($children->sig); + $sig = Strings::base64UrlDecode($children->sig); $key_id = $children->sig->attributes()->key_id[0]; if ($key_id != '') { $handle = Strings::base64UrlDecode($key_id); } $b64url_data = Strings::base64UrlEncode($data); - $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data); + $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data); $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg); @@ -231,7 +230,7 @@ class Diaspora } $encrypted_aes_key_bundle = base64_decode($data->aes_key); - $ciphertext = base64_decode($data->encrypted_magic_envelope); + $ciphertext = base64_decode($data->encrypted_magic_envelope); $outer_key_bundle = ''; @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey); @@ -247,7 +246,7 @@ class Diaspora throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon'); } - $outer_iv = base64_decode($j_outer_key_bundle->iv); + $outer_iv = base64_decode($j_outer_key_bundle->iv); $outer_key = base64_decode($j_outer_key_bundle->key); $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext); @@ -280,16 +279,16 @@ class Diaspora $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data); // Build the signed data - $type = $base->data[0]->attributes()->type[0]; - $encoding = $base->encoding; - $alg = $base->alg; + $type = $base->data[0]->attributes()->type[0]; + $encoding = $base->encoding; + $alg = $base->alg; $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg); // This is the signature $signature = Strings::base64UrlDecode($base->sig); // Get the senders' public key - $key_id = $base->sig[0]->attributes()->key_id[0]; + $key_id = $base->sig[0]->attributes()->key_id[0]; $author_addr = base64_decode($key_id); if ($author_addr == '') { DI::logger()->notice('No author could be decoded. Discarding. Message: ' . $xml); @@ -302,7 +301,7 @@ class Diaspora try { $author = WebFingerUri::fromString($author_addr); - $key = self::key($author); + $key = self::key($author); if ($key == '') { throw new \InvalidArgumentException(); } @@ -347,7 +346,7 @@ class Diaspora */ public static function decode(string $xml, string $privKey = '') { - $public = false; + $public = false; $basedom = XML::parseString($xml); if (!is_object($basedom)) { @@ -357,11 +356,11 @@ class Diaspora $children = $basedom->children('https://joindiaspora.com/protocol'); $inner_aes_key = null; - $inner_iv = null; + $inner_iv = null; if ($children->header) { $public = true; - $idom = $children->header; + $idom = $children->header; } else { // This happens with posts from a relais if (empty($privKey)) { @@ -372,14 +371,14 @@ class Diaspora $encrypted_header = json_decode(base64_decode($children->encrypted_header)); $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key); - $ciphertext = base64_decode($encrypted_header->ciphertext); + $ciphertext = base64_decode($encrypted_header->ciphertext); $outer_key_bundle = ''; openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey); $j_outer_key_bundle = json_decode($outer_key_bundle); - $outer_iv = base64_decode($j_outer_key_bundle->iv); + $outer_iv = base64_decode($j_outer_key_bundle->iv); $outer_key = base64_decode($j_outer_key_bundle->key); $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext); @@ -387,7 +386,7 @@ class Diaspora DI::logger()->info('decrypted', ['data' => $decrypted]); $idom = XML::parseString($decrypted); - $inner_iv = base64_decode($idom->iv); + $inner_iv = base64_decode($idom->iv); $inner_aes_key = base64_decode($idom->aes_key); } @@ -428,10 +427,10 @@ class Diaspora // stash away some other stuff for later - $type = $base->data[0]->attributes()->type[0]; - $keyhash = $base->sig[0]->attributes()->keyhash[0]; + $type = $base->data[0]->attributes()->type[0]; + $keyhash = $base->sig[0]->attributes()->keyhash[0]; $encoding = $base->encoding; - $alg = $base->alg; + $alg = $base->alg; $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg); @@ -496,7 +495,7 @@ class Diaspora } $importer = [ - 'uid' => 0, + 'uid' => 0, 'page-flags' => User::PAGE_FLAGS_FREELOVE ]; $success = self::dispatch($importer, $msg, $fields, $direction); @@ -641,15 +640,16 @@ class Diaspora } } - $type = $element->getName(); + $type = $element->getName(); $orig_type = $type; DI::logger()->debug('Got message', ['type' => $type, 'message' => $msg['message']]); // All retractions are handled identically from now on. // In the new version there will only be "retraction". - if (in_array($type, ['signed_retraction', 'relayable_retraction'])) + if (in_array($type, ['signed_retraction', 'relayable_retraction'])) { $type = 'retraction'; + } if ($type == 'request') { $type = 'contact'; @@ -657,8 +657,8 @@ class Diaspora $fields = new SimpleXMLElement('<' . $type . '/>'); - $signed_data = ''; - $author_signature = null; + $signed_data = ''; + $author_signature = null; $parent_author_signature = null; foreach ($element->children() as $fieldname => $entry) { @@ -750,7 +750,7 @@ class Diaspora } if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) { - DI::logger()->info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]); + DI::logger()->info('No valid parent author signature', ['author' => $msg['author'], 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $parent_author_signature]); return false; } } @@ -766,7 +766,7 @@ class Diaspora } if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) { - DI::logger()->info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]); + DI::logger()->info('No valid author signature for author', ['author' => $fields->author, 'type' => $type, 'signed data' => $signed_data, 'message' => $msg['message'], 'signature' => $author_signature]); return false; } else { return $fields; @@ -982,7 +982,7 @@ class Diaspora } else { // No local match, restoring absolute remote URL from author scheme and host $author_url = parse_url($author_link); - $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]'; + $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]'; } return $return; @@ -1186,7 +1186,7 @@ class Diaspora ]; $condition = ['uid' => $uid, 'guid' => $guid]; - $item = Post::selectFirst($fields, $condition); + $item = Post::selectFirst($fields, $condition); if (!DBA::isResult($item)) { try { @@ -1231,17 +1231,17 @@ class Diaspora private static function authorContactByUrl(array $def_contact, string $contact_url, int $uid): array { $condition = ['nurl' => Strings::normaliseLink($contact_url), 'uid' => $uid]; - $contact = DBA::selectFirst('contact', ['id', 'network'], $condition); + $contact = DBA::selectFirst('contact', ['id', 'network'], $condition); if (DBA::isResult($contact)) { - $cid = $contact['id']; + $cid = $contact['id']; $network = $contact['network']; } else { - $cid = $def_contact['id']; + $cid = $def_contact['id']; $network = Protocol::DIASPORA; } return [ - 'cid' => $cid, + 'cid' => $cid, 'network' => $network ]; } @@ -1283,7 +1283,7 @@ class Diaspora } $platform = ''; - $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]); + $gserver = DBA::selectFirst('gserver', ['platform'], ['nurl' => Strings::normaliseLink($contact['baseurl'])]); if (!empty($gserver['platform'])) { $platform = strtolower($gserver['platform']); DI::logger()->info('Detected platform', ['platform' => $platform, 'url' => $contact['url']]); @@ -1355,7 +1355,7 @@ class Diaspora // Check signature $signed_text = 'AccountMigration:' . $old_author . ':' . $new_author; - $key = self::key($old_author); + $key = self::key($old_author); if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) { DI::logger()->notice('No valid signature for migration.'); return false; @@ -1487,10 +1487,10 @@ class Diaspora */ private static function receiveComment(array $importer, WebFingerUri $sender, SimpleXMLElement $data, string $xml, int $direction): bool { - $author = WebFingerUri::fromString(XML::unescape($data->author)); - $guid = XML::unescape($data->guid); + $author = WebFingerUri::fromString(XML::unescape($data->author)); + $guid = XML::unescape($data->guid); $parent_guid = XML::unescape($data->parent_guid); - $text = XML::unescape($data->text); + $text = XML::unescape($data->text); if (isset($data->created_at)) { $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); @@ -1500,7 +1500,7 @@ class Diaspora if (isset($data->thread_parent_guid)) { $thread_parent_guid = XML::unescape($data->thread_parent_guid); - $thr_parent = self::getUriFromGuid($thread_parent_guid); + $thr_parent = self::getUriFromGuid($thread_parent_guid); } else { $thr_parent = ''; } @@ -1536,24 +1536,24 @@ class Diaspora $datarray = []; - $datarray['uid'] = $importer['uid']; + $datarray['uid'] = $importer['uid']; $datarray['contact-id'] = $author_contact['cid']; - $datarray['network'] = $author_contact['network']; + $datarray['network'] = $author_contact['network']; $datarray['author-link'] = $author_url; - $datarray['author-id'] = Contact::getIdForURL($author_url); + $datarray['author-id'] = Contact::getIdForURL($author_url); $datarray['owner-link'] = $contact['url']; - $datarray['owner-id'] = Contact::getIdForURL($contact['url']); + $datarray['owner-id'] = Contact::getIdForURL($contact['url']); // Will be overwritten for sharing accounts in Item::insert $datarray = self::setDirection($datarray, $direction); - $datarray['guid'] = $guid; - $datarray['uri'] = self::getUriFromGuid($guid, $author); + $datarray['guid'] = $guid; + $datarray['uri'] = self::getUriFromGuid($guid, $author); $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]); - $datarray['verb'] = Activity::POST; + $datarray['verb'] = Activity::POST; $datarray['gravity'] = Item::GRAVITY_COMMENT; $datarray['private'] = $toplevel_parent_item['private']; @@ -1565,17 +1565,17 @@ class Diaspora $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri']; $datarray['object-type'] = Activity\ObjectType::COMMENT; - $datarray['post-type'] = Item::PT_NOTE; + $datarray['post-type'] = Item::PT_NOTE; $datarray['protocol'] = Conversation::PARCEL_DIASPORA; - $datarray['source'] = $xml; + $datarray['source'] = $xml; $datarray = self::setDirection($datarray, $direction); $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at; $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']); - $body = Markdown::toBBCode($text); + $body = Markdown::toBBCode($text); $datarray['body'] = self::replacePeopleGuid($body, $author_url); @@ -1628,8 +1628,8 @@ class Diaspora private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool { $author_handle = XML::unescape($data->author); - $guid = XML::unescape($data->guid); - $subject = XML::unescape($data->subject); + $guid = XML::unescape($data->guid); + $subject = XML::unescape($data->subject); // "diaspora_handle" is the element name from the old version // "author" is the element name from the new version @@ -1647,10 +1647,10 @@ class Diaspora return false; } - $msg_guid = XML::unescape($mesg->guid); + $msg_guid = XML::unescape($mesg->guid); $msg_conversation_guid = XML::unescape($mesg->conversation_guid); - $msg_text = XML::unescape($mesg->text); - $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at)); + $msg_text = XML::unescape($mesg->text); + $msg_created_at = DateTimeFormat::utc(XML::unescape($mesg->created_at)); if ($msg_conversation_guid != $guid) { DI::logger()->notice('Message conversation guid does not belong to the current conversation.', ['guid' => $guid]); @@ -1688,10 +1688,10 @@ class Diaspora private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data) { $author_handle = XML::unescape($data->author); - $guid = XML::unescape($data->guid); - $subject = XML::unescape($data->subject); - $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); - $participants = XML::unescape($data->participants); + $guid = XML::unescape($data->guid); + $subject = XML::unescape($data->subject); + $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); + $participants = XML::unescape($data->participants); $messages = $data->message; @@ -1751,11 +1751,11 @@ class Diaspora */ private static function receiveLike(array $importer, WebFingerUri $sender, SimpleXMLElement $data, int $direction): bool { - $author = WebFingerUri::fromString(XML::unescape($data->author)); - $guid = XML::unescape($data->guid); + $author = WebFingerUri::fromString(XML::unescape($data->author)); + $guid = XML::unescape($data->guid); $parent_guid = XML::unescape($data->parent_guid); $parent_type = XML::unescape($data->parent_type); - $positive = XML::unescape($data->positive); + $positive = XML::unescape($data->positive); // likes on comments aren't supported by Diaspora - only on posts // But maybe this will be supported in the future, so we will accept it. @@ -1804,19 +1804,19 @@ class Diaspora $datarray['protocol'] = Conversation::PARCEL_DIASPORA; - $datarray['uid'] = $importer['uid']; + $datarray['uid'] = $importer['uid']; $datarray['contact-id'] = $author_contact['cid']; - $datarray['network'] = $author_contact['network']; + $datarray['network'] = $author_contact['network']; $datarray = self::setDirection($datarray, $direction); $datarray['owner-link'] = $datarray['author-link'] = $author_url; - $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url); + $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url); $datarray['guid'] = $guid; - $datarray['uri'] = self::getUriFromGuid($guid, $author); + $datarray['uri'] = self::getUriFromGuid($guid, $author); - $datarray['verb'] = $verb; + $datarray['verb'] = $verb; $datarray['gravity'] = Item::GRAVITY_ACTIVITY; $datarray['private'] = $toplevel_parent_item['private']; @@ -1837,7 +1837,7 @@ class Diaspora // like on comments have the comment as parent. So we need to fetch the toplevel parent if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) { $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]); - $origin = $toplevel['origin']; + $origin = $toplevel['origin']; } else { $origin = $toplevel_parent_item['origin']; } @@ -1880,11 +1880,11 @@ class Diaspora */ private static function receiveMessage(array $importer, SimpleXMLElement $data): bool { - $author_uri = WebFingerUri::fromString(XML::unescape($data->author)); - $guid = XML::unescape($data->guid); + $author_uri = WebFingerUri::fromString(XML::unescape($data->author)); + $guid = XML::unescape($data->guid); $conversation_guid = XML::unescape($data->conversation_guid); - $text = XML::unescape($data->text); - $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); + $text = XML::unescape($data->text); + $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); $contact = self::allowedContactByHandle($importer, $author_uri, true); if (!$contact) { @@ -1895,7 +1895,7 @@ class Diaspora GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA); } - $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid]; + $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid]; $conversation = DBA::selectFirst('conv', [], $condition); if (!DBA::isResult($conversation)) { DI::logger()->notice('Conversation not available.'); @@ -1943,8 +1943,8 @@ class Diaspora */ private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool { - $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author))); - $guid = XML::unescape($data->guid); + $author = WebFingerUri::fromString(strtolower(XML::unescape($data->author))); + $guid = XML::unescape($data->guid); $parent_guid = XML::unescape($data->parent_guid); $contact = self::allowedContactByHandle($importer, $author, true); @@ -1988,20 +1988,20 @@ class Diaspora $datarray['protocol'] = Conversation::PARCEL_DIASPORA; - $datarray['uid'] = $importer['uid']; + $datarray['uid'] = $importer['uid']; $datarray['contact-id'] = $author_contact['cid']; - $datarray['network'] = $author_contact['network']; + $datarray['network'] = $author_contact['network']; $datarray = self::setDirection($datarray, $direction); $datarray['owner-link'] = $datarray['author-link'] = $author_url; - $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url); + $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($author_url); $datarray['guid'] = $guid; - $datarray['uri'] = self::getUriFromGuid($guid, $author); + $datarray['uri'] = self::getUriFromGuid($guid, $author); - $datarray['verb'] = Activity::FOLLOW; - $datarray['gravity'] = Item::GRAVITY_ACTIVITY; + $datarray['verb'] = Activity::FOLLOW; + $datarray['gravity'] = Item::GRAVITY_ACTIVITY; $datarray['thr-parent'] = $toplevel_parent_item['uri']; $datarray['object-type'] = Activity\ObjectType::NOTE; @@ -2099,14 +2099,14 @@ class Diaspora return false; } - $name = XML::unescape($data->first_name) . ((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : ''); - $image_url = XML::unescape($data->image_url); - $birthday = XML::unescape($data->birthday); - $about = Markdown::toBBCode(XML::unescape($data->bio)); - $location = Markdown::toBBCode(XML::unescape($data->location)); + $name = XML::unescape($data->first_name) . ((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : ''); + $image_url = XML::unescape($data->image_url); + $birthday = XML::unescape($data->birthday); + $about = Markdown::toBBCode(XML::unescape($data->bio)); + $location = Markdown::toBBCode(XML::unescape($data->location)); $searchable = (XML::unescape($data->searchable) == 'true'); - $nsfw = (XML::unescape($data->nsfw) == 'true'); - $tags = XML::unescape($data->tag_string); + $nsfw = (XML::unescape($data->nsfw) == 'true'); + $tags = XML::unescape($data->tag_string); $tags = explode('#', $tags); @@ -2147,9 +2147,9 @@ class Diaspora } $fields = [ - 'name' => $name, 'location' => $location, - 'name-date' => DateTimeFormat::utcNow(), 'about' => $about, - 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords, + 'name' => $name, 'location' => $location, + 'name-date' => DateTimeFormat::utcNow(), 'about' => $about, + 'addr' => $author->getAddr(), 'nick' => $author->getUser(), 'keywords' => $keywords, 'unsearchable' => !$searchable, 'sensitive' => $nsfw ]; @@ -2194,7 +2194,7 @@ class Diaspora private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool { $author_handle = XML::unescape($data->author); - $recipient = XML::unescape($data->recipient); + $recipient = XML::unescape($data->recipient); if (!$author_handle || !$recipient) { return false; @@ -2312,8 +2312,8 @@ class Diaspora */ private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool { - $author = WebFingerUri::fromString(XML::unescape($data->author)); - $guid = XML::unescape($data->guid); + $author = WebFingerUri::fromString(XML::unescape($data->author)); + $guid = XML::unescape($data->guid); $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); try { $root_author = WebFingerUri::fromString(XML::unescape($data->root_author)); @@ -2347,25 +2347,25 @@ class Diaspora $datarray = []; - $datarray['uid'] = $importer['uid']; + $datarray['uid'] = $importer['uid']; $datarray['contact-id'] = $contact['id']; - $datarray['network'] = Protocol::DIASPORA; + $datarray['network'] = Protocol::DIASPORA; $datarray['author-link'] = $contact['url']; - $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0); + $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0); $datarray['owner-link'] = $datarray['author-link']; - $datarray['owner-id'] = $datarray['author-id']; + $datarray['owner-id'] = $datarray['author-id']; - $datarray['guid'] = $guid; - $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author); + $datarray['guid'] = $guid; + $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($guid, $author); $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]); - $datarray['verb'] = Activity::POST; + $datarray['verb'] = Activity::POST; $datarray['gravity'] = Item::GRAVITY_PARENT; $datarray['protocol'] = Conversation::PARCEL_DIASPORA; - $datarray['source'] = $xml; + $datarray['source'] = $xml; $datarray = self::setDirection($datarray, $direction); @@ -2624,11 +2624,11 @@ class Diaspora */ private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction) { - $author = WebFingerUri::fromString(XML::unescape($data->author)); - $guid = XML::unescape($data->guid); - $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); - $public = XML::unescape($data->public); - $text = XML::unescape($data->text); + $author = WebFingerUri::fromString(XML::unescape($data->author)); + $guid = XML::unescape($data->guid); + $created_at = DateTimeFormat::utc(XML::unescape($data->created_at)); + $public = XML::unescape($data->public); + $text = XML::unescape($data->text); $provider_display_name = XML::unescape($data->provider_display_name); $contact = self::allowedContactByHandle($importer, $author); @@ -2688,7 +2688,7 @@ class Diaspora } $datarray['object-type'] = Activity\ObjectType::IMAGE; - $datarray['post-type'] = Item::PT_IMAGE; + $datarray['post-type'] = Item::PT_IMAGE; } elseif ($data->poll) { $datarray['post-type'] = Item::PT_POLL; } @@ -2798,10 +2798,10 @@ class Diaspora return false; } - $aes_key = random_bytes(32); + $aes_key = random_bytes(32); $b_aes_key = base64_encode($aes_key); - $iv = random_bytes(16); - $b_iv = base64_encode($iv); + $iv = random_bytes(16); + $b_iv = base64_encode($iv); $ciphertext = self::aesEncrypt($aes_key, $iv, $msg); @@ -2814,7 +2814,7 @@ class Diaspora $json_object = json_encode( [ - 'aes_key' => base64_encode($encrypted_key_bundle), + 'aes_key' => base64_encode($encrypted_key_bundle), 'encrypted_magic_envelope' => base64_encode($ciphertext) ] ); @@ -2834,12 +2834,12 @@ class Diaspora public static function buildMagicEnvelope(string $msg, array $user): string { $b64url_data = Strings::base64UrlEncode($msg); - $data = str_replace(["\n", "\r", ' ', "\t"], ['', '', '', ''], $b64url_data); + $data = str_replace(["\n", "\r", ' ', "\t"], ['', '', '', ''], $b64url_data); - $key_id = Strings::base64UrlEncode(self::myHandle($user)); - $type = 'application/xml'; - $encoding = 'base64url'; - $alg = 'RSA-SHA256'; + $key_id = Strings::base64UrlEncode(self::myHandle($user)); + $type = 'application/xml'; + $encoding = 'base64url'; + $alg = 'RSA-SHA256'; $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg); // Fallback if the private key wasn't transmitted in the expected field @@ -2848,7 +2848,7 @@ class Diaspora } $signature = Crypto::rsaSign($signable_data, $user['uprvkey']); - $sig = Strings::base64UrlEncode($signature); + $sig = Strings::base64UrlEncode($signature); $xmldata = [ 'me:env' => [ @@ -2935,7 +2935,7 @@ class Diaspora // We always try to use the data from the diaspora-contact table. // This is important for transmitting data to Friendica servers. try { - $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr'])); + $target = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr'])); $dest_url = $public_batch ? $target->batch : $target->notify; } catch (HTTPException\NotFoundException | \InvalidArgumentException $e) { } @@ -3069,9 +3069,9 @@ class Diaspora // If the item belongs to a user, we take this user id. if ($item['uid'] == 0) { // @todo Possibly use an administrator account? - $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON]; + $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'account-type' => User::ACCOUNT_TYPE_PERSON]; $first_user = DBA::selectFirst('user', ['uid'], $condition, ['order' => ['uid']]); - $owner = User::getOwnerDataById($first_user['uid']); + $owner = User::getOwnerDataById($first_user['uid']); } else { $owner = User::getOwnerDataById($item['uid']); } @@ -3079,8 +3079,8 @@ class Diaspora $author_handle = self::myHandle($owner); $message = [ - 'author' => $author_handle, - 'guid' => System::createUUID(), + 'author' => $author_handle, + 'guid' => System::createUUID(), 'parent_type' => 'Post', 'parent_guid' => $item['guid'] ]; @@ -3107,14 +3107,14 @@ class Diaspora public static function sendAccountMigration(array $owner, array $contact, int $uid): int { $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr'); - $profile = self::createProfileData($uid); + $profile = self::createProfileData($uid); $signed_text = 'AccountMigration:' . $old_handle . ':' . $profile['author']; - $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256')); + $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256')); $message = [ - 'author' => $old_handle, - 'profile' => $profile, + 'author' => $old_handle, + 'profile' => $profile, 'signature' => $signature ]; @@ -3158,10 +3158,10 @@ class Diaspora */ $message = [ - 'author' => self::myHandle($owner), + 'author' => self::myHandle($owner), 'recipient' => $contact['addr'], 'following' => 'true', - 'sharing' => 'true' + 'sharing' => 'true' ]; DI::logger()->info('Send share', ['msg' => $message]); @@ -3270,9 +3270,9 @@ class Diaspora } if ($event['location']) { $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']); - $coord = Map::getCoordinates($event['location']); + $coord = Map::getCoordinates($event['location']); - $location = []; + $location = []; $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location'])); if (!empty($coord['lat']) && !empty($coord['lon'])) { $location['lat'] = $coord['lat']; @@ -3310,9 +3310,9 @@ class Diaspora $myaddr = self::myHandle($owner); - $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true'); + $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true'); $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM); - $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM); + $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM); // Detect a share element and do a reshare if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) { @@ -3366,24 +3366,25 @@ class Diaspora $location = []; - if ($item['location'] != '') + if ($item['location'] != '') { $location['address'] = $item['location']; + } if ($item['coord'] != '') { - $coord = explode(' ', $item['coord']); + $coord = explode(' ', $item['coord']); $location['lat'] = $coord[0]; $location['lng'] = $coord[1]; } $message = [ - 'author' => $myaddr, - 'guid' => $item['guid'], - 'created_at' => $created, - 'edited_at' => $edited, - 'public' => $public, - 'text' => $body, + 'author' => $myaddr, + 'guid' => $item['guid'], + 'created_at' => $created, + 'edited_at' => $edited, + 'public' => $public, + 'text' => $body, 'provider_display_name' => $item['app'], - 'location' => $location + 'location' => $location ]; if ($native_photos) { @@ -3514,7 +3515,7 @@ class Diaspora } $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment'); - $positive = null; + $positive = null; if ($item['verb'] === Activity::LIKE) { $positive = 'true'; } elseif ($item['verb'] === Activity::DISLIKE) { @@ -3563,10 +3564,10 @@ class Diaspora } return [ - 'author' => self::myHandle($owner), - 'guid' => $item['guid'], - 'parent_guid' => $parent['guid'], - 'status' => $attend_answer, + 'author' => self::myHandle($owner), + 'guid' => $item['guid'], + 'parent_guid' => $parent['guid'], + 'status' => $attend_answer, 'author_signature' => '' ]; } @@ -3616,17 +3617,17 @@ class Diaspora $body = self::prependParentAuthorMention($body, $thread_parent_item['author-link']); } - $text = html_entity_decode(BBCode::toMarkdown($body)); + $text = html_entity_decode(BBCode::toMarkdown($body)); $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM); - $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM); + $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM); $comment = [ - 'author' => self::myHandle($owner), - 'guid' => $item['guid'], - 'created_at' => $created, - 'edited_at' => $edited, - 'parent_guid' => $toplevel_item['guid'], - 'text' => $text, + 'author' => self::myHandle($owner), + 'guid' => $item['guid'], + 'created_at' => $created, + 'edited_at' => $edited, + 'parent_guid' => $toplevel_item['guid'], + 'text' => $text, 'author_signature' => '', ]; @@ -3658,13 +3659,13 @@ class Diaspora if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) { $message = self::constructAttend($item, $owner); - $type = 'event_participation'; + $type = 'event_participation'; } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) { $message = self::constructLike($item, $owner); - $type = 'like'; + $type = 'like'; } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) { $message = self::constructComment($item, $owner); - $type = 'comment'; + $type = 'comment'; } if (empty($message)) { @@ -3753,7 +3754,7 @@ class Diaspora } $message = [ - 'author' => $itemaddr, + 'author' => $itemaddr, 'target_guid' => $item['guid'], 'target_type' => $target_type ]; @@ -3784,28 +3785,28 @@ class Diaspora return -1; } - $body = BBCode::toMarkdown($item['body']); + $body = BBCode::toMarkdown($item['body']); $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM); $msg = [ - 'author' => $myaddr, - 'guid' => $item['guid'], + 'author' => $myaddr, + 'guid' => $item['guid'], 'conversation_guid' => $cnv['guid'], - 'text' => $body, - 'created_at' => $created, + 'text' => $body, + 'created_at' => $created, ]; if ($item['reply']) { $message = $msg; - $type = 'message'; + $type = 'message'; } else { $message = [ - 'author' => $cnv['creator'], - 'guid' => $cnv['guid'], - 'subject' => $cnv['subject'], - 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM), + 'author' => $cnv['creator'], + 'guid' => $cnv['guid'], + 'subject' => $cnv['subject'], + 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM), 'participants' => $cnv['recips'], - 'message' => $msg + 'message' => $msg ]; $type = 'conversation'; @@ -3836,14 +3837,14 @@ class Diaspora // Take the first word as first name $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name)); - $last = (($first === $name) ? '' : trim(substr($name, strlen($first)))); + $last = (($first === $name) ? '' : trim(substr($name, strlen($first)))); if ((strlen($first) < 32) && (strlen($last) < 32)) { return ['first' => $first, 'last' => $last]; } // Take the last word as last name $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name)); - $last = (($first === $name) ? '' : trim(substr($name, strlen($first)))); + $last = (($first === $name) ? '' : trim(substr($name, strlen($first)))); if ((strlen($first) < 32) && (strlen($last) < 32)) { return ['first' => $first, 'last' => $last]; @@ -3852,12 +3853,12 @@ class Diaspora // Take the first 32 characters if there is no space in the first 32 characters if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) { $first = substr($name, 0, 32); - $last = substr($name, 32); + $last = substr($name, 32); return ['first' => $first, 'last' => $last]; } $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' '))); - $last = (($first === $name) ? '' : trim(substr($name, strlen($first)))); + $last = (($first === $name) ? '' : trim(substr($name, strlen($first)))); // Check if the last name is longer than 32 characters if (strlen($last) > 32) { @@ -3912,7 +3913,7 @@ class Diaspora $data['birthday'] = ''; if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) { - [$year, $month, $day] = sscanf($profile['dob'], '%4d-%2d-%2d'); + list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d'); if ($year < 1004) { $year = 1004; } @@ -3921,12 +3922,12 @@ class Diaspora $data['bio'] = BBCode::toMarkdown($profile['about'] ?? ''); - $data['location'] = $profile['location']; + $data['location'] = $profile['location']; $data['tag_string'] = ''; if ($profile['pub_keywords']) { - $kw = str_replace(',', ' ', $profile['pub_keywords']); - $kw = str_replace(' ', ' ', $kw); + $kw = str_replace(',', ' ', $profile['pub_keywords']); + $kw = str_replace(' ', ' ', $kw); $arr = explode(' ', $kw); if (count($arr)) { for ($x = 0; $x < 5; $x++) { @@ -4003,7 +4004,8 @@ class Diaspora } if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) { - DI::logger()->warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]);; + DI::logger()->warning('Item is neither a like nor a dislike', ['uid' => $uid, 'item[verb]' => $item['verb']]); + ; return false; } @@ -4120,8 +4122,8 @@ class Diaspora 'quote-uri-id' => $UriId, 'allow_cid' => $owner['allow_cid'] ?? '', 'allow_gid' => $owner['allow_gid'] ?? '', - 'deny_cid' => $owner['deny_cid'] ?? '', - 'deny_gid' => $owner['deny_gid'] ?? '', + 'deny_cid' => $owner['deny_cid'] ?? '', + 'deny_gid' => $owner['deny_gid'] ?? '', ]; if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) { diff --git a/src/Protocol/Email.php b/src/Protocol/Email.php index a2d87eeaa9..340e3421f5 100644 --- a/src/Protocol/Email.php +++ b/src/Protocol/Email.php @@ -127,7 +127,7 @@ class Email */ public static function getMessage($mbox, int $uid, string $reply, array $item): array { - $ret = $item; + $ret = $item; $struc = (($mbox && $uid) ? @imap_fetchstructure($mbox, $uid, FT_UID) : null); if (!$struc) { @@ -154,7 +154,7 @@ class Email $message = ['text' => $text, 'html' => '', 'item' => $ret]; Hook::callAll('email_getmessage', $message); - $ret = $message['item']; + $ret = $message['item']; $ret['body'] = $message['text']; } } else { @@ -186,7 +186,7 @@ class Email } $ret['body'] = self::removeGPG($ret['body']); - $msg = self::removeSig($ret['body']); + $msg = self::removeSig($ret['body']); $ret['body'] = $msg['body']; $ret['body'] = self::convertQuote($ret['body'], $reply); @@ -221,8 +221,8 @@ class Email // DECODE DATA $data = ($partno) - ? @imap_fetchbody($mbox, $uid, $partno, FT_UID|FT_PEEK) - : @imap_body($mbox, $uid, FT_UID|FT_PEEK); + ? @imap_fetchbody($mbox, $uid, $partno, FT_UID | FT_PEEK) + : @imap_body($mbox, $uid, FT_UID | FT_PEEK); // Any part may be encoded, even plain text messages, so check everything. if ($p->encoding == 4) { @@ -261,7 +261,7 @@ class Email if ($p->type == 0 && $data) { // Messages may be split in different parts because of inline attachments, // so append parts together with blank row. - if (strtolower($p->subtype)==$subtype) { + if (strtolower($p->subtype) == $subtype) { $data = iconv($params['charset'], 'UTF-8//IGNORE', $data); return (trim($data) ."\n\n"); } else { @@ -285,7 +285,7 @@ class Email if (isset($p->parts) && $p->parts) { $x = ""; foreach ($p->parts as $partno0 => $p2) { - $x .= self::messageGetPart($mbox, $uid, $p2, $partno . '.' . ($partno0+1), $subtype); // 1.2, 1.2.1, etc. + $x .= self::messageGetPart($mbox, $uid, $p2, $partno . '.' . ($partno0 + 1), $subtype); // 1.2, 1.2.1, etc. } return $x; } @@ -301,10 +301,10 @@ class Email */ public static function encodeHeader(string $in_str, string $charset): string { - $out_str = $in_str; + $out_str = $in_str; $need_to_convert = false; - for ($x = 0; $x < strlen($in_str); $x ++) { + for ($x = 0; $x < strlen($in_str); $x++) { if ((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) { $need_to_convert = true; } @@ -316,8 +316,8 @@ class Email if ($out_str && $charset) { // define start delimiter, end delimiter and spacer - $end = "?="; - $start = "=?" . $charset . "?B?"; + $end = "?="; + $start = "=?" . $charset . "?B?"; $spacer = $end . "\r\n " . $start; // determine length of encoded text within chunks @@ -344,7 +344,7 @@ class Email // remove trailing spacer and // add start and end delimiters - $spacer = preg_quote($spacer, '/'); + $spacer = preg_quote($spacer, '/'); $out_str = preg_replace("/" . $spacer . "$/", "", $out_str); $out_str = $start . $out_str . $end; } @@ -374,7 +374,7 @@ class Email $part = uniqid('', true); - $html = Item::prepareBody($item); + $html = Item::prepareBody($item); $headers .= "Mime-Version: 1.0\n"; $headers .= 'Content-Type: multipart/alternative; boundary="=_'.$part.'"'."\n\n"; @@ -571,13 +571,13 @@ class Email */ private static function removeSig(string $message): array { - $sigpos = strrpos($message, "\n-- \n"); + $sigpos = strrpos($message, "\n-- \n"); $quotepos = strrpos($message, "[/quote]"); if ($sigpos == 0) { // Especially for web.de who are using that as a separator - $message = str_replace("\n___________________________________________________________\n", "\n-- \n", $message); - $sigpos = strrpos($message, "\n-- \n"); + $message = str_replace("\n___________________________________________________________\n", "\n-- \n", $message); + $sigpos = strrpos($message, "\n-- \n"); $quotepos = strrpos($message, "[/quote]"); } @@ -592,10 +592,10 @@ class Email if (!empty($result[1]) && !empty($result[2])) { $cleaned = trim($result[1])."\n"; - $sig = trim($result[2]); + $sig = trim($result[2]); } else { $cleaned = $message; - $sig = ''; + $sig = ''; } return ['body' => $cleaned, 'sig' => $sig]; @@ -611,13 +611,13 @@ class Email { $arrbody = explode("\n", trim($message)); - $lines = []; + $lines = []; $lineno = 0; foreach ($arrbody as $i => $line) { $currquotelevel = 0; - $currline = $line; - while ((strlen($currline)>0) && ((substr($currline, 0, 1) == '>') + $currline = $line; + while ((strlen($currline) > 0) && ((substr($currline, 0, 1) == '>') || (substr($currline, 0, 1) == ' '))) { if (substr($currline, 0, 1) == '>') { $currquotelevel++; @@ -627,8 +627,8 @@ class Email } $quotelevel = 0; - $nextline = trim($arrbody[$i + 1] ?? ''); - while ((strlen($nextline)>0) && ((substr($nextline, 0, 1) == '>') + $nextline = trim($arrbody[$i + 1] ?? ''); + while ((strlen($nextline) > 0) && ((substr($nextline, 0, 1) == '>') || (substr($nextline, 0, 1) == ' '))) { if (substr($nextline, 0, 1) == '>') { $quotelevel++; @@ -642,7 +642,7 @@ class Email $lines[$lineno] .= ' '; } - while ((strlen($line)>0) && ((substr($line, 0, 1) == '>') + while ((strlen($line) > 0) && ((substr($line, 0, 1) == '>') || (substr($line, 0, 1) == ' '))) { $line = ltrim(substr($line, 1)); @@ -663,34 +663,35 @@ class Email private static function convertQuote(string $body, string $reply): string { // Convert Quotes - $arrbody = explode("\n", trim($body)); + $arrbody = explode("\n", trim($body)); $arrlevel = []; for ($i = 0; $i < count($arrbody); $i++) { $quotelevel = 0; - $quoteline = $arrbody[$i]; + $quoteline = $arrbody[$i]; - while ((strlen($quoteline)>0) and ((substr($quoteline, 0, 1) == '>') + while ((strlen($quoteline) > 0) and ((substr($quoteline, 0, 1) == '>') || (substr($quoteline, 0, 1) == ' '))) { - if (substr($quoteline, 0, 1) == '>') + if (substr($quoteline, 0, 1) == '>') { $quotelevel++; + } $quoteline = ltrim(substr($quoteline, 1)); } $arrlevel[$i] = $quotelevel; - $arrbody[$i] = $quoteline; + $arrbody[$i] = $quoteline; } - $quotelevel = 0; + $quotelevel = 0; $arrbodyquoted = []; for ($i = 0; $i < count($arrbody); $i++) { $previousquote = $quotelevel; - $quotelevel = $arrlevel[$i]; + $quotelevel = $arrlevel[$i]; while ($previousquote < $quotelevel) { - $quote = "[quote]"; + $quote = "[quote]"; $arrbody[$i] = $quote.$arrbody[$i]; $previousquote++; } @@ -726,8 +727,8 @@ class Email do { $oldmessage = $message; - $message = preg_replace('=\[/quote\][\s](.*?)\[quote\]=i', '$1', $message); - $message = str_replace('[/quote][quote]', '', $message); + $message = preg_replace('=\[/quote\][\s](.*?)\[quote\]=i', '$1', $message); + $message = str_replace('[/quote][quote]', '', $message); } while ($message != $oldmessage); $quotes = []; @@ -738,12 +739,12 @@ class Email while (($pos = strpos($message, '[quote', $start)) > 0) { $quotes[$pos] = -1; - $start = $pos + 7; + $start = $pos + 7; $startquotes++; } $endquotes = 0; - $start = 0; + $start = 0; while (($pos = strpos($message, '[/quote]', $start)) > 0) { $start = $pos + 7; @@ -759,7 +760,7 @@ class Email while (($pos = strpos($message, '[/quote]', $start)) > 0) { $quotes[$pos] = 1; - $start = $pos + 7; + $start = $pos + 7; } if (strtolower(substr($message, -8)) != '[/quote]') { @@ -773,12 +774,13 @@ class Email foreach ($quotes as $index => $quote) { $quotelevel += $quote; - if (($quotelevel == 0) and ($quotestart == 0)) + if (($quotelevel == 0) and ($quotestart == 0)) { $quotestart = $index; + } } if ($quotestart != 0) { - $message = trim(substr($message, 0, $quotestart))."\n[spoiler]".substr($message, $quotestart+7, -8) . '[/spoiler]'; + $message = trim(substr($message, 0, $quotestart))."\n[spoiler]".substr($message, $quotestart + 7, -8) . '[/spoiler]'; } return $message; diff --git a/src/Protocol/Feed.php b/src/Protocol/Feed.php index 4fea37e4e8..fa1ea3b302 100644 --- a/src/Protocol/Feed.php +++ b/src/Protocol/Feed.php @@ -88,14 +88,14 @@ class Feed $xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/'); $xpath->registerNamespace('poco', ActivityNamespace::POCO); - $author = []; - $atomns = 'atom'; - $entries = null; + $author = []; + $atomns = 'atom'; + $entries = null; $protocol = Conversation::PARCEL_UNKNOWN; // Is it RDF? if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) { - $protocol = Conversation::PARCEL_RDF; + $protocol = Conversation::PARCEL_RDF; $author['author-link'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()'); $author['author-name'] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()'); @@ -106,9 +106,9 @@ class Feed } if ($xpath->query('/opml')->length > 0) { - $protocol = Conversation::PARCEL_OPML; + $protocol = Conversation::PARCEL_OPML; $author['author-name'] = XML::getFirstNodeValue($xpath, '/opml/head/title/text()'); - $entries = $xpath->query('/opml/body/outline'); + $entries = $xpath->query('/opml/body/outline'); } // Is it Atom? @@ -116,7 +116,7 @@ class Feed $protocol = Conversation::PARCEL_ATOM; } elseif ($xpath->query('/atom03:feed')->length > 0) { $protocol = Conversation::PARCEL_ATOM03; - $atomns = 'atom03'; + $atomns = 'atom03'; } if (in_array($protocol, [Conversation::PARCEL_ATOM, Conversation::PARCEL_ATOM03])) { @@ -203,7 +203,7 @@ class Feed // Is it RSS? if ($xpath->query('/rss/channel')->length > 0) { - $protocol = Conversation::PARCEL_RSS; + $protocol = Conversation::PARCEL_RSS; $author['author-link'] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()'); $author['author-name'] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()'); @@ -251,8 +251,8 @@ class Feed $author['author-avatar'] = $contact['thumb']; - $author['owner-link'] = $contact['url']; - $author['owner-name'] = $contact['name']; + $author['owner-link'] = $contact['url']; + $author['owner-name'] = $contact['name']; $author['owner-avatar'] = $contact['thumb']; } @@ -269,7 +269,7 @@ class Feed 'contact-id' => $contact['id'] ?? 0, ]; - $datarray['protocol'] = $protocol; + $datarray['protocol'] = $protocol; $datarray['direction'] = Conversation::PULL; if (!is_object($entries)) { @@ -277,12 +277,12 @@ class Feed return []; } - $items = []; + $items = []; $creation_dates = []; // Limit the number of items that are about to be fetched $total_items = ($entries->length - 1); - $max_items = DI::config()->get('system', 'max_feed_items'); + $max_items = DI::config()->get('system', 'max_feed_items'); if (($max_items > 0) && ($total_items > $max_items)) { $total_items = $max_items; } @@ -311,7 +311,7 @@ class Feed if ($entry->nodeName == 'outline') { $isrss = false; $plink = ''; - $uri = ''; + $uri = ''; foreach ($entry->attributes as $attribute) { switch ($attribute->nodeName) { case 'title': @@ -336,7 +336,7 @@ class Feed } } $item['plink'] = $plink ?: $uri; - $item['uri'] = $uri ?: $plink; + $item['uri'] = $uri ?: $plink; if (!$isrss || empty($item['uri'])) { continue; } @@ -476,9 +476,9 @@ class Feed $enclosures = $xpath->query("enclosure|$atomns:link[@rel='enclosure']", $entry); if (!empty($enclosures)) { foreach ($enclosures as $enclosure) { - $href = ''; + $href = ''; $length = null; - $type = null; + $type = null; foreach ($enclosure->attributes as $attribute) { if (in_array($attribute->name, ['url', 'href'])) { @@ -505,7 +505,7 @@ class Feed } } - $taglist = []; + $taglist = []; $categories = $xpath->query('category', $entry); foreach ($categories as $category) { $taglist[] = $category->nodeValue; @@ -526,7 +526,7 @@ class Feed } if (empty($body)) { - $body = $summary; + $body = $summary; $summary = ''; } @@ -537,16 +537,16 @@ class Feed } $item['body'] = self::formatBody($body, $basepath); - $summary = self::formatBody($summary, $basepath); + $summary = self::formatBody($summary, $basepath); if (($item['body'] == '') && ($item['title'] != '')) { - $item['body'] = $item['title']; + $item['body'] = $item['title']; $item['title'] = ''; } if ($dryRun) { $item['attachments'] = $attachments; - $items[] = $item; + $items[] = $item; break; } elseif (!Item::isValid($item)) { DI::logger()->info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]); @@ -582,7 +582,7 @@ class Feed $summary = ''; } - $saved_body = $item['body']; + $saved_body = $item['body']; $saved_title = $item['title']; if (self::replaceBodyWithTitle($item['body'], $item['title'])) { @@ -612,7 +612,7 @@ class Feed // Take the data that was provided by the feed if the query is empty if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) { $data['title'] = $saved_title; - $item['body'] = $saved_body; + $item['body'] = $saved_body; } $data_text = strip_tags(trim($data['text'] ?? '')); @@ -623,11 +623,11 @@ class Feed } // We always strip the title since it will be added in the page information - $item['title'] = ''; - $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false); - $taglist = $fetch_further_information == LocalRelationship::FFI_BOTH ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : []; + $item['title'] = ''; + $item['body'] = $item['body'] . "\n" . PageInfo::getFooterFromData($data, false); + $taglist = $fetch_further_information == LocalRelationship::FFI_BOTH ? PageInfo::getTagsFromUrl($item['plink'], $preview, $contact['ffi_keyword_denylist'] ?? '') : []; $item['object-type'] = Activity\ObjectType::BOOKMARK; - $attachments = []; + $attachments = []; foreach (['audio', 'video'] as $elementname) { if (!empty($data[$elementname])) { @@ -674,7 +674,7 @@ class Feed DI::logger()->info('Stored feed', ['item' => $item]); - $notify = Item::isRemoteSelf($contact, $item); + $notify = Item::isRemoteSelf($contact, $item); $item['wall'] = (bool)$notify; // Distributed items should have a well-formatted URI. @@ -696,7 +696,7 @@ class Feed Post\Delayed::publish($item, $notify, $taglist, $attachments); } else { $postings[] = [ - 'item' => $item, 'notify' => $notify, + 'item' => $item, 'notify' => $notify, 'taglist' => $taglist, 'attachments' => $attachments ]; } @@ -707,11 +707,11 @@ class Feed if (!empty($postings)) { $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0); - $total = count($postings); + $total = count($postings); if ($total > 1) { // Posts shouldn't be delayed more than a day $interval = min(1440, self::getPollInterval($contact)); - $delay = max(round(($interval * 60) / $total), 60 * $min_posting); + $delay = max(round(($interval * 60) / $total), 60 * $min_posting); DI::logger()->info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]); } else { $delay = 0; @@ -795,15 +795,15 @@ class Feed if (!empty($creation_dates)) { // Count the post frequency and the earliest and latest post date - $frequency = []; - $oldest = time(); - $newest = 0; + $frequency = []; + $oldest = time(); + $newest = 0; $newest_date = ''; foreach ($creation_dates as $date) { $timestamp = strtotime($date); - $day = intdiv($timestamp, 86400); - $hour = $timestamp % 86400; + $day = intdiv($timestamp, 86400); + $hour = $timestamp % 86400; // Only have a look at values from the last seven days if (((time() / 86400) - $day) < 7) { @@ -824,7 +824,7 @@ class Feed } if ($newest < $day) { - $newest = $day; + $newest = $day; $newest_date = $date; } } @@ -862,7 +862,7 @@ class Feed // Assume at least four hours between oldest and newest post per day - should be okay for news outlets $duration = max($entry['high'] - $entry['low'], 14400); - $ppd = (86400 / $duration) * $entry['count']; + $ppd = (86400 / $duration) * $entry['count']; if ($ppd > $max) { $max = $ppd; } @@ -980,7 +980,7 @@ class Feed $pos = strrpos($title, '...'); if ($pos > 0) { $title = substr($title, 0, $pos); - $body = substr($body, 0, $pos); + $body = substr($body, 0, $pos); } } return ($title == $body); @@ -1019,7 +1019,7 @@ class Feed $previous_created = $last_update; $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update); - $authorid = Contact::getIdForURL($owner['url']); + $authorid = Contact::getIdForURL($owner['url']); $condition = [ "`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?) @@ -1049,7 +1049,7 @@ class Feed $items = Post::toArray($ret); - $doc = new DOMDocument('1.0', 'utf-8'); + $doc = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = self::addHeader($doc, $owner, $filter); @@ -1085,7 +1085,7 @@ class Feed $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed'); $doc->appendChild($root); - $title = ''; + $title = ''; $selfUri = '/feed/' . $owner['nick'] . '/'; switch ($filter) { case 'activity': @@ -1198,7 +1198,7 @@ class Feed 'link', '', [ - 'rel' => 'alternate', 'type' => 'text/html', + 'rel' => 'alternate', 'type' => 'text/html', 'href' => DI::baseUrl() . '/display/' . $item['guid'] ] ); @@ -1290,11 +1290,11 @@ class Feed // Remove the share element before fetching the first line $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body'])); - $title = BBCode::toPlaintext($title) . "\n"; - $pos = strpos($title, "\n"); + $title = BBCode::toPlaintext($title) . "\n"; + $pos = strpos($title, "\n"); $trailer = ''; if (($pos == 0) || ($pos > 100)) { - $pos = 100; + $pos = 100; $trailer = '...'; } @@ -1347,8 +1347,8 @@ class Feed { foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) { $attributes = ['rel' => 'enclosure', - 'href' => $attachment['url'], - 'type' => $attachment['mimetype']]; + 'href' => $attachment['url'], + 'type' => $attachment['mimetype']]; if (!empty($attachment['size'])) { $attributes['length'] = intval($attachment['size']); @@ -1401,9 +1401,9 @@ class Feed if ($owner['contact-type'] == Contact::TYPE_COMMUNITY) { $entry->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY); - $contact = Contact::getByURL($item['author-link']) ?: $owner; + $contact = Contact::getByURL($item['author-link']) ?: $owner; $contact['nickname'] = $contact['nickname'] ?? $contact['nick']; - $author = self::addAuthor($doc, $contact); + $author = self::addAuthor($doc, $contact); $entry->appendChild($author); } } else { diff --git a/src/Protocol/Relay.php b/src/Protocol/Relay.php index 994772d191..b2396ba288 100644 --- a/src/Protocol/Relay.php +++ b/src/Protocol/Relay.php @@ -33,7 +33,7 @@ use Friendica\Util\Strings; class Relay { const SCOPE_NONE = ''; - const SCOPE_ALL = 'all'; + const SCOPE_ALL = 'all'; const SCOPE_TAGS = 'tags'; /** @@ -76,7 +76,7 @@ class Relay if (!empty($causerid)) { $contact = Contact::getById($causerid, ['url']); - $causer = $contact['url'] ?? ''; + $causer = $contact['url'] ?? ''; } else { $causer = ''; } @@ -86,7 +86,7 @@ class Relay if ($scope == self::SCOPE_TAGS) { $tagList = self::getSubscribedTags(); } else { - $tagList = []; + $tagList = []; } $denyTags = Strings::getTagArrayByString($config->get('system', 'relay_deny_tags')); @@ -96,7 +96,7 @@ class Relay $max_tags = $config->get('system', 'relay_max_tags'); if ($max_tags && (count($tags) > $max_tags) && preg_match('/[^@!#]\[url\=.*?\].*?\[\/url\]/ism', $body)) { - $cleaned = preg_replace('/[@!#]\[url\=.*?\].*?\[\/url\]/ism', '', $body); + $cleaned = preg_replace('/[@!#]\[url\=.*?\].*?\[\/url\]/ism', '', $body); $content_cleaned = mb_strtolower(BBCode::toPlaintext($cleaned, false)); if (strlen($content_cleaned) < strlen($content) / 2) { @@ -223,12 +223,12 @@ class Relay } $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY]; - $old = DBA::selectFirst('contact', [], $condition); + $old = DBA::selectFirst('contact', [], $condition); if (!DBA::isResult($old)) { $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($gserver['url'])]; - $old = DBA::selectFirst('contact', [], $condition); + $old = DBA::selectFirst('contact', [], $condition); if (DBA::isResult($old)) { - $fields['gsid'] = $gserver['id']; + $fields['gsid'] = $gserver['id']; $fields['contact-type'] = Contact::TYPE_RELAY; DI::logger()->info('Assigning missing data for relay contact', ['server' => $gserver['url'], 'id' => $old['id']]); } @@ -245,15 +245,15 @@ class Relay Contact::update($fields, ['id' => $old['id']], $old); } else { $default = ['created' => DateTimeFormat::utcNow(), - 'name' => 'relay', 'nick' => 'relay', 'url' => $gserver['url'], - 'nurl' => Strings::normaliseLink($gserver['url']), - 'network' => Protocol::DIASPORA, 'uid' => 0, - 'batch' => $gserver['url'] . '/receive/public', - 'rel' => Contact::FOLLOWER, 'blocked' => false, - 'pending' => false, 'writable' => true, - 'gsid' => $gserver['id'], - 'unsearchable' => true, - 'baseurl' => $gserver['url'], 'contact-type' => Contact::TYPE_RELAY]; + 'name' => 'relay', 'nick' => 'relay', 'url' => $gserver['url'], + 'nurl' => Strings::normaliseLink($gserver['url']), + 'network' => Protocol::DIASPORA, 'uid' => 0, + 'batch' => $gserver['url'] . '/receive/public', + 'rel' => Contact::FOLLOWER, 'blocked' => false, + 'pending' => false, 'writable' => true, + 'gsid' => $gserver['id'], + 'unsearchable' => true, + 'baseurl' => $gserver['url'], 'contact-type' => Contact::TYPE_RELAY]; $fields = array_merge($default, $fields); @@ -278,14 +278,14 @@ class Relay $relay_contact = $contact; } elseif (empty($contact['baseurl'])) { if (!empty($contact['batch'])) { - $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY]; + $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => Contact::TYPE_RELAY]; $relay_contact = DBA::selectFirst('contact', [], $condition); } else { return; } } else { $gserver = ['id' => $contact['gsid'] ?: GServer::getID($contact['baseurl'], true), - 'url' => $contact['baseurl'], 'network' => $contact['network']]; + 'url' => $contact['baseurl'], 'network' => $contact['network']]; $relay_contact = self::getContact($gserver, []); } @@ -324,7 +324,7 @@ class Relay DBA::close($servers); // All tags of the current post - $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]); + $tags = DBA::select('tag-view', ['name'], ['uri-id' => $parent['uri-id'], 'type' => Tag::HASHTAG]); $taglist = []; while ($tag = DBA::fetch($tags)) { $taglist[] = $tag['name']; @@ -376,8 +376,11 @@ class Relay */ public static function getList(array $fields = []): array { - return DBA::selectToArray('apcontact', $fields, - ["`type` IN (?, ?) AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)", 'Application', 'Service', 0, Contact::FRIEND]); + return DBA::selectToArray( + 'apcontact', + $fields, + ["`type` IN (?, ?) AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)", 'Application', 'Service', 0, Contact::FRIEND] + ); } /** @@ -392,7 +395,7 @@ class Relay { // Fetch the relay contact $condition = ['uid' => 0, 'gsid' => $gserver['id'], 'contact-type' => Contact::TYPE_RELAY]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); if (DBA::isResult($contact)) { if ($contact['archive'] || $contact['blocked']) { return false; diff --git a/src/Security/BasicAuth.php b/src/Security/BasicAuth.php index a04e050c6a..fe89bf452e 100644 --- a/src/Security/BasicAuth.php +++ b/src/Security/BasicAuth.php @@ -103,7 +103,7 @@ class BasicAuth * * @return integer User ID */ - private static function getUserIdByAuth(bool $do_login = true):int + private static function getUserIdByAuth(bool $do_login = true): int { self::$current_user_id = 0; @@ -111,14 +111,14 @@ class BasicAuth if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) { $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6)); if (!empty($userpass) && strpos($userpass, ':')) { - list($name, $password) = explode(':', $userpass); + list($name, $password) = explode(':', $userpass); $_SERVER['PHP_AUTH_USER'] = $name; - $_SERVER['PHP_AUTH_PW'] = $password; + $_SERVER['PHP_AUTH_PW'] = $password; } } $user = $_SERVER['PHP_AUTH_USER'] ?? ''; - $password = $_SERVER['PHP_AUTH_PW'] ?? ''; + $password = $_SERVER['PHP_AUTH_PW'] ?? ''; // allow "user@server" login (but ignore 'server' part) $at = strstr($user, "@", true); @@ -130,10 +130,10 @@ class BasicAuth $record = null; $addon_auth = [ - 'username' => trim($user), - 'password' => trim($password), + 'username' => trim($user), + 'password' => trim($password), 'authenticated' => 0, - 'user_record' => null, + 'user_record' => null, ]; /* @@ -148,7 +148,7 @@ class BasicAuth } else { try { $user_id = User::getIdFromPasswordAuthentication(trim($user), trim($password), true); - $record = DBA::selectFirst('user', [], ['uid' => $user_id]); + $record = DBA::selectFirst('user', [], ['uid' => $user_id]); } catch (Exception $ex) { $record = []; } diff --git a/src/Security/OAuth.php b/src/Security/OAuth.php index d00d27b8d3..5fd93936ad 100644 --- a/src/Security/OAuth.php +++ b/src/Security/OAuth.php @@ -120,7 +120,7 @@ class OAuth if (!empty($redirect_uri)) { $redirect_uri = strtok($redirect_uri, '?'); - $condition = DBA::mergeConditions($condition, ["`redirect_uri` LIKE ?", '%' . $redirect_uri . '%']); + $condition = DBA::mergeConditions($condition, ["`redirect_uri` LIKE ?", '%' . $redirect_uri . '%']); } $application = DBA::selectFirst('application', [], $condition); diff --git a/src/Util/Crypto.php b/src/Util/Crypto.php index da4645ea0e..4c0e9b72dc 100644 --- a/src/Util/Crypto.php +++ b/src/Util/Crypto.php @@ -89,7 +89,7 @@ class Crypto openssl_pkey_export($result, $response['prvkey']); // Get public key - $pkey = openssl_pkey_get_details($result); + $pkey = openssl_pkey_get_details($result); $response['pubkey'] = $pkey["key"]; return $response; @@ -164,9 +164,9 @@ class Crypto } $fn = 'encrypt' . strtoupper($alg); if (method_exists(__CLASS__, $fn)) { - $result = ['encrypted' => true]; - $key = random_bytes(256); - $iv = random_bytes(256); + $result = ['encrypted' => true]; + $key = random_bytes(256); + $iv = random_bytes(256); $result['data'] = Strings::base64UrlEncode(self::$fn($data, $key, $iv), true); // log the offending call so we can track it down @@ -205,9 +205,9 @@ class Crypto DI::logger()->notice('aes_encapsulate: no key. data: ' . $data); } - $key = random_bytes(32); - $iv = random_bytes(16); - $result = ['encrypted' => true]; + $key = random_bytes(32); + $iv = random_bytes(16); + $result = ['encrypted' => true]; $result['data'] = Strings::base64UrlEncode(self::encryptAES256CBC($data, $key, $iv), true); // log the offending call so we can track it down diff --git a/src/Util/DateTimeFormat.php b/src/Util/DateTimeFormat.php index 3e10eb1b53..42b49cbf7d 100644 --- a/src/Util/DateTimeFormat.php +++ b/src/Util/DateTimeFormat.php @@ -23,7 +23,7 @@ class DateTimeFormat const JSON = 'Y-m-d\TH:i:s.v\Z'; const API = 'D M d H:i:s +0000 Y'; - static $localTimezone = 'UTC'; + public static $localTimezone = 'UTC'; public static function setLocalTimeZone(string $timezone) { diff --git a/src/Util/HTTPSignature.php b/src/Util/HTTPSignature.php index a544119616..9cf155f4ff 100644 --- a/src/Util/HTTPSignature.php +++ b/src/Util/HTTPSignature.php @@ -49,19 +49,19 @@ class HTTPSignature { $headers = null; $spoofable = false; - $result = [ - 'signer' => '', - 'header_signed' => false, - 'header_valid' => false + $result = [ + 'signer' => '', + 'header_signed' => false, + 'header_valid' => false ]; // Decide if $data arrived via controller submission or curl. - $headers = []; + $headers = []; $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . $_SERVER['REQUEST_URI']; foreach ($_SERVER as $k => $v) { if (strpos($k, 'HTTP_') === 0) { - $field = str_replace('_', '-', strtolower(substr($k, 5))); + $field = str_replace('_', '-', strtolower(substr($k, 5))); $headers[$field] = $v; } } @@ -98,7 +98,7 @@ class HTTPSignature if ($key && function_exists($key)) { $result['signer'] = $sig_block['keyId']; - $key = $key($sig_block['keyId']); + $key = $key($sig_block['keyId']); } DI::logger()->info('Got keyID ' . $sig_block['keyId']); @@ -136,7 +136,7 @@ class HTTPSignature $return_headers = $head; } - $alg = 'sha512'; + $alg = 'sha512'; $algorithm = 'rsa-sha512'; $x = self::sign($head, $prvkey, $alg); @@ -158,7 +158,7 @@ class HTTPSignature */ private static function sign(array $head, string $prvkey, string $alg = 'sha256'): array { - $ret = []; + $ret = []; $headers = ''; $fields = ''; @@ -220,10 +220,10 @@ class HTTPSignature } $return = [ - 'keyId' => $headers['keyId'] ?? '', + 'keyId' => $headers['keyId'] ?? '', 'algorithm' => $headers['algorithm'] ?? 'rsa-sha256', - 'created' => $headers['created'] ?? null, - 'expires' => $headers['expires'] ?? null, + 'created' => $headers['created'] ?? null, + 'expires' => $headers['expires'] ?? null, 'headers' => explode(' ', $headers['headers'] ?? ''), 'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')), ]; @@ -268,17 +268,17 @@ class HTTPSignature $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); // Header data that is about to be signed. - $host = strtolower(parse_url($target, PHP_URL_HOST)); - $path = parse_url($target, PHP_URL_PATH); - $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true)); + $host = strtolower(parse_url($target, PHP_URL_HOST)); + $path = parse_url($target, PHP_URL_PATH); + $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true)); $content_length = strlen($content); - $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP); + $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP); $headers = [ - 'Date' => $date, + 'Date' => $date, 'Content-Length' => $content_length, - 'Digest' => $digest, - 'Host' => $host + 'Digest' => $digest, + 'Host' => $host ]; $signed_data = "(request-target): post " . $path . "\ndate: " . $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host; @@ -289,7 +289,7 @@ class HTTPSignature $headers['Content-Type'] = 'application/activity+json'; - $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'), HttpClientRequest::ACTIVITYPUB); + $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'), HttpClientRequest::ACTIVITYPUB); $return_code = $postResult->getReturnCode(); DI::logger()->info('Transmit to ' . $target . ' returned ' . $return_code); @@ -318,10 +318,10 @@ class HTTPSignature return false; } - $activity = JsonLD::compact($data); - $type = JsonLD::fetchElement($activity, '@type'); + $activity = JsonLD::compact($data); + $type = JsonLD::fetchElement($activity, '@type'); $trust_source = true; - $object_data = Receiver::prepareObjectData($activity, $uid, true, $trust_source, $owner['url']); + $object_data = Receiver::prepareObjectData($activity, $uid, true, $trust_source, $owner['url']); if (empty($object_data)) { return false; } @@ -387,7 +387,7 @@ class HTTPSignature * @param int $gsid Server ID * @throws \Exception */ - static public function setInboxStatus(string $url, bool $success, bool $shared = false, int $gsid = null) + public static function setInboxStatus(string $url, bool $success, bool $shared = false, int $gsid = null) { $now = DateTimeFormat::utcNow(); @@ -434,7 +434,7 @@ class HTTPSignature $stamp1 = strtotime($status['success']); } - $stamp2 = strtotime($now); + $stamp2 = strtotime($now); $previous_stamp = strtotime($status['previous']); // Archive the inbox when there had been failures for five days. @@ -629,19 +629,19 @@ class HTTPSignature $actor = ''; } - $headers = []; + $headers = []; $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH); // First take every header foreach ($http_headers as $k => $v) { - $field = str_replace('_', '-', strtolower($k)); + $field = str_replace('_', '-', strtolower($k)); $headers[$field] = $v; } // Now add every http header foreach ($http_headers as $k => $v) { if (strpos($k, 'HTTP_') === 0) { - $field = str_replace('_', '-', strtolower(substr($k, 5))); + $field = str_replace('_', '-', strtolower(substr($k, 5))); $headers[$field] = $v; } } diff --git a/src/Util/Images.php b/src/Util/Images.php index 804ba73877..5fcdb29381 100644 --- a/src/Util/Images.php +++ b/src/Util/Images.php @@ -403,19 +403,19 @@ class Images // constrain the width - let the height float. if ((($height * 9) / 16) > $width) { - $dest_width = $max; + $dest_width = $max; $dest_height = intval(ceil(($height * $max) / $width)); } elseif ($width > $height) { // else constrain both dimensions - $dest_width = $max; + $dest_width = $max; $dest_height = intval(ceil(($height * $max) / $width)); } else { - $dest_width = intval(ceil(($width * $max) / $height)); + $dest_width = intval(ceil(($width * $max) / $height)); $dest_height = $max; } } else { if ($width > $max) { - $dest_width = $max; + $dest_width = $max; $dest_height = intval(ceil(($height * $max) / $width)); } else { if ($height > $max) { @@ -423,14 +423,14 @@ class Images // but width is OK - don't do anything if ((($height * 9) / 16) > $width) { - $dest_width = $width; + $dest_width = $width; $dest_height = $height; } else { - $dest_width = intval(ceil(($width * $max) / $height)); + $dest_width = intval(ceil(($width * $max) / $height)); $dest_height = $max; } } else { - $dest_width = $width; + $dest_width = $width; $dest_height = $height; } } diff --git a/src/Util/JsonLD.php b/src/Util/JsonLD.php index 833de559d7..3301ca1b40 100644 --- a/src/Util/JsonLD.php +++ b/src/Util/JsonLD.php @@ -62,7 +62,7 @@ class JsonLD break; default: switch (parse_url($url, PHP_URL_PATH)) { - case '/schemas/litepub-0.1.jsonld'; + case '/schemas/litepub-0.1.jsonld': $url = DI::basePath() . '/static/litepub-0.1.jsonld'; break; case '/apschema/v1.2': @@ -117,10 +117,10 @@ class JsonLD $jsonobj = json_decode(json_encode($json, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); try { - $normalized = jsonld_normalize($jsonobj, array('algorithm' => 'URDNA2015', 'format' => 'application/nquads')); + $normalized = jsonld_normalize($jsonobj, ['algorithm' => 'URDNA2015', 'format' => 'application/nquads']); } catch (Exception $e) { - $normalized = false; - $messages = []; + $normalized = false; + $messages = []; $currentException = $e; do { $messages[] = $currentException->getMessage(); @@ -148,23 +148,23 @@ class JsonLD jsonld_set_document_loader('Friendica\Util\JsonLD::documentLoader'); $context = (object)[ - 'as' => 'https://www.w3.org/ns/activitystreams#', - 'w3id' => 'https://w3id.org/security#', - 'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'], - 'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'], - 'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'], - 'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'], - 'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'], - 'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'], - 'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id'], - 'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id'], - 'sc' => (object)['@id' => 'http://schema.org#', '@type' => '@id'], - 'pt' => (object)['@id' => 'https://joinpeertube.org/ns#', '@type' => '@id'], + 'as' => 'https://www.w3.org/ns/activitystreams#', + 'w3id' => 'https://w3id.org/security#', + 'ldp' => (object)['@id' => 'http://www.w3.org/ns/ldp#', '@type' => '@id'], + 'vcard' => (object)['@id' => 'http://www.w3.org/2006/vcard/ns#', '@type' => '@id'], + 'dfrn' => (object)['@id' => 'http://purl.org/macgirvin/dfrn/1.0/', '@type' => '@id'], + 'diaspora' => (object)['@id' => 'https://diasporafoundation.org/ns/', '@type' => '@id'], + 'ostatus' => (object)['@id' => 'http://ostatus.org#', '@type' => '@id'], + 'dc' => (object)['@id' => 'http://purl.org/dc/terms/', '@type' => '@id'], + 'toot' => (object)['@id' => 'http://joinmastodon.org/ns#', '@type' => '@id'], + 'litepub' => (object)['@id' => 'http://litepub.social/ns#', '@type' => '@id'], + 'sc' => (object)['@id' => 'http://schema.org#', '@type' => '@id'], + 'pt' => (object)['@id' => 'https://joinpeertube.org/ns#', '@type' => '@id'], 'mobilizon' => (object)['@id' => 'https://joinmobilizon.org/ns#', '@type' => '@id'], - 'fedibird' => (object)['@id' => 'http://fedibird.com/ns#', '@type' => '@id'], - 'misskey' => (object)['@id' => 'https://misskey-hub.net/ns#', '@type' => '@id'], - 'pixelfed' => (object)['@id' => 'http://pixelfed.org/ns#', '@type' => '@id'], - 'lemmy' => (object)['@id' => 'https://join-lemmy.org/ns#', '@type' => '@id'], + 'fedibird' => (object)['@id' => 'http://fedibird.com/ns#', '@type' => '@id'], + 'misskey' => (object)['@id' => 'https://misskey-hub.net/ns#', '@type' => '@id'], + 'pixelfed' => (object)['@id' => 'http://pixelfed.org/ns#', '@type' => '@id'], + 'lemmy' => (object)['@id' => 'https://join-lemmy.org/ns#', '@type' => '@id'], ]; $orig_json = $json; diff --git a/src/Util/LDSignature.php b/src/Util/LDSignature.php index 8728915dd0..f5c86d4843 100644 --- a/src/Util/LDSignature.php +++ b/src/Util/LDSignature.php @@ -74,14 +74,14 @@ class LDSignature public static function sign(array $data, array $owner): array { $options = [ - 'type' => 'RsaSignature2017', - 'nonce' => Strings::getRandomHex(64), + 'type' => 'RsaSignature2017', + 'nonce' => Strings::getRandomHex(64), 'creator' => $owner['url'] . '#main-key', 'created' => DateTimeFormat::utcNow(DateTimeFormat::ATOM), ]; - $ohash = self::hash(self::signableOptions($options)); - $dhash = self::hash(self::signableData($data)); + $ohash = self::hash(self::signableOptions($options)); + $dhash = self::hash(self::signableData($data)); $options['signatureValue'] = base64_encode(Crypto::rsaSign($ohash . $dhash, $owner['uprvkey'])); return array_merge($data, ['signature' => $options]); diff --git a/src/Util/Network.php b/src/Util/Network.php index a9c14779c7..1584faea3f 100644 --- a/src/Util/Network.php +++ b/src/Util/Network.php @@ -20,7 +20,6 @@ use Psr\Http\Message\UriInterface; class Network { - /** * Return raw post data from a post request * @@ -58,7 +57,7 @@ class Network } $xrd_timeout = DI::config()->get('system', 'xrd_timeout'); - $host = parse_url($url, PHP_URL_HOST); + $host = parse_url($url, PHP_URL_HOST); if (empty($host) || !(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) { return false; @@ -66,7 +65,7 @@ class Network if (in_array(parse_url($url, PHP_URL_SCHEME), ['https', 'http'])) { $options = [HttpClientOptions::VERIFY => true, HttpClientOptions::TIMEOUT => $xrd_timeout, - HttpClientOptions::REQUEST => HttpClientRequest::URLVERIFIER]; + HttpClientOptions::REQUEST => HttpClientRequest::URLVERIFIER]; try { $curlResult = DI::httpClient()->head($url, $options); } catch (\Exception $e) { @@ -298,9 +297,9 @@ class Network public static function lookupAvatarByEmail(string $email): string { - $avatar['size'] = 300; - $avatar['email'] = $email; - $avatar['url'] = ''; + $avatar['size'] = 300; + $avatar['email'] = $email; + $avatar['url'] = ''; $avatar['success'] = false; Hook::callAll('avatar_lookup', $avatar); @@ -340,18 +339,18 @@ class Network 'fb_action_ids', 'fb_action_types', 'fb_ref', 'awesm', 'wtrid', 'woo_campaign', 'woo_source', 'woo_medium', 'woo_content', 'woo_term'] - ) + ) ) { $pair = $param . '=' . urlencode($value); - $url = str_replace($pair, '', $url); + $url = str_replace($pair, '', $url); // Second try: if the url isn't encoded completely $pair = $param . '=' . str_replace(' ', '+', $value); - $url = str_replace($pair, '', $url); + $url = str_replace($pair, '', $url); // Third try: Maybe the url isn't encoded at all $pair = $param . '=' . $value; - $url = str_replace($pair, '', $url); + $url = str_replace($pair, '', $url); $url = str_replace(['?&', '&&'], ['?', ''], $url); } @@ -383,7 +382,7 @@ class Network $base = [ 'scheme' => parse_url($basepath, PHP_URL_SCHEME), - 'host' => parse_url($basepath, PHP_URL_HOST), + 'host' => parse_url($basepath, PHP_URL_HOST), ]; $parts = array_merge($base, parse_url('/' . ltrim($url, '/'))); @@ -463,7 +462,7 @@ class Network $pathparts1 = explode('/', $parts1['path']); $pathparts2 = explode('/', $parts2['path']); - $i = 0; + $i = 0; $path = ''; do { $path1 = $pathparts1[$i] ?? ''; @@ -491,7 +490,7 @@ class Network $parts = parse_url($uri); if (!empty($parts['scheme']) && !empty($parts['host'])) { $parts['host'] = self::idnToAscii($parts['host']); - $uri = (string)Uri::fromParts($parts); + $uri = (string)Uri::fromParts($parts); } else { $parts = explode('@', $uri); if (count($parts) == 2) { diff --git a/src/Util/ParseUrl.php b/src/Util/ParseUrl.php index 8e86007695..5b75c27094 100644 --- a/src/Util/ParseUrl.php +++ b/src/Util/ParseUrl.php @@ -77,7 +77,7 @@ class ParseUrl return []; } - $contenttype = $curlResult->getContentType(); + $contenttype = $curlResult->getContentType(); if (empty($contenttype)) { return ['application', 'octet-stream']; } @@ -108,14 +108,16 @@ class ParseUrl { if (empty($url)) { return [ - 'url' => '', + 'url' => '', 'type' => 'error', ]; } $urlHash = hash('sha256', $url); - $parsed_url = DBA::selectFirst('parsed_url', ['content'], + $parsed_url = DBA::selectFirst( + 'parsed_url', + ['content'], ['url_hash' => $urlHash, 'oembed' => false] ); if (!empty($parsed_url['content'])) { @@ -186,7 +188,7 @@ class ParseUrl { if (empty($url)) { return [ - 'url' => '', + 'url' => '', 'type' => 'error', ]; } @@ -203,8 +205,8 @@ class ParseUrl $url = Network::stripTrackingQueryParams($url); $siteinfo = [ - 'url' => $url, - 'type' => 'link', + 'url' => $url, + 'type' => 'link', 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE), ]; @@ -244,12 +246,12 @@ class ParseUrl if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') { if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) { - $maxAge = max(86400, (int)array_pop($matches)); + $maxAge = max(86400, (int)array_pop($matches)); $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds"); } } - $body = $curlResult->getBodyString(); + $body = $curlResult->getBodyString(); $siteinfo['size'] = mb_strlen($body); $charset = ''; @@ -259,7 +261,8 @@ class ParseUrl if (isset($mediaType->parameters['charset'])) { $charset = $mediaType->parameters['charset']; } - } catch(\InvalidArgumentException $e) {} + } catch(\InvalidArgumentException $e) { + } $siteinfo['charset'] = $charset; @@ -305,9 +308,9 @@ class ParseUrl } if (@$meta_tag['http-equiv'] == 'refresh') { - $path = $meta_tag['content']; + $path = $meta_tag['content']; $pathinfo = explode(';', $path); - $content = ''; + $content = ''; foreach ($pathinfo as $value) { if (substr(strtolower($value), 0, 4) == 'url=') { $content = substr($value, 4); @@ -487,7 +490,7 @@ class ParseUrl if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) { $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…'; - $pos = mb_strrpos($siteinfo['text'], '.'); + $pos = mb_strrpos($siteinfo['text'], '.'); if ($pos > self::MIN_DESC_COUNT) { $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1); } @@ -510,7 +513,7 @@ class ParseUrl * @param array $siteinfo * @return array */ - private static function checkMedia(string $page_url, array $siteinfo) : array + private static function checkMedia(string $page_url, array $siteinfo): array { if (!empty($siteinfo['images'])) { array_walk($siteinfo['images'], function (&$image) use ($page_url) { @@ -521,13 +524,13 @@ class ParseUrl */ if (!empty($image['url'])) { $image['url'] = self::completeUrl($image['url'], $page_url); - $photodata = Images::getInfoFromURLCached($image['url']); + $photodata = Images::getInfoFromURLCached($image['url']); if (($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) { - $image['src'] = $image['url']; - $image['width'] = $photodata[0]; - $image['height'] = $photodata[1]; + $image['src'] = $image['url']; + $image['width'] = $photodata[0]; + $image['height'] = $photodata[1]; $image['contenttype'] = $photodata['mime']; - $image['blurhash'] = $photodata['blurhash'] ?? null; + $image['blurhash'] = $photodata['blurhash'] ?? null; unset($image['url']); ksort($image); } else { @@ -544,14 +547,14 @@ class ParseUrl foreach (['audio', 'video'] as $element) { if (!empty($siteinfo[$element])) { array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) { - $url = ''; - $embed = ''; - $content = ''; + $url = ''; + $embed = ''; + $content = ''; $contenttype = ''; foreach (['embed', 'content', 'url'] as $field) { if (!empty($media[$field])) { $media[$field] = self::completeUrl($media[$field], $page_url); - $type = self::getContentType($media[$field]); + $type = self::getContentType($media[$field]); if (($type[0] ?? '') == 'text') { if ($field == 'embed') { $embed = $media[$field]; @@ -559,7 +562,7 @@ class ParseUrl $url = $media[$field]; } } elseif (!empty($type[0])) { - $content = $media[$field]; + $content = $media[$field]; $contenttype = implode('/', $type); } } @@ -706,7 +709,7 @@ class ParseUrl } elseif (!empty($jsonld['@type'])) { $siteinfo = self::parseJsonLd($siteinfo, $jsonld); } elseif (!empty($jsonld)) { - $keys = array_keys($jsonld); + $keys = array_keys($jsonld); $numeric_keys = true; foreach ($keys as $key) { if (!is_int($key)) { @@ -810,7 +813,7 @@ class ParseUrl case 'Person': case 'Patient': case 'PerformingGroup': - case 'DanceGroup'; + case 'DanceGroup': case 'MusicGroup': case 'TheaterGroup': return self::parseJsonLdWebPerson($siteinfo, $jsonld); @@ -953,7 +956,7 @@ class ParseUrl $content = JsonLD::fetchElement($jsonld, 'keywords'); if (!empty($content)) { $siteinfo['keywords'] = []; - $keywords = explode(',', $content); + $keywords = explode(',', $content); foreach ($keywords as $keyword) { $siteinfo['keywords'][] = trim($keyword); } diff --git a/src/Util/Proxy.php b/src/Util/Proxy.php index 1e49f7bbf5..f6f76603e9 100644 --- a/src/Util/Proxy.php +++ b/src/Util/Proxy.php @@ -37,7 +37,8 @@ class Proxy /** * Private constructor */ - private function __construct () { + private function __construct() + { // No instances from utilities classes } diff --git a/src/Util/Strings.php b/src/Util/Strings.php index 60bb83e0d5..efa0994ec3 100644 --- a/src/Util/Strings.php +++ b/src/Util/Strings.php @@ -155,7 +155,7 @@ class Strings { if ($network != '') { if ($url != '') { - $gsid = ContactSelector::getServerIdForProfile($url); + $gsid = ContactSelector::getServerIdForProfile($url); $network_name = '' . ContactSelector::networkToName($network, '', $gsid) . ''; } else { $network_name = ContactSelector::networkToName($network); @@ -214,8 +214,8 @@ class Strings $units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; $bytes = max($bytes, 0); - $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); - $pow = min($pow, count($units) - 1); + $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); + $pow = min($pow, count($units) - 1); $bytes /= pow(1024, $pow); return round($bytes, $precision) . ' ' . $units[$pow]; @@ -448,13 +448,13 @@ class Strings if ($start < 0) { $start = max(0, $string_length + $start); - } else if ($start > $string_length) { + } elseif ($start > $string_length) { $start = $string_length; } if ($length < 0) { $length = max(0, $string_length - $start + $length); - } else if ($length > $string_length) { + } elseif ($length > $string_length) { $length = $string_length; } @@ -544,8 +544,10 @@ class Strings switch ($last) { case 'g': $shorthand *= 1024; + // no break case 'm': $shorthand *= 1024; + // no break case 'k': $shorthand *= 1024; } @@ -567,7 +569,7 @@ class Strings return $url; } - $scheme = [$parts['scheme'] . '://www.', $parts['scheme'] . '://']; + $scheme = [$parts['scheme'] . '://www.', $parts['scheme'] . '://']; $styled_url = str_replace($scheme, '', $url); if (!empty($max_length) && strlen($styled_url) > $max_length) { diff --git a/src/Util/XML.php b/src/Util/XML.php index 8cf0e86b82..cf5689c361 100644 --- a/src/Util/XML.php +++ b/src/Util/XML.php @@ -45,9 +45,9 @@ class XML $root = new SimpleXMLElement('<' . $key . '>' . self::escape($value ?? '') . ''); } - $dom = dom_import_simplexml($root)->ownerDocument; + $dom = dom_import_simplexml($root)->ownerDocument; $dom->formatOutput = true; - $xml = $dom; + $xml = $dom; $xml_text = $dom->saveXML(); @@ -154,7 +154,7 @@ class XML $element = $doc->createElement($element, self::escape($value)); foreach ($attributes as $key => $value) { - $attribute = $doc->createAttribute($key); + $attribute = $doc->createAttribute($key); $attribute->value = self::escape($value ?? ''); $element->appendChild($attribute); } @@ -199,7 +199,7 @@ class XML && (get_class($xml_element) == 'SimpleXMLElement') ) { $xml_element_copy = $xml_element; - $xml_element = get_object_vars($xml_element); + $xml_element = get_object_vars($xml_element); } if (is_array($xml_element)) { @@ -210,12 +210,12 @@ class XML foreach ($xml_element as $key => $value) { $recursion_depth++; - $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth); + $result_array[strtolower($key)] = self::elementToArray($value, $recursion_depth); $recursion_depth--; } if ($recursion_depth == 0) { - $temp_array = $result_array; + $temp_array = $result_array; $result_array = [ strtolower($xml_element_copy->getName()) => $temp_array, ]; @@ -306,7 +306,7 @@ class XML $attributes = isset($data['attributes']) ? $data['attributes'] : null; $value = isset($data['value']) ? $data['value'] : null; - $result = []; + $result = []; $attributes_data = []; if (isset($value)) { @@ -330,14 +330,14 @@ class XML // See tag status and do the needed. if ($namespaces && strpos($tag, ':')) { - $namespc = substr($tag, 0, strrpos($tag, ':')); - $tag = strtolower(substr($tag, strlen($namespc)+1)); + $namespc = substr($tag, 0, strrpos($tag, ':')); + $tag = strtolower(substr($tag, strlen($namespc) + 1)); $result['@namespace'] = $namespc; } $tag = strtolower($tag); if ($type == 'open') { // The starting of the tag '' - $parent[$level-1] = &$current; + $parent[$level - 1] = &$current; if (!is_array($current) || (!in_array($tag, array_keys($current)))) { // Insert New tag $current[$tag] = $result; if ($attributes_data) { @@ -352,7 +352,7 @@ class XML $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result; $repeated_tag_index[$tag . '_' . $level]++; } else { // This section will make the value an array if multiple tags with the same name appear together - $current[$tag] = [$current[$tag], $result]; // This will combine the existing item and the new item together to make an array + $current[$tag] = [$current[$tag], $result]; // This will combine the existing item and the new item together to make an array $repeated_tag_index[$tag . '_' . $level] = 2; if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well @@ -360,13 +360,13 @@ class XML unset($current[$tag.'_attr']); } } - $last_item_index = $repeated_tag_index[$tag . '_' . $level]-1; - $current = &$current[$tag][$last_item_index]; + $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1; + $current = &$current[$tag][$last_item_index]; } } elseif ($type == 'complete') { // Tags that ends in 1 line '' //See if the key is already taken. if (!isset($current[$tag])) { //New Key - $current[$tag] = $result; + $current[$tag] = $result; $repeated_tag_index[$tag . '_' . $level] = 1; if ($priority == 'tag' and $attributes_data) { $current[$tag. '_attr'] = $attributes_data; @@ -382,7 +382,7 @@ class XML } $repeated_tag_index[$tag . '_' . $level]++; } else { // If it is not an array... - $current[$tag] = [$current[$tag], $result]; //...Make it an array using the existing value and the new value + $current[$tag] = [$current[$tag], $result]; //...Make it an array using the existing value and the new value $repeated_tag_index[$tag . '_' . $level] = 1; if ($priority == 'tag' and $get_attributes) { if (isset($current[$tag.'_attr'])) { // The attribute of the last(0th) tag must be moved as well @@ -399,7 +399,7 @@ class XML } } } elseif ($type == 'close') { // End of tag '' - $current = &$parent[$level-1]; + $current = &$parent[$level - 1]; } } @@ -416,7 +416,7 @@ class XML public static function deleteNode(DOMDocument $doc, string $node) { $xpath = new DOMXPath($doc); - $list = $xpath->query('//' . $node); + $list = $xpath->query('//' . $node); foreach ($list as $child) { $child->parentNode->removeChild($child); } diff --git a/src/Worker/APDelivery.php b/src/Worker/APDelivery.php index 2d1df8cca4..0c986d3bab 100644 --- a/src/Worker/APDelivery.php +++ b/src/Worker/APDelivery.php @@ -12,6 +12,7 @@ use Friendica\DI; use Friendica\Model\Post; use Friendica\Model\User; use Friendica\Protocol\ActivityPub; + class APDelivery { /** @@ -31,7 +32,7 @@ class APDelivery if (ActivityPub\Transmitter::archivedInbox($inbox)) { DI::logger()->info('Inbox is archived', ['cmd' => $cmd, 'inbox' => $inbox, 'id' => $item_id, 'uri-id' => $uri_id, 'uid' => $uid]); if (empty($uri_id) && !empty($item_id)) { - $item = Post::selectFirst(['uri-id'], ['id' => $item_id]); + $item = Post::selectFirst(['uri-id'], ['id' => $item_id]); $uri_id = $item['uri-id'] ?? 0; } if (empty($uri_id)) { diff --git a/src/Worker/DelayedPublish.php b/src/Worker/DelayedPublish.php index 8020a042d4..ef2d69277c 100644 --- a/src/Worker/DelayedPublish.php +++ b/src/Worker/DelayedPublish.php @@ -12,17 +12,17 @@ use Friendica\Model\Post; class DelayedPublish { - /** + /** * Publish a post, used for delayed postings - * - * @param array $item - * @param int $notify - * @param array $taglist - * @param array $attachments - * @param int $preparation_mode - * @param string $uri - * @return void - */ + * + * @param array $item + * @param int $notify + * @param array $taglist + * @param array $attachments + * @param int $preparation_mode + * @param string $uri + * @return void + */ public static function execute(array $item, int $notify = 0, array $taglist = [], array $attachments = [], int $preparation_mode = Post\Delayed::PREPARED, string $uri = '') { $id = Post\Delayed::publish($item, $notify, $taglist, $attachments, $preparation_mode, $uri); diff --git a/src/Worker/Directory.php b/src/Worker/Directory.php index e9a9102277..1490fc076f 100644 --- a/src/Worker/Directory.php +++ b/src/Worker/Directory.php @@ -47,7 +47,8 @@ class Directory return; } - private static function updateAll() { + private static function updateAll() + { $users = DBA::select('owner-view', ['url'], ['net-publish' => true, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]); while ($user = DBA::fetch($users)) { Worker::add(Worker::PRIORITY_LOW, 'Directory', $user['url']); diff --git a/src/Worker/Expire.php b/src/Worker/Expire.php index 77a37e4b5f..3387fe0973 100644 --- a/src/Worker/Expire.php +++ b/src/Worker/Expire.php @@ -47,16 +47,23 @@ class Expire $r = DBA::select('user', ['uid', 'username'], ["`expire` != ?", 0]); while ($row = DBA::fetch($r)) { DI::logger()->info('Calling expiry', ['user' => $row['uid'], 'username' => $row['username']]); - Worker::add(['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], - 'Expire', (int)$row['uid']); + Worker::add( + ['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], + 'Expire', + (int)$row['uid'] + ); } DBA::close($r); DI::logger()->notice('calling hooks'); foreach (Hook::getByName('expire') as $hook) { DI::logger()->info('Calling expire', ['hook' => $hook[1]]); - Worker::add(['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], - 'Expire', 'hook', $hook[1]); + Worker::add( + ['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], + 'Expire', + 'hook', + $hook[1] + ); } DI::logger()->notice('calling hooks done'); diff --git a/src/Worker/ExpireAndRemoveUsers.php b/src/Worker/ExpireAndRemoveUsers.php index 816475e8ee..6fbb6a14ca 100644 --- a/src/Worker/ExpireAndRemoveUsers.php +++ b/src/Worker/ExpireAndRemoveUsers.php @@ -29,7 +29,7 @@ class ExpireAndRemoveUsers // Ensure to never remove the user with uid=0 DBA::update('user', ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, - 'account_expires_on' => DBA::NULL_DATETIME], ['uid' => 0]); + 'account_expires_on' => DBA::NULL_DATETIME], ['uid' => 0]); // Remove any freshly expired account $users = DBA::select('user', ['uid'], ['account_expired' => true, 'account_removed' => false]); diff --git a/src/Worker/ExpirePosts.php b/src/Worker/ExpirePosts.php index e1c8fe1685..1d4e546a37 100644 --- a/src/Worker/ExpirePosts.php +++ b/src/Worker/ExpirePosts.php @@ -73,10 +73,10 @@ class ExpirePosts DI::logger()->notice('Delete expired posts'); // physically remove anything that has been deleted for more than two months $condition = ["`gravity` = ? AND `deleted` AND `edited` < ?", Item::GRAVITY_PARENT, DateTimeFormat::utc('now - 60 days')]; - $pass = 0; + $pass = 0; do { ++$pass; - $rows = DBA::select('post-user', ['uri-id', 'uid'], $condition, ['limit' => $limit]); + $rows = DBA::select('post-user', ['uri-id', 'uid'], $condition, ['limit' => $limit]); $affected_count = 0; while ($row = Post::fetch($rows)) { DI::logger()->info('Delete expired item', ['pass' => $pass, 'uri-id' => $row['uri-id']]); @@ -108,7 +108,7 @@ class ExpirePosts } DI::logger()->notice('Start collecting orphaned entries', ['table' => $table]); - $uris = DBA::select($table, ['uri-id'], ["NOT `uri-id` IN (SELECT `uri-id` FROM `post-user`)"]); + $uris = DBA::select($table, ['uri-id'], ["NOT `uri-id` IN (SELECT `uri-id` FROM `post-user`)"]); $affected_count = 0; DI::logger()->notice('Deleting orphaned entries - start', ['table' => $table]); while ($rows = DBA::toArray($uris, false, 100)) { @@ -132,7 +132,7 @@ class ExpirePosts { DI::logger()->notice('Adding missing entries'); - $rows = 0; + $rows = 0; $userposts = DBA::select('post-user', [], ["`uri-id` not in (select `uri-id` from `post`)"]); while ($fields = DBA::fetch($userposts)) { $post_fields = DI::dbaDefinition()->truncateFieldsForTable('post', $fields); @@ -146,10 +146,10 @@ class ExpirePosts DI::logger()->notice('No post entries added'); } - $rows = 0; + $rows = 0; $userposts = DBA::select('post-user', [], ["`gravity` = ? AND `uri-id` not in (select `uri-id` from `post-thread`)", Item::GRAVITY_PARENT]); while ($fields = DBA::fetch($userposts)) { - $post_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread', $fields); + $post_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread', $fields); $post_fields['commented'] = $post_fields['changed'] = $post_fields['created']; DBA::insert('post-thread', $post_fields, Database::INSERT_IGNORE); $rows++; @@ -161,10 +161,10 @@ class ExpirePosts DI::logger()->notice('No post-thread entries added'); } - $rows = 0; + $rows = 0; $userposts = DBA::select('post-user', [], ["`gravity` = ? AND `id` not in (select `post-user-id` from `post-thread-user`)", Item::GRAVITY_PARENT]); while ($fields = DBA::fetch($userposts)) { - $post_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread-user', $fields); + $post_fields = DI::dbaDefinition()->truncateFieldsForTable('post-thread-user', $fields); $post_fields['commented'] = $post_fields['changed'] = $post_fields['created']; DBA::insert('post-thread-user', $post_fields, Database::INSERT_IGNORE); $rows++; @@ -223,7 +223,7 @@ class ExpirePosts $pass = 0; do { ++$pass; - $uris = DBA::select('item-uri', ['id'], $condition, ['limit' => $limit]); + $uris = DBA::select('item-uri', ['id'], $condition, ['limit' => $limit]); $total = DBA::numRows($uris); DI::logger()->notice('Start deleting orphaned URI-ID', ['pass' => $pass, 'last-id' => $item['uri-id']]); $affected_count = 0; @@ -249,7 +249,7 @@ class ExpirePosts return; } - $expire_days = DI::config()->get('system', 'dbclean-expire-days'); + $expire_days = DI::config()->get('system', 'dbclean-expire-days'); $expire_days_unclaimed = DI::config()->get('system', 'dbclean-expire-unclaimed'); if (empty($expire_days_unclaimed)) { $expire_days_unclaimed = $expire_days; @@ -306,7 +306,7 @@ class ExpirePosts $pass = 0; do { ++$pass; - $uris = DBA::select('post-user', ['uri-id'], $condition, ['limit' => $limit]); + $uris = DBA::select('post-user', ['uri-id'], $condition, ['limit' => $limit]); $total = DBA::numRows($uris); DI::logger()->notice('Start deleting unclaimed public items', ['pass' => $pass]); $affected_count = 0; diff --git a/src/Worker/Notifier.php b/src/Worker/Notifier.php index eccb0bb602..d0938bfcad 100644 --- a/src/Worker/Notifier.php +++ b/src/Worker/Notifier.php @@ -47,42 +47,50 @@ class Notifier DI::logger()->info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]); - $target_id = $post_uriid; + $target_id = $post_uriid; $recipients = []; $delivery_contacts_stmt = null; - $target_item = []; - $parent = []; - $thr_parent = []; - $items = []; - $delivery_queue_count = 0; - $ap_contacts = []; + $target_item = []; + $parent = []; + $thr_parent = []; + $items = []; + $delivery_queue_count = 0; + $ap_contacts = []; if ($cmd == Delivery::MAIL) { $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]); if (!DBA::isResult($message)) { return; } - $uid = $message['uid']; + $uid = $message['uid']; $recipients[] = $message['contact-id']; $inboxes = ActivityPub\Transmitter::fetchTargetInboxesFromMail($target_id); foreach ($inboxes as $inbox => $receivers) { $ap_contacts = array_merge($ap_contacts, $receivers); DI::logger()->info('Delivery via ActivityPub', ['cmd' => $cmd, 'target' => $target_id, 'inbox' => $inbox]); - Worker::add(['priority' => Worker::PRIORITY_HIGH, 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], - 'APDelivery', $cmd, $target_id, $inbox, $uid, $receivers, $post_uriid); + Worker::add( + ['priority' => Worker::PRIORITY_HIGH, 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], + 'APDelivery', + $cmd, + $target_id, + $inbox, + $uid, + $receivers, + $post_uriid + ); } } elseif ($cmd == Delivery::SUGGESTION) { - $suggest = DI::fsuggest()->selectOneById($target_id); - $uid = $suggest->uid; + $suggest = DI::fsuggest()->selectOneById($target_id); + $uid = $suggest->uid; $recipients[] = $suggest->cid; } elseif ($cmd == Delivery::REMOVAL) { return self::notifySelfRemoval($target_id, $appHelper->getQueueValue('priority'), $appHelper->getQueueValue('created')); } elseif ($cmd == Delivery::RELOCATION) { $uid = $target_id; - $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]]; + $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]]; $delivery_contacts_stmt = DBA::select('contact', ['id', 'uri-id', 'url', 'addr', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition); } else { $post = Post::selectFirst(['id'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]); @@ -93,7 +101,7 @@ class Notifier $target_id = $post['id']; // find ancestors - $condition = ['id' => $target_id, 'visible' => true]; + $condition = ['id' => $target_id, 'visible' => true]; $target_item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition); $target_item = Post\Media::addHTMLAttachmentToItem($target_item); @@ -111,8 +119,8 @@ class Notifier return; } - $condition = ['parent' => $target_item['parent'], 'visible' => true]; - $params = ['order' => ['id']]; + $condition = ['parent' => $target_item['parent'], 'visible' => true]; + $params = ['order' => ['id']]; $items_stmt = Post::select(Item::DELIVER_FIELDLIST, $condition, $params); if (!DBA::isResult($items_stmt)) { DI::logger()->info('No item found', ['cmd' => $cmd, 'target' => $target_id]); @@ -145,14 +153,14 @@ class Notifier $only_ap_delivery = false; - $followup = false; + $followup = false; $recipients_followup = []; if (!empty($target_item) && !empty($items)) { $parent = $items[0]; - $fields = ['network', 'private', 'author-id', 'author-link', 'author-network', 'owner-id']; - $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']]; + $fields = ['network', 'private', 'author-id', 'author-link', 'author-network', 'owner-id']; + $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']]; $thr_parent = Post::selectFirst($fields, $condition); if (empty($thr_parent)) { $thr_parent = $parent; @@ -162,9 +170,9 @@ class Notifier // Restrict distribution to AP, when there are no permissions. if (!self::isRemovalActivity($cmd, $owner, Protocol::ACTIVITYPUB) && ($target_item['private'] == Item::PRIVATE) && empty($target_item['allow_cid']) && empty($target_item['allow_gid']) && empty($target_item['deny_cid']) && empty($target_item['deny_gid'])) { - $only_ap_delivery = true; - $public_message = false; - $diaspora_delivery = false; + $only_ap_delivery = true; + $public_message = false; + $diaspora_delivery = false; } if (!$target_item['origin'] && $target_item['network'] == Protocol::ACTIVITYPUB) { @@ -225,10 +233,10 @@ class Notifier if ($relay_to_owner) { // local followup to remote post - $followup = true; - $public_message = false; // not public - $recipients = [$parent['contact-id']]; - $recipients_followup = [$parent['contact-id']]; + $followup = true; + $public_message = false; // not public + $recipients = [$parent['contact-id']]; + $recipients_followup = [$parent['contact-id']]; DI::logger()->info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]); } elseif ($exclusive_delivery) { @@ -264,9 +272,9 @@ class Notifier $aclFormatter = DI::aclFormatter(); - $allow_people = $aclFormatter->expand($parent['allow_cid']); + $allow_people = $aclFormatter->expand($parent['allow_cid']); $allow_circles = Circle::expand($uid, $aclFormatter->expand($parent['allow_gid']), true); - $deny_people = $aclFormatter->expand($parent['deny_cid']); + $deny_people = $aclFormatter->expand($parent['deny_cid']); $deny_circles = Circle::expand($uid, $aclFormatter->expand($parent['deny_gid'])); foreach ($items as $item) { @@ -283,7 +291,7 @@ class Notifier } $recipients = array_unique(array_merge($recipients, $allow_people, $allow_circles)); - $deny = array_unique(array_merge($deny_people, $deny_circles)); + $deny = array_unique(array_merge($deny_people, $deny_circles)); $recipients = array_diff($recipients, $deny); // If this is a public message and pubmail is set on the parent, include all your email contacts @@ -320,21 +328,21 @@ class Notifier $recipients = $recipients_followup; } - $apdelivery = self::activityPubDelivery($cmd, $target_item, $parent, $thr_parent, $appHelper->getQueueValue('priority'), $appHelper->getQueueValue('created'), $recipients); + $apdelivery = self::activityPubDelivery($cmd, $target_item, $parent, $thr_parent, $appHelper->getQueueValue('priority'), $appHelper->getQueueValue('created'), $recipients); $ap_contacts = $apdelivery['contacts']; $delivery_queue_count += $apdelivery['count']; if (!$only_ap_delivery) { if (empty($delivery_contacts_stmt)) { $condition = ['id' => $recipients, 'self' => false, 'uid' => [0, $uid], - 'blocked' => false, 'pending' => false, 'archive' => false]; + 'blocked' => false, 'pending' => false, 'archive' => false]; if (!empty($networks)) { $condition['network'] = $networks; } $delivery_contacts_stmt = DBA::select('contact', ['id', 'uri-id', 'addr', 'url', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition); } - $conversants = []; + $conversants = []; $batch_delivery = false; if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) { @@ -343,9 +351,12 @@ class Notifier if ($diaspora_delivery && !$unlisted) { $batch_delivery = true; - $participants = DBA::selectToArray('contact', ['batch', 'network', 'protocol', 'baseurl', 'gsid', 'id', 'url', 'name'], + $participants = DBA::selectToArray( + 'contact', + ['batch', 'network', 'protocol', 'baseurl', 'gsid', 'id', 'url', 'name'], ["`network` = ? AND `batch` != '' AND `uid` = ? AND `rel` != ? AND NOT `blocked` AND NOT `pending` AND NOT `archive`", Protocol::DIASPORA, $owner['uid'], Contact::SHARING], - ['group_by' => ['batch', 'network', 'protocol']]); + ['group_by' => ['batch', 'network', 'protocol']] + ); // Fetch the participation list // The function will ensure that there are no duplicates @@ -415,7 +426,7 @@ class Notifier */ private static function delivery(string $cmd, int $post_uriid, int $sender_uid, array $target_item, array $parent, array $thr_parent, array $owner, bool $batch_delivery, bool $in_batch, array $contacts, array $ap_contacts, array $conversants = []): int { - $appHelper = DI::appHelper(); + $appHelper = DI::appHelper(); $delivery_queue_count = 0; if (!empty($target_item['verb']) && ($target_item['verb'] == Activity::ANNOUNCE)) { @@ -617,8 +628,15 @@ class Notifier $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser($self_user_id); foreach ($inboxes as $inbox => $receivers) { DI::logger()->info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]); - Worker::add(['priority' => Worker::PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true], - 'APDelivery', Delivery::REMOVAL, 0, $inbox, $self_user_id, $receivers); + Worker::add( + ['priority' => Worker::PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true], + 'APDelivery', + Delivery::REMOVAL, + 0, + $inbox, + $self_user_id, + $receivers + ); Worker::coolDown(); } @@ -665,7 +683,7 @@ class Notifier return ['count' => 0, 'contacts' => []]; } - $inboxes = []; + $inboxes = []; $relay_inboxes = []; $uid = $target_item['contact-uid'] ?: $target_item['uid']; @@ -682,7 +700,7 @@ class Notifier $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid); if (in_array($target_item['private'], [Item::PUBLIC])) { - $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($target_item['id'], $inboxes); + $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($target_item['id'], $inboxes); $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes(); } @@ -727,7 +745,7 @@ class Notifier } $delivery_queue_count = 0; - $contacts = []; + $contacts = []; foreach ($inboxes as $inbox => $receivers) { $contacts = array_merge($contacts, $receivers); @@ -763,8 +781,16 @@ class Notifier Post\Delivery::add($target_item['uri-id'], $uid, $inbox, $target_item['created'], $cmd, $receivers); Worker::add([Worker::PRIORITY_HIGH, 'dont_fork' => true], 'APDelivery', '', 0, $inbox, 0); } else { - if (Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true], - 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, $receivers, $target_item['uri-id'])) { + if (Worker::add( + ['priority' => $priority, 'created' => $created, 'dont_fork' => true], + 'APDelivery', + $cmd, + $target_item['id'], + $inbox, + $uid, + $receivers, + $target_item['uri-id'] + )) { $delivery_queue_count++; } } diff --git a/src/Worker/OnePoll.php b/src/Worker/OnePoll.php index 5fb4293d84..6137539612 100644 --- a/src/Worker/OnePoll.php +++ b/src/Worker/OnePoll.php @@ -167,7 +167,7 @@ class OnePoll if ($curlResult->redirectIsPermanent()) { DI::logger()->notice('Poll address permanently changed', [ - 'id' => $contact['id'], + 'id' => $contact['id'], 'uid' => $contact['uid'], 'old' => $contact['poll'], 'new' => $curlResult->getRedirectUrl(), @@ -222,9 +222,9 @@ class OnePoll $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $importer_uid]); $condition = ["`server` != ? AND `user` != ? AND `port` != ? AND `uid` = ?", '', '', 0, $importer_uid]; - $mailconf = DBA::selectFirst('mailacct', [], $condition); + $mailconf = DBA::selectFirst('mailacct', [], $condition); if (DBA::isResult($user) && DBA::isResult($mailconf)) { - $mailbox = Email::constructMailboxName($mailconf); + $mailbox = Email::constructMailboxName($mailconf); $password = ''; openssl_private_decrypt(hex2bin($mailconf['pass']), $password, $user['prvkey']); $mbox = Email::connect($mailbox, $mailconf['user'], $password); @@ -278,18 +278,19 @@ class OnePoll // $meta = Email::messageMeta($mbox, $msg_uid); // Have we seen it before? - $fields = ['deleted', 'id']; + $fields = ['deleted', 'id']; $condition = ['uid' => $importer_uid, 'uri' => $datarray['uri']]; - $item = Post::selectFirst($fields, $condition); + $item = Post::selectFirst($fields, $condition); if (DBA::isResult($item)) { DI::logger()->info('Mail: Seen before ' . $msg_uid . ' for ' . $mailconf['user'] . ' UID: ' . $importer_uid . ' URI: ' . $datarray['uri']); // Only delete when mails aren't automatically moved or deleted - if (($mailconf['action'] != 1) && ($mailconf['action'] != 3)) + if (($mailconf['action'] != 1) && ($mailconf['action'] != 3)) { if ($meta->deleted && ! $item['deleted']) { $fields = ['deleted' => true, 'changed' => $updated]; Item::update($fields, ['id' => $item['id']]); } + } switch ($mailconf['action']) { case 0: @@ -327,19 +328,19 @@ class OnePoll if ($raw_refs) { $refs_arr = explode(' ', $raw_refs); if (count($refs_arr)) { - for ($x = 0; $x < count($refs_arr); $x ++) { - $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '],['', '', ''], $refs_arr[$x])); + for ($x = 0; $x < count($refs_arr); $x++) { + $refs_arr[$x] = Email::msgid2iri(str_replace(['<', '>', ' '], ['', '', ''], $refs_arr[$x])); } } $condition = ['uri' => $refs_arr, 'uid' => $importer_uid]; - $parent = Post::selectFirst(['uri'], $condition); + $parent = Post::selectFirst(['uri'], $condition); if (DBA::isResult($parent)) { $datarray['thr-parent'] = $parent['uri']; } } // Decoding the header - $subject = imap_mime_header_decode($meta->subject ?? ''); + $subject = imap_mime_header_decode($meta->subject ?? ''); $datarray['title'] = ""; foreach ($subject as $subpart) { if ($subpart->charset != "default") { @@ -364,8 +365,8 @@ class OnePoll // If it seems to be a reply but a header couldn't be found take the last message with matching subject if (empty($datarray['thr-parent']) && $reply) { $condition = ['title' => $datarray['title'], 'uid' => $importer_uid, 'network' => Protocol::MAIL]; - $params = ['order' => ['created' => true]]; - $parent = Post::selectFirst(['uri'], $condition, $params); + $params = ['order' => ['created' => true]]; + $parent = Post::selectFirst(['uri'], $condition, $params); if (DBA::isResult($parent)) { $datarray['thr-parent'] = $parent['uri']; } @@ -400,12 +401,12 @@ class OnePoll $fromname = $headers->from[0]->personal; } - $datarray['author-name'] = $fromname; - $datarray['author-link'] = 'mailto:' . $frommail; + $datarray['author-name'] = $fromname; + $datarray['author-link'] = 'mailto:' . $frommail; $datarray['author-avatar'] = $contact['photo']; - $datarray['owner-name'] = $contact['name']; - $datarray['owner-link'] = 'mailto:' . $contact['addr']; + $datarray['owner-name'] = $contact['name']; + $datarray['owner-link'] = 'mailto:' . $contact['addr']; $datarray['owner-avatar'] = $contact['photo']; if (empty($datarray['thr-parent']) || ($datarray['thr-parent'] === $datarray['uri'])) { @@ -413,7 +414,7 @@ class OnePoll } if (!DI::pConfig()->get($importer_uid, 'system', 'allow_public_email_replies')) { - $datarray['private'] = Item::PRIVATE; + $datarray['private'] = Item::PRIVATE; $datarray['allow_cid'] = '<' . $contact['id'] . '>'; } diff --git a/src/Worker/PollContacts.php b/src/Worker/PollContacts.php index 9a5405bbc5..5bb7987ee6 100644 --- a/src/Worker/PollContacts.php +++ b/src/Worker/PollContacts.php @@ -29,11 +29,15 @@ class PollContacts $condition = ['network' => [Protocol::FEED, Protocol::MAIL], 'self' => false, 'blocked' => false, 'archive' => false]; if (!empty($abandon_days)) { - $condition = DBA::mergeConditions($condition, - ["`uid` != ? AND `uid` IN (SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `last-activity` > ?)", 0, DateTimeFormat::utc('now - ' . $abandon_days . ' days')]); - } else { - $condition = DBA::mergeConditions($condition, - ["`uid` != ? AND `uid` IN (SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`)", 0]); + $condition = DBA::mergeConditions( + $condition, + ["`uid` != ? AND `uid` IN (SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired` AND `last-activity` > ?)", 0, DateTimeFormat::utc('now - ' . $abandon_days . ' days')] + ); + } else { + $condition = DBA::mergeConditions( + $condition, + ["`uid` != ? AND `uid` IN (SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`)", 0] + ); } $contacts = DBA::select('contact', ['id', 'nick', 'name', 'network', 'archive', 'last-update', 'priority', 'rating'], $condition); @@ -47,10 +51,10 @@ class PollContacts continue; } - $now = DateTimeFormat::utcNow(); + $now = DateTimeFormat::utcNow(); $next_update = DateTimeFormat::utc($contact['last-update'] . ' + ' . $interval . ' minute'); - if ($now < $next_update) { + if ($now < $next_update) { DI::logger()->debug('No update', ['cid' => $contact['id'], 'interval' => $interval, 'next' => $next_update, 'now' => $now]); continue; } diff --git a/src/Worker/ProfileUpdate.php b/src/Worker/ProfileUpdate.php index 700da98d8e..fe88b387e6 100644 --- a/src/Worker/ProfileUpdate.php +++ b/src/Worker/ProfileUpdate.php @@ -16,7 +16,8 @@ use Friendica\Protocol\ActivityPub; /** * Send updated profile data to Diaspora and ActivityPub */ -class ProfileUpdate { +class ProfileUpdate +{ /** * Sends updated profile data to Diaspora and ActivityPub * @@ -35,7 +36,8 @@ class ProfileUpdate { foreach ($inboxes as $inbox => $receivers) { DI::logger()->info('Profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub'); - Worker::add(['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], + Worker::add( + ['priority' => $appHelper->getQueueValue('priority'), 'created' => $appHelper->getQueueValue('created'), 'dont_fork' => true], 'APDelivery', Delivery::PROFILEUPDATE, 0, diff --git a/src/Worker/PushSubscription.php b/src/Worker/PushSubscription.php index b1c07996f1..b7cba9ccae 100644 --- a/src/Worker/PushSubscription.php +++ b/src/Worker/PushSubscription.php @@ -75,7 +75,7 @@ class PushSubscription } $message = DI::notificationFactory()->getMessageFromNotification($notification); - $title = $message['plain'] ?? ''; + $title = $message['plain'] ?? ''; $push = Subscription::create([ 'contentEncoding' => 'aesgcm', diff --git a/src/Worker/RemoveUnusedAvatars.php b/src/Worker/RemoveUnusedAvatars.php index 8cebde12d2..3d1013a279 100644 --- a/src/Worker/RemoveUnusedAvatars.php +++ b/src/Worker/RemoveUnusedAvatars.php @@ -33,7 +33,7 @@ class RemoveUnusedAvatars $total = DBA::count('contact', $condition); DI::logger()->notice('Starting removal', ['total' => $total]); - $count = 0; + $count = 0; $contacts = DBA::select('contact', ['id', 'uri-id', 'uid', 'photo', 'thumb', 'micro'], $condition); while ($contact = DBA::fetch($contacts)) { if (Avatar::deleteCache($contact) || Photo::delete(['uid' => 0, 'contact-id' => $contact['id'], 'photo-type' => [Photo::CONTACT_AVATAR, Photo::CONTACT_BANNER]])) { @@ -52,8 +52,8 @@ class RemoveUnusedAvatars private static function fixPhotoContacts() { - $total = 0; - $deleted = 0; + $total = 0; + $deleted = 0; $updated1 = 0; $updated2 = 0; DI::logger()->notice('Starting contact fix'); @@ -61,7 +61,7 @@ class RemoveUnusedAvatars while ($photo = DBA::fetch($photos)) { $total++; $photo_contact = Contact::getById($photo['contact-id']); - $resource = Photo::ridFromURI($photo_contact['photo']); + $resource = Photo::ridFromURI($photo_contact['photo']); if ($photo['resource-id'] == $resource) { $contact = DBA::selectFirst('contact', [], ['nurl' => $photo_contact['nurl'], 'uid' => 0]); if (!empty($contact['photo']) && ($contact['photo'] == $photo_contact['photo'])) { @@ -70,7 +70,7 @@ class RemoveUnusedAvatars $updated1++; } } else { - $updated = false; + $updated = false; $contacts = DBA::select('contact', [], ['nurl' => $photo_contact['nurl']]); while ($contact = DBA::fetch($contacts)) { if ($photo['resource-id'] == Photo::ridFromURI($contact['photo'])) { @@ -96,7 +96,7 @@ class RemoveUnusedAvatars { $size = [4 => 'photo', 5 => 'thumb', 6 => 'micro']; - $total = 0; + $total = 0; $deleted = 0; DI::logger()->notice('Starting duplicate removal'); $photos = DBA::p("SELECT `photo`.`id`, `photo`.`uid`, `photo`.`scale`, `photo`.`album`, `photo`.`contact-id`, `photo`.`resource-id`, `contact`.`photo`, `contact`.`thumb`, `contact`.`micro` FROM `photo` INNER JOIN `contact` ON `contact`.`id` = `photo`.`contact-id` and `photo`.`contact-id` != ? AND `photo`.`scale` IN (?, ?, ?)", 0, 4, 5, 6); diff --git a/src/Worker/RemoveUnusedContacts.php b/src/Worker/RemoveUnusedContacts.php index 3419b69421..dd6b7e58d0 100644 --- a/src/Worker/RemoveUnusedContacts.php +++ b/src/Worker/RemoveUnusedContacts.php @@ -68,7 +68,7 @@ class RemoveUnusedContacts } $contacts = DBA::select('contact', ['id', 'uid', 'photo', 'thumb', 'micro'], $condition, ['limit' => 1000]); - $count = 0; + $count = 0; while ($contact = DBA::fetch($contacts)) { ++$count; Photo::delete(['uid' => $contact['uid'], 'contact-id' => $contact['id']]); diff --git a/src/Worker/SpoolPost.php b/src/Worker/SpoolPost.php index aab2b7a975..0e70e3a440 100644 --- a/src/Worker/SpoolPost.php +++ b/src/Worker/SpoolPost.php @@ -14,11 +14,13 @@ use Friendica\Model\Item; /** * Posts items that where spooled because they couldn't be posted. */ -class SpoolPost { - public static function execute() { +class SpoolPost +{ + public static function execute() + { $path = System::getSpoolPath(); - if (($path != '') && is_writable($path)){ + if (($path != '') && is_writable($path)) { if ($dh = opendir($path)) { while (($file = readdir($dh)) !== false) { diff --git a/src/Worker/UpdateBlockedServers.php b/src/Worker/UpdateBlockedServers.php index ab38a5dd85..6ecd4dd9e5 100644 --- a/src/Worker/UpdateBlockedServers.php +++ b/src/Worker/UpdateBlockedServers.php @@ -20,8 +20,8 @@ class UpdateBlockedServers public static function execute() { DI::logger()->info('Update blocked servers - start'); - $gservers = DBA::select('gserver', ['id', 'url', 'blocked']); - $changed = 0; + $gservers = DBA::select('gserver', ['id', 'url', 'blocked']); + $changed = 0; $unchanged = 0; while ($gserver = DBA::fetch($gservers)) { $blocked = Network::isUrlBlocked($gserver['url']); diff --git a/src/Worker/UpdateContacts.php b/src/Worker/UpdateContacts.php index bb7e236661..d73ea683c7 100644 --- a/src/Worker/UpdateContacts.php +++ b/src/Worker/UpdateContacts.php @@ -27,7 +27,7 @@ class UpdateContacts } $updating = Worker::countWorkersByCommand('UpdateContact'); - $limit = $update_limit - $updating; + $limit = $update_limit - $updating; if ($limit <= 0) { DI::logger()->info('The number of currently running jobs exceed the limit'); return; @@ -42,8 +42,8 @@ class UpdateContacts } $condition = DBA::mergeConditions(["`next-update` < ?", DateTimeFormat::utcNow()], $condition); - $contacts = DBA::select('contact', ['id', 'url', 'gsid', 'baseurl'], $condition, ['order' => ['next-update'], 'limit' => $limit]); - $count = 0; + $contacts = DBA::select('contact', ['id', 'url', 'gsid', 'baseurl'], $condition, ['order' => ['next-update'], 'limit' => $limit]); + $count = 0; while ($contact = DBA::fetch($contacts)) { if (Contact::isLocal($contact['url'])) { continue; @@ -51,7 +51,7 @@ class UpdateContacts try { if ((!empty($contact['gsid']) || !empty($contact['baseurl'])) && GServer::reachable($contact)) { - $stamp = (float)microtime(true); + $stamp = (float)microtime(true); $success = Contact::updateFromProbe($contact['id']); DI::logger()->debug('Direct update', ['id' => $contact['id'], 'count' => $count, 'duration' => round((float)microtime(true) - $stamp, 3), 'success' => $success]); ++$count; diff --git a/src/Worker/UpdateGServers.php b/src/Worker/UpdateGServers.php index a5eb626dba..76736381db 100644 --- a/src/Worker/UpdateGServers.php +++ b/src/Worker/UpdateGServers.php @@ -28,15 +28,15 @@ class UpdateGServers } $updating = Worker::countWorkersByCommand('UpdateGServer'); - $limit = $update_limit - $updating; + $limit = $update_limit - $updating; if ($limit <= 0) { DI::logger()->info('The number of currently running jobs exceed the limit'); return; } - $total = DBA::count('gserver'); + $total = DBA::count('gserver'); $condition = ["NOT `blocked` AND `next_contact` < ? AND (`nurl` != ? OR `url` != ?)", DateTimeFormat::utcNow(), '', '']; - $outdated = DBA::count('gserver', $condition); + $outdated = DBA::count('gserver', $condition); DI::logger()->info('Server status', ['total' => $total, 'outdated' => $outdated, 'updating' => $limit]); $gservers = DBA::select('gserver', ['id', 'url', 'nurl', 'failed', 'created', 'last_contact'], $condition, ['limit' => $limit]); diff --git a/tests/src/Console/AutomaticInstallationConsoleTest.php b/tests/src/Console/AutomaticInstallationConsoleTest.php index 9bc673ff4f..7fe56bb152 100644 --- a/tests/src/Console/AutomaticInstallationConsoleTest.php +++ b/tests/src/Console/AutomaticInstallationConsoleTest.php @@ -57,13 +57,14 @@ class AutomaticInstallationConsoleTest extends ConsoleTestCase */ private $dice; - public function setUp() : void + public function setUp(): void { static::markTestSkipped('Needs class \'Installer\' as constructing argument for console tests'); parent::setUp(); - $this->setUpVfsDir();; + $this->setUpVfsDir(); + ; if ($this->root->hasChild('config' . DIRECTORY_SEPARATOR . 'local.config.php')) { $this->root->getChild('config') @@ -75,8 +76,8 @@ class AutomaticInstallationConsoleTest extends ConsoleTestCase $l10nMock->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $this->dice->shouldReceive('create') - ->with(L10n::class) - ->andReturn($l10nMock); + ->with(L10n::class) + ->andReturn($l10nMock); DI::init($this->dice); @@ -115,11 +116,11 @@ class AutomaticInstallationConsoleTest extends ConsoleTestCase 'empty' => [ 'data' => [ 'database' => [ - 'hostname' => '', - 'username' => '', - 'password' => '', - 'database' => '', - 'port' => '', + 'hostname' => '', + 'username' => '', + 'password' => '', + 'database' => '', + 'port' => '', ], 'config' => [ 'php_path' => '', @@ -127,23 +128,23 @@ class AutomaticInstallationConsoleTest extends ConsoleTestCase 'admin_email' => '', ], 'system' => [ - 'basepath' => '', - 'urlpath' => '', - 'url' => 'http://friendica.local', - 'ssl_policy' => 0, + 'basepath' => '', + 'urlpath' => '', + 'url' => 'http://friendica.local', + 'ssl_policy' => 0, 'default_timezone' => '', - 'language' => '', + 'language' => '', ], ], ], 'normal' => [ 'data' => [ 'database' => [ - 'hostname' => 'testhost', - 'port' => 3306, - 'username' => 'friendica', - 'password' => 'a password', - 'database' => 'database', + 'hostname' => 'testhost', + 'port' => 3306, + 'username' => 'friendica', + 'password' => 'a password', + 'database' => 'database', ], 'config' => [ 'php_path' => '', @@ -151,23 +152,23 @@ class AutomaticInstallationConsoleTest extends ConsoleTestCase 'admin_email' => 'admin@philipp.info', ], 'system' => [ - 'urlpath' => 'test/it', - 'url' => 'http://friendica.local/test/it', - 'basepath' => '', - 'ssl_policy' => '2', + 'urlpath' => 'test/it', + 'url' => 'http://friendica.local/test/it', + 'basepath' => '', + 'ssl_policy' => '2', 'default_timezone' => 'en', - 'language' => 'Europe/Berlin', + 'language' => 'Europe/Berlin', ], ], ], 'special' => [ 'data' => [ 'database' => [ - 'hostname' => 'testhost.new.domain', - 'port' => 3341, - 'username' => 'fr"§%ica', - 'password' => '$%\"gse', - 'database' => 'db', + 'hostname' => 'testhost.new.domain', + 'port' => 3341, + 'username' => 'fr"§%ica', + 'password' => '$%\"gse', + 'database' => 'db', ], 'config' => [ 'php_path' => '', @@ -175,12 +176,12 @@ class AutomaticInstallationConsoleTest extends ConsoleTestCase 'admin_email' => 'admin@philipp.info', ], 'system' => [ - 'urlpath' => 'test/it', - 'url' => 'https://friendica.local/test/it', - 'basepath' => '', - 'ssl_policy' => '1', + 'urlpath' => 'test/it', + 'url' => 'https://friendica.local/test/it', + 'basepath' => '', + 'ssl_policy' => '1', 'default_timezone' => 'en', - 'language' => 'Europe/Berlin', + 'language' => 'Europe/Berlin', ], ], ], @@ -562,22 +563,22 @@ CONF; $console = new AutomaticInstallation($this->consoleArgv); - $option = function($var, $cat, $key) use ($data, $console) { + $option = function ($var, $cat, $key) use ($data, $console) { if (!empty($data[$cat][$key])) { $console->setOption($var, $data[$cat][$key]); } }; - $option('dbhost' , 'database', 'hostname'); - $option('dbport' , 'database', 'port'); - $option('dbuser' , 'database', 'username'); - $option('dbpass' , 'database', 'password'); - $option('dbdata' , 'database', 'database'); - $option('url' , 'system' , 'url'); - $option('phppath' , 'config' , 'php_path'); - $option('admin' , 'config' , 'admin_email'); - $option('tz' , 'system' , 'default_timezone'); - $option('lang' , 'system' , 'language'); - $option('basepath' , 'system' , 'basepath'); + $option('dbhost', 'database', 'hostname'); + $option('dbport', 'database', 'port'); + $option('dbuser', 'database', 'username'); + $option('dbpass', 'database', 'password'); + $option('dbdata', 'database', 'database'); + $option('url', 'system', 'url'); + $option('phppath', 'config', 'php_path'); + $option('admin', 'config', 'admin_email'); + $option('tz', 'system', 'default_timezone'); + $option('lang', 'system', 'language'); + $option('basepath', 'system', 'basepath'); $txt = $this->dumpExecute($console); diff --git a/update.php b/update.php index b954247162..d9cd656f8d 100644 --- a/update.php +++ b/update.php @@ -59,15 +59,15 @@ function update_1298() { $keys = ['gender', 'marital', 'sexual']; foreach ($keys as $translateKey) { - $allData = DBA::select('profile', ['id', $translateKey]); + $allData = DBA::select('profile', ['id', $translateKey]); $allLangs = DI::l10n()->getAvailableLanguages(); - $success = 0; - $fail = 0; + $success = 0; + $fail = 0; foreach ($allData as $key => $data) { $toTranslate = $data[$translateKey]; if ($toTranslate != '') { foreach ($allLangs as $key => $lang) { - $a = new \stdClass(); + $a = new \stdClass(); $a->strings = []; // First we get the localizations @@ -95,7 +95,7 @@ function update_1298() } else { DBA::update('profile', [$translateKey => $key], ['id' => $data['id']]); DI::logger()->notice('Updated contact', ['action' => 'update', 'contact' => $data['id'], "$translateKey" => $key, - 'was' => $data[$translateKey]]); + 'was' => $data[$translateKey]]); Contact::updateSelfFromUserID($data['id']); Profile::publishUpdate($data['id']); @@ -190,7 +190,7 @@ function update_1330() // Update attachments and photos if (!DBA::e("UPDATE `photo` SET `photo`.`backend-class` = SUBSTR(`photo`.`backend-class`, 25) WHERE `photo`.`backend-class` LIKE 'Friendica\\\Model\\\Storage\\\%' ESCAPE '|'") || - !DBA::e("UPDATE `attach` SET `attach`.`backend-class` = SUBSTR(`attach`.`backend-class`, 25) WHERE `attach`.`backend-class` LIKE 'Friendica\\\Model\\\Storage\\\%' ESCAPE '|'")) { + !DBA::e("UPDATE `attach` SET `attach`.`backend-class` = SUBSTR(`attach`.`backend-class`, 25) WHERE `attach`.`backend-class` LIKE 'Friendica\\\Model\\\Storage\\\%' ESCAPE '|'")) { return Update::FAILED; }; @@ -200,7 +200,7 @@ function update_1330() function update_1332() { $condition = ["`is-default` IS NOT NULL"]; - $profiles = DBA::select('profile', [], $condition); + $profiles = DBA::select('profile', [], $condition); while ($profile = DBA::fetch($profiles)) { Profile::migrate($profile); @@ -650,13 +650,19 @@ function pre_update_1377() function update_1380() { - if (!DBA::e("UPDATE `notify` INNER JOIN `item` ON `item`.`id` = `notify`.`iid` SET `notify`.`uri-id` = `item`.`uri-id` WHERE `notify`.`uri-id` IS NULL AND `notify`.`otype` IN (?, ?)", - Notification\ObjectType::ITEM, Notification\ObjectType::PERSON)) { + if (!DBA::e( + "UPDATE `notify` INNER JOIN `item` ON `item`.`id` = `notify`.`iid` SET `notify`.`uri-id` = `item`.`uri-id` WHERE `notify`.`uri-id` IS NULL AND `notify`.`otype` IN (?, ?)", + Notification\ObjectType::ITEM, + Notification\ObjectType::PERSON + )) { return Update::FAILED; } - if (!DBA::e("UPDATE `notify` INNER JOIN `item` ON `item`.`id` = `notify`.`parent` SET `notify`.`parent-uri-id` = `item`.`uri-id` WHERE `notify`.`parent-uri-id` IS NULL AND `notify`.`otype` IN (?, ?)", - Notification\ObjectType::ITEM, Notification\ObjectType::PERSON)) { + if (!DBA::e( + "UPDATE `notify` INNER JOIN `item` ON `item`.`id` = `notify`.`parent` SET `notify`.`parent-uri-id` = `item`.`uri-id` WHERE `notify`.`parent-uri-id` IS NULL AND `notify`.`otype` IN (?, ?)", + Notification\ObjectType::ITEM, + Notification\ObjectType::PERSON + )) { return Update::FAILED; } @@ -763,7 +769,7 @@ function update_1398() if (!DBA::e("INSERT IGNORE INTO `post-thread` (`uri-id`, `owner-id`, `author-id`, `network`, `created`, `received`, `changed`, `commented`) SELECT `uri-id`, `owner-id`, `author-id`, `network`, `created`, `received`, `changed`, `commented` FROM `thread`")) { - return Update::FAILED; + return Update::FAILED; } if (!DBStructure::existsTable('thread')) { @@ -772,7 +778,7 @@ function update_1398() if (!DBA::e("UPDATE `post-thread-user` INNER JOIN `thread` ON `thread`.`uid` = `post-thread-user`.`uid` AND `thread`.`uri-id` = `post-thread-user`.`uri-id` SET `post-thread-user`.`mention` = `thread`.`mention`")) { - return Update::FAILED; + return Update::FAILED; } return Update::SUCCESS; @@ -784,7 +790,7 @@ function update_1399() SET `post-thread-user`.`contact-id` = `post-user`.`contact-id`, `post-thread-user`.`unseen` = `post-user`.`unseen`, `post-thread-user`.`hidden` = `post-user`.`hidden`, `post-thread-user`.`origin` = `post-user`.`origin`, `post-thread-user`.`psid` = `post-user`.`psid`, `post-thread-user`.`post-user-id` = `post-user`.`id`")) { - return Update::FAILED; + return Update::FAILED; } return Update::SUCCESS; @@ -796,7 +802,7 @@ function update_1400() `created`, `received`, `edited`, `gravity`, `causer-id`, `post-type`, `vid`, `private`, `visible`, `deleted`, `global`) SELECT `uri-id`, `parent-uri-id`, `thr-parent-id`, `owner-id`, `author-id`, `network`, `created`, `received`, `edited`, `gravity`, `causer-id`, `post-type`, `vid`, `private`, `visible`, `deleted`, `global` FROM `item`")) { - return Update::FAILED; + return Update::FAILED; } if (!DBA::e("UPDATE `post-user` INNER JOIN `item` ON `item`.`uri-id` = `post-user`.`uri-id` AND `item`.`uid` = `post-user`.`uid` @@ -936,7 +942,7 @@ function update_1419() { $mails = DBA::select('mail', ['id', 'from-url', 'uri', 'parent-uri', 'guid'], [], ['order' => ['id']]); while ($mail = DBA::fetch($mails)) { - $fields = []; + $fields = []; $fields['author-id'] = Contact::getIdForURL($mail['from-url'], 0, false); if (empty($fields['author-id'])) { continue; @@ -1015,7 +1021,7 @@ function update_1439() if (!empty($fcontact['url'])) { $id = Contact::getIdForURL($fcontact['url']); if (!empty($id)) { - DBA::update('intro',['suggest-cid' => $id], ['id' => $intro['id']]); + DBA::update('intro', ['suggest-cid' => $id], ['id' => $intro['id']]); } } } @@ -1076,7 +1082,7 @@ function update_1444() function update_1446() { $distributed_cache_driver_source = DI::config()->getCache()->getSource('system', 'distributed_cache_driver'); - $cache_driver_source = DI::config()->getCache()->getSource('system', 'cache_driver'); + $cache_driver_source = DI::config()->getCache()->getSource('system', 'cache_driver'); // In case the distributed cache driver is the default value, but the current cache driver isn't default, // we assume that the distributed cache driver should be the same as the current cache driver @@ -1196,7 +1202,7 @@ function update_1509() foreach ($addons as $addon) { $newConfig->set('addons', $addon['name'], [ 'last_update' => $addon['timestamp'], - 'admin' => (bool)$addon['plugin_admin'], + 'admin' => (bool)$addon['plugin_admin'], ]); } @@ -1251,7 +1257,7 @@ function update_1514() if (file_exists(dirname(__FILE__) . '/config/node.config.php')) { $transactionalConfig = DI::config()->beginTransaction(); - $oldConfig = include dirname(__FILE__) . '/config/node.config.php'; + $oldConfig = include dirname(__FILE__) . '/config/node.config.php'; if (is_array($oldConfig)) { $categories = array_keys($oldConfig); @@ -1525,4 +1531,4 @@ function update_1573() } DBA::close($media); return Update::SUCCESS; -} \ No newline at end of file +} diff --git a/view/theme/frio/theme.php b/view/theme/frio/theme.php index 1d9db39f77..d98cf3198f 100644 --- a/view/theme/frio/theme.php +++ b/view/theme/frio/theme.php @@ -29,7 +29,7 @@ const FRIO_SCHEME_ACCENT_GREEN = '#218f39'; const FRIO_SCHEME_ACCENT_PINK = '#d900a9'; const FRIO_DEFAULT_SCHEME = 'light'; -const FRIO_CUSTOM_SCHEME = '---'; +const FRIO_CUSTOM_SCHEME = '---'; /* * This script can be included even when the app is in maintenance mode which requires us to avoid any config call @@ -80,9 +80,9 @@ function frio_install() function frio_item_photo_links(&$body_info) { $occurence = 0; - $p = Plaintext::getBoundariesPosition($body_info['html'], ''); + $p = Plaintext::getBoundariesPosition($body_info['html'], ''); while ($p !== false && ($occurence++ < 500)) { - $link = substr($body_info['html'], $p['start'], $p['end'] - $p['start']); + $link = substr($body_info['html'], $p['start'], $p['end'] - $p['start']); $matches = []; preg_match('/\/photos\/[\w]+\/image\/([\w]+)/', $link, $matches); @@ -116,7 +116,7 @@ function frio_item_photo_menu(&$arr) { foreach ($arr['menu'] as $k => $v) { if (strpos($v, 'message/new/') === 0) { - $v = 'javascript:addToModal(\'' . $v . '\'); return false;'; + $v = 'javascript:addToModal(\'' . $v . '\'); return false;'; $arr['menu'][$k] = $v; } } @@ -154,7 +154,7 @@ function frio_contact_photo_menu(&$args) // and if it's a friendica contact we set it to false foreach ($args['menu'] as $k => $v) { if ($k === 'status' || $k === 'profile' || $k === 'photos') { - $v[2] = (($args['contact']['network'] === 'dfrn') ? false : true); + $v[2] = (($args['contact']['network'] === 'dfrn') ? false : true); $args['menu'][$k][2] = $v[2]; } } @@ -210,7 +210,7 @@ function frio_remote_nav(array &$nav_info) 'icon' => Contact::getMicro($remoteUser), 'name' => $remoteUser['name'], ]; - $server_url = $remoteUser['baseurl']; + $server_url = $remoteUser['baseurl']; } if (!DI::userSession()->getLocalUserId() && !empty($server_url) && !is_null($remoteUser)) { diff --git a/view/theme/vier/style.php b/view/theme/vier/style.php index 7590ef248e..92b8787227 100644 --- a/view/theme/vier/style.php +++ b/view/theme/vier/style.php @@ -50,8 +50,11 @@ header('Last-Modified: '.$modified); if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && isset($_SERVER['HTTP_IF_NONE_MATCH'])) { $cached_modified = gmdate('r', strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])); - $cached_etag = str_replace(['"', "-gzip"], ['', ''], - stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])); + $cached_etag = str_replace( + ['"', "-gzip"], + ['', ''], + stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) + ); if (($cached_modified == $modified) && ($cached_etag == $etag)) { throw new NotModifiedException(); From d38edfc6ca441cf414d69f08a8b6c7544f069eae Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 13:40:31 +0000 Subject: [PATCH 47/91] Fix code style --- src/Protocol/DFRN.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Protocol/DFRN.php b/src/Protocol/DFRN.php index a2c60cd27c..be6dfc206d 100644 --- a/src/Protocol/DFRN.php +++ b/src/Protocol/DFRN.php @@ -1508,7 +1508,7 @@ class DFRN $fields = [ 'title' => $item['title'] ?? '', - 'body' => $item['body'] ?? '', + 'body' => $item['body'] ?? '', 'changed' => DateTimeFormat::utcNow(), 'edited' => DateTimeFormat::utc($item['edited']), ]; From 0de00003c69dbb1671f80cecee9779cd0870ed2e Mon Sep 17 00:00:00 2001 From: Art4 Date: Mon, 13 Jan 2025 22:38:07 +0000 Subject: [PATCH 48/91] add Backward Compatibility Promise --- doc/Developers-Intro.md | 73 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md index c500b27741..e37313c73f 100644 --- a/doc/Developers-Intro.md +++ b/doc/Developers-Intro.md @@ -156,3 +156,76 @@ If you are interested in improving those clients, please contact the developers * iOS: *currently no client* * 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) + +## Backward compatability + +### Backward Compatibility Promise + +Friendica can be extended by addons. These addons relies on many internal classes and conventions. 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. + +We promise BC inside every major release. If one release breaks BC, this should considered as a bug and will be fix in a bugfix release. + +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` propertyies (via Reflection) +- Accessing `private` methods (via Reflection) +- Accessing `private` constants (via Reflection) +- New properties on overrided `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 + +Breaking changes will be happen only in a new release but MUST be hard deprecated first. + +### 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 maintainer 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 addons developers might be notified by their IDE or other tools that the usage of the class is deprecated. In Friendica we can now start to replace all occurences and usage of this class with the alternative. + +The deprecation albel COULD be remain over multiple releases. As long as the deprecated code is used inside Friendica or the offical addon repository, it SHOULD NOT be hard deprecated. + +**2. Hard deprecation** + +If the deprecated code is no longer used inside Friendica or the offical addons it MUST be hard deprecated. The code MUST NOT be deleted. It MUST be stay for at least to the next major release. + +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 be 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.02 and will be removed in the next major release, 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 the next release. The addon maintainer now has the time until the next release to fix the deprecations. + +**3. Code Removing** + +Once a major release is published we as the Friendica maintainers can remove all code that is hard deprecated. From 34e6d29d1fd1a501bc15873434bf7445feccf1dd Mon Sep 17 00:00:00 2001 From: Artur Weigandt Date: Mon, 13 Jan 2025 23:56:27 +0100 Subject: [PATCH 49/91] Apply suggestions from code review --- doc/Developers-Intro.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md index e37313c73f..d44a2c6224 100644 --- a/doc/Developers-Intro.md +++ b/doc/Developers-Intro.md @@ -170,7 +170,7 @@ Inspired by the [Symonfy BC promise](https://symfony.com/doc/current/contributin - 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` propertyies (via Reflection) +- Accessing `private` properties (via Reflection) - Accessing `private` methods (via Reflection) - Accessing `private` constants (via Reflection) - New properties on overrided `protected` methods @@ -196,13 +196,13 @@ If we as the Friendica maintainers decide to remove some functions, classes, int class Logger {/* ... */} ``` -This way addons developers might be notified by their IDE or other tools that the usage of the class is deprecated. In Friendica we can now start to replace all occurences and usage of this class with the alternative. +This way addon developers might be notified 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 albel COULD be remain over multiple releases. As long as the deprecated code is used inside Friendica or the offical addon repository, it SHOULD NOT be hard deprecated. +The deprecation label COULD be remain over multiple releases. As long as the deprecated code 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 offical addons it MUST be hard deprecated. The code MUST NOT be deleted. It MUST be stay for at least to the next major release. +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. It MUST be stay for at least to the next major release. 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 be trigger an error: From c47323e358b9841eb287c71e54ae549ea5f6d62d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakobus=20Sch=C3=BCrz?= Date: Tue, 14 Jan 2025 05:49:48 +0100 Subject: [PATCH 50/91] do not change cursor position while replacing upload-placeholder fixes #14695 Save caret position just before replacing the upload-placeholder. replace upload-placeholder Set caret position to the position in textarea as before replacing action. Setting caret position considers the position before or after placeholder and therefore the textlength of server-response to find the right place. --- view/js/dropzone-factory.js | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/view/js/dropzone-factory.js b/view/js/dropzone-factory.js index dcc0468cb2..5c97394721 100644 --- a/view/js/dropzone-factory.js +++ b/view/js/dropzone-factory.js @@ -35,7 +35,13 @@ var DzFactory = function (max_imagesize) { if (targetTextarea.setRangeText) { //if setRangeText function is supported by current browser let u = "[upload-" + file.name + "]"; - targetTextarea.setRangeText(serverResponse, targetTextarea.value.indexOf(u), targetTextarea.value.indexOf(u) + u.length, "end"); + let c = targetTextarea.selectionStart; + if (c > targetTextarea.value.indexOf(u)) { + c = c + serverResponse.length - u.length; + } + targetTextarea.setRangeText(serverResponse, targetTextarea.value.indexOf(u), targetTextarea.value.indexOf(u) + u.length); + targetTextarea.selectionStart = c; + targetTextarea.selectionEnd = c; } else { targetTextarea.focus(); document.execCommand('insertText', false /*no UI*/, serverResponse); From dc382b5288cc62bda17ac238e320fe00323993d1 Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 14 Jan 2025 06:06:28 +0000 Subject: [PATCH 51/91] Changed contact update rule / added logging --- src/Module/Photo.php | 5 +++-- src/Worker/UpdateContact.php | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/Module/Photo.php b/src/Module/Photo.php index 30e6d57672..87da6be55b 100644 --- a/src/Module/Photo.php +++ b/src/Module/Photo.php @@ -27,6 +27,7 @@ use Friendica\Network\HTTPException; use Friendica\Network\HTTPException\NotModifiedException; use Friendica\Object\Image; use Friendica\Security\OpenWebAuth; +use Friendica\Util\DateTimeFormat; use Friendica\Util\Images; use Friendica\Util\ParseUrl; use Friendica\Util\Proxy; @@ -297,7 +298,7 @@ class Photo extends BaseApi return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0); 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); if (empty($contact)) { return false; @@ -355,7 +356,7 @@ class Photo extends BaseApi } else { // Only update federated accounts that hadn't failed before and hadn't been updated recently $update = in_array($contact['network'], Protocol::FEDERATED) && !$contact['failed'] - && ((time() - strtotime($contact['updated']) > 86400)); + && ($contact['next-update'] < DateTimeFormat::utcNow()); if ($update) { $curlResult = DI::httpClient()->head($url, [HttpClientOptions::ACCEPT_CONTENT => HttpClientAccept::IMAGE, HttpClientOptions::REQUEST => HttpClientRequest::CONTENTTYPE]); $update = !$curlResult->isSuccess() && ($curlResult->getReturnCode() == 404); diff --git a/src/Worker/UpdateContact.php b/src/Worker/UpdateContact.php index aad6a93db2..ded4679fe6 100644 --- a/src/Worker/UpdateContact.php +++ b/src/Worker/UpdateContact.php @@ -51,6 +51,7 @@ class UpdateContact return 0; } + Logger::debug('Update contact', ['id' => $contact_id]); return Worker::add($run_parameters, 'UpdateContact', $contact_id); } } From 8345ada757764e7128fcb3319f0889c86da6b4ab Mon Sep 17 00:00:00 2001 From: Michael Date: Tue, 14 Jan 2025 06:06:39 +0000 Subject: [PATCH 52/91] Fixed codestyle --- src/Module/Photo.php | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Module/Photo.php b/src/Module/Photo.php index 87da6be55b..c3582ee655 100644 --- a/src/Module/Photo.php +++ b/src/Module/Photo.php @@ -65,19 +65,19 @@ class Photo extends BaseApi OpenWebAuth::addVisitorCookieForHTTPSigner($this->server); - $customsize = 0; + $customsize = 0; $square_resize = true; - $scale = null; - $stamp = microtime(true); + $scale = null; + $stamp = microtime(true); // User avatar if (!empty($this->parameters['type'])) { if (!empty($this->parameters['customsize'])) { - $customsize = intval($this->parameters['customsize']); + $customsize = intval($this->parameters['customsize']); $square_resize = !in_array($this->parameters['type'], ['media', 'preview']); } if (!empty($this->parameters['guid'])) { - $guid = $this->parameters['guid']; + $guid = $this->parameters['guid']; $account = DBA::selectFirst('account-user-view', ['id'], ['guid' => $guid], ['order' => ['uid' => true]]); if (empty($account)) { throw new HTTPException\NotFoundException(); @@ -92,7 +92,7 @@ class Photo extends BaseApi if (!empty($this->parameters['nickname_ext'])) { $nickname = pathinfo($this->parameters['nickname_ext'], PATHINFO_FILENAME); - $user = User::getByNickname($nickname, ['uid']); + $user = User::getByNickname($nickname, ['uid']); if (empty($user)) { throw new HTTPException\NotFoundException(); } @@ -112,9 +112,9 @@ class Photo extends BaseApi $photo = self::getPhotoById($id, $this->parameters['type'], $customsize ?: Proxy::PIXEL_SMALL); } else { $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME); - $scale = 0; + $scale = 0; if (substr($photoid, -2, 1) == '-') { - $scale = intval(substr($photoid, -1, 1)); + $scale = intval(substr($photoid, -1, 1)); $photoid = substr($photoid, 0, -2); } @@ -176,7 +176,7 @@ class Photo extends BaseApi Logger::warning('Invalid photo', ['id' => $photo['id']]); if (in_array($photo['backend-class'], [ExternalResource::NAME])) { $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']); } else { $error = DI::l10n()->t('Invalid photo with id %s.', $photo['id']); } @@ -230,13 +230,13 @@ class Photo extends BaseApi $output = microtime(true) - $stamp; $total = microtime(true) - $totalstamp; - $rest = $total - ($fetch + $data + $checksum + $output); + $rest = $total - ($fetch + $data + $checksum + $output); if (!is_null($scale) && ($scale < 4)) { Logger::debug('Performance:', [ - 'scale' => $scale, 'resource' => $photo['resource-id'], - 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3), - 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3), + 'scale' => $scale, 'resource' => $photo['resource-id'], + 'total' => number_format($total, 3), 'fetch' => number_format($fetch, 3), + 'data' => number_format($data, 3), 'checksum' => number_format($checksum, 3), 'output' => number_format($output, 3), 'rest' => number_format($rest, 3) ]); } @@ -298,7 +298,7 @@ class Photo extends BaseApi return MPhoto::createPhotoForExternalResource($link['url'], (int)DI::userSession()->getLocalUserId(), $link['mimetype'] ?? '', $link['blurhash'] ?? '', $link['width'] ?? 0, $link['height'] ?? 0); case 'contact': - $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'blurhash', 'xmpp', 'addr', 'network', 'failed', 'updated', 'next-update']; + $fields = ['uid', 'uri-id', 'url', 'nurl', 'avatar', 'photo', 'blurhash', 'xmpp', 'addr', 'network', 'failed', 'updated', 'next-update']; $contact = Contact::getById($id, $fields); if (empty($contact)) { return false; @@ -359,7 +359,7 @@ class Photo extends BaseApi && ($contact['next-update'] < DateTimeFormat::utcNow()); if ($update) { $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]); } if ($update) { @@ -402,7 +402,7 @@ class Photo extends BaseApi } return MPhoto::createPhotoForExternalResource($url, 0, $mimetext, $contact['blurhash'] ?? null, $customsize, $customsize); case 'header': - $fields = ['uid', 'url', 'header', 'network', 'gsid']; + $fields = ['uid', 'url', 'header', 'network', 'gsid']; $contact = Contact::getById($id, $fields); if (empty($contact)) { return false; From 6e6903e073e64e44c5462dc612dbc01020abdd36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakobus=20Sch=C3=BCrz?= Date: Tue, 14 Jan 2025 11:17:48 +0100 Subject: [PATCH 53/91] add upload for video/*, audio/* and application/* via dropzone Upload videos, audios and documents (all mimetype application/*) via Drag&Drop and Copy&Paste in new postings and comments as attachments. The same as images before with placeholder on insert-position. You can write text while upload is done. --- view/js/dropzone-factory.js | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/view/js/dropzone-factory.js b/view/js/dropzone-factory.js index 5c97394721..33fe796dd3 100644 --- a/view/js/dropzone-factory.js +++ b/view/js/dropzone-factory.js @@ -9,7 +9,7 @@ var DzFactory = function (max_imagesize) { paramName: 'userfile', // The name that will be used to transfer the file maxFilesize: max_imagesize, // MB url: '/media/photo/upload?album=', - acceptedFiles: 'image/*', + acceptedFiles: 'image/*,video/*,audio/*,application/*', clickable: true, dictDefaultMessage: dzStrings.dictDefaultMessage, dictFallbackMessage: dzStrings.dictFallbackMessage, @@ -25,21 +25,45 @@ var DzFactory = function (max_imagesize) { accept: function(file, done) { const targetTextarea = document.getElementById(textareaElementId); if (targetTextarea.setRangeText) { - targetTextarea.setRangeText("\n[upload-" + file.name + "]\n", targetTextarea.selectionStart, targetTextarea.selectionEnd, "end"); + targetTextarea.setRangeText("\n[!upload-" + file.name + "]\n", targetTextarea.selectionStart, targetTextarea.selectionEnd, "end"); } done(); }, init: function() { + this.on("processing", function(file) { + switch(file.type) { + case String(file.type.match(/image\/.*/)): + this.options.url = "/media/photo/upload?album="; + break; + default: + this.options.url = "/media/attachment/upload?response=json"; + } + }); this.on('success', function(file, serverResponse) { const targetTextarea = document.getElementById(textareaElementId); if (targetTextarea.setRangeText) { //if setRangeText function is supported by current browser - let u = "[upload-" + file.name + "]"; + let u = "[!upload-" + file.name + "]"; + let srp = serverResponse; + if (typeof serverResponse === 'object' && + serverResponse.constructor === Object) { + if (serverResponse.ok) { + srp = "[attachment]" + + window.location.protocol + + "//" + + window.location.host + + "/attach/" + + serverResponse.id + + "[/attachment]"; + } else { + srp = "Upload failed"; + } + } let c = targetTextarea.selectionStart; if (c > targetTextarea.value.indexOf(u)) { c = c + serverResponse.length - u.length; } - targetTextarea.setRangeText(serverResponse, targetTextarea.value.indexOf(u), targetTextarea.value.indexOf(u) + u.length); + targetTextarea.setRangeText(srp, targetTextarea.value.indexOf(u), targetTextarea.value.indexOf(u) + u.length); targetTextarea.selectionStart = c; targetTextarea.selectionEnd = c; } else { From 3801382ffe7c73826b09f3fcb1588961c35a3431 Mon Sep 17 00:00:00 2001 From: Artur Weigandt Date: Tue, 14 Jan 2025 19:52:03 +0100 Subject: [PATCH 54/91] Update doc/Developers-Intro.md --- doc/Developers-Intro.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md index d44a2c6224..e9236f6934 100644 --- a/doc/Developers-Intro.md +++ b/doc/Developers-Intro.md @@ -163,7 +163,7 @@ If you are interested in improving those clients, please contact the developers Friendica can be extended by addons. These addons relies on many internal classes and conventions. 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. -We promise BC inside every major release. If one release breaks BC, this should considered as a bug and will be fix in a bugfix release. +We promise BC for deprecated code for at least 6 month. After this time the deprecated code will be remove with the next release. If a release breaks BC without deprecation, this SHOULD considered as a bug and BC SHOULD be restored in a bugfix release. 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: From 3dc467e208ceae967e569809adabc09ab0476d93 Mon Sep 17 00:00:00 2001 From: Artur Weigandt Date: Tue, 14 Jan 2025 20:29:20 +0100 Subject: [PATCH 55/91] Increase BC to 6 months --- doc/Developers-Intro.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md index e9236f6934..39462d20f7 100644 --- a/doc/Developers-Intro.md +++ b/doc/Developers-Intro.md @@ -157,14 +157,12 @@ If you are interested in improving those clients, please contact the developers * 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) -## Backward compatability +## Backward compatibility ### Backward Compatibility Promise Friendica can be extended by addons. These addons relies on many internal classes and conventions. 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. -We promise BC for deprecated code for at least 6 month. After this time the deprecated code will be remove with the next release. If a release breaks BC without deprecation, this SHOULD considered as a bug and BC SHOULD be restored in a bugfix release. - 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` @@ -173,12 +171,10 @@ Inspired by the [Symonfy BC promise](https://symfony.com/doc/current/contributin - Accessing `private` properties (via Reflection) - Accessing `private` methods (via Reflection) - Accessing `private` constants (via Reflection) -- New properties on overrided `protected` methods +- 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 -Breaking changes will be happen only in a new release but MUST be hard deprecated first. - ### 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 maintainer a chance to adjust their addons. @@ -196,13 +192,13 @@ If we as the Friendica maintainers decide to remove some functions, classes, int class Logger {/* ... */} ``` -This way addon developers might be notified 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. +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 deprecated code is used inside Friendica or the official addon repository, it SHOULD NOT be hard deprecated. +The deprecation label COULD be remain over multiple releases. As long as the `@deprecated` labeled code 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. It MUST be stay for at least to the next major release. +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 6 months. Hard deprecated code COULD remain longer than 6 months, depending on when a release appears. Addon developer MUST NOT consider that they have more than 6 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 be trigger an error: @@ -215,17 +211,23 @@ Hard deprecation code means that the code triggers an `E_USER_DEPRECATION` error class Logger { public static function info(string $message, array $context = []) { - trigger_error('Class `' . __CLASS__ . '` is deprecated since 2025.02 and will be removed in the next major release, use constructor injection or `DI::logger()` instead.', E_USER_DEPRECATED); + trigger_error('Class `' . __CLASS__ . '` is deprecated since 2025.05 and will be removed after 6 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 the next release. The addon maintainer now has the time until the next release to fix the deprecations. +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 6 months 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 in `2025.05` and COULD be removed earliest with the `2025.11` release. **3. Code Removing** -Once a major release is published we as the Friendica maintainers can remove all code that is hard deprecated. +We promise BC for deprecated code for at least 6 month, 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 is published 6 months after the deprecation. + +If a release breaks BC without deprecation or earlier than 6 months, this SHOULD considered as a bug and BC SHOULD be restored in a bugfix release. From aad362fee30ae85d2691a67a08a0b1a07d8250a2 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 15 Jan 2025 21:51:10 +0000 Subject: [PATCH 56/91] Improved handling of archive poszs --- src/Protocol/ATProtocol/Processor.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Protocol/ATProtocol/Processor.php b/src/Protocol/ATProtocol/Processor.php index aa57299abf..1a9286ee45 100755 --- a/src/Protocol/ATProtocol/Processor.php +++ b/src/Protocol/ATProtocol/Processor.php @@ -354,6 +354,10 @@ class Processor 'source' => json_encode($data), ]; + if ((time() - strtotime($item['created'])) > 600) { + $item['received'] = $item['created']; + } + if ($this->postExists($item['uri'], [$uid])) { $this->logger->info('Post already exists for user', ['uri' => $item['uri'], 'uid' => $uid]); return []; From 860dbacf1bfe3d6e1df35b950ce4670cbcb9a9aa Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 15 Jan 2025 21:52:44 +0000 Subject: [PATCH 57/91] Fixed codestyle --- src/Protocol/ATProtocol/Processor.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Protocol/ATProtocol/Processor.php b/src/Protocol/ATProtocol/Processor.php index 1a9286ee45..f551f6a273 100755 --- a/src/Protocol/ATProtocol/Processor.php +++ b/src/Protocol/ATProtocol/Processor.php @@ -170,7 +170,7 @@ class Processor } } $item['source'] = json_encode($post); - $item = $this->addMedia($post->thread->post->embed, $item, 0); + $item = $this->addMedia($post->thread->post->embed, $item, 0); } $id = Item::insert($item); @@ -547,7 +547,7 @@ class Processor 'preview' => $image->thumb, 'description' => $image->alt, 'height' => $image->aspectRatio->height ?? null, - 'width' => $image->aspectRatio->width ?? null, + 'width' => $image->aspectRatio->width ?? null, ]; Post\Media::insert($media); } From 11593bb88732f0dc97acc89c0e1d1bba6aa172f4 Mon Sep 17 00:00:00 2001 From: Artur Weigandt Date: Thu, 16 Jan 2025 16:07:32 +0100 Subject: [PATCH 58/91] Adjust fromat --- doc/Developers-Intro.md | 41 ++++++++++++++++++++++++++++++----------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md index 39462d20f7..f07b711648 100644 --- a/doc/Developers-Intro.md +++ b/doc/Developers-Intro.md @@ -161,7 +161,11 @@ If you are interested in improving those clients, please contact the developers ### Backward Compatibility Promise -Friendica can be extended by addons. These addons relies on many internal classes and conventions. 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. +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: @@ -177,11 +181,13 @@ Inspired by the [Symonfy BC promise](https://symfony.com/doc/current/contributin ### 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 maintainer a chance to adjust their addons. +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. +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 /** @@ -192,15 +198,22 @@ If we as the Friendica maintainers decide to remove some functions, classes, int 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. +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 `@deprecated` labeled code is used inside Friendica or the official addon repository, it SHOULD NOT be hard deprecated. +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 6 months. Hard deprecated code COULD remain longer than 6 months, depending on when a release appears. Addon developer MUST NOT consider that they have more than 6 months to adjust their code. +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 6 months. +Hard deprecated code COULD remain longer than 6 months, depending on when a release appears. +Addon developer MUST NOT consider that they have more than 6 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 be trigger an error: +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 be trigger an error: ```php /** @@ -220,14 +233,20 @@ class Logger { } ``` -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 6 months to fix the deprecations. +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 6 months 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 in `2025.05` and COULD be removed earliest with the `2025.11` release. +Please note that the deprecation message contains the release that will be released next. +In the example the code was hard deprecated in `2025.05` and COULD be removed earliest with the `2025.11` release. **3. Code Removing** -We promise BC for deprecated code for at least 6 month, starting from the release the deprecation was announced. After this time the deprecated code COULD be remove within the next release. +We promise BC for deprecated code for at least 6 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 is published 6 months after the deprecation. +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 is published 6 months after the deprecation. If a release breaks BC without deprecation or earlier than 6 months, this SHOULD considered as a bug and BC SHOULD be restored in a bugfix release. From d42b31bee64814beeaa0ae5c6c3ff43da46b701f Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 19 Jan 2025 13:24:59 +0000 Subject: [PATCH 59/91] Fix exception "Argument #2 ($jsonld) must be of type array, string given" --- src/Util/ParseUrl.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Util/ParseUrl.php b/src/Util/ParseUrl.php index 97ecdb977b..464d03c8d0 100644 --- a/src/Util/ParseUrl.php +++ b/src/Util/ParseUrl.php @@ -455,7 +455,8 @@ class ParseUrl $list = $xpath->query("//script[@type='application/ld+json']"); foreach ($list as $node) { if (!empty($node->nodeValue)) { - if ($jsonld = json_decode($node->nodeValue, true)) { + $jsonld = json_decode($node->nodeValue, true); + if (is_array($jsonld)) { $siteinfo = self::parseParts($siteinfo, $jsonld); } } From d2b1eaaaa9119058408930abb8b8a976d99760b9 Mon Sep 17 00:00:00 2001 From: Michael Date: Sun, 19 Jan 2025 13:26:22 +0000 Subject: [PATCH 60/91] Fix codestyle --- src/Util/ParseUrl.php | 52 ++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/src/Util/ParseUrl.php b/src/Util/ParseUrl.php index 464d03c8d0..54af953544 100644 --- a/src/Util/ParseUrl.php +++ b/src/Util/ParseUrl.php @@ -78,7 +78,7 @@ class ParseUrl return []; } - $contenttype = $curlResult->getContentType(); + $contenttype = $curlResult->getContentType(); if (empty($contenttype)) { return ['application', 'octet-stream']; } @@ -109,16 +109,14 @@ class ParseUrl { if (empty($url)) { return [ - 'url' => '', + 'url' => '', 'type' => 'error', ]; } $urlHash = hash('sha256', $url); - $parsed_url = DBA::selectFirst('parsed_url', ['content'], - ['url_hash' => $urlHash, 'oembed' => false] - ); + $parsed_url = DBA::selectFirst('parsed_url', ['content'], ['url_hash' => $urlHash, 'oembed' => false]); if (!empty($parsed_url['content'])) { $data = unserialize($parsed_url['content']); return $data; @@ -187,7 +185,7 @@ class ParseUrl { if (empty($url)) { return [ - 'url' => '', + 'url' => '', 'type' => 'error', ]; } @@ -204,8 +202,8 @@ class ParseUrl $url = Network::stripTrackingQueryParams($url); $siteinfo = [ - 'url' => $url, - 'type' => 'link', + 'url' => $url, + 'type' => 'link', 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE), ]; @@ -246,11 +244,13 @@ class ParseUrl if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')[0] ?? '') { if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) { $maxAge = max(86400, (int)array_pop($matches)); + $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds"); } } $body = $curlResult->getBodyString(); + $siteinfo['size'] = mb_strlen($body); $charset = ''; @@ -260,7 +260,8 @@ class ParseUrl if (isset($mediaType->parameters['charset'])) { $charset = $mediaType->parameters['charset']; } - } catch(\InvalidArgumentException $e) {} + } catch(\InvalidArgumentException $e) { + } $siteinfo['charset'] = $charset; @@ -306,10 +307,9 @@ class ParseUrl } if (@$meta_tag['http-equiv'] == 'refresh') { - $path = $meta_tag['content']; - $pathinfo = explode(';', $path); + $path = $meta_tag['content']; $content = ''; - foreach ($pathinfo as $value) { + foreach (explode(';', $path) as $value) { if (substr(strtolower($value), 0, 4) == 'url=') { $content = substr($value, 4); } @@ -489,6 +489,7 @@ class ParseUrl if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) { $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…'; + $pos = mb_strrpos($siteinfo['text'], '.'); if ($pos > self::MIN_DESC_COUNT) { $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1); @@ -512,7 +513,7 @@ class ParseUrl * @param array $siteinfo * @return array */ - private static function checkMedia(string $page_url, array $siteinfo) : array + private static function checkMedia(string $page_url, array $siteinfo): array { if (!empty($siteinfo['images'])) { array_walk($siteinfo['images'], function (&$image) use ($page_url) { @@ -523,13 +524,14 @@ class ParseUrl */ if (!empty($image['url'])) { $image['url'] = self::completeUrl($image['url'], $page_url); + $photodata = Images::getInfoFromURLCached($image['url']); if (($photodata) && ($photodata[0] > 50) && ($photodata[1] > 50)) { - $image['src'] = $image['url']; - $image['width'] = $photodata[0]; - $image['height'] = $photodata[1]; + $image['src'] = $image['url']; + $image['width'] = $photodata[0]; + $image['height'] = $photodata[1]; $image['contenttype'] = $photodata['mime']; - $image['blurhash'] = $photodata['blurhash'] ?? null; + $image['blurhash'] = $photodata['blurhash'] ?? null; unset($image['url']); ksort($image); } else { @@ -546,13 +548,14 @@ class ParseUrl foreach (['audio', 'video'] as $element) { if (!empty($siteinfo[$element])) { array_walk($siteinfo[$element], function (&$media) use ($page_url, &$siteinfo) { - $url = ''; - $embed = ''; - $content = ''; + $url = ''; + $embed = ''; + $content = ''; $contenttype = ''; foreach (['embed', 'content', 'url'] as $field) { if (!empty($media[$field])) { $media[$field] = self::completeUrl($media[$field], $page_url); + $type = self::getContentType($media[$field]); if (($type[0] ?? '') == 'text') { if ($field == 'embed') { @@ -561,7 +564,7 @@ class ParseUrl $url = $media[$field]; } } elseif (!empty($type[0])) { - $content = $media[$field]; + $content = $media[$field]; $contenttype = implode('/', $type); } } @@ -708,7 +711,7 @@ class ParseUrl } elseif (!empty($jsonld['@type'])) { $siteinfo = self::parseJsonLd($siteinfo, $jsonld); } elseif (!empty($jsonld)) { - $keys = array_keys($jsonld); + $keys = array_keys($jsonld); $numeric_keys = true; foreach ($keys as $key) { if (!is_int($key)) { @@ -812,7 +815,7 @@ class ParseUrl case 'Person': case 'Patient': case 'PerformingGroup': - case 'DanceGroup'; + case 'DanceGroup': case 'MusicGroup': case 'TheaterGroup': return self::parseJsonLdWebPerson($siteinfo, $jsonld); @@ -955,8 +958,7 @@ class ParseUrl $content = JsonLD::fetchElement($jsonld, 'keywords'); if (!empty($content)) { $siteinfo['keywords'] = []; - $keywords = explode(',', $content); - foreach ($keywords as $keyword) { + foreach (explode(',', $content) as $keyword) { $siteinfo['keywords'][] = trim($keyword); } } From 8c8067c624237262a55d8831667e968e10617f34 Mon Sep 17 00:00:00 2001 From: Marek Bachmann Date: Tue, 21 Jan 2025 18:28:20 +0000 Subject: [PATCH 61/91] fixed button readabilid in media browser for dark appereance in frio theme --- view/theme/frio/templates/media/browser.tpl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/view/theme/frio/templates/media/browser.tpl b/view/theme/frio/templates/media/browser.tpl index 2249cb6e4d..8ddc9bb6bc 100644 --- a/view/theme/frio/templates/media/browser.tpl +++ b/view/theme/frio/templates/media/browser.tpl @@ -40,7 +40,7 @@
    {{foreach $folders as $folder}}
  • - +
  • {{/foreach}}
From c6a9e7aa4cea6faeb734a2376b12902a431cb1a4 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 15 Jan 2025 07:42:47 +0000 Subject: [PATCH 62/91] New option to only update contacts with local relations --- src/Model/Contact.php | 19 +- src/Model/GServer.php | 4 - src/Module/Admin/Site.php | 3 + src/Worker/UpdateContact.php | 36 ++ static/settings.config.php | 4 + view/lang/C/messages.po | 708 ++++++++++++----------- view/templates/admin/site.tpl | 1 + view/theme/frio/templates/admin/site.tpl | 1 + 8 files changed, 416 insertions(+), 360 deletions(-) diff --git a/src/Model/Contact.php b/src/Model/Contact.php index 083f66287f..7cac007a64 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -362,10 +362,8 @@ class Contact return []; } - $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true; - // 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 { UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); } catch (\InvalidArgumentException $e) { @@ -537,6 +535,17 @@ class Contact 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 * @@ -1318,9 +1327,7 @@ class Contact if (!empty($contact)) { $contact_id = $contact['id']; - $background_update = DI::config()->get('system', 'update_active_contacts') ? $contact['local-data'] : true; - - if ($background_update && !self::isLocal($url) && Protocol::supportsProbe($contact['network']) && ($contact['next-update'] < DateTimeFormat::utcNow())) { + if (UpdateContact::isUpdatable($contact['id'])) { try { UpdateContact::add(['priority' => Worker::PRIORITY_LOW, 'dont_fork' => true], $contact['id']); } catch (\InvalidArgumentException $e) { diff --git a/src/Model/GServer.php b/src/Model/GServer.php index 933ca8d74c..ee9661b796 100644 --- a/src/Model/GServer.php +++ b/src/Model/GServer.php @@ -2488,10 +2488,6 @@ class GServer */ public static function discover() { - if (!DI::config()->get('system', 'discover_servers')) { - return; - } - // Update the server list self::discoverFederation(); diff --git a/src/Module/Admin/Site.php b/src/Module/Admin/Site.php index c162acce9b..e56e45f0a5 100644 --- a/src/Module/Admin/Site.php +++ b/src/Module/Admin/Site.php @@ -105,6 +105,7 @@ class Site extends BaseAdmin $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); $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); $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); @@ -178,6 +179,7 @@ class Site extends BaseAdmin $transactionConfig->set('system', 'optimize_tables' , $optimize_tables); $transactionConfig->set('system', 'contact_discovery' , $contact_discovery); $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', 'poco_requery_days' , $poco_requery_days); $transactionConfig->set('system', 'poco_discovery' , $poco_discovery); @@ -546,6 +548,7 @@ class Site extends BaseAdmin '
  • ' . DI::l10n()->t('Interactors - contacts of our local contacts and contacts who interacted on locally visible postings are discovered for their followers/followings.') . '
  • ', $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_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.')], '$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.')], diff --git a/src/Worker/UpdateContact.php b/src/Worker/UpdateContact.php index 88f157ad51..24c65a3d3c 100644 --- a/src/Worker/UpdateContact.php +++ b/src/Worker/UpdateContact.php @@ -7,10 +7,12 @@ namespace Friendica\Worker; +use Friendica\Core\Protocol; use Friendica\Core\Worker; use Friendica\DI; use Friendica\Model\Contact; use Friendica\Network\HTTPException\InternalServerErrorException; +use Friendica\Util\DateTimeFormat; class UpdateContact { @@ -54,4 +56,38 @@ class UpdateContact DI::logger()->debug('Update contact', ['id' => $contact_id]); return Worker::add($run_parameters, 'UpdateContact', $contact_id); } + + public static function isUpdatable(int $contact_id): bool + { + $contact = Contact::selectFirst(['next-update', 'local-data', 'url', 'network', 'uid'], ['id' => $contact_id]); + if (empty($contact)) { + return false; + } + + if ($contact['next-update'] > DateTimeFormat::utcNow()) { + return false; + } + + if (DI::config()->get('system', 'update_known_contacts') && ($contact['uid'] == 0) && !Contact::hasRelations($contact_id)) { + Logger::debug('No local relations, contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + return false; + } + + if (DI::config()->get('system', 'update_active_contacts') && $contact['local-data']) { + Logger::debug('No local data, contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + return false; + } + + if (Contact::isLocal($contact['url'])) { + Logger::debug('Local contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + return false; + } + + if (!Protocol::supportsProbe($contact['network'])) { + Logger::debug('Contact does not support probe, it will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + return false; + } + + return true; + } } diff --git a/static/settings.config.php b/static/settings.config.php index 68418f6ff3..869065ce6e 100644 --- a/static/settings.config.php +++ b/static/settings.config.php @@ -257,6 +257,10 @@ return [ // When activated, only public contacts will be activated regularly that are used for example in items or tags. 'update_active_contacts' => false, + // update_known_contacts (Boolean) + // When activated, only public contacts will be activated regularly that are in a contact list of a local user. + 'update_known_contacts' => false, + // url (String) // The fully-qualified URL of this Friendica node. // Used by the worker in a non-HTTP execution environment. diff --git a/view/lang/C/messages.po b/view/lang/C/messages.po index 32b8f6e97c..971063d596 100644 --- a/view/lang/C/messages.po +++ b/view/lang/C/messages.po @@ -8,7 +8,7 @@ msgid "" msgstr "" "Project-Id-Version: 2025.02-dev\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2025-01-04 20:55-0500\n" +"POT-Creation-Date: 2025-01-15 07:37+0000\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" @@ -297,8 +297,8 @@ msgstr "" #: src/Module/Debug/ActivityPubConversion.php:128 #: src/Module/Debug/Babel.php:279 src/Module/Debug/Localtime.php:50 #: src/Module/Debug/Probe.php:40 src/Module/Debug/WebFinger.php:37 -#: src/Module/FriendSuggest.php:132 src/Module/Install.php:220 -#: src/Module/Install.php:260 src/Module/Install.php:295 +#: src/Module/FriendSuggest.php:132 src/Module/Install.php:219 +#: src/Module/Install.php:259 src/Module/Install.php:296 #: src/Module/Invite.php:162 src/Module/Item/Compose.php:185 #: src/Module/Moderation/Item/Source.php:74 #: src/Module/Moderation/Report/Create.php:154 @@ -646,7 +646,7 @@ msgstr "" msgid "Map" msgstr "" -#: src/App.php:394 +#: src/App.php:369 msgid "Apologies but the website is unavailable at the moment." msgstr "" @@ -765,15 +765,15 @@ msgstr "" msgid "No system theme config value set." msgstr "" -#: src/BaseModule.php:395 +#: src/BaseModule.php:409 msgid "The form security token was not correct. This probably happened because the form has been opened for too long (>3 hours) before submitting it." msgstr "" -#: src/BaseModule.php:422 +#: src/BaseModule.php:436 msgid "All contacts" msgstr "" -#: src/BaseModule.php:427 src/Content/Conversation/Factory/Channel.php:32 +#: src/BaseModule.php:441 src/Content/Conversation/Factory/Channel.php:32 #: src/Content/Widget.php:254 src/Core/ACL.php:182 src/Module/Contact.php:395 #: src/Module/Privacy/PermissionTooltip.php:150 #: src/Module/Privacy/PermissionTooltip.php:172 @@ -781,28 +781,28 @@ msgstr "" msgid "Followers" msgstr "" -#: src/BaseModule.php:432 src/Content/Widget.php:255 src/Module/Contact.php:398 +#: src/BaseModule.php:446 src/Content/Widget.php:255 src/Module/Contact.php:398 #: src/Module/Settings/Channels.php:145 msgid "Following" msgstr "" -#: src/BaseModule.php:437 src/Content/Widget.php:256 src/Module/Contact.php:401 +#: src/BaseModule.php:451 src/Content/Widget.php:256 src/Module/Contact.php:401 msgid "Mutual friends" msgstr "" -#: src/BaseModule.php:445 +#: src/BaseModule.php:459 msgid "Common" msgstr "" -#: src/Console/Addon.php:162 src/Console/Addon.php:186 +#: src/Console/Addon.php:163 src/Console/Addon.php:187 msgid "Addon not found" msgstr "" -#: src/Console/Addon.php:166 +#: src/Console/Addon.php:167 msgid "Addon already enabled" msgstr "" -#: src/Console/Addon.php:190 +#: src/Console/Addon.php:191 msgid "Addon already disabled" msgstr "" @@ -1745,7 +1745,7 @@ msgid "Display posts done by accounts with the selected account type." msgstr "" #: src/Content/Feature.php:120 src/Content/Widget.php:610 -#: src/Module/Admin/Site.php:464 src/Module/BaseSettings.php:113 +#: src/Module/Admin/Site.php:466 src/Module/BaseSettings.php:113 #: src/Module/Settings/Channels.php:211 src/Module/Settings/Display.php:323 msgid "Channels" msgstr "" @@ -1857,31 +1857,31 @@ msgstr "" msgid "Follow Thread" msgstr "" -#: src/Content/Item.php:420 src/Model/Contact.php:1245 +#: src/Content/Item.php:420 src/Model/Contact.php:1254 msgid "View Status" msgstr "" -#: src/Content/Item.php:421 src/Content/Item.php:444 src/Model/Contact.php:1180 -#: src/Model/Contact.php:1236 src/Model/Contact.php:1246 +#: src/Content/Item.php:421 src/Content/Item.php:444 src/Model/Contact.php:1189 +#: src/Model/Contact.php:1245 src/Model/Contact.php:1255 #: src/Module/Directory.php:143 src/Module/Settings/Profile/Index.php:250 msgid "View Profile" msgstr "" -#: src/Content/Item.php:422 src/Model/Contact.php:1247 +#: src/Content/Item.php:422 src/Model/Contact.php:1256 msgid "View Photos" msgstr "" -#: src/Content/Item.php:423 src/Model/Contact.php:1214 +#: src/Content/Item.php:423 src/Model/Contact.php:1223 #: src/Model/Profile.php:446 msgid "Network Posts" msgstr "" -#: src/Content/Item.php:424 src/Model/Contact.php:1238 -#: src/Model/Contact.php:1249 +#: src/Content/Item.php:424 src/Model/Contact.php:1247 +#: src/Model/Contact.php:1258 msgid "View Contact" msgstr "" -#: src/Content/Item.php:425 src/Model/Contact.php:1250 +#: src/Content/Item.php:425 src/Model/Contact.php:1259 msgid "Send PM" msgstr "" @@ -1921,7 +1921,7 @@ msgid "Search Text" msgstr "" #: src/Content/Item.php:441 src/Content/Widget.php:66 -#: src/Model/Contact.php:1239 src/Model/Contact.php:1251 +#: src/Model/Contact.php:1248 src/Model/Contact.php:1260 #: src/Module/Contact/Follow.php:152 view/theme/vier/theme.php:183 msgid "Connect/Follow" msgstr "" @@ -2397,7 +2397,7 @@ msgstr "" msgid "Organisations" msgstr "" -#: src/Content/Widget.php:554 src/Model/Contact.php:1751 +#: src/Content/Widget.php:554 src/Model/Contact.php:1758 msgid "News" msgstr "" @@ -2451,12 +2451,12 @@ msgstr[1] "" msgid "More Trending Tags" msgstr "" -#: src/Content/Widget/VCard.php:95 src/Model/Contact.php:1208 +#: src/Content/Widget/VCard.php:95 src/Model/Contact.php:1217 #: src/Model/Profile.php:440 msgid "Post to group" msgstr "" -#: src/Content/Widget/VCard.php:100 src/Model/Contact.php:1212 +#: src/Content/Widget/VCard.php:100 src/Model/Contact.php:1221 #: src/Model/Profile.php:444 src/Module/Moderation/Item/Source.php:80 msgid "Mention" msgstr "" @@ -2484,13 +2484,13 @@ msgstr "" msgid "Network:" msgstr "" -#: src/Content/Widget/VCard.php:119 src/Model/Contact.php:1240 -#: src/Model/Contact.php:1252 src/Model/Profile.php:457 +#: src/Content/Widget/VCard.php:119 src/Model/Contact.php:1249 +#: src/Model/Contact.php:1261 src/Model/Profile.php:457 #: src/Module/Contact/Profile.php:476 msgid "Unfollow" msgstr "" -#: src/Content/Widget/VCard.php:125 src/Model/Contact.php:1210 +#: src/Content/Widget/VCard.php:125 src/Model/Contact.php:1219 #: src/Model/Profile.php:442 msgid "View group" msgstr "" @@ -2557,8 +2557,8 @@ msgstr "" msgid "You may need to import the file \"database.sql\" manually using phpmyadmin or mysql." msgstr "" -#: src/Core/Installer.php:184 src/Module/Install.php:193 -#: src/Module/Install.php:336 +#: src/Core/Installer.php:184 src/Module/Install.php:192 +#: src/Module/Install.php:337 msgid "Please see the file \"doc/INSTALL.md\"." msgstr "" @@ -3194,84 +3194,84 @@ msgstr "" msgid "Edit circles" msgstr "" -#: src/Model/Contact.php:1259 src/Module/Moderation/Users/Pending.php:88 +#: src/Model/Contact.php:1268 src/Module/Moderation/Users/Pending.php:88 #: src/Module/Notifications/Introductions.php:124 #: src/Module/Notifications/Introductions.php:197 msgid "Approve" msgstr "" -#: src/Model/Contact.php:1595 src/Model/Contact.php:1667 +#: src/Model/Contact.php:1602 src/Model/Contact.php:1674 #: src/Module/Contact/Profile.php:360 #, php-format msgid "%s has blocked you" msgstr "" -#: src/Model/Contact.php:1747 +#: src/Model/Contact.php:1754 msgid "Organisation" msgstr "" -#: src/Model/Contact.php:1755 +#: src/Model/Contact.php:1762 msgid "Group" msgstr "" -#: src/Model/Contact.php:1759 src/Module/Moderation/BaseUsers.php:122 +#: src/Model/Contact.php:1766 src/Module/Moderation/BaseUsers.php:122 msgid "Relay" msgstr "" -#: src/Model/Contact.php:3085 +#: src/Model/Contact.php:3092 msgid "Disallowed profile URL." msgstr "" -#: src/Model/Contact.php:3090 src/Module/Friendica.php:88 +#: src/Model/Contact.php:3097 src/Module/Friendica.php:88 msgid "Blocked domain" msgstr "" -#: src/Model/Contact.php:3095 +#: src/Model/Contact.php:3102 msgid "Connect URL missing." msgstr "" -#: src/Model/Contact.php:3104 +#: src/Model/Contact.php:3111 msgid "The contact could not be added. Please check the relevant network credentials in your Settings -> Social Networks page." msgstr "" -#: src/Model/Contact.php:3122 +#: src/Model/Contact.php:3129 #, php-format msgid "Expected network %s does not match actual network %s" msgstr "" -#: src/Model/Contact.php:3139 +#: src/Model/Contact.php:3146 msgid "This seems to be a relay account. They can't be followed by users." msgstr "" -#: src/Model/Contact.php:3146 +#: src/Model/Contact.php:3153 msgid "The profile address specified does not provide adequate information." msgstr "" -#: src/Model/Contact.php:3148 +#: src/Model/Contact.php:3155 msgid "No compatible communication protocols or feeds were discovered." msgstr "" -#: src/Model/Contact.php:3151 +#: src/Model/Contact.php:3158 msgid "An author or name was not found." msgstr "" -#: src/Model/Contact.php:3154 +#: src/Model/Contact.php:3161 msgid "No browser URL could be matched to this address." msgstr "" -#: src/Model/Contact.php:3157 +#: src/Model/Contact.php:3164 msgid "Unable to match @-style Identity Address with a known protocol or email contact." msgstr "" -#: src/Model/Contact.php:3158 +#: src/Model/Contact.php:3165 msgid "Use mailto: in front of address to force email check." msgstr "" -#: src/Model/Contact.php:3164 +#: src/Model/Contact.php:3171 msgid "Limited profile. This person will be unable to receive direct/personal notifications from you." msgstr "" -#: src/Model/Contact.php:3223 +#: src/Model/Contact.php:3230 msgid "Unable to retrieve contact information." msgstr "" @@ -3469,7 +3469,7 @@ msgstr "" msgid "[no subject]" msgstr "" -#: src/Model/Photo.php:1192 src/Module/Media/Photo/Upload.php:154 +#: src/Model/Photo.php:1195 src/Module/Media/Photo/Upload.php:154 msgid "Wall Photos" msgstr "" @@ -3885,7 +3885,7 @@ msgstr "" #: src/Module/Admin/Addons/Details.php:95 src/Module/Admin/Addons/Index.php:59 #: src/Module/Admin/Federation.php:213 src/Module/Admin/Logs/Settings.php:74 #: src/Module/Admin/Logs/View.php:71 src/Module/Admin/Queue.php:59 -#: src/Module/Admin/Site.php:447 src/Module/Admin/Storage.php:124 +#: src/Module/Admin/Site.php:449 src/Module/Admin/Storage.php:124 #: src/Module/Admin/Summary.php:173 src/Module/Admin/Themes/Details.php:82 #: src/Module/Admin/Themes/Index.php:103 src/Module/Admin/Tos.php:63 #: src/Module/Moderation/Users/Create.php:47 @@ -3923,7 +3923,7 @@ msgid "Addon %s failed to install." msgstr "" #: src/Module/Admin/Addons/Index.php:61 src/Module/Admin/Features.php:69 -#: src/Module/Admin/Logs/Settings.php:76 src/Module/Admin/Site.php:450 +#: src/Module/Admin/Logs/Settings.php:76 src/Module/Admin/Site.php:452 #: src/Module/Admin/Themes/Index.php:105 src/Module/Admin/Tos.php:72 #: src/Module/Settings/Account.php:507 src/Module/Settings/Addons.php:64 #: src/Module/Settings/Connectors.php:143 @@ -4124,8 +4124,8 @@ msgid "Enable Debugging" msgstr "" #: src/Module/Admin/Logs/Settings.php:80 src/Module/Admin/Logs/Settings.php:81 -#: src/Module/Admin/Logs/Settings.php:82 src/Module/Admin/Site.php:470 -#: src/Module/Admin/Site.php:478 +#: src/Module/Admin/Logs/Settings.php:82 src/Module/Admin/Site.php:472 +#: src/Module/Admin/Site.php:480 msgid "Read-only because it is set by an environment variable" msgstr "" @@ -4274,257 +4274,257 @@ msgstr "" msgid "Priority" msgstr "" -#: src/Module/Admin/Site.php:230 +#: src/Module/Admin/Site.php:232 #, php-format msgid "%s is no valid input for maximum media size" msgstr "" -#: src/Module/Admin/Site.php:235 +#: src/Module/Admin/Site.php:237 #, php-format msgid "%s is no valid input for maximum image size" msgstr "" -#: src/Module/Admin/Site.php:362 src/Module/Settings/Display.php:212 +#: src/Module/Admin/Site.php:364 src/Module/Settings/Display.php:212 msgid "No special theme for mobile devices" msgstr "" -#: src/Module/Admin/Site.php:379 src/Module/Settings/Display.php:222 +#: src/Module/Admin/Site.php:381 src/Module/Settings/Display.php:222 #, php-format msgid "%s - (Experimental)" msgstr "" -#: src/Module/Admin/Site.php:391 +#: src/Module/Admin/Site.php:393 msgid "No community page" msgstr "" -#: src/Module/Admin/Site.php:392 +#: src/Module/Admin/Site.php:394 msgid "No community page for visitors" msgstr "" -#: src/Module/Admin/Site.php:393 +#: src/Module/Admin/Site.php:395 msgid "Public postings from users of this site" msgstr "" -#: src/Module/Admin/Site.php:394 +#: src/Module/Admin/Site.php:396 msgid "Public postings from the federated network" msgstr "" -#: src/Module/Admin/Site.php:395 +#: src/Module/Admin/Site.php:397 msgid "Public postings from local users and the federated network" msgstr "" -#: src/Module/Admin/Site.php:401 +#: src/Module/Admin/Site.php:403 msgid "Multi user instance" msgstr "" -#: src/Module/Admin/Site.php:424 +#: src/Module/Admin/Site.php:426 msgid "Closed" msgstr "" -#: src/Module/Admin/Site.php:425 +#: src/Module/Admin/Site.php:427 msgid "Requires approval" msgstr "" -#: src/Module/Admin/Site.php:426 +#: src/Module/Admin/Site.php:428 msgid "Open" msgstr "" -#: src/Module/Admin/Site.php:430 +#: src/Module/Admin/Site.php:432 msgid "Don't check" msgstr "" -#: src/Module/Admin/Site.php:431 +#: src/Module/Admin/Site.php:433 msgid "check the stable version" msgstr "" -#: src/Module/Admin/Site.php:432 +#: src/Module/Admin/Site.php:434 msgid "check the development version" msgstr "" -#: src/Module/Admin/Site.php:436 +#: src/Module/Admin/Site.php:438 msgid "none" msgstr "" -#: src/Module/Admin/Site.php:437 +#: src/Module/Admin/Site.php:439 msgid "Local contacts" msgstr "" -#: src/Module/Admin/Site.php:438 +#: src/Module/Admin/Site.php:440 msgid "Interactors" msgstr "" -#: src/Module/Admin/Site.php:448 src/Module/BaseAdmin.php:76 +#: src/Module/Admin/Site.php:450 src/Module/BaseAdmin.php:76 msgid "Site" msgstr "" -#: src/Module/Admin/Site.php:449 +#: src/Module/Admin/Site.php:451 msgid "General Information" msgstr "" -#: src/Module/Admin/Site.php:451 +#: src/Module/Admin/Site.php:453 msgid "Republish users to directory" msgstr "" -#: src/Module/Admin/Site.php:452 src/Module/Register.php:146 +#: src/Module/Admin/Site.php:454 src/Module/Register.php:146 msgid "Registration" msgstr "" -#: src/Module/Admin/Site.php:453 +#: src/Module/Admin/Site.php:455 msgid "File upload" msgstr "" -#: src/Module/Admin/Site.php:454 +#: src/Module/Admin/Site.php:456 msgid "Policies" msgstr "" -#: src/Module/Admin/Site.php:455 src/Module/Calendar/Event/Form.php:238 +#: src/Module/Admin/Site.php:457 src/Module/Calendar/Event/Form.php:238 #: src/Module/Contact.php:528 src/Module/Profile/Profile.php:267 msgid "Advanced" msgstr "" -#: src/Module/Admin/Site.php:456 +#: src/Module/Admin/Site.php:458 msgid "Auto Discovered Contact Directory" msgstr "" -#: src/Module/Admin/Site.php:457 +#: src/Module/Admin/Site.php:459 msgid "Performance" msgstr "" -#: src/Module/Admin/Site.php:458 +#: src/Module/Admin/Site.php:460 msgid "Worker" msgstr "" -#: src/Module/Admin/Site.php:459 +#: src/Module/Admin/Site.php:461 msgid "Message Relay" msgstr "" -#: src/Module/Admin/Site.php:460 +#: src/Module/Admin/Site.php:462 msgid "Use the command \"console relay\" in the command line to add or remove relays." msgstr "" -#: src/Module/Admin/Site.php:461 +#: src/Module/Admin/Site.php:463 msgid "The system is not subscribed to any relays at the moment." msgstr "" -#: src/Module/Admin/Site.php:462 +#: src/Module/Admin/Site.php:464 msgid "The system is currently subscribed to the following relays:" msgstr "" -#: src/Module/Admin/Site.php:465 +#: src/Module/Admin/Site.php:467 msgid "Relocate Node" msgstr "" -#: src/Module/Admin/Site.php:466 +#: src/Module/Admin/Site.php:468 msgid "Relocating your node enables you to change the DNS domain of this node and keep all the existing users and posts. This process takes a while and can only be started from the relocate console command like this:" msgstr "" -#: src/Module/Admin/Site.php:467 +#: src/Module/Admin/Site.php:469 msgid "(Friendica directory)# bin/console relocate https://newdomain.com" msgstr "" -#: src/Module/Admin/Site.php:470 +#: src/Module/Admin/Site.php:472 msgid "Site name" msgstr "" -#: src/Module/Admin/Site.php:471 +#: src/Module/Admin/Site.php:473 msgid "Sender Email" msgstr "" -#: src/Module/Admin/Site.php:471 +#: src/Module/Admin/Site.php:473 msgid "The email address your server shall use to send notification emails from." msgstr "" -#: src/Module/Admin/Site.php:472 +#: src/Module/Admin/Site.php:474 msgid "Name of the system actor" msgstr "" -#: src/Module/Admin/Site.php:472 +#: src/Module/Admin/Site.php:474 msgid "Name of the internal system account that is used to perform ActivityPub requests. This must be an unused username. If set, this can't be changed again." msgstr "" -#: src/Module/Admin/Site.php:473 +#: src/Module/Admin/Site.php:475 msgid "Banner/Logo" msgstr "" -#: src/Module/Admin/Site.php:474 +#: src/Module/Admin/Site.php:476 msgid "Email Banner/Logo" msgstr "" -#: src/Module/Admin/Site.php:475 +#: src/Module/Admin/Site.php:477 msgid "Shortcut icon" msgstr "" -#: src/Module/Admin/Site.php:475 +#: src/Module/Admin/Site.php:477 msgid "Link to an icon that will be used for browsers." msgstr "" -#: src/Module/Admin/Site.php:476 +#: src/Module/Admin/Site.php:478 msgid "Touch icon" msgstr "" -#: src/Module/Admin/Site.php:476 +#: src/Module/Admin/Site.php:478 msgid "Link to an icon that will be used for tablets and mobiles." msgstr "" -#: src/Module/Admin/Site.php:477 +#: src/Module/Admin/Site.php:479 msgid "Additional Info" msgstr "" -#: src/Module/Admin/Site.php:477 +#: src/Module/Admin/Site.php:479 #, php-format msgid "For public servers: you can add additional information here that will be listed at %s/servers." msgstr "" -#: src/Module/Admin/Site.php:478 +#: src/Module/Admin/Site.php:480 msgid "System language" msgstr "" -#: src/Module/Admin/Site.php:479 +#: src/Module/Admin/Site.php:481 msgid "System theme" msgstr "" -#: src/Module/Admin/Site.php:479 +#: src/Module/Admin/Site.php:481 #, php-format msgid "Default system theme - may be over-ridden by user profiles - Change default theme settings" msgstr "" -#: src/Module/Admin/Site.php:480 +#: src/Module/Admin/Site.php:482 msgid "Mobile system theme" msgstr "" -#: src/Module/Admin/Site.php:480 +#: src/Module/Admin/Site.php:482 msgid "Theme for mobile devices" msgstr "" -#: src/Module/Admin/Site.php:481 +#: src/Module/Admin/Site.php:483 msgid "Force SSL" msgstr "" -#: src/Module/Admin/Site.php:481 +#: src/Module/Admin/Site.php:483 msgid "Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops." msgstr "" -#: src/Module/Admin/Site.php:482 +#: src/Module/Admin/Site.php:484 msgid "Show help entry from navigation menu" msgstr "" -#: src/Module/Admin/Site.php:482 +#: src/Module/Admin/Site.php:484 msgid "Displays the menu entry for the Help pages from the navigation menu. It is always accessible by calling /help directly." msgstr "" -#: src/Module/Admin/Site.php:483 +#: src/Module/Admin/Site.php:485 msgid "Single user instance" msgstr "" -#: src/Module/Admin/Site.php:483 +#: src/Module/Admin/Site.php:485 msgid "Make this instance multi-user or single-user for the named user" msgstr "" -#: src/Module/Admin/Site.php:485 +#: src/Module/Admin/Site.php:487 msgid "Maximum image size" msgstr "" -#: src/Module/Admin/Site.php:485 +#: src/Module/Admin/Site.php:487 #, php-format msgid "" "Maximum size in bytes of uploaded images. Default is 0, which means no limits. You can put k, m, or g behind the desired value for KiB, MiB, GiB, respectively.\n" @@ -4532,27 +4532,27 @@ msgid "" "\t\t\t\t\t\t\t\t\t\t\t\t\tCurrently upload_max_filesize is set to %s (%s byte)" msgstr "" -#: src/Module/Admin/Site.php:489 +#: src/Module/Admin/Site.php:491 msgid "Maximum image length" msgstr "" -#: src/Module/Admin/Site.php:489 +#: src/Module/Admin/Site.php:491 msgid "Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits." msgstr "" -#: src/Module/Admin/Site.php:490 +#: src/Module/Admin/Site.php:492 msgid "JPEG image quality" msgstr "" -#: src/Module/Admin/Site.php:490 +#: src/Module/Admin/Site.php:492 msgid "Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality." msgstr "" -#: src/Module/Admin/Site.php:491 +#: src/Module/Admin/Site.php:493 msgid "Maximum media file size" msgstr "" -#: src/Module/Admin/Site.php:491 +#: src/Module/Admin/Site.php:493 #, php-format msgid "" "Maximum size in bytes of uploaded media files. Default is 0, which means no limits. You can put k, m, or g behind the desired value for KiB, MiB, GiB, respectively.\n" @@ -4560,739 +4560,747 @@ msgid "" "\t\t\t\t\t\t\t\t\t\t\t\t\tCurrently upload_max_filesize is set to %s (%s byte)" msgstr "" -#: src/Module/Admin/Site.php:496 +#: src/Module/Admin/Site.php:498 msgid "Register policy" msgstr "" -#: src/Module/Admin/Site.php:497 +#: src/Module/Admin/Site.php:499 msgid "Maximum Users" msgstr "" -#: src/Module/Admin/Site.php:497 +#: src/Module/Admin/Site.php:499 msgid "If defined, the register policy is automatically closed when the given number of users is reached and reopens the registry when the number drops below the limit. It only works when the policy is set to open or close, but not when the policy is set to approval." msgstr "" -#: src/Module/Admin/Site.php:498 +#: src/Module/Admin/Site.php:500 msgid "Maximum Daily Registrations" msgstr "" -#: src/Module/Admin/Site.php:498 +#: src/Module/Admin/Site.php:500 msgid "If registration is permitted above, this sets the maximum number of new user registrations to accept per day. If register is set to closed, this setting has no effect." msgstr "" -#: src/Module/Admin/Site.php:499 +#: src/Module/Admin/Site.php:501 msgid "Register text" msgstr "" -#: src/Module/Admin/Site.php:499 +#: src/Module/Admin/Site.php:501 msgid "Will be displayed prominently on the registration page. You can use BBCode here." msgstr "" -#: src/Module/Admin/Site.php:500 +#: src/Module/Admin/Site.php:502 msgid "Forbidden Nicknames" msgstr "" -#: src/Module/Admin/Site.php:500 +#: src/Module/Admin/Site.php:502 msgid "Comma separated list of nicknames that are forbidden from registration. Preset is a list of role names according RFC 2142." msgstr "" -#: src/Module/Admin/Site.php:501 +#: src/Module/Admin/Site.php:503 msgid "Accounts abandoned after x days" msgstr "" -#: src/Module/Admin/Site.php:501 +#: src/Module/Admin/Site.php:503 msgid "Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit." msgstr "" -#: src/Module/Admin/Site.php:502 +#: src/Module/Admin/Site.php:504 msgid "Allowed friend domains" msgstr "" -#: src/Module/Admin/Site.php:502 +#: src/Module/Admin/Site.php:504 msgid "Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains" msgstr "" -#: src/Module/Admin/Site.php:503 +#: src/Module/Admin/Site.php:505 msgid "Allowed email domains" msgstr "" -#: src/Module/Admin/Site.php:503 +#: src/Module/Admin/Site.php:505 msgid "Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains" msgstr "" -#: src/Module/Admin/Site.php:504 +#: src/Module/Admin/Site.php:506 msgid "Disallowed email domains" msgstr "" -#: src/Module/Admin/Site.php:504 +#: src/Module/Admin/Site.php:506 msgid "Comma separated list of domains which are rejected as email addresses for registrations to this site. Wildcards are accepted." msgstr "" -#: src/Module/Admin/Site.php:505 +#: src/Module/Admin/Site.php:507 msgid "No OEmbed rich content" msgstr "" -#: src/Module/Admin/Site.php:505 +#: src/Module/Admin/Site.php:507 msgid "Don't show the rich content (e.g. embedded PDF), except from the domains listed below." msgstr "" -#: src/Module/Admin/Site.php:506 +#: src/Module/Admin/Site.php:508 msgid "Trusted third-party domains" msgstr "" -#: src/Module/Admin/Site.php:506 +#: src/Module/Admin/Site.php:508 msgid "Comma separated list of domains from which content is allowed to be embedded in posts like with OEmbed. All sub-domains of the listed domains are allowed as well." msgstr "" -#: src/Module/Admin/Site.php:507 +#: src/Module/Admin/Site.php:509 msgid "Block public" msgstr "" -#: src/Module/Admin/Site.php:507 +#: src/Module/Admin/Site.php:509 msgid "Check to block public access to all otherwise public personal pages on this site unless you are currently logged in." msgstr "" -#: src/Module/Admin/Site.php:508 +#: src/Module/Admin/Site.php:510 msgid "Force publish" msgstr "" -#: src/Module/Admin/Site.php:508 +#: src/Module/Admin/Site.php:510 msgid "Check to force all profiles on this site to be listed in the site directory." msgstr "" -#: src/Module/Admin/Site.php:508 +#: src/Module/Admin/Site.php:510 msgid "Enabling this may violate privacy laws like the GDPR" msgstr "" -#: src/Module/Admin/Site.php:509 +#: src/Module/Admin/Site.php:511 msgid "Global directory URL" msgstr "" -#: src/Module/Admin/Site.php:509 +#: src/Module/Admin/Site.php:511 msgid "URL to the global directory. If this is not set, the global directory is completely unavailable to the application." msgstr "" -#: src/Module/Admin/Site.php:510 +#: src/Module/Admin/Site.php:512 msgid "Private posts by default for new users" msgstr "" -#: src/Module/Admin/Site.php:510 +#: src/Module/Admin/Site.php:512 msgid "Set default post permissions for all new members to the default privacy circle rather than public." msgstr "" -#: src/Module/Admin/Site.php:511 +#: src/Module/Admin/Site.php:513 msgid "Don't include post content in email notifications" msgstr "" -#: src/Module/Admin/Site.php:511 +#: src/Module/Admin/Site.php:513 msgid "Don't include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure." msgstr "" -#: src/Module/Admin/Site.php:512 +#: src/Module/Admin/Site.php:514 msgid "Disallow public access to addons listed in the apps menu." msgstr "" -#: src/Module/Admin/Site.php:512 +#: src/Module/Admin/Site.php:514 msgid "Checking this box will restrict addons listed in the apps menu to members only." msgstr "" -#: src/Module/Admin/Site.php:513 +#: src/Module/Admin/Site.php:515 msgid "Don't embed private images in posts" msgstr "" -#: src/Module/Admin/Site.php:513 +#: src/Module/Admin/Site.php:515 msgid "Don't replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while." msgstr "" -#: src/Module/Admin/Site.php:514 +#: src/Module/Admin/Site.php:516 msgid "Explicit Content" msgstr "" -#: src/Module/Admin/Site.php:514 +#: src/Module/Admin/Site.php:516 msgid "Set this to announce that your node is used mostly for explicit content that might not be suited for minors. This information will be published in the node information and might be used, e.g. by the global directory, to filter your node from listings of nodes to join. Additionally a note about this will be shown at the user registration page." msgstr "" -#: src/Module/Admin/Site.php:515 +#: src/Module/Admin/Site.php:517 msgid "Only local search" msgstr "" -#: src/Module/Admin/Site.php:515 +#: src/Module/Admin/Site.php:517 msgid "Blocks search for users who are not logged in to prevent crawlers from blocking your system." msgstr "" -#: src/Module/Admin/Site.php:516 +#: src/Module/Admin/Site.php:518 msgid "Blocked tags for trending tags" msgstr "" -#: src/Module/Admin/Site.php:516 +#: src/Module/Admin/Site.php:518 msgid "Comma separated list of hashtags that shouldn't be displayed in the trending tags." msgstr "" -#: src/Module/Admin/Site.php:517 +#: src/Module/Admin/Site.php:519 msgid "Cache contact avatars" msgstr "" -#: src/Module/Admin/Site.php:517 +#: src/Module/Admin/Site.php:519 msgid "Locally store the avatar pictures of the contacts. This uses a lot of storage space but it increases the performance." msgstr "" -#: src/Module/Admin/Site.php:518 +#: src/Module/Admin/Site.php:520 msgid "Allow Users to set remote_self" msgstr "" -#: src/Module/Admin/Site.php:518 +#: src/Module/Admin/Site.php:520 msgid "With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream." msgstr "" -#: src/Module/Admin/Site.php:519 +#: src/Module/Admin/Site.php:521 msgid "Allow Users to set up relay channels" msgstr "" -#: src/Module/Admin/Site.php:519 +#: src/Module/Admin/Site.php:521 msgid "If enabled, it is possible to create relay users that are used to reshare content based on user defined channels." msgstr "" -#: src/Module/Admin/Site.php:520 +#: src/Module/Admin/Site.php:522 msgid "Adjust the feed poll frequency" msgstr "" -#: src/Module/Admin/Site.php:520 +#: src/Module/Admin/Site.php:522 msgid "Automatically detect and set the best feed poll frequency." msgstr "" -#: src/Module/Admin/Site.php:521 +#: src/Module/Admin/Site.php:523 msgid "Minimum poll interval" msgstr "" -#: src/Module/Admin/Site.php:521 +#: src/Module/Admin/Site.php:523 msgid "Minimal distance in minutes between two polls for mail and feed contacts. Reasonable values are between 1 and 59." msgstr "" -#: src/Module/Admin/Site.php:522 +#: src/Module/Admin/Site.php:524 msgid "Enable multiple registrations" msgstr "" -#: src/Module/Admin/Site.php:522 +#: src/Module/Admin/Site.php:524 msgid "Enable users to register additional accounts for use as pages." msgstr "" -#: src/Module/Admin/Site.php:523 +#: src/Module/Admin/Site.php:525 msgid "Enable OpenID" msgstr "" -#: src/Module/Admin/Site.php:523 +#: src/Module/Admin/Site.php:525 msgid "Enable OpenID support for registration and logins." msgstr "" -#: src/Module/Admin/Site.php:524 +#: src/Module/Admin/Site.php:526 msgid "Enable full name check" msgstr "" -#: src/Module/Admin/Site.php:524 +#: src/Module/Admin/Site.php:526 msgid "Prevents users from registering with a display name with fewer than two parts separated by spaces." msgstr "" -#: src/Module/Admin/Site.php:525 +#: src/Module/Admin/Site.php:527 msgid "Email administrators on new registration" msgstr "" -#: src/Module/Admin/Site.php:525 +#: src/Module/Admin/Site.php:527 msgid "If enabled and the system is set to an open registration, an email for each new registration is sent to the administrators." msgstr "" -#: src/Module/Admin/Site.php:526 +#: src/Module/Admin/Site.php:528 msgid "Community pages for visitors" msgstr "" -#: src/Module/Admin/Site.php:526 +#: src/Module/Admin/Site.php:528 msgid "Which community pages should be available for visitors. Local users always see both pages." msgstr "" -#: src/Module/Admin/Site.php:527 +#: src/Module/Admin/Site.php:529 msgid "Posts per user on community page" msgstr "" -#: src/Module/Admin/Site.php:527 +#: src/Module/Admin/Site.php:529 msgid "The maximum number of posts per user on the local community page. This is useful, when a single user floods the local community page." msgstr "" -#: src/Module/Admin/Site.php:528 +#: src/Module/Admin/Site.php:530 msgid "Posts per server on community page" msgstr "" -#: src/Module/Admin/Site.php:528 +#: src/Module/Admin/Site.php:530 msgid "The maximum number of posts per server on the global community page. This is useful, when posts from a single server flood the global community page." msgstr "" -#: src/Module/Admin/Site.php:530 +#: src/Module/Admin/Site.php:532 msgid "Enable Mail support" msgstr "" -#: src/Module/Admin/Site.php:530 +#: src/Module/Admin/Site.php:532 msgid "Enable built-in mail support to poll IMAP folders and to reply via mail." msgstr "" -#: src/Module/Admin/Site.php:531 +#: src/Module/Admin/Site.php:533 msgid "Mail support can't be enabled because the PHP IMAP module is not installed." msgstr "" -#: src/Module/Admin/Site.php:533 +#: src/Module/Admin/Site.php:535 msgid "Diaspora support can't be enabled because Friendica was installed into a sub directory." msgstr "" -#: src/Module/Admin/Site.php:534 +#: src/Module/Admin/Site.php:536 msgid "Enable Diaspora support" msgstr "" -#: src/Module/Admin/Site.php:534 +#: src/Module/Admin/Site.php:536 msgid "Enable built-in Diaspora network compatibility for communicating with diaspora servers." msgstr "" -#: src/Module/Admin/Site.php:535 +#: src/Module/Admin/Site.php:537 msgid "Verify SSL" msgstr "" -#: src/Module/Admin/Site.php:535 +#: src/Module/Admin/Site.php:537 msgid "If you wish, you can turn on strict certificate checking. This will mean you cannot connect (at all) to self-signed SSL sites." msgstr "" -#: src/Module/Admin/Site.php:536 +#: src/Module/Admin/Site.php:538 msgid "Proxy user" msgstr "" -#: src/Module/Admin/Site.php:536 +#: src/Module/Admin/Site.php:538 msgid "User name for the proxy server." msgstr "" -#: src/Module/Admin/Site.php:537 +#: src/Module/Admin/Site.php:539 msgid "Proxy URL" msgstr "" -#: src/Module/Admin/Site.php:537 +#: src/Module/Admin/Site.php:539 msgid "If you want to use a proxy server that Friendica should use to connect to the network, put the URL of the proxy here." msgstr "" -#: src/Module/Admin/Site.php:538 +#: src/Module/Admin/Site.php:540 msgid "Network timeout" msgstr "" -#: src/Module/Admin/Site.php:538 +#: src/Module/Admin/Site.php:540 msgid "Value is in seconds. Set to 0 for unlimited (not recommended)." msgstr "" -#: src/Module/Admin/Site.php:539 +#: src/Module/Admin/Site.php:541 msgid "Maximum Load Average" msgstr "" -#: src/Module/Admin/Site.php:539 +#: src/Module/Admin/Site.php:541 #, php-format msgid "Maximum system load before delivery and poll processes are deferred - default %d." msgstr "" -#: src/Module/Admin/Site.php:540 +#: src/Module/Admin/Site.php:542 msgid "Minimal Memory" msgstr "" -#: src/Module/Admin/Site.php:540 +#: src/Module/Admin/Site.php:542 msgid "Minimal free memory in MB for the worker. Needs access to /proc/meminfo - default 0 (deactivated)." msgstr "" -#: src/Module/Admin/Site.php:541 +#: src/Module/Admin/Site.php:543 msgid "Periodically optimize tables" msgstr "" -#: src/Module/Admin/Site.php:541 +#: src/Module/Admin/Site.php:543 msgid "Periodically optimize tables like the cache and the workerqueue" msgstr "" -#: src/Module/Admin/Site.php:543 +#: src/Module/Admin/Site.php:545 msgid "Discover followers/followings from contacts" msgstr "" -#: src/Module/Admin/Site.php:543 +#: src/Module/Admin/Site.php:545 msgid "If enabled, contacts are checked for their followers and following contacts." msgstr "" -#: src/Module/Admin/Site.php:544 +#: src/Module/Admin/Site.php:546 msgid "None - deactivated" msgstr "" -#: src/Module/Admin/Site.php:545 +#: src/Module/Admin/Site.php:547 msgid "Local contacts - contacts of our local contacts are discovered for their followers/followings." msgstr "" -#: src/Module/Admin/Site.php:546 +#: src/Module/Admin/Site.php:548 msgid "Interactors - contacts of our local contacts and contacts who interacted on locally visible postings are discovered for their followers/followings." msgstr "" -#: src/Module/Admin/Site.php:548 +#: src/Module/Admin/Site.php:550 msgid "Only update contacts/servers with local data" msgstr "" -#: src/Module/Admin/Site.php:548 +#: src/Module/Admin/Site.php:550 msgid "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." msgstr "" -#: src/Module/Admin/Site.php:549 +#: src/Module/Admin/Site.php:551 +msgid "Only update contacts with relations" +msgstr "" + +#: src/Module/Admin/Site.php:551 +msgid "If enabled, the system will only look for changes in contacts that are in a contact list of a user on this system." +msgstr "" + +#: src/Module/Admin/Site.php:552 msgid "Synchronize the contacts with the directory server" msgstr "" -#: src/Module/Admin/Site.php:549 +#: src/Module/Admin/Site.php:552 msgid "if enabled, the system will check periodically for new contacts on the defined directory server." msgstr "" -#: src/Module/Admin/Site.php:551 +#: src/Module/Admin/Site.php:554 msgid "Discover contacts from other servers" msgstr "" -#: src/Module/Admin/Site.php:551 +#: src/Module/Admin/Site.php:554 msgid "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." msgstr "" -#: src/Module/Admin/Site.php:552 +#: src/Module/Admin/Site.php:555 msgid "Days between requery" msgstr "" -#: src/Module/Admin/Site.php:552 +#: src/Module/Admin/Site.php:555 msgid "Number of days after which a server is requeried for their contacts and servers it knows of. This is only used when the discovery is activated." msgstr "" -#: src/Module/Admin/Site.php:553 +#: src/Module/Admin/Site.php:556 msgid "Search the local directory" msgstr "" -#: src/Module/Admin/Site.php:553 +#: src/Module/Admin/Site.php:556 msgid "Search the local directory instead of the global directory. When searching locally, every search will be executed on the global directory in the background. This improves the search results when the search is repeated." msgstr "" -#: src/Module/Admin/Site.php:555 +#: src/Module/Admin/Site.php:558 msgid "Publish server information" msgstr "" -#: src/Module/Admin/Site.php:555 +#: src/Module/Admin/Site.php:558 msgid "If enabled, general server and usage data will be published. The data contains the name and version of the server, number of users with public profiles, number of posts and the activated protocols and connectors. See the-federation.info for details." msgstr "" -#: src/Module/Admin/Site.php:557 +#: src/Module/Admin/Site.php:560 msgid "Check upstream version" msgstr "" -#: src/Module/Admin/Site.php:557 +#: src/Module/Admin/Site.php:560 msgid "Enables checking for new Friendica versions at github. If there is a new version, you will be informed in the admin panel overview." msgstr "" -#: src/Module/Admin/Site.php:558 +#: src/Module/Admin/Site.php:561 msgid "Suppress Tags" msgstr "" -#: src/Module/Admin/Site.php:558 +#: src/Module/Admin/Site.php:561 msgid "Suppress showing a list of hashtags at the end of the posting." msgstr "" -#: src/Module/Admin/Site.php:559 +#: src/Module/Admin/Site.php:562 msgid "Clean database" msgstr "" -#: src/Module/Admin/Site.php:559 +#: src/Module/Admin/Site.php:562 msgid "Remove old remote items, orphaned database records and old content from some other helper tables." msgstr "" -#: src/Module/Admin/Site.php:560 +#: src/Module/Admin/Site.php:563 msgid "Lifespan of remote items" msgstr "" -#: src/Module/Admin/Site.php:560 +#: src/Module/Admin/Site.php:563 msgid "When the database cleanup is enabled, this defines the days after which remote items will be deleted. Own items, and marked or filed items are always kept. 0 disables this behaviour." msgstr "" -#: src/Module/Admin/Site.php:561 +#: src/Module/Admin/Site.php:564 msgid "Lifespan of unclaimed items" msgstr "" -#: src/Module/Admin/Site.php:561 +#: src/Module/Admin/Site.php:564 msgid "When the database cleanup is enabled, this defines the days after which unclaimed remote items (mostly content from the relay) will be deleted. Default value is 90 days. Defaults to the general lifespan value of remote items if set to 0." msgstr "" -#: src/Module/Admin/Site.php:562 +#: src/Module/Admin/Site.php:565 msgid "Lifespan of raw conversation data" msgstr "" -#: src/Module/Admin/Site.php:562 +#: src/Module/Admin/Site.php:565 msgid "The conversation data is used for ActivityPub, as well as for debug purposes. It should be safe to remove it after 14 days, default is 90 days." msgstr "" -#: src/Module/Admin/Site.php:563 +#: src/Module/Admin/Site.php:566 msgid "Maximum numbers of comments per post" msgstr "" -#: src/Module/Admin/Site.php:563 +#: src/Module/Admin/Site.php:566 msgid "How much comments should be shown for each post? Default value is 100." msgstr "" -#: src/Module/Admin/Site.php:564 +#: src/Module/Admin/Site.php:567 msgid "Maximum numbers of comments per post on the display page" msgstr "" -#: src/Module/Admin/Site.php:564 +#: src/Module/Admin/Site.php:567 msgid "How many comments should be shown on the single view for each post? Default value is 1000." msgstr "" -#: src/Module/Admin/Site.php:565 +#: src/Module/Admin/Site.php:568 msgid "Items per page" msgstr "" -#: src/Module/Admin/Site.php:565 +#: src/Module/Admin/Site.php:568 msgid "Number of items per page in stream pages (network, community, profile/contact statuses, search)." msgstr "" -#: src/Module/Admin/Site.php:566 +#: src/Module/Admin/Site.php:569 msgid "Items per page for mobile devices" msgstr "" -#: src/Module/Admin/Site.php:566 +#: src/Module/Admin/Site.php:569 msgid "Number of items per page in stream pages (network, community, profile/contact statuses, search) for mobile devices." msgstr "" -#: src/Module/Admin/Site.php:567 +#: src/Module/Admin/Site.php:570 msgid "Temp path" msgstr "" -#: src/Module/Admin/Site.php:567 +#: src/Module/Admin/Site.php:570 msgid "If you have a restricted system where the webserver can't access the system temp path, enter another path here." msgstr "" -#: src/Module/Admin/Site.php:568 +#: src/Module/Admin/Site.php:571 msgid "Only search in tags" msgstr "" -#: src/Module/Admin/Site.php:568 +#: src/Module/Admin/Site.php:571 msgid "On large systems the text search can slow down the system extremely." msgstr "" -#: src/Module/Admin/Site.php:569 +#: src/Module/Admin/Site.php:572 msgid "Limited search scope" msgstr "" -#: src/Module/Admin/Site.php:569 +#: src/Module/Admin/Site.php:572 msgid "If enabled, searches will only be performed in the data used for the channels and not in all posts." msgstr "" -#: src/Module/Admin/Site.php:570 +#: src/Module/Admin/Site.php:573 msgid "Maximum age of items in the search table" msgstr "" -#: src/Module/Admin/Site.php:570 +#: src/Module/Admin/Site.php:573 msgid "Maximum age of items in the search table in days. Lower values will increase the performance and reduce disk usage. 0 means no age restriction." msgstr "" -#: src/Module/Admin/Site.php:571 +#: src/Module/Admin/Site.php:574 msgid "Generate counts per contact circle when calculating network count" msgstr "" -#: src/Module/Admin/Site.php:571 +#: src/Module/Admin/Site.php:574 msgid "On systems with users that heavily use contact circles the query can be very expensive." msgstr "" -#: src/Module/Admin/Site.php:572 +#: src/Module/Admin/Site.php:575 msgid "Process \"view\" activities" msgstr "" -#: src/Module/Admin/Site.php:572 +#: src/Module/Admin/Site.php:575 msgid "\"view\" activities are mostly geberated by Peertube systems. Per default they are not processed for performance reasons. Only activate this option on performant system." msgstr "" -#: src/Module/Admin/Site.php:573 +#: src/Module/Admin/Site.php:576 msgid "Days, after which a contact is archived" msgstr "" -#: src/Module/Admin/Site.php:573 +#: src/Module/Admin/Site.php:576 msgid "Number of days that we try to deliver content or to update the contact data before we archive a contact." msgstr "" -#: src/Module/Admin/Site.php:575 +#: src/Module/Admin/Site.php:578 msgid "Maximum number of parallel workers" msgstr "" -#: src/Module/Admin/Site.php:575 +#: src/Module/Admin/Site.php:578 #, php-format msgid "On shared hosters set this to %d. On larger systems, values of %d are great. Default value is %d." msgstr "" -#: src/Module/Admin/Site.php:576 +#: src/Module/Admin/Site.php:579 msgid "Maximum load for workers" msgstr "" -#: src/Module/Admin/Site.php:576 +#: src/Module/Admin/Site.php:579 msgid "Maximum load that causes a cooldown before each worker function call." msgstr "" -#: src/Module/Admin/Site.php:577 +#: src/Module/Admin/Site.php:580 msgid "Enable fastlane" msgstr "" -#: src/Module/Admin/Site.php:577 +#: src/Module/Admin/Site.php:580 msgid "When enabed, the fastlane mechanism starts an additional worker if processes with higher priority are blocked by processes of lower priority." msgstr "" -#: src/Module/Admin/Site.php:578 +#: src/Module/Admin/Site.php:581 msgid "Decoupled receiver" msgstr "" -#: src/Module/Admin/Site.php:578 +#: src/Module/Admin/Site.php:581 msgid "Decouple incoming ActivityPub posts by processing them in the background via a worker process. Only enable this on fast systems." msgstr "" -#: src/Module/Admin/Site.php:579 +#: src/Module/Admin/Site.php:582 msgid "Cron interval" msgstr "" -#: src/Module/Admin/Site.php:579 +#: src/Module/Admin/Site.php:582 msgid "Minimal period in minutes between two calls of the \"Cron\" worker job." msgstr "" -#: src/Module/Admin/Site.php:580 +#: src/Module/Admin/Site.php:583 msgid "Worker defer limit" msgstr "" -#: src/Module/Admin/Site.php:580 +#: src/Module/Admin/Site.php:583 msgid "Per default the systems tries delivering for 15 times before dropping it." msgstr "" -#: src/Module/Admin/Site.php:581 +#: src/Module/Admin/Site.php:584 msgid "Worker fetch limit" msgstr "" -#: src/Module/Admin/Site.php:581 +#: src/Module/Admin/Site.php:584 msgid "Number of worker tasks that are fetched in a single query. Higher values should increase the performance, too high values will mostly likely decrease it. Only change it, when you know how to measure the performance of your system." msgstr "" -#: src/Module/Admin/Site.php:583 +#: src/Module/Admin/Site.php:586 msgid "Direct relay transfer" msgstr "" -#: src/Module/Admin/Site.php:583 +#: src/Module/Admin/Site.php:586 msgid "Enables the direct transfer to other servers without using the relay servers" msgstr "" -#: src/Module/Admin/Site.php:584 +#: src/Module/Admin/Site.php:587 msgid "Relay scope" msgstr "" -#: src/Module/Admin/Site.php:584 +#: src/Module/Admin/Site.php:587 msgid "Can be \"all\" or \"tags\". \"all\" means that every public post should be received. \"tags\" means that only posts with selected tags should be received." msgstr "" -#: src/Module/Admin/Site.php:584 src/Module/Contact/Profile.php:315 +#: src/Module/Admin/Site.php:587 src/Module/Contact/Profile.php:315 #: src/Module/Settings/Display.php:259 #: src/Module/Settings/TwoFactor/Index.php:132 msgid "Disabled" msgstr "" -#: src/Module/Admin/Site.php:584 +#: src/Module/Admin/Site.php:587 msgid "all" msgstr "" -#: src/Module/Admin/Site.php:584 +#: src/Module/Admin/Site.php:587 msgid "tags" msgstr "" -#: src/Module/Admin/Site.php:585 +#: src/Module/Admin/Site.php:588 msgid "Server tags" msgstr "" -#: src/Module/Admin/Site.php:585 +#: src/Module/Admin/Site.php:588 msgid "Comma separated list of tags for the \"tags\" subscription." msgstr "" -#: src/Module/Admin/Site.php:586 +#: src/Module/Admin/Site.php:589 msgid "Deny Server tags" msgstr "" -#: src/Module/Admin/Site.php:586 +#: src/Module/Admin/Site.php:589 msgid "Comma separated list of tags that are rejected." msgstr "" -#: src/Module/Admin/Site.php:587 +#: src/Module/Admin/Site.php:590 msgid "Maximum amount of tags" msgstr "" -#: src/Module/Admin/Site.php:587 +#: src/Module/Admin/Site.php:590 msgid "Maximum amount of tags in a post before it is rejected as spam. The post has to contain at least one link. Posts from subscribed accounts will not be rejected." msgstr "" -#: src/Module/Admin/Site.php:588 +#: src/Module/Admin/Site.php:591 msgid "Allow user tags" msgstr "" -#: src/Module/Admin/Site.php:588 +#: src/Module/Admin/Site.php:591 msgid "If enabled, the tags from the saved searches will used for the \"tags\" subscription in addition to the \"relay_server_tags\"." msgstr "" -#: src/Module/Admin/Site.php:589 +#: src/Module/Admin/Site.php:592 msgid "Deny undetected languages" msgstr "" -#: src/Module/Admin/Site.php:589 +#: src/Module/Admin/Site.php:592 msgid "If enabled, posts with undetected languages will be rejected." msgstr "" -#: src/Module/Admin/Site.php:590 +#: src/Module/Admin/Site.php:593 msgid "Language Quality" msgstr "" -#: src/Module/Admin/Site.php:590 +#: src/Module/Admin/Site.php:593 msgid "The minimum language quality that is required to accept the post." msgstr "" -#: src/Module/Admin/Site.php:591 +#: src/Module/Admin/Site.php:594 msgid "Number of languages for the language detection" msgstr "" -#: src/Module/Admin/Site.php:591 +#: src/Module/Admin/Site.php:594 msgid "The system detects a list of languages per post. Only if the desired languages are in the list, the message will be accepted. The higher the number, the more posts will be falsely detected." msgstr "" -#: src/Module/Admin/Site.php:593 +#: src/Module/Admin/Site.php:596 msgid "Maximum age of channel" msgstr "" -#: src/Module/Admin/Site.php:593 +#: src/Module/Admin/Site.php:596 msgid "This defines the maximum age in hours of items that should be displayed in channels. This affects the channel performance." msgstr "" -#: src/Module/Admin/Site.php:594 +#: src/Module/Admin/Site.php:597 msgid "Maximum number of channel posts" msgstr "" -#: src/Module/Admin/Site.php:594 +#: src/Module/Admin/Site.php:597 msgid "For performance reasons, the channels use a dedicated table to store content. The higher the value the slower the channels." msgstr "" -#: src/Module/Admin/Site.php:595 +#: src/Module/Admin/Site.php:598 msgid "Interaction score days" msgstr "" -#: src/Module/Admin/Site.php:595 +#: src/Module/Admin/Site.php:598 msgid "Number of days that are used to calculate the interaction score." msgstr "" -#: src/Module/Admin/Site.php:596 +#: src/Module/Admin/Site.php:599 msgid "Maximum number of posts per author" msgstr "" -#: src/Module/Admin/Site.php:596 +#: src/Module/Admin/Site.php:599 msgid "Maximum number of posts per page by author if the contact frequency is set to \"Display only few posts\". If there are more posts, then the post with the most interactions will be displayed." msgstr "" -#: src/Module/Admin/Site.php:597 +#: src/Module/Admin/Site.php:600 msgid "Sharer interaction days" msgstr "" -#: src/Module/Admin/Site.php:597 +#: src/Module/Admin/Site.php:600 msgid "Number of days of the last interaction that are used to define which sharers are used for the \"sharers of sharers\" channel." msgstr "" -#: src/Module/Admin/Site.php:600 +#: src/Module/Admin/Site.php:603 msgid "Start Relocation" msgstr "" @@ -5837,12 +5845,12 @@ msgstr "" #: src/Module/Calendar/Event/Form.php:195 #: src/Module/Calendar/Event/Form.php:223 src/Module/Debug/Probe.php:45 -#: src/Module/Install.php:187 src/Module/Install.php:213 -#: src/Module/Install.php:218 src/Module/Install.php:232 -#: src/Module/Install.php:241 src/Module/Install.php:246 -#: src/Module/Install.php:252 src/Module/Install.php:257 -#: src/Module/Install.php:271 src/Module/Install.php:284 -#: src/Module/Install.php:311 +#: src/Module/Install.php:186 src/Module/Install.php:212 +#: src/Module/Install.php:217 src/Module/Install.php:231 +#: src/Module/Install.php:240 src/Module/Install.php:245 +#: src/Module/Install.php:251 src/Module/Install.php:256 +#: src/Module/Install.php:270 src/Module/Install.php:283 +#: src/Module/Install.php:312 #: src/Module/Moderation/Blocklist/Server/Add.php:125 #: src/Module/Moderation/Blocklist/Server/Add.php:127 #: src/Module/Moderation/Blocklist/Server/Import.php:116 @@ -7097,132 +7105,132 @@ msgstr "" msgid "Welcome to %s" msgstr "" -#: src/Module/Install.php:175 +#: src/Module/Install.php:174 msgid "Friendica Communications Server - Setup" msgstr "" -#: src/Module/Install.php:186 +#: src/Module/Install.php:185 msgid "System check" msgstr "" -#: src/Module/Install.php:188 src/Module/Install.php:233 -#: src/Module/Install.php:312 +#: src/Module/Install.php:187 src/Module/Install.php:232 +#: src/Module/Install.php:313 msgid "Requirement not satisfied" msgstr "" -#: src/Module/Install.php:189 +#: src/Module/Install.php:188 msgid "Optional requirement not satisfied" msgstr "" -#: src/Module/Install.php:190 +#: src/Module/Install.php:189 msgid "OK" msgstr "" -#: src/Module/Install.php:194 +#: src/Module/Install.php:193 msgid "Next" msgstr "" -#: src/Module/Install.php:195 +#: src/Module/Install.php:194 msgid "Check again" msgstr "" -#: src/Module/Install.php:208 +#: src/Module/Install.php:207 msgid "Base settings" msgstr "" -#: src/Module/Install.php:210 +#: src/Module/Install.php:209 msgid "Base path to installation" msgstr "" -#: src/Module/Install.php:212 +#: src/Module/Install.php:211 msgid "If the system cannot detect the correct path to your installation, enter the correct path here. This setting should only be set if you are using a restricted system and symbolic links to your webroot." msgstr "" -#: src/Module/Install.php:215 +#: src/Module/Install.php:214 msgid "The Friendica system URL" msgstr "" -#: src/Module/Install.php:217 +#: src/Module/Install.php:216 msgid "Overwrite this field in case the system URL determination isn't right, otherwise leave it as is." msgstr "" -#: src/Module/Install.php:228 +#: src/Module/Install.php:227 msgid "Database connection" msgstr "" -#: src/Module/Install.php:229 +#: src/Module/Install.php:228 msgid "In order to install Friendica we need to know how to connect to your database." msgstr "" -#: src/Module/Install.php:230 +#: src/Module/Install.php:229 msgid "Please contact your hosting provider or site administrator if you have questions about these settings." msgstr "" -#: src/Module/Install.php:231 +#: src/Module/Install.php:230 msgid "The database you specify below should already exist. If it does not, please create it before continuing." msgstr "" -#: src/Module/Install.php:238 +#: src/Module/Install.php:237 msgid "Database Server Name" msgstr "" -#: src/Module/Install.php:243 +#: src/Module/Install.php:242 msgid "Database Login Name" msgstr "" -#: src/Module/Install.php:249 +#: src/Module/Install.php:248 msgid "Database Login Password" msgstr "" -#: src/Module/Install.php:251 +#: src/Module/Install.php:250 msgid "For security reasons the password must not be empty" msgstr "" -#: src/Module/Install.php:254 +#: src/Module/Install.php:253 msgid "Database Name" msgstr "" -#: src/Module/Install.php:258 src/Module/Install.php:286 +#: src/Module/Install.php:257 src/Module/Install.php:286 msgid "Please select a default timezone for your website" msgstr "" -#: src/Module/Install.php:273 +#: src/Module/Install.php:272 msgid "Site settings" msgstr "" -#: src/Module/Install.php:281 +#: src/Module/Install.php:280 msgid "Site administrator email address" msgstr "" -#: src/Module/Install.php:283 +#: src/Module/Install.php:282 msgid "Your account email address must match this in order to use the web admin panel." msgstr "" -#: src/Module/Install.php:290 +#: src/Module/Install.php:291 msgid "System Language:" msgstr "" -#: src/Module/Install.php:292 +#: src/Module/Install.php:293 msgid "Set the default language for your Friendica installation interface and to send emails." msgstr "" -#: src/Module/Install.php:304 +#: src/Module/Install.php:305 msgid "Your Friendica site database has been installed." msgstr "" -#: src/Module/Install.php:314 +#: src/Module/Install.php:315 msgid "Installation finished" msgstr "" -#: src/Module/Install.php:334 +#: src/Module/Install.php:335 msgid "

    What next

    " msgstr "" -#: src/Module/Install.php:335 +#: src/Module/Install.php:336 msgid "IMPORTANT: You will need to [manually] setup a scheduled task for the worker." msgstr "" -#: src/Module/Install.php:338 +#: src/Module/Install.php:339 #, php-format msgid "Go to your new Friendica node registration page and register as new user. Remember to use the same email you have entered as administrator email. This will allow you to enter the site admin panel." msgstr "" @@ -8436,21 +8444,21 @@ msgstr "" msgid "Search in Friendica %s" msgstr "" -#: src/Module/Photo.php:108 +#: src/Module/Photo.php:109 msgid "The Photo is not available." msgstr "" -#: src/Module/Photo.php:133 +#: src/Module/Photo.php:134 #, php-format msgid "The Photo with id %s is not available." msgstr "" -#: src/Module/Photo.php:178 +#: src/Module/Photo.php:179 #, php-format msgid "Invalid external resource with url %s." msgstr "" -#: src/Module/Photo.php:180 +#: src/Module/Photo.php:181 #, php-format msgid "Invalid photo with id %s." msgstr "" @@ -11728,7 +11736,7 @@ msgstr "" msgid "Quote shared by: %s" msgstr "" -#: src/Protocol/ActivityPub/Receiver.php:558 +#: src/Protocol/ActivityPub/Receiver.php:566 msgid "Chat" msgstr "" diff --git a/view/templates/admin/site.tpl b/view/templates/admin/site.tpl index 35e46dd712..f4cfd5b41d 100644 --- a/view/templates/admin/site.tpl +++ b/view/templates/admin/site.tpl @@ -112,6 +112,7 @@

    {{$portable_contacts}}

    {{include file="field_select.tpl" field=$contact_discovery}} {{include file="field_checkbox.tpl" field=$update_active_contacts}} + {{include file="field_checkbox.tpl" field=$update_known_contacts}} {{include file="field_checkbox.tpl" field=$synchronize_directory}} {{include file="field_checkbox.tpl" field=$poco_discovery}} {{include file="field_input.tpl" field=$poco_requery_days}} diff --git a/view/theme/frio/templates/admin/site.tpl b/view/theme/frio/templates/admin/site.tpl index bc55ab9a62..ad2667dc7f 100644 --- a/view/theme/frio/templates/admin/site.tpl +++ b/view/theme/frio/templates/admin/site.tpl @@ -228,6 +228,7 @@
    {{include file="field_select.tpl" field=$contact_discovery}} {{include file="field_checkbox.tpl" field=$update_active_contacts}} + {{include file="field_checkbox.tpl" field=$update_known_contacts}} {{include file="field_checkbox.tpl" field=$synchronize_directory}} {{include file="field_checkbox.tpl" field=$poco_discovery}} {{include file="field_input.tpl" field=$poco_requery_days}} From 1eaab5e4107ef3a3ee23b7a990a0137f45138b45 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 15 Jan 2025 07:51:30 +0000 Subject: [PATCH 63/91] Issue 14692: Prevent loops with remote servers --- src/Util/HTTPSignature.php | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/Util/HTTPSignature.php b/src/Util/HTTPSignature.php index a544119616..b4ecf32eb6 100644 --- a/src/Util/HTTPSignature.php +++ b/src/Util/HTTPSignature.php @@ -604,13 +604,14 @@ class HTTPSignature /** * Gets a signer from a given HTTP request * - * @param string $content - * @param array $http_headers + * @param string $content + * @param array $http_headers + * @param ?boolean $update true = always update, false = never update, null = update when not found or outdated * * @return string|null|false Signer * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ - public static function getSigner(string $content, array $http_headers) + public static function getSigner(string $content, array $http_headers, bool $update = null) { if (empty($http_headers['HTTP_SIGNATURE'])) { DI::logger()->debug('No HTTP_SIGNATURE header'); @@ -700,7 +701,7 @@ class HTTPSignature return false; } - $key = self::fetchKey($sig_block['keyId'], $actor); + $key = self::fetchKey($sig_block['keyId'], $actor, $update); if (empty($key)) { DI::logger()->info('Empty key'); return false; @@ -802,17 +803,18 @@ class HTTPSignature /** * fetches a key for a given id and actor * - * @param string $id - * @param string $actor + * @param string $id + * @param string $actor + * @param ?boolean $update true = always update, false = never update, null = update when not found or outdated * * @return array with actor url and public key * @throws \Exception */ - private static function fetchKey(string $id, string $actor): array + private static function fetchKey(string $id, string $actor, bool $update = null): array { $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id); - $profile = APContact::getByURL($url); + $profile = APContact::getByURL($url, $update); if (!empty($profile)) { DI::logger()->info('Taking key from id', ['id' => $id]); return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']]; From b9f5a4f7453f6c5be2a0989023991a75b8c0a907 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 10:53:34 +0000 Subject: [PATCH 64/91] Rename back App::load() --- src/App.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/App.php b/src/App.php index 73f2913b1a..776b5ea909 100644 --- a/src/App.php +++ b/src/App.php @@ -158,7 +158,7 @@ class App $this->session = $this->container->create(IHandleUserSessions::class); $this->appHelper = $this->container->create(AppHelper::class); - $this->loadSetupForFrontend( + $this->load( $request, $this->container->create(DbaDefinition::class), $this->container->create(ViewDefinition::class), @@ -272,7 +272,7 @@ class App /** * Load the whole app instance */ - private function loadSetupForFrontend(ServerRequestInterface $request, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition) + private function load(ServerRequestInterface $request, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition) { if ($this->config->get('system', 'ini_max_execution_time') !== false) { set_time_limit((int)$this->config->get('system', 'ini_max_execution_time')); From bf28afb65100cc2ae3bad5929d113639dc3101a0 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 11:56:23 +0000 Subject: [PATCH 65/91] Remove dependency for ServerRequestInterface in App::load() --- src/App.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/App.php b/src/App.php index 776b5ea909..5ee8562dbf 100644 --- a/src/App.php +++ b/src/App.php @@ -159,7 +159,7 @@ class App $this->appHelper = $this->container->create(AppHelper::class); $this->load( - $request, + $request->getServerParams(), $this->container->create(DbaDefinition::class), $this->container->create(ViewDefinition::class), ); @@ -272,7 +272,7 @@ class App /** * Load the whole app instance */ - private function load(ServerRequestInterface $request, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition) + private function load(array $serverParams, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition) { if ($this->config->get('system', 'ini_max_execution_time') !== false) { set_time_limit((int)$this->config->get('system', 'ini_max_execution_time')); @@ -294,7 +294,7 @@ class App if ($this->mode->has(Mode::DBAVAILABLE)) { Core\Hook::loadHooks(); - $loader = (new Config())->createConfigFileManager($this->appHelper->getBasePath(), $request->getServerParams()); + $loader = (new Config())->createConfigFileManager($this->appHelper->getBasePath(), $serverParams); Core\Hook::callAll('load_config', $loader); // Hooks are now working, reload the whole definitions with hook enabled From 064b70f4c0f1318d5993f2fe830fa359bedacf53 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 11:59:24 +0000 Subject: [PATCH 66/91] Move Mode::setExecutor() call inside App::runFrontend() --- src/App.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/App.php b/src/App.php index 5ee8562dbf..6546d56778 100644 --- a/src/App.php +++ b/src/App.php @@ -166,8 +166,6 @@ class App $this->registerTemplateEngine(); - $this->mode->setExecutor(Mode::INDEX); - $this->runFrontend( $this->container->create(IManagePersonalConfigValues::class), $this->container->create(Page::class), @@ -348,6 +346,8 @@ class App float $start_time, ServerRequestInterface $request ) { + $this->mode->setExecutor(Mode::INDEX); + $httpInput = new HTTPInputData($request->getServerParams()); $serverVars = $request->getServerParams(); $queryVars = $request->getQueryParams(); From 76aec2d5750f10eeb2603972ac0eb9bbc62a28c8 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 12:06:53 +0000 Subject: [PATCH 67/91] Inject Mode into App::load() via parameter --- src/App.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/App.php b/src/App.php index 6546d56778..c823cfd5b3 100644 --- a/src/App.php +++ b/src/App.php @@ -162,6 +162,7 @@ class App $request->getServerParams(), $this->container->create(DbaDefinition::class), $this->container->create(ViewDefinition::class), + $this->mode, ); $this->registerTemplateEngine(); @@ -270,7 +271,7 @@ class App /** * Load the whole app instance */ - private function load(array $serverParams, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition) + private function load(array $serverParams, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition, Mode $mode) { if ($this->config->get('system', 'ini_max_execution_time') !== false) { set_time_limit((int)$this->config->get('system', 'ini_max_execution_time')); @@ -290,7 +291,7 @@ class App $this->profiler->reset(); - if ($this->mode->has(Mode::DBAVAILABLE)) { + if ($mode->has(Mode::DBAVAILABLE)) { Core\Hook::loadHooks(); $loader = (new Config())->createConfigFileManager($this->appHelper->getBasePath(), $serverParams); Core\Hook::callAll('load_config', $loader); From 52c6f93c9adc497decc7abf75b17ecf345b279da Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 12:11:06 +0000 Subject: [PATCH 68/91] Inject Mode into App::runFrontend() via parameter --- src/App.php | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/App.php b/src/App.php index c823cfd5b3..6cda9d989b 100644 --- a/src/App.php +++ b/src/App.php @@ -168,6 +168,7 @@ class App $this->registerTemplateEngine(); $this->runFrontend( + $this->mode, $this->container->create(IManagePersonalConfigValues::class), $this->container->create(Page::class), $this->container->create(Nav::class), @@ -340,6 +341,7 @@ class App * @throws \ImagickException */ private function runFrontend( + Mode $mode, IManagePersonalConfigValues $pconfig, Page $page, Nav $nav, @@ -347,7 +349,7 @@ class App float $start_time, ServerRequestInterface $request ) { - $this->mode->setExecutor(Mode::INDEX); + $mode->setExecutor(Mode::INDEX); $httpInput = new HTTPInputData($request->getServerParams()); $serverVars = $request->getServerParams(); @@ -366,11 +368,11 @@ class App try { // Missing DB connection: ERROR - if ($this->mode->has(Mode::LOCALCONFIGPRESENT) && !$this->mode->has(Mode::DBAVAILABLE)) { + if ($mode->has(Mode::LOCALCONFIGPRESENT) && !$mode->has(Mode::DBAVAILABLE)) { throw new HTTPException\InternalServerErrorException($this->l10n->t('Apologies but the website is unavailable at the moment.')); } - if (!$this->mode->isInstall()) { + if (!$mode->isInstall()) { // Force SSL redirection if ($this->config->get('system', 'force_ssl') && (empty($serverVars['HTTPS']) || $serverVars['HTTPS'] === 'off') && @@ -384,7 +386,7 @@ class App DID::routeRequest($this->args->getCommand(), $serverVars); - if ($this->mode->isNormal() && !$this->mode->isBackend()) { + if ($mode->isNormal() && !$mode->isBackend()) { $requester = HTTPSignature::getSigner('', $serverVars); if (!empty($requester)) { OpenWebAuth::addVisitorCookieForHandle($requester); @@ -392,7 +394,7 @@ class App } // ZRL - if (!empty($queryVars['zrl']) && $this->mode->isNormal() && !$this->mode->isBackend() && !$this->session->getLocalUserId()) { + if (!empty($queryVars['zrl']) && $mode->isNormal() && !$mode->isBackend() && !$this->session->getLocalUserId()) { // Only continue when the given profile link seems valid. // Valid profile links contain a path with "/profile/" and no query parameters if ((parse_url($queryVars['zrl'], PHP_URL_QUERY) == '') && @@ -407,12 +409,12 @@ class App } } - if (!empty($queryVars['owt']) && $this->mode->isNormal()) { + if (!empty($queryVars['owt']) && $mode->isNormal()) { $token = $queryVars['owt']; OpenWebAuth::init($token); } - if (!$this->mode->isBackend()) { + if (!$mode->isBackend()) { $this->auth->withSession(); } @@ -428,7 +430,7 @@ class App // in install mode, any url loads install module // but we need "view" module for stylesheet - if ($this->mode->isInstall() && $moduleName !== 'install') { + if ($mode->isInstall() && $moduleName !== 'install') { $this->baseURL->redirect('install'); } else { Core\Update::check($this->appHelper->getBasePath(), false); @@ -478,7 +480,7 @@ class App $page['page_title'] = $moduleName; // The "view" module is required to show the theme CSS - if (!$this->mode->isInstall() && !$this->mode->has(Mode::MAINTENANCEDISABLED) && $moduleName !== 'view') { + if (!$mode->isInstall() && !$mode->has(Mode::MAINTENANCEDISABLED) && $moduleName !== 'view') { $module = $this->createModuleInstance(Maintenance::class); } else { // determine the module class and save it to the module instance @@ -500,7 +502,7 @@ class App // Wrapping HTML responses in the theme template if ($response->getHeaderLine(ICanCreateResponses::X_HEADER) === ICanCreateResponses::TYPE_HTML) { - $response = $page->run($this->appHelper, $this->session, $this->baseURL, $this->args, $this->mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig, $nav, $this->session->getLocalUserId()); + $response = $page->run($this->appHelper, $this->session, $this->baseURL, $this->args, $mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig, $nav, $this->session->getLocalUserId()); } $this->logger->debug('Request processed sucessfully', ['response' => $response->getStatusCode(), 'address' => $serverVars['REMOTE_ADDR'] ?? '', 'request' => $requeststring, 'referer' => $serverVars['HTTP_REFERER'] ?? '', 'user-agent' => $serverVars['HTTP_USER_AGENT'] ?? '', 'duration' => number_format(microtime(true) - $request_start, 3)]); From fdb14f23f26dc935bb8108c030796b9d9c52f822 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 12:13:57 +0000 Subject: [PATCH 69/91] Inject config into App::load() via parameter --- src/App.php | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/App.php b/src/App.php index 6cda9d989b..af8c391426 100644 --- a/src/App.php +++ b/src/App.php @@ -163,6 +163,7 @@ class App $this->container->create(DbaDefinition::class), $this->container->create(ViewDefinition::class), $this->mode, + $this->config, ); $this->registerTemplateEngine(); @@ -272,14 +273,19 @@ class App /** * Load the whole app instance */ - private function load(array $serverParams, DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition, Mode $mode) - { - if ($this->config->get('system', 'ini_max_execution_time') !== false) { - set_time_limit((int)$this->config->get('system', 'ini_max_execution_time')); + private function load( + array $serverParams, + DbaDefinition $dbaDefinition, + ViewDefinition $viewDefinition, + Mode $mode, + IManageConfigValues $config + ): 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) { - ini_set('pcre.backtrack_limit', (int)$this->config->get('system', 'ini_pcre_backtrack_limit')); + if ($config->get('system', 'ini_pcre_backtrack_limit') !== false) { + 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 From 6c0a2eaefc385f2776224f73e07238c10aa81c33 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 12:36:14 +0000 Subject: [PATCH 70/91] Inject config into App::loadDefaultTimezone() via parameter --- src/App.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/App.php b/src/App.php index af8c391426..41ae4fd1b7 100644 --- a/src/App.php +++ b/src/App.php @@ -308,7 +308,7 @@ class App $viewDefinition->load(true); } - $this->loadDefaultTimezone(); + $this->loadDefaultTimezone($config); } /** @@ -318,10 +318,10 @@ class App * * @global string $default_timezone */ - private function loadDefaultTimezone() + private function loadDefaultTimezone(IManageConfigValues $config) { - if ($this->config->get('system', 'default_timezone')) { - $timezone = $this->config->get('system', 'default_timezone', 'UTC'); + if ($config->get('system', 'default_timezone')) { + $timezone = $config->get('system', 'default_timezone', 'UTC'); } else { global $default_timezone; $timezone = $default_timezone ?? '' ?: 'UTC'; From e57424ec35aa8df1ffdf2faf9713c1f699f2546d Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 12:46:24 +0000 Subject: [PATCH 71/91] Inject profiler into App::load() via parameter --- src/App.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/App.php b/src/App.php index 41ae4fd1b7..af1147e091 100644 --- a/src/App.php +++ b/src/App.php @@ -164,6 +164,7 @@ class App $this->container->create(ViewDefinition::class), $this->mode, $this->config, + $this->profiler, ); $this->registerTemplateEngine(); @@ -278,7 +279,8 @@ class App DbaDefinition $dbaDefinition, ViewDefinition $viewDefinition, Mode $mode, - IManageConfigValues $config + IManageConfigValues $config, + Profiler $profiler ): void { if ($config->get('system', 'ini_max_execution_time') !== false) { set_time_limit((int) $config->get('system', 'ini_max_execution_time')); @@ -296,7 +298,7 @@ class App // Ensure that all "strtotime" operations do run timezone independent date_default_timezone_set('UTC'); - $this->profiler->reset(); + $profiler->reset(); if ($mode->has(Mode::DBAVAILABLE)) { Core\Hook::loadHooks(); From 7cc37ff2cb972da993134c173e99b817a3778982 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 13:17:53 +0000 Subject: [PATCH 72/91] Inject AppHelper into App::load() via parameter --- src/App.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/App.php b/src/App.php index af1147e091..6ebac26d49 100644 --- a/src/App.php +++ b/src/App.php @@ -165,6 +165,7 @@ class App $this->mode, $this->config, $this->profiler, + $this->appHelper, ); $this->registerTemplateEngine(); @@ -280,7 +281,8 @@ class App ViewDefinition $viewDefinition, Mode $mode, IManageConfigValues $config, - Profiler $profiler + 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')); @@ -302,7 +304,7 @@ class App if ($mode->has(Mode::DBAVAILABLE)) { Core\Hook::loadHooks(); - $loader = (new Config())->createConfigFileManager($this->appHelper->getBasePath(), $serverParams); + $loader = (new Config())->createConfigFileManager($appHelper->getBasePath(), $serverParams); Core\Hook::callAll('load_config', $loader); // Hooks are now working, reload the whole definitions with hook enabled From 15446f35a5943d243521a53e76d90c40f6d709ff Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 13:19:17 +0000 Subject: [PATCH 73/91] Inject AppHelper into App::loadDefaultTimezone() via parameter --- src/App.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/App.php b/src/App.php index 6ebac26d49..8af9ec9272 100644 --- a/src/App.php +++ b/src/App.php @@ -312,7 +312,7 @@ class App $viewDefinition->load(true); } - $this->loadDefaultTimezone($config); + $this->loadDefaultTimezone($config, $appHelper); } /** @@ -322,7 +322,7 @@ class App * * @global string $default_timezone */ - private function loadDefaultTimezone(IManageConfigValues $config) + private function loadDefaultTimezone(IManageConfigValues $config, AppHelper $appHelper) { if ($config->get('system', 'default_timezone')) { $timezone = $config->get('system', 'default_timezone', 'UTC'); @@ -331,7 +331,7 @@ class App $timezone = $default_timezone ?? '' ?: 'UTC'; } - $this->appHelper->setTimeZone($timezone); + $appHelper->setTimeZone($timezone); } /** From c9bcc45d7cb578eaddcdf38afa55cd94669bd702 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 13:47:58 +0000 Subject: [PATCH 74/91] Provide $_SERVER to App::processConsole() --- bin/console.php | 2 +- bin/daemon.php | 4 +++- bin/jetstream.php | 4 +++- bin/worker.php | 4 +++- src/App.php | 5 ++++- 5 files changed, 14 insertions(+), 5 deletions(-) diff --git a/bin/console.php b/bin/console.php index ad612f4363..a20f3f7e02 100755 --- a/bin/console.php +++ b/bin/console.php @@ -19,4 +19,4 @@ $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $app = \Friendica\App::fromContainer($container); -$app->processConsole($_SERVER['argv'] ?? []); +$app->processConsole($_SERVER); diff --git a/bin/daemon.php b/bin/daemon.php index 546f207e08..25f902eacd 100755 --- a/bin/daemon.php +++ b/bin/daemon.php @@ -24,11 +24,13 @@ chdir(dirname(__DIR__)); require dirname(__DIR__) . '/vendor/autoload.php'; +// BC: Add console command as second argument $argv = $_SERVER['argv'] ?? []; array_splice($argv, 1, 0, "daemon"); +$_SERVER['argv'] = $argv; $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $app = \Friendica\App::fromContainer($container); -$app->processConsole($argv); +$app->processConsole($_SERVER); diff --git a/bin/jetstream.php b/bin/jetstream.php index 156f961856..b96dfa0e51 100755 --- a/bin/jetstream.php +++ b/bin/jetstream.php @@ -19,11 +19,13 @@ chdir(dirname(__DIR__)); require dirname(__DIR__) . '/vendor/autoload.php'; +// BC: Add console command as second argument $argv = $_SERVER['argv'] ?? []; array_splice($argv, 1, 0, "jetstream"); +$_SERVER['argv'] = $argv; $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $app = \Friendica\App::fromContainer($container); -$app->processConsole($argv); +$app->processConsole($_SERVER); diff --git a/bin/worker.php b/bin/worker.php index a79d8836a7..b72a8e2514 100755 --- a/bin/worker.php +++ b/bin/worker.php @@ -21,11 +21,13 @@ chdir(dirname(__DIR__)); require dirname(__DIR__) . '/vendor/autoload.php'; +// BC: Add console command as second argument $argv = $_SERVER['argv'] ?? []; array_splice($argv, 1, 0, "worker"); +$_SERVER['argv'] = $argv; $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $app = \Friendica\App::fromContainer($container); -$app->processConsole($argv); +$app->processConsole($_SERVER); diff --git a/src/App.php b/src/App.php index 8af9ec9272..6bdb20d45c 100644 --- a/src/App.php +++ b/src/App.php @@ -181,8 +181,11 @@ class App ); } - public function processConsole(array $argv): void + + public function processConsole(array $serverParams): void { + $argv = $serverParams['argv'] ?? []; + $this->setupContainerForAddons(); $this->setupLogChannel($this->determineLogChannel($argv)); From 5a40fdd7e1dc5fce26511afd7101ed17074c43be Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 13:53:30 +0000 Subject: [PATCH 75/91] Call App::load() on App::processConsole() and procesEjabberd() --- bin/auth_ejabberd.php | 2 +- src/App.php | 22 +++++++++++++++++++++- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/bin/auth_ejabberd.php b/bin/auth_ejabberd.php index bc976e61a4..595ccf204a 100755 --- a/bin/auth_ejabberd.php +++ b/bin/auth_ejabberd.php @@ -52,4 +52,4 @@ $container = \Friendica\Core\DiceContainer::fromBasePath(dirname(__DIR__)); $app = \Friendica\App::fromContainer($container); -$app->processEjabberd(); +$app->processEjabberd($_SERVER); diff --git a/src/App.php b/src/App.php index 6bdb20d45c..d622eacbb5 100644 --- a/src/App.php +++ b/src/App.php @@ -194,12 +194,22 @@ class App $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(); (\Friendica\Core\Console::create($this->container, $argv))->execute(); } - public function processEjabberd(): void + public function processEjabberd(array $serverParams): void { $this->setupContainerForAddons(); @@ -209,6 +219,16 @@ class App $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 */ $basePath = $this->container->create(BasePath::class); From ed184ab52091ece1d77f2f61fb4d6e8b09640bce Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 13:58:50 +0000 Subject: [PATCH 76/91] Revert "Inject Mode into App::runFrontend() via parameter" This reverts commit 52c6f93c9adc497decc7abf75b17ecf345b279da. --- src/App.php | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/App.php b/src/App.php index d622eacbb5..564da764f9 100644 --- a/src/App.php +++ b/src/App.php @@ -171,7 +171,6 @@ class App $this->registerTemplateEngine(); $this->runFrontend( - $this->mode, $this->container->create(IManagePersonalConfigValues::class), $this->container->create(Page::class), $this->container->create(Nav::class), @@ -374,7 +373,6 @@ class App * @throws \ImagickException */ private function runFrontend( - Mode $mode, IManagePersonalConfigValues $pconfig, Page $page, Nav $nav, @@ -382,7 +380,7 @@ class App float $start_time, ServerRequestInterface $request ) { - $mode->setExecutor(Mode::INDEX); + $this->mode->setExecutor(Mode::INDEX); $httpInput = new HTTPInputData($request->getServerParams()); $serverVars = $request->getServerParams(); @@ -401,11 +399,11 @@ class App try { // Missing DB connection: ERROR - if ($mode->has(Mode::LOCALCONFIGPRESENT) && !$mode->has(Mode::DBAVAILABLE)) { + if ($this->mode->has(Mode::LOCALCONFIGPRESENT) && !$this->mode->has(Mode::DBAVAILABLE)) { throw new HTTPException\InternalServerErrorException($this->l10n->t('Apologies but the website is unavailable at the moment.')); } - if (!$mode->isInstall()) { + if (!$this->mode->isInstall()) { // Force SSL redirection if ($this->config->get('system', 'force_ssl') && (empty($serverVars['HTTPS']) || $serverVars['HTTPS'] === 'off') && @@ -419,7 +417,7 @@ class App DID::routeRequest($this->args->getCommand(), $serverVars); - if ($mode->isNormal() && !$mode->isBackend()) { + if ($this->mode->isNormal() && !$this->mode->isBackend()) { $requester = HTTPSignature::getSigner('', $serverVars); if (!empty($requester)) { OpenWebAuth::addVisitorCookieForHandle($requester); @@ -427,7 +425,7 @@ class App } // ZRL - if (!empty($queryVars['zrl']) && $mode->isNormal() && !$mode->isBackend() && !$this->session->getLocalUserId()) { + if (!empty($queryVars['zrl']) && $this->mode->isNormal() && !$this->mode->isBackend() && !$this->session->getLocalUserId()) { // Only continue when the given profile link seems valid. // Valid profile links contain a path with "/profile/" and no query parameters if ((parse_url($queryVars['zrl'], PHP_URL_QUERY) == '') && @@ -442,12 +440,12 @@ class App } } - if (!empty($queryVars['owt']) && $mode->isNormal()) { + if (!empty($queryVars['owt']) && $this->mode->isNormal()) { $token = $queryVars['owt']; OpenWebAuth::init($token); } - if (!$mode->isBackend()) { + if (!$this->mode->isBackend()) { $this->auth->withSession(); } @@ -463,7 +461,7 @@ class App // in install mode, any url loads install module // but we need "view" module for stylesheet - if ($mode->isInstall() && $moduleName !== 'install') { + if ($this->mode->isInstall() && $moduleName !== 'install') { $this->baseURL->redirect('install'); } else { Core\Update::check($this->appHelper->getBasePath(), false); @@ -513,7 +511,7 @@ class App $page['page_title'] = $moduleName; // The "view" module is required to show the theme CSS - if (!$mode->isInstall() && !$mode->has(Mode::MAINTENANCEDISABLED) && $moduleName !== 'view') { + if (!$this->mode->isInstall() && !$this->mode->has(Mode::MAINTENANCEDISABLED) && $moduleName !== 'view') { $module = $this->createModuleInstance(Maintenance::class); } else { // determine the module class and save it to the module instance @@ -535,7 +533,7 @@ class App // Wrapping HTML responses in the theme template if ($response->getHeaderLine(ICanCreateResponses::X_HEADER) === ICanCreateResponses::TYPE_HTML) { - $response = $page->run($this->appHelper, $this->session, $this->baseURL, $this->args, $mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig, $nav, $this->session->getLocalUserId()); + $response = $page->run($this->appHelper, $this->session, $this->baseURL, $this->args, $this->mode, $response, $this->l10n, $this->profiler, $this->config, $pconfig, $nav, $this->session->getLocalUserId()); } $this->logger->debug('Request processed sucessfully', ['response' => $response->getStatusCode(), 'address' => $serverVars['REMOTE_ADDR'] ?? '', 'request' => $requeststring, 'referer' => $serverVars['HTTP_REFERER'] ?? '', 'user-agent' => $serverVars['HTTP_USER_AGENT'] ?? '', 'duration' => number_format(microtime(true) - $request_start, 3)]); From a6c1b2eaf3459b55cb7e477da6e6b7543a62e9fe Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 14:59:01 +0000 Subject: [PATCH 77/91] Change BC promise to 5 months, fix some wording --- doc/Developers-Intro.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md index f07b711648..99e84739d0 100644 --- a/doc/Developers-Intro.md +++ b/doc/Developers-Intro.md @@ -164,7 +164,7 @@ If you are interested in improving those clients, please contact the developers 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. +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: @@ -208,12 +208,12 @@ As long as the code that is labeled with `@deprecated` is used inside Friendica 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 6 months. -Hard deprecated code COULD remain longer than 6 months, depending on when a release appears. -Addon developer MUST NOT consider that they have more than 6 months to adjust their code. +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 be trigger an error: +For instance with the deprecated class `Friendica\Core\Logger` the call of every method should trigger an error: ```php /** @@ -224,7 +224,7 @@ For instance with the deprecated class `Friendica\Core\Logger` the call of every class Logger { public static function info(string $message, array $context = []) { - trigger_error('Class `' . __CLASS__ . '` is deprecated since 2025.05 and will be removed after 6 months, use constructor injection or `DI::logger()` instead.', E_USER_DEPRECATED); + 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); } @@ -234,19 +234,19 @@ class Logger { ``` 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 6 months to fix the deprecations. +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 in `2025.05` and COULD be removed earliest with the `2025.11` release. +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 6 months, starting from the release the deprecation was announced. +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 is published 6 months after the deprecation. +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 6 months, this SHOULD considered as a bug and BC SHOULD be restored in a bugfix release. +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. From 92aabbdcecea8a16b342e554ab2a7ba44587b2ef Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 15:24:32 +0000 Subject: [PATCH 78/91] Mark App as final and internal --- src/App.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/App.php b/src/App.php index 73f2913b1a..b756a847d9 100644 --- a/src/App.php +++ b/src/App.php @@ -57,6 +57,7 @@ use Psr\Log\LoggerInterface; * and anything else that might need to be passed around * before we spit the page out. * + * @final */ class App { @@ -64,6 +65,9 @@ class App const CODENAME = 'Interrupted Fern'; const VERSION = '2025.02-dev'; + /** + * @internal + */ public static function fromContainer(Container $container): self { return new self($container); @@ -130,6 +134,9 @@ class App $this->container = $container; } + /** + * @internal + */ public function processRequest(ServerRequestInterface $request, float $start_time): void { $this->container->addRule(Mode::class, [ @@ -178,6 +185,9 @@ class App ); } + /** + * @internal + */ public function processConsole(array $argv): void { $this->setupContainerForAddons(); @@ -193,6 +203,9 @@ class App (\Friendica\Core\Console::create($this->container, $argv))->execute(); } + /** + * @internal + */ public function processEjabberd(): void { $this->setupContainerForAddons(); From 700cedd69b8779287a8f665f687f1869f653718b Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 15:31:11 +0000 Subject: [PATCH 79/91] Mark DI::getDice() as internal --- src/DI.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/DI.php b/src/DI.php index 7d1114ac5c..c9c973f722 100644 --- a/src/DI.php +++ b/src/DI.php @@ -60,7 +60,8 @@ abstract class DI /** * 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 */ From 69830b9c03113702f7e061ece21781694c63c6b6 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 15:43:26 +0000 Subject: [PATCH 80/91] Move deprecation message into bin-files --- bin/daemon.php | 4 +++- bin/jetstream.php | 4 +++- bin/worker.php | 4 +++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/bin/daemon.php b/bin/daemon.php index 546f207e08..c3d945d941 100755 --- a/bin/daemon.php +++ b/bin/daemon.php @@ -6,7 +6,7 @@ * * 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,6 +24,8 @@ chdir(dirname(__DIR__)); 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); + $argv = $_SERVER['argv'] ?? []; array_splice($argv, 1, 0, "daemon"); diff --git a/bin/jetstream.php b/bin/jetstream.php index 156f961856..2aa1886c6e 100755 --- a/bin/jetstream.php +++ b/bin/jetstream.php @@ -6,7 +6,7 @@ * * 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') { @@ -19,6 +19,8 @@ chdir(dirname(__DIR__)); 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); + $argv = $_SERVER['argv'] ?? []; array_splice($argv, 1, 0, "jetstream"); diff --git a/bin/worker.php b/bin/worker.php index a79d8836a7..f099bc8e66 100755 --- a/bin/worker.php +++ b/bin/worker.php @@ -8,7 +8,7 @@ * * 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') { @@ -21,6 +21,8 @@ chdir(dirname(__DIR__)); 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); + $argv = $_SERVER['argv'] ?? []; array_splice($argv, 1, 0, "worker"); From 23fcb4f87fd87b29c9585ce5699bdd93cfbabfc7 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 15:47:49 +0000 Subject: [PATCH 81/91] Dont show deprecation message twice --- src/Console/Daemon.php | 5 ++--- src/Console/JetstreamDaemon.php | 5 ++--- src/Console/Worker.php | 5 ++--- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Console/Daemon.php b/src/Console/Daemon.php index c8165a1d9b..f115ec0b66 100644 --- a/src/Console/Daemon.php +++ b/src/Console/Daemon.php @@ -10,6 +10,7 @@ declare(strict_types=1); namespace Friendica\Console; use Asika\SimpleConsole\CommandArgsException; +use Asika\SimpleConsole\Console; use Friendica\App\Mode; use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\KeyValueStorage\Capability\IManageKeyValuePairs; @@ -27,7 +28,7 @@ use RuntimeException; /** * Console command for interacting with the daemon */ -final class Daemon extends AbstractConsole +final class Daemon extends Console { public const LOG_CHANNEL = LogChannel::DAEMON; @@ -93,8 +94,6 @@ HELP; protected function doExecute() { - $this->checkDeprecated('daemon'); - if ($this->mode->isInstall()) { throw new RuntimeException("Friendica isn't properly installed yet"); } diff --git a/src/Console/JetstreamDaemon.php b/src/Console/JetstreamDaemon.php index d34e5780c2..6071e01f49 100644 --- a/src/Console/JetstreamDaemon.php +++ b/src/Console/JetstreamDaemon.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace Friendica\Console; +use Asika\SimpleConsole\Console; use Friendica\App\Mode; use Friendica\Core\Addon; use Friendica\Core\Config\Capability\IManageConfigValues; @@ -22,7 +23,7 @@ use RuntimeException; /** * Console command for interacting with the daemon */ -final class JetstreamDaemon extends AbstractConsole +final class JetstreamDaemon extends Console { public const LOG_CHANNEL = LogChannel::DAEMON; @@ -79,8 +80,6 @@ HELP; protected function doExecute() { - $this->checkDeprecated('jetstream'); - if ($this->mode->isInstall()) { throw new RuntimeException("Friendica isn't properly installed yet"); } diff --git a/src/Console/Worker.php b/src/Console/Worker.php index 1c7eeae002..41de4f1764 100644 --- a/src/Console/Worker.php +++ b/src/Console/Worker.php @@ -9,6 +9,7 @@ declare(strict_types=1); namespace Friendica\Console; +use Asika\SimpleConsole\Console; use Friendica\App\Mode; use Friendica\Core\Logger\Capability\LogChannel; use Friendica\Core\Update; @@ -19,7 +20,7 @@ use Friendica\Util\BasePath; /** * Console command for starting worker */ -final class Worker extends AbstractConsole +final class Worker extends Console { public const LOG_CHANNEL = LogChannel::WORKER; @@ -69,8 +70,6 @@ HELP; protected function doExecute() { - $this->checkDeprecated('worker'); - $this->mode->setExecutor(Mode::WORKER); // Check the database structure and possibly fixes it From 65b79b5ea0365ade02886c7aa171cfc24a821102 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 15:57:21 +0000 Subject: [PATCH 82/91] Remove unused AbstractConsole --- src/Console/AbstractConsole.php | 39 --------------------------------- src/Console/Daemon.php | 3 --- src/Console/JetstreamDaemon.php | 3 --- src/Console/Worker.php | 3 --- 4 files changed, 48 deletions(-) delete mode 100644 src/Console/AbstractConsole.php diff --git a/src/Console/AbstractConsole.php b/src/Console/AbstractConsole.php deleted file mode 100644 index 0b8c1d6eb8..0000000000 --- a/src/Console/AbstractConsole.php +++ /dev/null @@ -1,39 +0,0 @@ -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)); - } - } -} diff --git a/src/Console/Daemon.php b/src/Console/Daemon.php index f115ec0b66..a21ff26fc6 100644 --- a/src/Console/Daemon.php +++ b/src/Console/Daemon.php @@ -14,7 +14,6 @@ use Asika\SimpleConsole\Console; use Friendica\App\Mode; use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\KeyValueStorage\Capability\IManageKeyValuePairs; -use Friendica\Core\Logger\Capability\LogChannel; use Friendica\Core\System; use Friendica\Core\Update; use Friendica\Core\Worker; @@ -30,8 +29,6 @@ use RuntimeException; */ final class Daemon extends Console { - public const LOG_CHANNEL = LogChannel::DAEMON; - private Mode $mode; private IManageConfigValues $config; private IManageKeyValuePairs $keyValue; diff --git a/src/Console/JetstreamDaemon.php b/src/Console/JetstreamDaemon.php index 6071e01f49..8bb1e7e106 100644 --- a/src/Console/JetstreamDaemon.php +++ b/src/Console/JetstreamDaemon.php @@ -15,7 +15,6 @@ use Friendica\Core\Addon; use Friendica\Core\Config\Capability\IManageConfigValues; use Friendica\Core\Hook; use Friendica\Core\KeyValueStorage\Capability\IManageKeyValuePairs; -use Friendica\Core\Logger\Capability\LogChannel; use Friendica\Protocol\ATProtocol\Jetstream; use Friendica\System\Daemon as SysDaemon; use RuntimeException; @@ -25,8 +24,6 @@ use RuntimeException; */ final class JetstreamDaemon extends Console { - public const LOG_CHANNEL = LogChannel::DAEMON; - private Mode $mode; private IManageConfigValues $config; private IManageKeyValuePairs $keyValue; diff --git a/src/Console/Worker.php b/src/Console/Worker.php index 41de4f1764..97b7160d03 100644 --- a/src/Console/Worker.php +++ b/src/Console/Worker.php @@ -11,7 +11,6 @@ namespace Friendica\Console; use Asika\SimpleConsole\Console; use Friendica\App\Mode; -use Friendica\Core\Logger\Capability\LogChannel; use Friendica\Core\Update; use Friendica\Core\Worker as CoreWorker; use Friendica\Core\Worker\Repository\Process as ProcessRepository; @@ -22,8 +21,6 @@ use Friendica\Util\BasePath; */ final class Worker extends Console { - public const LOG_CHANNEL = LogChannel::WORKER; - private Mode $mode; private BasePath $basePath; private ProcessRepository $processRepo; From 0b84cf401daf73d4fff52e0f1d2287be10b8f591 Mon Sep 17 00:00:00 2001 From: Art4 Date: Wed, 22 Jan 2025 19:52:48 +0000 Subject: [PATCH 83/91] Mark more new classes as internal --- src/AppLegacy.php | 1 + src/Core/Container.php | 2 ++ src/Core/DiceContainer.php | 2 ++ src/Core/Logger/Factory/LegacyLoggerFactory.php | 2 ++ src/Core/Logger/LoggerManager.php | 2 ++ 5 files changed, 9 insertions(+) diff --git a/src/AppLegacy.php b/src/AppLegacy.php index 4aa3f25e4c..8ec6b0aabc 100644 --- a/src/AppLegacy.php +++ b/src/AppLegacy.php @@ -32,6 +32,7 @@ use Friendica\Util\Strings; * and anything else that might need to be passed around * before we spit the page out. * + * @internal */ final class AppLegacy implements AppHelper { diff --git a/src/Core/Container.php b/src/Core/Container.php index 1017590a85..55e0826122 100644 --- a/src/Core/Container.php +++ b/src/Core/Container.php @@ -11,6 +11,8 @@ namespace Friendica\Core; /** * Dependency Injection Container + * + * @internal */ interface Container { diff --git a/src/Core/DiceContainer.php b/src/Core/DiceContainer.php index 304c1e411d..bd1eaf8043 100644 --- a/src/Core/DiceContainer.php +++ b/src/Core/DiceContainer.php @@ -13,6 +13,8 @@ use Dice\Dice; /** * Wrapper for the Dice class to make some basic setups + * + * @internal */ final class DiceContainer implements Container { diff --git a/src/Core/Logger/Factory/LegacyLoggerFactory.php b/src/Core/Logger/Factory/LegacyLoggerFactory.php index 5c91d11771..2c7b6c0237 100644 --- a/src/Core/Logger/Factory/LegacyLoggerFactory.php +++ b/src/Core/Logger/Factory/LegacyLoggerFactory.php @@ -26,6 +26,8 @@ use Psr\Log\LoggerInterface; * * @see \Friendica\Core\Logger\Factory\StreamLogger * @see \Friendica\Core\Logger\Factory\SyslogLogger + * + * @internal */ final class LegacyLoggerFactory implements LoggerFactory { diff --git a/src/Core/Logger/LoggerManager.php b/src/Core/Logger/LoggerManager.php index 697756099d..8379c91995 100644 --- a/src/Core/Logger/LoggerManager.php +++ b/src/Core/Logger/LoggerManager.php @@ -21,6 +21,8 @@ use Psr\Log\NullLogger; /** * Manager for the core logging instances + * + * @internal */ final class LoggerManager { From bccf95a088838975295b7411508a6b0c8ce8d480 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 22 Jan 2025 20:26:05 +0000 Subject: [PATCH 84/91] Changes after review --- src/Util/HTTPSignature.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Util/HTTPSignature.php b/src/Util/HTTPSignature.php index b4ecf32eb6..ebaeab028c 100644 --- a/src/Util/HTTPSignature.php +++ b/src/Util/HTTPSignature.php @@ -604,14 +604,14 @@ class HTTPSignature /** * Gets a signer from a given HTTP request * - * @param string $content - * @param array $http_headers + * @param string $content Body of the request + * @param array $http_headers array containing the HTTP headers * @param ?boolean $update true = always update, false = never update, null = update when not found or outdated * * @return string|null|false Signer * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ - public static function getSigner(string $content, array $http_headers, bool $update = null) + public static function getSigner(string $content, array $http_headers, ?bool $update = null) { if (empty($http_headers['HTTP_SIGNATURE'])) { DI::logger()->debug('No HTTP_SIGNATURE header'); @@ -803,14 +803,14 @@ class HTTPSignature /** * fetches a key for a given id and actor * - * @param string $id - * @param string $actor + * @param string $id keyId of the signature block + * @param string $actor Actor URI * @param ?boolean $update true = always update, false = never update, null = update when not found or outdated * * @return array with actor url and public key * @throws \Exception */ - private static function fetchKey(string $id, string $actor, bool $update = null): array + private static function fetchKey(string $id, string $actor, ?bool $update = null): array { $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id); From 0f8786f8b18be97f1c7a92f5e72fcc7b5fcb1968 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 22 Jan 2025 20:31:14 +0000 Subject: [PATCH 85/91] Fix codestyle --- src/Util/HTTPSignature.php | 50 +++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 22 deletions(-) diff --git a/src/Util/HTTPSignature.php b/src/Util/HTTPSignature.php index ebaeab028c..bb5d8c6b5a 100644 --- a/src/Util/HTTPSignature.php +++ b/src/Util/HTTPSignature.php @@ -49,19 +49,21 @@ class HTTPSignature { $headers = null; $spoofable = false; - $result = [ - 'signer' => '', - 'header_signed' => false, - 'header_valid' => false + $result = [ + 'signer' => '', + 'header_signed' => false, + 'header_valid' => false ]; // Decide if $data arrived via controller submission or curl. $headers = []; + $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . $_SERVER['REQUEST_URI']; foreach ($_SERVER as $k => $v) { if (strpos($k, 'HTTP_') === 0) { $field = str_replace('_', '-', strtolower(substr($k, 5))); + $headers[$field] = $v; } } @@ -98,6 +100,7 @@ class HTTPSignature if ($key && function_exists($key)) { $result['signer'] = $sig_block['keyId']; + $key = $key($sig_block['keyId']); } @@ -136,7 +139,7 @@ class HTTPSignature $return_headers = $head; } - $alg = 'sha512'; + $alg = 'sha512'; $algorithm = 'rsa-sha512'; $x = self::sign($head, $prvkey, $alg); @@ -158,7 +161,7 @@ class HTTPSignature */ private static function sign(array $head, string $prvkey, string $alg = 'sha256'): array { - $ret = []; + $ret = []; $headers = ''; $fields = ''; @@ -220,10 +223,10 @@ class HTTPSignature } $return = [ - 'keyId' => $headers['keyId'] ?? '', + 'keyId' => $headers['keyId'] ?? '', 'algorithm' => $headers['algorithm'] ?? 'rsa-sha256', - 'created' => $headers['created'] ?? null, - 'expires' => $headers['expires'] ?? null, + 'created' => $headers['created'] ?? null, + 'expires' => $headers['expires'] ?? null, 'headers' => explode(' ', $headers['headers'] ?? ''), 'signature' => base64_decode(preg_replace('/\s+/', '', $headers['signature'] ?? '')), ]; @@ -268,17 +271,17 @@ class HTTPSignature $content = json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); // Header data that is about to be signed. - $host = strtolower(parse_url($target, PHP_URL_HOST)); - $path = parse_url($target, PHP_URL_PATH); - $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true)); + $host = strtolower(parse_url($target, PHP_URL_HOST)); + $path = parse_url($target, PHP_URL_PATH); + $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true)); $content_length = strlen($content); - $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP); + $date = DateTimeFormat::utcNow(DateTimeFormat::HTTP); $headers = [ - 'Date' => $date, + 'Date' => $date, 'Content-Length' => $content_length, - 'Digest' => $digest, - 'Host' => $host + 'Digest' => $digest, + 'Host' => $host ]; $signed_data = "(request-target): post " . $path . "\ndate: " . $date . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host; @@ -289,7 +292,7 @@ class HTTPSignature $headers['Content-Type'] = 'application/activity+json'; - $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'), HttpClientRequest::ACTIVITYPUB); + $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'), HttpClientRequest::ACTIVITYPUB); $return_code = $postResult->getReturnCode(); DI::logger()->info('Transmit to ' . $target . ' returned ' . $return_code); @@ -318,10 +321,10 @@ class HTTPSignature return false; } - $activity = JsonLD::compact($data); - $type = JsonLD::fetchElement($activity, '@type'); + $activity = JsonLD::compact($data); + $type = JsonLD::fetchElement($activity, '@type'); $trust_source = true; - $object_data = Receiver::prepareObjectData($activity, $uid, true, $trust_source, $owner['url']); + $object_data = Receiver::prepareObjectData($activity, $uid, true, $trust_source, $owner['url']); if (empty($object_data)) { return false; } @@ -387,7 +390,7 @@ class HTTPSignature * @param int $gsid Server ID * @throws \Exception */ - static public function setInboxStatus(string $url, bool $success, bool $shared = false, int $gsid = null) + public static function setInboxStatus(string $url, bool $success, bool $shared = false, int $gsid = null) { $now = DateTimeFormat::utcNow(); @@ -434,7 +437,7 @@ class HTTPSignature $stamp1 = strtotime($status['success']); } - $stamp2 = strtotime($now); + $stamp2 = strtotime($now); $previous_stamp = strtotime($status['previous']); // Archive the inbox when there had been failures for five days. @@ -631,11 +634,13 @@ class HTTPSignature } $headers = []; + $headers['(request-target)'] = strtolower(DI::args()->getMethod()) . ' ' . parse_url($http_headers['REQUEST_URI'], PHP_URL_PATH); // First take every header foreach ($http_headers as $k => $v) { $field = str_replace('_', '-', strtolower($k)); + $headers[$field] = $v; } @@ -643,6 +648,7 @@ class HTTPSignature foreach ($http_headers as $k => $v) { if (strpos($k, 'HTTP_') === 0) { $field = str_replace('_', '-', strtolower(substr($k, 5))); + $headers[$field] = $v; } } From d74ca3ecf565f1c58112b508adf3514fcedeb286 Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 22 Jan 2025 20:56:21 +0000 Subject: [PATCH 86/91] Fix codestyle --- src/Model/Contact.php | 202 +++++++-------- src/Model/GServer.php | 231 +++++++++-------- src/Module/Admin/Site.php | 495 ++++++++++++++++++------------------- static/settings.config.php | 2 +- 4 files changed, 476 insertions(+), 454 deletions(-) diff --git a/src/Model/Contact.php b/src/Model/Contact.php index 7cac007a64..a7dfa08dcf 100644 --- a/src/Model/Contact.php +++ b/src/Model/Contact.php @@ -74,12 +74,12 @@ class Contact * This will only be assigned to contacts, not to user accounts * @{ */ - const TYPE_UNKNOWN = -1; - const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON; + const TYPE_UNKNOWN = -1; + const TYPE_PERSON = User::ACCOUNT_TYPE_PERSON; const TYPE_ORGANISATION = User::ACCOUNT_TYPE_ORGANISATION; - const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS; - const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY; - const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY; + const TYPE_NEWS = User::ACCOUNT_TYPE_NEWS; + const TYPE_COMMUNITY = User::ACCOUNT_TYPE_COMMUNITY; + const TYPE_RELAY = User::ACCOUNT_TYPE_RELAY; /** * @} */ @@ -335,7 +335,7 @@ class Contact if (!empty($fields)) { foreach (['id', 'next-update', 'network', 'local-data'] as $internal) { if (!in_array($internal, $fields)) { - $fields[] = $internal; + $fields[] = $internal; $removal[] = $internal; } } @@ -353,9 +353,9 @@ class Contact // Then the alias (which could be anything) if (!DBA::isResult($contact)) { // The link could be provided as http although we stored it as https - $ssl_url = str_replace('http://', 'https://', $url); + $ssl_url = str_replace('http://', 'https://', $url); $condition = ['`alias` IN (?, ?, ?) AND `uid` = ? AND NOT `deleted`', $url, Strings::normaliseLink($url), $ssl_url, $uid]; - $contact = DBA::selectFirst('contact', $fields, $condition, $options); + $contact = DBA::selectFirst('contact', $fields, $condition, $options); } if (!DBA::isResult($contact)) { @@ -846,7 +846,7 @@ class Contact } $fields = ['uid', 'username', 'nickname', 'page-flags', 'account-type', 'prvkey', 'pubkey']; - $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]); + $user = DBA::selectFirst('user', $fields, ['uid' => $uid, 'verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false]); if (!DBA::isResult($user)) { return false; } @@ -877,11 +877,11 @@ class Contact 'network' => Protocol::DFRN, 'url' => $url, // it seems as if ported accounts can have wrong values, so we make sure that now everything is fine. - 'nurl' => Strings::normaliseLink($url), - 'uri-id' => ItemURI::getIdByURI($url), - 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3), - 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'], - 'poll' => DI::baseUrl() . '/feed/' . $user['nickname'], + 'nurl' => Strings::normaliseLink($url), + 'uri-id' => ItemURI::getIdByURI($url), + 'addr' => $user['nickname'] . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3), + 'notify' => DI::baseUrl() . '/dfrn_notify/' . $user['nickname'], + 'poll' => DI::baseUrl() . '/feed/' . $user['nickname'], ]; $avatar = Photo::selectFirst(['resource-id', 'type'], ['uid' => $uid, 'profile' => true]); @@ -906,14 +906,14 @@ class Contact $fields['micro'] = self::getDefaultAvatar($fields, Proxy::SIZE_MICRO); } - $fields['avatar'] = User::getAvatarUrl($user); - $fields['header'] = User::getBannerUrl($user); - $fields['forum'] = in_array($user['page-flags'], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_COMM_MAN]); - $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP; - $fields['unsearchable'] = !$profile['net-publish']; + $fields['avatar'] = User::getAvatarUrl($user); + $fields['header'] = User::getBannerUrl($user); + $fields['forum'] = in_array($user['page-flags'], [User::PAGE_FLAGS_COMMUNITY, User::PAGE_FLAGS_COMM_MAN]); + $fields['prv'] = $user['page-flags'] == User::PAGE_FLAGS_PRVGROUP; + $fields['unsearchable'] = !$profile['net-publish']; $fields['manually-approve'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP, User::PAGE_FLAGS_COMM_MAN]); - $fields['baseurl'] = DI::baseUrl(); - $fields['gsid'] = GServer::getID($fields['baseurl'], true); + $fields['baseurl'] = DI::baseUrl(); + $fields['gsid'] = GServer::getID($fields['baseurl'], true); $update = false; @@ -1092,7 +1092,7 @@ class Contact public static function markForArchival(array $contact) { if ((!isset($contact['uri-id']) || !isset($contact['url']) || !isset($contact['archive']) || !isset($contact['self']) || !isset($contact['term-date'])) && !empty($contact['id'])) { - $fields = ['id', 'uri-id', 'url', 'archive', 'self', 'term-date']; + $fields = ['id', 'uri-id', 'url', 'archive', 'self', 'term-date']; $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]); if (!DBA::isResult($contact)) { return; @@ -1144,7 +1144,7 @@ class Contact { // Always unarchive the relay contact entry if (!empty($contact['batch']) && !empty($contact['term-date']) && ($contact['term-date'] > DBA::NULL_DATETIME)) { - $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false, 'unsearchable' => true]; + $fields = ['failed' => false, 'term-date' => DBA::NULL_DATETIME, 'archive' => false, 'unsearchable' => true]; $condition = ['uid' => 0, 'network' => Protocol::FEDERATED, 'batch' => $contact['batch'], 'contact-type' => self::TYPE_RELAY]; if (!DBA::exists('contact', array_merge($condition, $fields))) { self::update($fields, $condition); @@ -1158,7 +1158,7 @@ class Contact } if ((!isset($contact['url']) || !isset($contact['uri-id'])) && !empty($contact['id'])) { - $fields = ['id', 'uri-id', 'url', 'batch', 'term-date']; + $fields = ['id', 'uri-id', 'url', 'batch', 'term-date']; $contact = DBA::selectFirst('contact', $fields, ['id' => $contact['id']]); if (!DBA::isResult($contact)) { return; @@ -1214,11 +1214,11 @@ class Contact if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) { $mention_label = DI::l10n()->t('Post to group'); - $mention_url = 'compose/0?body=!' . $contact['addr']; + $mention_url = 'compose/0?body=!' . $contact['addr']; $network_label = DI::l10n()->t('View group'); } else { $mention_label = DI::l10n()->t('Mention'); - $mention_url = 'compose/0?body=@' . $contact['addr']; + $mention_url = 'compose/0?body=@' . $contact['addr']; $network_label = DI::l10n()->t('Network Posts'); } $network_url = 'contact/' . $contact['id'] . '/conversations'; @@ -1376,10 +1376,10 @@ class Contact if (DBA::isResult($personal_contact) && !Probe::isProbable($personal_contact['network'])) { DI::logger()->info('Take contact data from personal contact', ['url' => $url, 'update' => $update, 'contact' => $personal_contact]); - $data = $personal_contact; - $data['photo'] = $personal_contact['avatar']; + $data = $personal_contact; + $data['photo'] = $personal_contact['avatar']; $data['account-type'] = $personal_contact['contact-type']; - $data['hide'] = $personal_contact['unsearchable']; + $data['hide'] = $personal_contact['unsearchable']; unset($data['avatar']); unset($data['contact-type']); unset($data['unsearchable']); @@ -1411,17 +1411,17 @@ class Contact if (!$contact_id) { // We only insert the basic data. The rest will be done in "updateFromProbeArray" $fields = [ - 'uid' => $uid, - 'url' => $data['url'], - 'baseurl' => $data['baseurl'] ?? '', - 'nurl' => Strings::normaliseLink($data['url']), - 'network' => $data['network'], - 'created' => DateTimeFormat::utcNow(), - 'rel' => self::SHARING, - 'writable' => 1, - 'blocked' => 0, - 'readonly' => 0, - 'pending' => 0, + 'uid' => $uid, + 'url' => $data['url'], + 'baseurl' => $data['baseurl'] ?? '', + 'nurl' => Strings::normaliseLink($data['url']), + 'network' => $data['network'], + 'created' => DateTimeFormat::utcNow(), + 'rel' => self::SHARING, + 'writable' => 1, + 'blocked' => 0, + 'readonly' => 0, + 'pending' => 0, ]; $condition = ['nurl' => Strings::normaliseLink($data['url']), 'uid' => $uid, 'deleted' => false]; @@ -1634,13 +1634,13 @@ class Contact if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) { $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl'); - $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); + $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); } else { $o = ''; } $fields = array_merge(Item::DISPLAY_FIELDLIST, ['featured']); - $items = Post::toArray(Post::selectForUser($uid, $fields, $condition, $params)); + $items = Post::toArray(Post::selectForUser($uid, $fields, $condition, $params)); $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACT_POSTS); @@ -1697,7 +1697,7 @@ class Contact if (DI::pConfig()->get($uid, 'system', 'infinite_scroll')) { $tpl = Renderer::getMarkupTemplate('infinite_scroll_head.tpl'); - $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); + $o = Renderer::replaceMacros($tpl, ['$reload_uri' => DI::args()->getQueryString()]); } else { $o = ''; } @@ -1713,7 +1713,7 @@ class Contact $sql2 = "SELECT `thr-parent-id` AS `uri-id`, `created` FROM `post-user-view` WHERE " . array_shift($condition2); $union = array_merge($condition1, $condition2); - $sql = $sql1 . " UNION " . $sql2; + $sql = $sql1 . " UNION " . $sql2; $sql .= " ORDER BY `created` DESC LIMIT ?, ?"; $union = array_merge($union, [$pager->getStart(), $pager->getItemsPerPage()]); @@ -1722,7 +1722,7 @@ class Contact if (empty($last_created) && ($pager->getStart() == 0)) { $fields = ['uri-id', 'thr-parent-id', 'gravity', 'author-id', 'created']; $pinned = Post\Collection::selectToArrayForContact($cid, Post\Collection::FEATURED, $fields); - $items = array_merge($items, $pinned); + $items = array_merge($items, $pinned); } $o .= DI::conversation()->render($items, ConversationContent::MODE_CONTACTS, $update, false, 'pinned_created', $uid); @@ -1913,9 +1913,9 @@ class Contact */ private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array { - $update = false; + $update = false; $contact_fields = []; - $fields = ['photo', 'thumb', 'micro']; + $fields = ['photo', 'thumb', 'micro']; foreach ($fields as $field) { if (isset($contact[$field])) { $contact_fields[] = $field; @@ -1971,7 +1971,7 @@ class Contact if (!empty($contact['gsid'])) { // Use default banners for certain platforms - $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]); + $gserver = DBA::selectFirst('gserver', ['platform'], ['id' => $contact['gsid']]); $platform = strtolower($gserver['platform'] ?? ''); } else { $platform = ''; @@ -2016,18 +2016,18 @@ class Contact switch ($size) { case Proxy::SIZE_MICRO: $avatar['size'] = 48; - $default = self::DEFAULT_AVATAR_MICRO; + $default = self::DEFAULT_AVATAR_MICRO; break; case Proxy::SIZE_THUMB: $avatar['size'] = 80; - $default = self::DEFAULT_AVATAR_THUMB; + $default = self::DEFAULT_AVATAR_THUMB; break; case Proxy::SIZE_SMALL: default: $avatar['size'] = 300; - $default = self::DEFAULT_AVATAR_PHOTO; + $default = self::DEFAULT_AVATAR_PHOTO; break; } @@ -2036,14 +2036,14 @@ class Contact $type = Contact::TYPE_PERSON; if (!empty($contact['id'])) { - $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]); - $platform = $account['platform'] ?? ''; + $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['id' => $contact['id']]); + $platform = $account['platform'] ?? ''; $type = $account['contact-type'] ?? Contact::TYPE_PERSON; } if (empty($platform) && !empty($contact['uri-id'])) { - $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]); - $platform = $account['platform'] ?? ''; + $account = DBA::selectFirst('account-user-view', ['platform', 'contact-type'], ['uri-id' => $contact['uri-id']]); + $platform = $account['platform'] ?? ''; $type = $account['contact-type'] ?? Contact::TYPE_PERSON; } @@ -2153,7 +2153,7 @@ class Contact return DI::baseUrl() . $default; } - $avatar['url'] = ''; + $avatar['url'] = ''; $avatar['success'] = false; Hook::callAll('avatar_lookup', $avatar); @@ -2181,7 +2181,7 @@ class Contact if (empty($updated)) { $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]); $updated = $account['updated'] ?? ''; - $guid = $account['guid'] ?? ''; + $guid = $account['guid'] ?? ''; } $guid = urlencode($guid); @@ -2249,7 +2249,7 @@ class Contact if (empty($updated) || empty($guid)) { $account = DBA::selectFirst('account-user-view', ['updated', 'guid'], ['id' => $cid]); $updated = $account['updated'] ?? ''; - $guid = $account['guid'] ?? ''; + $guid = $account['guid'] ?? ''; } $guid = urlencode($guid); @@ -2380,11 +2380,11 @@ class Contact if ($default_avatar && Proxy::isLocalImage($avatar)) { $fields = [ - 'avatar' => $avatar, + 'avatar' => $avatar, 'avatar-date' => DateTimeFormat::utcNow(), - 'photo' => $avatar, - 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB), - 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO) + 'photo' => $avatar, + 'thumb' => self::getDefaultAvatar($contact, Proxy::SIZE_THUMB), + 'micro' => self::getDefaultAvatar($contact, Proxy::SIZE_MICRO) ]; DI::logger()->debug('Use default avatar', ['id' => $cid, 'uid' => $uid]); } @@ -2423,11 +2423,11 @@ class Contact $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true); if ($photos) { $fields = [ - 'avatar' => $avatar, - 'photo' => $photos[0], - 'thumb' => $photos[1], - 'micro' => $photos[2], - 'blurhash' => $photos[3], + 'avatar' => $avatar, + 'photo' => $photos[0], + 'thumb' => $photos[1], + 'micro' => $photos[2], + 'blurhash' => $photos[3], 'avatar-date' => DateTimeFormat::utcNow(), ]; $update = true; @@ -2480,7 +2480,7 @@ class Contact { // Update contact data for all users $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)) { DI::logger()->info('Deleting contact', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $url]); self::remove($contact['id']); @@ -2607,7 +2607,7 @@ class Contact public static function removeDuplicates(string $nurl, int $uid) { $condition = ['nurl' => $nurl, 'uid' => $uid, 'self' => false, 'deleted' => false, 'network' => Protocol::FEDERATED]; - $count = DBA::count('contact', $condition); + $count = DBA::count('contact', $condition); if ($count <= 1) { return false; } @@ -2622,7 +2622,7 @@ class Contact DI::logger()->info('Found duplicates', ['count' => $count, 'first' => $first, 'uid' => $uid, 'nurl' => $nurl]); // 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]; $duplicates = DBA::select('contact', ['id', 'network'], $condition); while ($duplicate = DBA::fetch($duplicates)) { if (!in_array($duplicate['network'], Protocol::FEDERATED)) { @@ -2693,7 +2693,7 @@ class Contact $data = Probe::uri($contact['url'], $network, $contact['uid']); if (in_array($data['network'], Protocol::FEDERATED) && (parse_url($data['url'], PHP_URL_SCHEME) == 'http')) { - $ssl_url = str_replace('http://', 'https://', $contact['url']); + $ssl_url = str_replace('http://', 'https://', $contact['url']); $ssl_data = Probe::uri($ssl_url, $network, $contact['uid']); if (($ssl_data['network'] == $data['network']) && (parse_url($ssl_data['url'], PHP_URL_SCHEME) != 'http')) { $data = $ssl_data; @@ -2890,12 +2890,12 @@ class Contact } if (isset($ret['account-type']) && is_int($ret['account-type'])) { - $ret['forum'] = false; - $ret['prv'] = false; + $ret['forum'] = false; + $ret['prv'] = false; $ret['contact-type'] = $ret['account-type']; if (($ret['contact-type'] == User::ACCOUNT_TYPE_COMMUNITY) && isset($ret['manually-approve'])) { $ret['forum'] = (bool)!$ret['manually-approve']; - $ret['prv'] = (bool)!$ret['forum']; + $ret['prv'] = (bool)!$ret['forum']; } } @@ -2914,7 +2914,7 @@ class Contact } $update = false; - $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? ''); + $guid = ($ret['guid'] ?? '') ?: Item::guidFromUri($ret['url'], $ret['baseurl'] ?? $ret['alias'] ?? ''); // make sure to not overwrite existing values with blank entries except some technical fields $keep = ['batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'baseurl']; @@ -2981,7 +2981,7 @@ class Contact } if (($uid == 0) || in_array($ret['network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) { - $ret['last-update'] = $updated; + $ret['last-update'] = $updated; $ret['success_update'] = $updated; } @@ -3113,10 +3113,10 @@ class Contact if (!empty($arr['contact']['name'])) { $probed = false; - $ret = $arr['contact']; + $ret = $arr['contact']; } else { $probed = true; - $ret = Probe::uri($url, $network, $uid); + $ret = Probe::uri($url, $network, $uid); // Ensure that the public contact exists if ($ret['network'] != Protocol::PHANTOM) { @@ -3131,7 +3131,7 @@ class Contact // check if we already have a contact $condition = ['uid' => $uid, 'nurl' => Strings::normaliseLink($ret['url']), 'deleted' => false]; - $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition); + $contact = DBA::selectFirst('contact', ['id', 'rel', 'url', 'pending', 'hub-verify'], $condition); $protocol = self::getProtocol($ret['url'], $ret['network']); @@ -3210,7 +3210,7 @@ class Contact 'nick' => $ret['nick'], 'network' => $ret['network'], 'baseurl' => $ret['baseurl'], - 'gsid' => $ret['gsid'] ?? null, + 'gsid' => $ret['gsid'] ?? null, 'contact-type' => $ret['account-type'] ?? self::TYPE_PERSON, 'protocol' => $protocol, 'pubkey' => $ret['pubkey'], @@ -3230,7 +3230,7 @@ class Contact return $result; } - $contact_id = $contact['id']; + $contact_id = $contact['id']; $result['cid'] = $contact_id; if ($contact['contact-type'] == self::TYPE_COMMUNITY) { @@ -3275,7 +3275,7 @@ class Contact return false; } - $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked', 'baseurl']; + $fields = ['id', 'url', 'name', 'nick', 'avatar', 'photo', 'network', 'blocked', 'baseurl']; $pub_contact = DBA::selectFirst('contact', $fields, ['id' => $datarray['author-id']]); if (!DBA::isResult($pub_contact)) { // Should never happen @@ -3287,10 +3287,10 @@ class Contact return false; } - $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url']; - $name = $pub_contact['name']; - $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"]; - $nick = $pub_contact['nick']; + $url = ($datarray['author-link'] ?? '') ?: $pub_contact['url']; + $name = $pub_contact['name']; + $photo = ($pub_contact['avatar'] ?? '') ?: $pub_contact["photo"]; + $nick = $pub_contact['nick']; $network = $pub_contact['network']; // Ensure that we don't create a new contact when there already is one @@ -3368,7 +3368,7 @@ class Contact /// @TODO Encapsulate this into a function/method $fields = ['uid', 'username', 'email', 'page-flags', 'notify-flags', 'language']; - $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]); + $user = DBA::selectFirst('user', $fields, ['uid' => $importer['uid']]); if (DBA::isResult($user) && !in_array($user['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_FREELOVE, User::PAGE_FLAGS_COMMUNITY])) { // create notification if (is_array($contact_record)) { @@ -3402,7 +3402,7 @@ class Contact } $condition = ['uid' => $importer['uid'], 'url' => $url, 'pending' => true]; - $fields = ['pending' => false]; + $fields = ['pending' => false]; if ($user['page-flags'] == User::PAGE_FLAGS_FREELOVE) { $fields['rel'] = self::FRIEND; } @@ -3507,7 +3507,7 @@ class Contact DBA::update( 'contact', ['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd], - ['id' => $contact['id']] + ['id' => $contact['id']] ); } } @@ -3662,9 +3662,9 @@ class Contact */ public static function isGroup(int $contactid): bool { - $fields = ['contact-type']; + $fields = ['contact-type']; $condition = ['id' => $contactid]; - $contact = DBA::selectFirst('contact', $fields, $condition); + $contact = DBA::selectFirst('contact', $fields, $condition); if (!DBA::isResult($contact)) { return false; } @@ -3682,7 +3682,7 @@ class Contact public static function canReceivePrivateMessages(array $contact): bool { $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM; - $self = $contact['self'] ?? false; + $self = $contact['self'] ?? false; return in_array($protocol, [Protocol::DFRN, Protocol::DIASPORA, Protocol::ACTIVITYPUB]) && !$self; } @@ -3713,12 +3713,12 @@ class Contact } $condition = [ - 'network' => $networks, - 'server-failed' => false, - 'failed' => false, - 'deleted' => false, - 'unsearchable' => false, - 'uid' => $uid + 'network' => $networks, + 'server-failed' => false, + 'failed' => false, + 'deleted' => false, + 'unsearchable' => false, + 'uid' => $uid ]; if (!$show_blocked) { @@ -3762,10 +3762,10 @@ class Contact */ public static function addByUrls(array $urls): array { - $added = 0; - $updated = 0; + $added = 0; + $updated = 0; $unchanged = 0; - $count = 0; + $count = 0; foreach ($urls as $url) { if (empty($url) || !is_string($url)) { diff --git a/src/Model/GServer.php b/src/Model/GServer.php index ee9661b796..90f68b7725 100644 --- a/src/Model/GServer.php +++ b/src/Model/GServer.php @@ -39,44 +39,44 @@ use Psr\Http\Message\UriInterface; class GServer { // Directory types - const DT_NONE = 0; - const DT_POCO = 1; + const DT_NONE = 0; + const DT_POCO = 1; const DT_MASTODON = 2; // Methods to detect server types // Non endpoint specific methods - const DETECT_MANUAL = 0; - const DETECT_HEADER = 1; - const DETECT_BODY = 2; - const DETECT_HOST_META = 3; - const DETECT_CONTACTS = 4; - const DETECT_AP_ACTOR = 5; + const DETECT_MANUAL = 0; + const DETECT_HEADER = 1; + const DETECT_BODY = 2; + const DETECT_HOST_META = 3; + const DETECT_CONTACTS = 4; + const DETECT_AP_ACTOR = 5; const DETECT_AP_COLLECTION = 6; const DETECT_UNSPECIFIC = [self::DETECT_MANUAL, self::DETECT_HEADER, self::DETECT_BODY, self::DETECT_HOST_META, self::DETECT_CONTACTS, self::DETECT_AP_ACTOR]; // Implementation specific endpoints // @todo Possibly add Lemmy detection via the endpoint /api/v3/site - const DETECT_FRIENDIKA = 10; - const DETECT_FRIENDICA = 11; - const DETECT_STATUSNET = 12; - const DETECT_GNUSOCIAL = 13; - const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix + const DETECT_FRIENDIKA = 10; + const DETECT_FRIENDICA = 11; + const DETECT_STATUSNET = 12; + const DETECT_GNUSOCIAL = 13; + const DETECT_CONFIG_JSON = 14; // Statusnet, GNU Social, Older Hubzilla/Redmatrix const DETECT_SITEINFO_JSON = 15; // Newer Hubzilla - const DETECT_MASTODON_API = 16; - const DETECT_STATUS_PHP = 17; // Nextcloud - const DETECT_V1_CONFIG = 18; - const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap - const DETECT_THREADS = 21; + const DETECT_MASTODON_API = 16; + const DETECT_STATUS_PHP = 17; // Nextcloud + const DETECT_V1_CONFIG = 18; + const DETECT_SYSTEM_ACTOR = 20; // Mistpark, Osada, Roadhouse, Zap + const DETECT_THREADS = 21; // Standardized endpoints const DETECT_STATISTICS_JSON = 100; - const DETECT_NODEINFO_10 = 101; // Nodeinfo Version 1.0 - const DETECT_NODEINFO_20 = 102; // Nodeinfo Version 2.0 - const DETECT_NODEINFO2_10 = 103; // Nodeinfo2 Version 1.0 - const DETECT_NODEINFO_21 = 104; // Nodeinfo Version 2.1 - const DETECT_NODEINFO_22 = 105; // Nodeinfo Version 2.2 + const DETECT_NODEINFO_10 = 101; // Nodeinfo Version 1.0 + const DETECT_NODEINFO_20 = 102; // Nodeinfo Version 2.0 + const DETECT_NODEINFO2_10 = 103; // Nodeinfo2 Version 1.0 + const DETECT_NODEINFO_21 = 104; // Nodeinfo Version 2.1 + const DETECT_NODEINFO_22 = 105; // Nodeinfo Version 2.2 /** * Check for the existence of a server and adds it in the background if not existant @@ -343,7 +343,7 @@ class GServer $gserver = DBA::selectFirst('gserver', [], ['nurl' => Strings::normaliseLink($server_url)]); if (DBA::isResult($gserver)) { if ($gserver['created'] <= DBA::NULL_DATETIME) { - $fields = ['created' => DateTimeFormat::utcNow()]; + $fields = ['created' => DateTimeFormat::utcNow()]; $condition = ['nurl' => Strings::normaliseLink($server_url)]; self::update($fields, $condition); } @@ -450,9 +450,11 @@ class GServer $gserver = DBA::selectFirst('gserver', [], ['nurl' => $nurl]); if (DBA::isResult($gserver)) { $next_update = self::getNextUpdateDate(false, $gserver['created'], $gserver['last_contact']); - self::update(['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(), - 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null], - ['nurl' => $nurl]); + self::update( + ['url' => $url, 'failed' => true, 'blocked' => Network::isUrlBlocked($url), 'last_failure' => DateTimeFormat::utcNow(), + 'next_contact' => $next_update, 'network' => Protocol::PHANTOM, 'detection-method' => null], + ['nurl' => $nurl] + ); DI::logger()->info('Set failed status for existing server', ['url' => $url]); if (self::isDefunct($gserver)) { self::archiveContacts($gserver['id']); @@ -461,8 +463,8 @@ class GServer } self::insert(['url' => $url, 'nurl' => $nurl, - 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(), - 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]); + 'network' => Protocol::PHANTOM, 'created' => DateTimeFormat::utcNow(), + 'failed' => true, 'last_failure' => DateTimeFormat::utcNow()]); DI::logger()->info('Set failed status for new server', ['url' => $url]); } @@ -592,7 +594,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)) && (parse_url($url, PHP_URL_SCHEME) != parse_url($valid_url, PHP_URL_SCHEME))) { - $url = $valid_url; + $url = $valid_url; } $in_webroot = empty(parse_url($url, PHP_URL_PATH)); @@ -627,10 +629,10 @@ class GServer if ($serverdata['network'] == Protocol::PHANTOM) { if ($in_webroot) { // Fetch the landing page, possibly it reveals some data - $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9'; + $accept = 'application/activity+json,application/ld+json,application/json,*/*;q=0.9'; $curlResult = DI::httpClient()->get($url, $accept, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess() && $curlResult->getReturnCode() == '406') { - $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); + $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); $html_fetched = true; } else { $html_fetched = false; @@ -639,8 +641,8 @@ class GServer if ($curlResult->isSuccess()) { $json = json_decode($curlResult->getBodyString(), true); if (!empty($json) && is_array($json)) { - $data = self::fetchDataFromSystemActor($json, $serverdata); - $serverdata = $data['server']; + $data = self::fetchDataFromSystemActor($json, $serverdata); + $serverdata = $data['server']; $systemactor = $data['actor']; if (!$html_fetched && !in_array($serverdata['detection-method'], [self::DETECT_SYSTEM_ACTOR, self::DETECT_AP_COLLECTION])) { $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); @@ -739,7 +741,7 @@ class GServer return false; } - $serverdata['url'] = $url; + $serverdata['url'] = $url; $serverdata['nurl'] = Strings::normaliseLink($url); // We have to prevent an endless loop here. @@ -803,10 +805,11 @@ class GServer $gserver = DBA::selectFirst('gserver', ['network'], ['nurl' => Strings::normaliseLink($url)]); if (!DBA::isResult($gserver)) { $serverdata['created'] = DateTimeFormat::utcNow(); + $ret = self::insert($serverdata); - $id = DBA::lastInsertId(); + $id = DBA::lastInsertId(); } else { - $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]); + $ret = self::update($serverdata, ['nurl' => $serverdata['nurl']]); $gserver = DBA::selectFirst('gserver', ['id'], ['nurl' => $serverdata['nurl']]); if (DBA::isResult($gserver)) { $id = $gserver['id']; @@ -816,8 +819,8 @@ class GServer // Count the number of known contacts from this server if (!empty($id) && !in_array($serverdata['network'], [Protocol::PHANTOM, Protocol::FEED])) { $apcontacts = DBA::count('apcontact', ['gsid' => $id]); - $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]); - $max_users = max($apcontacts, $contacts); + $contacts = DBA::count('contact', ['uid' => 0, 'gsid' => $id, 'failed' => false]); + $max_users = max($apcontacts, $contacts); if ($max_users > $serverdata['registered-users']) { DI::logger()->info('Update registered users', ['id' => $id, 'url' => $serverdata['nurl'], 'registered-users' => $max_users]); self::update(['registered-users' => $max_users], ['id' => $id]); @@ -846,7 +849,7 @@ class GServer if (!empty($systemactor)) { $contact = Contact::getByURL($systemactor, true, ['gsid', 'baseurl', 'id', 'network', 'url', 'name']); - DI::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; @@ -879,9 +882,9 @@ class GServer $data['subscribe'] = (bool)($data['subscribe'] ?? false); if (!$data['subscribe'] || empty($data['scope']) || !in_array(strtolower($data['scope']), ['all', 'tags'])) { - $data['scope'] = ''; + $data['scope'] = ''; $data['subscribe'] = false; - $data['tags'] = []; + $data['tags'] = []; } $gserver = DBA::selectFirst('gserver', ['id', 'url', 'network', 'relay-subscribe', 'relay-scope'], ['nurl' => Strings::normaliseLink($server_url)]); @@ -975,13 +978,14 @@ class GServer return $serverdata; } - $valid = false; + $valid = false; $old_serverdata = $serverdata; $serverdata['detection-method'] = self::DETECT_STATISTICS_JSON; if (!empty($data['version'])) { $valid = true; + $serverdata['version'] = $data['version']; // 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. @@ -990,11 +994,13 @@ class GServer if (!empty($data['name'])) { $valid = true; + $serverdata['site_name'] = $data['name']; } if (!empty($data['network'])) { $valid = true; + $serverdata['platform'] = strtolower($data['network']); if ($serverdata['platform'] == 'diaspora') { @@ -1010,21 +1016,25 @@ class GServer if (!empty($data['total_users'])) { $valid = true; + $serverdata['registered-users'] = max($data['total_users'], 1); } if (!empty($data['active_users_monthly'])) { $valid = true; + $serverdata['active-month-users'] = max($data['active_users_monthly'], 0); } if (!empty($data['active_users_halfyear'])) { $valid = true; + $serverdata['active-halfyear-users'] = max($data['active_users_halfyear'], 0); } if (!empty($data['local_posts'])) { $valid = true; + $serverdata['local-posts'] = max($data['local_posts'], 0); } @@ -1065,8 +1075,8 @@ class GServer return []; } - $nodeinfo1_url = ''; - $nodeinfo2_url = ''; + $nodeinfo1_url = ''; + $nodeinfo2_url = ''; $detection_method = self::DETECT_MANUAL; foreach ($nodeinfo['links'] as $link) { @@ -1078,13 +1088,13 @@ class GServer if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') { $nodeinfo1_url = Network::addBasePath($link['href'], $httpResult->getUrl()); } elseif (($detection_method < self::DETECT_NODEINFO_20) && ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.0')) { - $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); + $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); $detection_method = self::DETECT_NODEINFO_20; } elseif (($detection_method < self::DETECT_NODEINFO_21) && ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.1')) { - $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); + $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); $detection_method = self::DETECT_NODEINFO_21; } elseif (($detection_method < self::DETECT_NODEINFO_22) && ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/2.2')) { - $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); + $nodeinfo2_url = Network::addBasePath($link['href'], $httpResult->getUrl()); $detection_method = self::DETECT_NODEINFO_22; } } @@ -1132,7 +1142,7 @@ class GServer $server = [ 'detection-method' => self::DETECT_NODEINFO_10, - 'register_policy' => Register::CLOSED + 'register_policy' => Register::CLOSED ]; if (!empty($nodeinfo['openRegistrations'])) { @@ -1232,8 +1242,8 @@ class GServer $server = [ 'detection-method' => $detection_method, - 'register_policy' => Register::CLOSED, - 'platform' => 'unknown', + 'register_policy' => Register::CLOSED, + 'platform' => 'unknown', ]; if (!empty($nodeinfo['openRegistrations'])) { @@ -1363,7 +1373,7 @@ class GServer $server = [ 'detection-method' => self::DETECT_NODEINFO2_10, - 'register_policy' => Register::CLOSED + 'register_policy' => Register::CLOSED ]; if (!empty($nodeinfo['openRegistrations'])) { @@ -1471,7 +1481,7 @@ class GServer if (!empty($data['platform'])) { $serverdata['platform'] = strtolower($data['platform']); - $serverdata['version'] = $data['version'] ?? 'N/A'; + $serverdata['version'] = $data['version'] ?? 'N/A'; } if (!empty($data['plugins'])) { @@ -1547,17 +1557,17 @@ class GServer $actor = JsonLD::compact($data, false); if (in_array(JsonLD::fetchElement($actor, '@type'), ActivityPub\Receiver::ACCOUNT_TYPES)) { - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['site_name'] = JsonLD::fetchElement($actor, 'as:name', '@value'); - $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value'); + $serverdata['info'] = JsonLD::fetchElement($actor, 'as:summary', '@value'); if (self::isNomad($actor)) { - $serverdata['platform'] = self::getNomadName($actor['@id']); - $serverdata['version'] = self::getNomadVersion($actor['@id']); + $serverdata['platform'] = self::getNomadName($actor['@id']); + $serverdata['version'] = self::getNomadVersion($actor['@id']); $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR; } elseif (!empty($actor['as:generator'])) { - $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value')); - $serverdata['platform'] = strtolower(array_shift($generator)); - $serverdata['version'] = self::getNomadVersion($actor['@id']); + $generator = explode(' ', JsonLD::fetchElement($actor['as:generator'], 'as:name', '@value')); + $serverdata['platform'] = strtolower(array_shift($generator)); + $serverdata['version'] = self::getNomadVersion($actor['@id']); $serverdata['detection-method'] = self::DETECT_SYSTEM_ACTOR; } else { $serverdata['detection-method'] = self::DETECT_AP_ACTOR; @@ -1565,8 +1575,8 @@ class GServer return ['server' => $serverdata, 'actor' => $actor['@id']]; } elseif ((JsonLD::fetchElement($actor, '@type') == 'as:Collection')) { // By now only Ktistec seems to provide collections this way - $serverdata['platform'] = 'ktistec'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['platform'] = 'ktistec'; + $serverdata['network'] = Protocol::ACTIVITYPUB; $serverdata['detection-method'] = self::DETECT_AP_COLLECTION; $actors = JsonLD::fetchElementArray($actor, 'as:items'); @@ -1610,7 +1620,7 @@ class GServer */ private static function getNomadName(string $url): string { - $name = 'nomad'; + $name = 'nomad'; $curlResult = DI::httpClient()->get($url . '/manifest', 'application/manifest+json', [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess() || ($curlResult->getBodyString() == '')) { if ($curlResult->getReturnCode() == 418) { @@ -1729,7 +1739,7 @@ class GServer private static function validHostMeta(string $url): bool { $xrd_timeout = DI::config()->get('system', 'xrd_timeout'); - $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); + $curlResult = DI::httpClient()->get($url . Probe::HOST_META, HttpClientAccept::XRD_XML, [HttpClientOptions::TIMEOUT => $xrd_timeout, HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess()) { return false; } @@ -1828,10 +1838,9 @@ class GServer } if (!empty($data['totalResults'])) { - $registeredUsers = $serverdata['registered-users'] ?? 0; - $serverdata['registered-users'] = max($data['totalResults'], $registeredUsers, 1); - $serverdata['directory-type'] = self::DT_POCO; - $serverdata['poco'] = $url . '/poco'; + $serverdata['registered-users'] = max($data['totalResults'], $serverdata['registered-users'] ?? 0, 1); + $serverdata['directory-type'] = self::DT_POCO; + $serverdata['poco'] = $url . '/poco'; } return $serverdata; @@ -1886,8 +1895,8 @@ class GServer if (!empty($data['instance']) && !empty($data['serverVersion'])) { $serverdata['platform'] = 'peertube'; - $serverdata['version'] = $data['serverVersion']; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['version'] = $data['serverVersion']; + $serverdata['network'] = Protocol::ACTIVITYPUB; if (!empty($data['instance']['name'])) { $serverdata['site_name'] = $data['instance']['name']; @@ -1934,7 +1943,7 @@ class GServer if (!empty($data['version'])) { $serverdata['platform'] = 'nextcloud'; - $serverdata['version'] = $data['version']; + $serverdata['version'] = $data['version']; if ($validHostMeta) { $serverdata['network'] = Protocol::ACTIVITYPUB; @@ -2012,8 +2021,9 @@ class GServer if (!empty($data['version'])) { $serverdata['platform'] = 'mastodon'; - $serverdata['version'] = $data['version'] ?? ''; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['version'] = $data['version'] ?? ''; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $valid = true; } @@ -2023,7 +2033,8 @@ class GServer if (!empty($data['title']) && empty($serverdata['platform']) && ($serverdata['network'] == Protocol::PHANTOM)) { $serverdata['platform'] = 'mastodon'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $valid = true; } @@ -2037,19 +2048,22 @@ class GServer if (!empty($serverdata['version']) && preg_match('/.*?\(compatible;\s(.*)\s(.*)\)/ism', $serverdata['version'], $matches)) { $serverdata['platform'] = strtolower($matches[1]); - $serverdata['version'] = $matches[2]; + $serverdata['version'] = $matches[2]; + $valid = true; } if (!empty($serverdata['version']) && strstr(strtolower($serverdata['version']), 'pleroma')) { $serverdata['platform'] = 'pleroma'; - $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); + $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); + $valid = true; } 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'; + $valid = true; } @@ -2086,14 +2100,14 @@ class GServer if (!empty($data['site']['platform'])) { $serverdata['platform'] = strtolower($data['site']['platform']['PLATFORM_NAME']); - $serverdata['version'] = $data['site']['platform']['STD_VERSION']; - $serverdata['network'] = Protocol::ZOT; + $serverdata['version'] = $data['site']['platform']['STD_VERSION']; + $serverdata['network'] = Protocol::ZOT; } if (!empty($data['site']['hubzilla'])) { $serverdata['platform'] = strtolower($data['site']['hubzilla']['PLATFORM_NAME']); - $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION']; - $serverdata['network'] = Protocol::ZOT; + $serverdata['version'] = $data['site']['hubzilla']['RED_VERSION']; + $serverdata['network'] = Protocol::ZOT; } if (!empty($data['site']['redmatrix'])) { @@ -2107,9 +2121,9 @@ class GServer $serverdata['network'] = Protocol::ZOT; } - $private = false; + $private = false; $inviteonly = false; - $closed = false; + $closed = false; if (!empty($data['site']['closed'])) { $closed = self::toBoolean($data['site']['closed']); @@ -2196,11 +2210,11 @@ class GServer if (!empty($serverdata['version']) && strtolower(substr($serverdata['version'], 0, 7)) == 'pleroma') { $serverdata['platform'] = 'pleroma'; - $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['version'] = trim(str_ireplace('pleroma', '', $serverdata['version'])); + $serverdata['network'] = Protocol::ACTIVITYPUB; } else { $serverdata['platform'] = 'statusnet'; - $serverdata['network'] = Protocol::OSTATUS; + $serverdata['network'] = Protocol::OSTATUS; } if (in_array($serverdata['detection-method'], self::DETECT_UNSPECIFIC)) { @@ -2226,11 +2240,11 @@ class GServer $curlResult = DI::httpClient()->get($url . '/friendica/json', HttpClientAccept::DEFAULT, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); if (!$curlResult->isSuccess()) { $curlResult = DI::httpClient()->get($url . '/friendika/json', HttpClientAccept::DEFAULT, [HttpClientOptions::REQUEST => HttpClientRequest::SERVERINFO]); - $friendika = true; - $platform = 'Friendika'; + $friendika = true; + $platform = 'Friendika'; } else { $friendika = false; - $platform = 'Friendica'; + $platform = 'Friendica'; } if (!$curlResult->isSuccess()) { @@ -2317,12 +2331,14 @@ class GServer $doc = new DOMDocument(); @$doc->loadHTML($curlResult->getBodyString()); $xpath = new DOMXPath($doc); + $assigned = false; // We can only detect honk via some HTML element on their page if ($xpath->query('//div[@id="honksonpage"]')->count() == 1) { $serverdata['platform'] = 'honk'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $assigned = true; } @@ -2358,9 +2374,11 @@ class GServer '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_replace('/', ' ', $platform); + $platform_parts = explode(' ', $platform); if ((count($platform_parts) >= 2) && in_array(strtolower($platform_parts[0]), array_values($platforms))) { $platform = $platform_parts[0]; + $serverdata['version'] = $platform_parts[1]; } if (in_array($platform, array_values($grouped_platforms['dfrn_platforms']))) { @@ -2372,6 +2390,7 @@ class GServer } if (in_array($platform, array_values($platforms))) { $serverdata['platform'] = $platform; + $assigned = true; } } @@ -2407,6 +2426,7 @@ class GServer if (in_array($attr['property'], ['og:platform', 'generator'])) { if (in_array($attr['content'], array_keys($platforms))) { $serverdata['platform'] = $platforms[$attr['content']]; + $assigned = true; } @@ -2422,9 +2442,10 @@ class GServer foreach ($list as $node) { foreach ($node->attributes as $attribute) { if (parse_url(trim($attribute->value), PHP_URL_HOST) == 'micro.blog') { - $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); + $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); $serverdata['platform'] = 'microblog'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $assigned = true; } } @@ -2435,9 +2456,10 @@ class GServer foreach ($list as $node) { foreach ($node->attributes as $attribute) { if (trim($attribute->value) == 'https://micro.blog/micropub') { - $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); + $serverdata['version'] = trim($serverdata['platform'] . ' ' . $serverdata['version']); $serverdata['platform'] = 'microblog'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; + $assigned = true; } } @@ -2463,15 +2485,15 @@ class GServer { if ($curlResult->getHeader('server') == 'Mastodon') { $serverdata['platform'] = 'mastodon'; - $serverdata['network'] = Protocol::ACTIVITYPUB; + $serverdata['network'] = Protocol::ACTIVITYPUB; } elseif ($curlResult->inHeader('x-diaspora-version')) { $serverdata['platform'] = 'diaspora'; - $serverdata['network'] = Protocol::DIASPORA; - $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? ''; + $serverdata['network'] = Protocol::DIASPORA; + $serverdata['version'] = $curlResult->getHeader('x-diaspora-version')[0] ?? ''; } elseif ($curlResult->inHeader('x-friendica-version')) { $serverdata['platform'] = 'friendica'; - $serverdata['network'] = Protocol::DFRN; - $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? ''; + $serverdata['network'] = Protocol::DFRN; + $serverdata['version'] = $curlResult->getHeader('x-friendica-version')[0] ?? ''; } else { return $serverdata; } @@ -2497,9 +2519,12 @@ class GServer $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], - ['order' => ['RAND()']]); + ['order' => ['RAND()']] + ); while ($gserver = DBA::fetch($gservers)) { DI::logger()->info('Update peer list', ['server' => $gserver['url'], 'id' => $gserver['id']]); @@ -2537,7 +2562,7 @@ class GServer // Discover federated servers $protocols = ['activitypub', 'diaspora', 'dfrn', 'ostatus']; foreach ($protocols as $protocol) { - $query = '{nodes(protocol:"' . $protocol . '"){host}}'; + $query = '{nodes(protocol:"' . $protocol . '"){host}}'; $curlResult = DI::httpClient()->fetch('https://the-federation.info/graphql?query=' . urlencode($query), HttpClientAccept::JSON, 0, '', HttpClientRequest::SERVERDISCOVER); if (!empty($curlResult)) { $data = json_decode($curlResult, true); @@ -2554,7 +2579,7 @@ class GServer $accesstoken = DI::config()->get('system', 'instances_social_key'); if (!empty($accesstoken)) { - $api = 'https://instances.social/api/1.0/instances/list?count=0'; + $api = 'https://instances.social/api/1.0/instances/list?count=0'; $curlResult = DI::httpClient()->get($api, HttpClientAccept::JSON, [HttpClientOptions::HEADERS => ['Authorization' => ['Bearer ' . $accesstoken], HttpClientOptions::REQUEST => HttpClientRequest::SERVERDISCOVER]]); if ($curlResult->isSuccess()) { $servers = json_decode($curlResult->getBodyString(), true); diff --git a/src/Module/Admin/Site.php b/src/Module/Admin/Site.php index e56e45f0a5..72ea6fa5a4 100644 --- a/src/Module/Admin/Site.php +++ b/src/Module/Admin/Site.php @@ -7,7 +7,6 @@ namespace Friendica\Module\Admin; -use Friendica\App; use Friendica\Core\Renderer; use Friendica\Core\Search; use Friendica\Core\System; @@ -20,7 +19,6 @@ use Friendica\Model\User; use Friendica\Module\BaseAdmin; use Friendica\Module\Conversation\Community; use Friendica\Module\Register; -use Friendica\Navigation\SystemMessages; use Friendica\Protocol\Relay; use Friendica\Util\BasePath; use Friendica\Util\EMailer\MailBuilder; @@ -58,81 +56,81 @@ class Site extends BaseAdmin $maximagelength = (!empty($_POST['maximagelength']) ? intval(trim($_POST['maximagelength'])) : -1); $jpegimagequality = (!empty($_POST['jpegimagequality']) ? intval(trim($_POST['jpegimagequality'])) : 100); - $register_policy = (!empty($_POST['register_policy']) ? intval(trim($_POST['register_policy'])) : 0); - $max_registered_users = (!empty($_POST['max_registered_users']) ? intval(trim($_POST['max_registered_users'])) : 0); - $daily_registrations = (!empty($_POST['max_daily_registrations']) ? intval(trim($_POST['max_daily_registrations'])) : 0); - $abandon_days = (!empty($_POST['abandon_days']) ? intval(trim($_POST['abandon_days'])) : 0); + $register_policy = (!empty($_POST['register_policy']) ? intval(trim($_POST['register_policy'])) : 0); + $max_registered_users = (!empty($_POST['max_registered_users']) ? intval(trim($_POST['max_registered_users'])) : 0); + $daily_registrations = (!empty($_POST['max_daily_registrations']) ? intval(trim($_POST['max_daily_registrations'])) : 0); + $abandon_days = (!empty($_POST['abandon_days']) ? intval(trim($_POST['abandon_days'])) : 0); - $register_text = (!empty($_POST['register_text']) ? strip_tags(trim($_POST['register_text'])) : ''); + $register_text = (!empty($_POST['register_text']) ? strip_tags(trim($_POST['register_text'])) : ''); - $allowed_sites = (!empty($_POST['allowed_sites']) ? trim($_POST['allowed_sites']) : ''); - $allowed_email = (!empty($_POST['allowed_email']) ? trim($_POST['allowed_email']) : ''); - $disallowed_email = (!empty($_POST['disallowed_email']) ? trim($_POST['disallowed_email']) : ''); - $forbidden_nicknames = (!empty($_POST['forbidden_nicknames']) ? strtolower(trim($_POST['forbidden_nicknames'])) : ''); - $system_actor_name = (!empty($_POST['system_actor_name']) ? trim($_POST['system_actor_name']) : ''); - $no_oembed_rich_content = !empty($_POST['no_oembed_rich_content']); - $allowed_oembed = (!empty($_POST['allowed_oembed']) ? trim($_POST['allowed_oembed']) : ''); - $block_public = !empty($_POST['block_public']); - $force_publish = !empty($_POST['publish_all']); - $global_directory = (!empty($_POST['directory']) ? trim($_POST['directory']) : ''); - $newuser_private = !empty($_POST['newuser_private']); - $enotify_no_content = !empty($_POST['enotify_no_content']); - $private_addons = !empty($_POST['private_addons']); - $disable_embedded = !empty($_POST['disable_embedded']); + $allowed_sites = (!empty($_POST['allowed_sites']) ? trim($_POST['allowed_sites']) : ''); + $allowed_email = (!empty($_POST['allowed_email']) ? trim($_POST['allowed_email']) : ''); + $disallowed_email = (!empty($_POST['disallowed_email']) ? trim($_POST['disallowed_email']) : ''); + $forbidden_nicknames = (!empty($_POST['forbidden_nicknames']) ? strtolower(trim($_POST['forbidden_nicknames'])) : ''); + $system_actor_name = (!empty($_POST['system_actor_name']) ? trim($_POST['system_actor_name']) : ''); + $no_oembed_rich_content = !empty($_POST['no_oembed_rich_content']); + $allowed_oembed = (!empty($_POST['allowed_oembed']) ? trim($_POST['allowed_oembed']) : ''); + $block_public = !empty($_POST['block_public']); + $force_publish = !empty($_POST['publish_all']); + $global_directory = (!empty($_POST['directory']) ? trim($_POST['directory']) : ''); + $newuser_private = !empty($_POST['newuser_private']); + $enotify_no_content = !empty($_POST['enotify_no_content']); + $private_addons = !empty($_POST['private_addons']); + $disable_embedded = !empty($_POST['disable_embedded']); $allow_users_remote_self = !empty($_POST['allow_users_remote_self']); - $allow_relay_channels = !empty($_POST['allow_relay_channels']); - $adjust_poll_frequency = !empty($_POST['adjust_poll_frequency']); - $min_poll_interval = (!empty($_POST['min_poll_interval']) ? intval(trim($_POST['min_poll_interval'])) : 0); - $explicit_content = !empty($_POST['explicit_content']); - $local_search = !empty($_POST['local_search']); - $blocked_tags = (!empty($_POST['blocked_tags']) ? trim($_POST['blocked_tags']) : ''); - $cache_contact_avatar = !empty($_POST['cache_contact_avatar']); + $allow_relay_channels = !empty($_POST['allow_relay_channels']); + $adjust_poll_frequency = !empty($_POST['adjust_poll_frequency']); + $min_poll_interval = (!empty($_POST['min_poll_interval']) ? intval(trim($_POST['min_poll_interval'])) : 0); + $explicit_content = !empty($_POST['explicit_content']); + $local_search = !empty($_POST['local_search']); + $blocked_tags = (!empty($_POST['blocked_tags']) ? trim($_POST['blocked_tags']) : ''); + $cache_contact_avatar = !empty($_POST['cache_contact_avatar']); - $enable_multi_reg = !empty($_POST['enable_multi_reg']); - $enable_openid = !empty($_POST['enable_openid']); - $enable_regfullname = !empty($_POST['enable_regfullname']); - $register_notification = !empty($_POST['register_notification']); - $community_page_style = (!empty($_POST['community_page_style']) ? intval(trim($_POST['community_page_style'])) : 0); + $enable_multi_reg = !empty($_POST['enable_multi_reg']); + $enable_openid = !empty($_POST['enable_openid']); + $enable_regfullname = !empty($_POST['enable_regfullname']); + $register_notification = !empty($_POST['register_notification']); + $community_page_style = (!empty($_POST['community_page_style']) ? intval(trim($_POST['community_page_style'])) : 0); $max_author_posts_community_page = (!empty($_POST['max_author_posts_community_page']) ? intval(trim($_POST['max_author_posts_community_page'])) : 0); $max_server_posts_community_page = (!empty($_POST['max_server_posts_community_page']) ? intval(trim($_POST['max_server_posts_community_page'])) : 0); - $verifyssl = !empty($_POST['verifyssl']); - $proxyuser = (!empty($_POST['proxyuser']) ? trim($_POST['proxyuser']) : ''); - $proxy = (!empty($_POST['proxy']) ? trim($_POST['proxy']) : ''); - $timeout = (!empty($_POST['timeout']) ? intval(trim($_POST['timeout'])) : 60); - $maxloadavg = (!empty($_POST['maxloadavg']) ? intval(trim($_POST['maxloadavg'])) : 20); - $min_memory = (!empty($_POST['min_memory']) ? intval(trim($_POST['min_memory'])) : 0); - $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); - $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); - $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_local_search = !empty($_POST['poco_local_search']); - $nodeinfo = !empty($_POST['nodeinfo']); - $mail_enabled = !empty($_POST['mail_enabled']); - $diaspora_enabled = !empty($_POST['diaspora_enabled']); - $force_ssl = !empty($_POST['force_ssl']); - $show_help = !empty($_POST['show_help']); - $dbclean = !empty($_POST['dbclean']); - $dbclean_expire_days = (!empty($_POST['dbclean_expire_days']) ? intval($_POST['dbclean_expire_days']) : 0); - $dbclean_unclaimed = (!empty($_POST['dbclean_unclaimed']) ? intval($_POST['dbclean_unclaimed']) : 0); - $dbclean_expire_conv = (!empty($_POST['dbclean_expire_conv']) ? intval($_POST['dbclean_expire_conv']) : 0); - $suppress_tags = !empty($_POST['suppress_tags']); - $max_comments = (!empty($_POST['max_comments']) ? intval($_POST['max_comments']) : 0); - $max_display_comments = (!empty($_POST['max_display_comments']) ? intval($_POST['max_display_comments']) : 0); - $itemspage_network = (!empty($_POST['itemspage_network']) ? intval($_POST['itemspage_network']) : 0); + $verifyssl = !empty($_POST['verifyssl']); + $proxyuser = (!empty($_POST['proxyuser']) ? trim($_POST['proxyuser']) : ''); + $proxy = (!empty($_POST['proxy']) ? trim($_POST['proxy']) : ''); + $timeout = (!empty($_POST['timeout']) ? intval(trim($_POST['timeout'])) : 60); + $maxloadavg = (!empty($_POST['maxloadavg']) ? intval(trim($_POST['maxloadavg'])) : 20); + $min_memory = (!empty($_POST['min_memory']) ? intval(trim($_POST['min_memory'])) : 0); + $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); + $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); + $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_local_search = !empty($_POST['poco_local_search']); + $nodeinfo = !empty($_POST['nodeinfo']); + $mail_enabled = !empty($_POST['mail_enabled']); + $diaspora_enabled = !empty($_POST['diaspora_enabled']); + $force_ssl = !empty($_POST['force_ssl']); + $show_help = !empty($_POST['show_help']); + $dbclean = !empty($_POST['dbclean']); + $dbclean_expire_days = (!empty($_POST['dbclean_expire_days']) ? intval($_POST['dbclean_expire_days']) : 0); + $dbclean_unclaimed = (!empty($_POST['dbclean_unclaimed']) ? intval($_POST['dbclean_unclaimed']) : 0); + $dbclean_expire_conv = (!empty($_POST['dbclean_expire_conv']) ? intval($_POST['dbclean_expire_conv']) : 0); + $suppress_tags = !empty($_POST['suppress_tags']); + $max_comments = (!empty($_POST['max_comments']) ? intval($_POST['max_comments']) : 0); + $max_display_comments = (!empty($_POST['max_display_comments']) ? intval($_POST['max_display_comments']) : 0); + $itemspage_network = (!empty($_POST['itemspage_network']) ? intval($_POST['itemspage_network']) : 0); $itemspage_network_mobile = (!empty($_POST['itemspage_network_mobile']) ? intval($_POST['itemspage_network_mobile']) : 0); - $temppath = (!empty($_POST['temppath']) ? trim($_POST['temppath']) : ''); - $singleuser = (!empty($_POST['singleuser']) ? trim($_POST['singleuser']) : ''); - $only_tag_search = !empty($_POST['only_tag_search']); - $limited_search_scope = !empty($_POST['limited_search_scope']); - $search_age_days = (!empty($_POST['search_age_days']) ? intval($_POST['search_age_days']) : 0); - $compute_circle_counts = !empty($_POST['compute_circle_counts']); - $process_view = !empty($_POST['process_view']); - $archival_days = (!empty($_POST['archival_days']) ? intval($_POST['archival_days']) : 0); - $check_new_version_url = (!empty($_POST['check_new_version_url']) ? trim($_POST['check_new_version_url']) : 'none'); + $temppath = (!empty($_POST['temppath']) ? trim($_POST['temppath']) : ''); + $singleuser = (!empty($_POST['singleuser']) ? trim($_POST['singleuser']) : ''); + $only_tag_search = !empty($_POST['only_tag_search']); + $limited_search_scope = !empty($_POST['limited_search_scope']); + $search_age_days = (!empty($_POST['search_age_days']) ? intval($_POST['search_age_days']) : 0); + $compute_circle_counts = !empty($_POST['compute_circle_counts']); + $process_view = !empty($_POST['process_view']); + $archival_days = (!empty($_POST['archival_days']) ? intval($_POST['archival_days']) : 0); + $check_new_version_url = (!empty($_POST['check_new_version_url']) ? trim($_POST['check_new_version_url']) : 'none'); $worker_queues = (!empty($_POST['worker_queues']) ? intval($_POST['worker_queues']) : 10); $worker_load_cooldown = (!empty($_POST['worker_load_cooldown']) ? intval($_POST['worker_load_cooldown']) : 0); @@ -141,7 +139,6 @@ class Site extends BaseAdmin $cron_interval = (!empty($_POST['cron_interval']) ? intval($_POST['cron_interval']) : 1); $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); - $relay_directly = !empty($_POST['relay_directly']); $relay_scope = (!empty($_POST['relay_scope']) ? trim($_POST['relay_scope']) : ''); @@ -160,7 +157,7 @@ class Site extends BaseAdmin $max_posts_per_author = (!empty($_POST['max_posts_per_author']) ? intval($_POST['max_posts_per_author']) : 0); $sharer_interaction_days = (!empty($_POST['sharer_interaction_days']) ? intval($_POST['sharer_interaction_days']) : 0); - $active_panel = (!empty($_POST['active_panel']) ? "#" . trim($_POST['active_panel']) : ''); + $active_panel = (!empty($_POST['active_panel']) ? "#" . trim($_POST['active_panel']) : ''); $transactionConfig = DI::config()->beginTransaction(); @@ -174,24 +171,24 @@ class Site extends BaseAdmin $diaspora_enabled = false; } - $transactionConfig->set('system', 'maxloadavg' , $maxloadavg); - $transactionConfig->set('system', 'min_memory' , $min_memory); - $transactionConfig->set('system', 'optimize_tables' , $optimize_tables); - $transactionConfig->set('system', 'contact_discovery' , $contact_discovery); - $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', 'poco_requery_days' , $poco_requery_days); - $transactionConfig->set('system', 'poco_discovery' , $poco_discovery); - $transactionConfig->set('system', 'poco_local_search' , $poco_local_search); - $transactionConfig->set('system', 'nodeinfo' , $nodeinfo); + $transactionConfig->set('system', 'maxloadavg', $maxloadavg); + $transactionConfig->set('system', 'min_memory', $min_memory); + $transactionConfig->set('system', 'optimize_tables', $optimize_tables); + $transactionConfig->set('system', 'contact_discovery', $contact_discovery); + $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', 'poco_requery_days', $poco_requery_days); + $transactionConfig->set('system', 'poco_discovery', $poco_discovery); + $transactionConfig->set('system', 'poco_local_search', $poco_local_search); + $transactionConfig->set('system', 'nodeinfo', $nodeinfo); if (DI::config()->isWritable('config', 'sitename')) { $transactionConfig->set('config', 'sitename', $sitename); } - $transactionConfig->set('config', 'sender_email' , $sender_email); - $transactionConfig->set('system', 'suppress_tags' , $suppress_tags); - $transactionConfig->set('system', 'shortcut_icon' , $shortcut_icon); - $transactionConfig->set('system', 'touch_icon' , $touch_icon); + $transactionConfig->set('config', 'sender_email', $sender_email); + $transactionConfig->set('system', 'suppress_tags', $suppress_tags); + $transactionConfig->set('system', 'shortcut_icon', $shortcut_icon); + $transactionConfig->set('system', 'touch_icon', $touch_icon); if ($banner == "") { $transactionConfig->delete('system', 'banner'); @@ -236,60 +233,60 @@ class Site extends BaseAdmin } else { DI::sysmsg()->addNotice(DI::l10n()->t('%s is no valid input for maximum image size', $maximagesize)); } - $transactionConfig->set('system', 'max_image_length' , $maximagelength); - $transactionConfig->set('system', 'jpeg_quality' , $jpegimagequality); + $transactionConfig->set('system', 'max_image_length', $maximagelength); + $transactionConfig->set('system', 'jpeg_quality', $jpegimagequality); - $transactionConfig->set('config', 'register_policy' , $register_policy); - $transactionConfig->set('config', 'max_registered_users' , $max_registered_users); + $transactionConfig->set('config', 'register_policy', $register_policy); + $transactionConfig->set('config', 'max_registered_users', $max_registered_users); $transactionConfig->set('system', 'max_daily_registrations', $daily_registrations); User::setRegisterMethodByUserCount(); - $transactionConfig->set('system', 'account_abandon_days' , $abandon_days); - $transactionConfig->set('config', 'register_text' , $register_text); - $transactionConfig->set('system', 'allowed_sites' , $allowed_sites); - $transactionConfig->set('system', 'allowed_email' , $allowed_email); - $transactionConfig->set('system', 'disallowed_email' , $disallowed_email); - $transactionConfig->set('system', 'forbidden_nicknames' , $forbidden_nicknames); - $transactionConfig->set('system', 'system_actor_name' , $system_actor_name); - $transactionConfig->set('system', 'no_oembed_rich_content' , $no_oembed_rich_content); - $transactionConfig->set('system', 'allowed_oembed' , $allowed_oembed); - $transactionConfig->set('system', 'block_public' , $block_public); - $transactionConfig->set('system', 'publish_all' , $force_publish); - $transactionConfig->set('system', 'newuser_private' , $newuser_private); - $transactionConfig->set('system', 'enotify_no_content' , $enotify_no_content); - $transactionConfig->set('system', 'disable_embedded' , $disable_embedded); + $transactionConfig->set('system', 'account_abandon_days', $abandon_days); + $transactionConfig->set('config', 'register_text', $register_text); + $transactionConfig->set('system', 'allowed_sites', $allowed_sites); + $transactionConfig->set('system', 'allowed_email', $allowed_email); + $transactionConfig->set('system', 'disallowed_email', $disallowed_email); + $transactionConfig->set('system', 'forbidden_nicknames', $forbidden_nicknames); + $transactionConfig->set('system', 'system_actor_name', $system_actor_name); + $transactionConfig->set('system', 'no_oembed_rich_content', $no_oembed_rich_content); + $transactionConfig->set('system', 'allowed_oembed', $allowed_oembed); + $transactionConfig->set('system', 'block_public', $block_public); + $transactionConfig->set('system', 'publish_all', $force_publish); + $transactionConfig->set('system', 'newuser_private', $newuser_private); + $transactionConfig->set('system', 'enotify_no_content', $enotify_no_content); + $transactionConfig->set('system', 'disable_embedded', $disable_embedded); $transactionConfig->set('system', 'allow_users_remote_self', $allow_users_remote_self); - $transactionConfig->set('system', 'allow_relay_channels' , $allow_relay_channels); - $transactionConfig->set('system', 'adjust_poll_frequency' , $adjust_poll_frequency); - $transactionConfig->set('system', 'min_poll_interval' , $min_poll_interval); - $transactionConfig->set('system', 'explicit_content' , $explicit_content); - $transactionConfig->set('system', 'local_search' , $local_search); - $transactionConfig->set('system', 'blocked_tags' , Strings::cleanTags($blocked_tags)); - $transactionConfig->set('system', 'cache_contact_avatar' , $cache_contact_avatar); - $transactionConfig->set('system', 'check_new_version_url' , $check_new_version_url); + $transactionConfig->set('system', 'allow_relay_channels', $allow_relay_channels); + $transactionConfig->set('system', 'adjust_poll_frequency', $adjust_poll_frequency); + $transactionConfig->set('system', 'min_poll_interval', $min_poll_interval); + $transactionConfig->set('system', 'explicit_content', $explicit_content); + $transactionConfig->set('system', 'local_search', $local_search); + $transactionConfig->set('system', 'blocked_tags', Strings::cleanTags($blocked_tags)); + $transactionConfig->set('system', 'cache_contact_avatar', $cache_contact_avatar); + $transactionConfig->set('system', 'check_new_version_url', $check_new_version_url); $transactionConfig->set('system', 'block_extended_register', !$enable_multi_reg); - $transactionConfig->set('system', 'no_openid' , !$enable_openid); - $transactionConfig->set('system', 'no_regfullname' , !$enable_regfullname); - $transactionConfig->set('system', 'register_notification' , $register_notification); - $transactionConfig->set('system', 'community_page_style' , $community_page_style); + $transactionConfig->set('system', 'no_openid', !$enable_openid); + $transactionConfig->set('system', 'no_regfullname', !$enable_regfullname); + $transactionConfig->set('system', 'register_notification', $register_notification); + $transactionConfig->set('system', 'community_page_style', $community_page_style); $transactionConfig->set('system', 'max_author_posts_community_page', $max_author_posts_community_page); $transactionConfig->set('system', 'max_server_posts_community_page', $max_server_posts_community_page); - $transactionConfig->set('system', 'verifyssl' , $verifyssl); - $transactionConfig->set('system', 'proxyuser' , $proxyuser); - $transactionConfig->set('system', 'proxy' , $proxy); - $transactionConfig->set('system', 'curl_timeout' , $timeout); - $transactionConfig->set('system', 'imap_disabled' , !$mail_enabled && function_exists('imap_open')); - $transactionConfig->set('system', 'diaspora_enabled' , $diaspora_enabled); + $transactionConfig->set('system', 'verifyssl', $verifyssl); + $transactionConfig->set('system', 'proxyuser', $proxyuser); + $transactionConfig->set('system', 'proxy', $proxy); + $transactionConfig->set('system', 'curl_timeout', $timeout); + $transactionConfig->set('system', 'imap_disabled', !$mail_enabled && function_exists('imap_open')); + $transactionConfig->set('system', 'diaspora_enabled', $diaspora_enabled); - $transactionConfig->set('config', 'private_addons' , $private_addons); + $transactionConfig->set('config', 'private_addons', $private_addons); - $transactionConfig->set('system', 'force_ssl' , $force_ssl); - $transactionConfig->set('system', 'hide_help' , !$show_help); + $transactionConfig->set('system', 'force_ssl', $force_ssl); + $transactionConfig->set('system', 'hide_help', !$show_help); - $transactionConfig->set('system', 'dbclean' , $dbclean); - $transactionConfig->set('system', 'dbclean-expire-days' , $dbclean_expire_days); + $transactionConfig->set('system', 'dbclean', $dbclean); + $transactionConfig->set('system', 'dbclean-expire-days', $dbclean_expire_days); $transactionConfig->set('system', 'dbclean_expire_conversation', $dbclean_expire_conv); if ($dbclean_unclaimed == 0) { @@ -316,28 +313,28 @@ class Site extends BaseAdmin $transactionConfig->set('system', 'process_view', $process_view); $transactionConfig->set('system', 'archival_days', $archival_days); - $transactionConfig->set('system', 'worker_queues' , $worker_queues); + $transactionConfig->set('system', 'worker_queues', $worker_queues); $transactionConfig->set('system', 'worker_load_cooldown', $worker_load_cooldown); - $transactionConfig->set('system', 'worker_fastlane' , $worker_fastlane); - $transactionConfig->set('system', 'decoupled_receiver' , $decoupled_receiver); - $transactionConfig->set('system', 'cron_interval' , max($cron_interval, 1)); - $transactionConfig->set('system', 'worker_defer_limit' , $worker_defer_limit); - $transactionConfig->set('system', 'worker_fetch_limit' , max($worker_fetch_limit, 1)); - - $transactionConfig->set('system', 'relay_directly' , $relay_directly); - $transactionConfig->set('system', 'relay_scope' , $relay_scope); - $transactionConfig->set('system', 'relay_server_tags' , Strings::cleanTags($relay_server_tags)); - $transactionConfig->set('system', 'relay_deny_tags' , Strings::cleanTags($relay_deny_tags)); - $transactionConfig->set('system', 'relay_max_tags' , $relay_max_tags); - $transactionConfig->set('system', 'relay_user_tags' , $relay_user_tags); - $transactionConfig->set('system', 'relay_deny_undetected_language', $relay_deny_undetected_language); - $transactionConfig->set('system', 'relay_language_quality' , $relay_language_quality); - $transactionConfig->set('system', 'relay_languages' , max($relay_languages, 1)); + $transactionConfig->set('system', 'worker_fastlane', $worker_fastlane); + $transactionConfig->set('system', 'decoupled_receiver', $decoupled_receiver); + $transactionConfig->set('system', 'cron_interval', max($cron_interval, 1)); + $transactionConfig->set('system', 'worker_defer_limit', $worker_defer_limit); + $transactionConfig->set('system', 'worker_fetch_limit', max($worker_fetch_limit, 1)); - $transactionConfig->set('channel', 'engagement_hours' , $engagement_hours); - $transactionConfig->set('channel', 'engagement_post_limit' , $engagement_post_limit); - $transactionConfig->set('channel', 'interaction_score_days' , $interaction_score_days); - $transactionConfig->set('channel', 'max_posts_per_author' , $max_posts_per_author); + $transactionConfig->set('system', 'relay_directly', $relay_directly); + $transactionConfig->set('system', 'relay_scope', $relay_scope); + $transactionConfig->set('system', 'relay_server_tags', Strings::cleanTags($relay_server_tags)); + $transactionConfig->set('system', 'relay_deny_tags', Strings::cleanTags($relay_deny_tags)); + $transactionConfig->set('system', 'relay_max_tags', $relay_max_tags); + $transactionConfig->set('system', 'relay_user_tags', $relay_user_tags); + $transactionConfig->set('system', 'relay_deny_undetected_language', $relay_deny_undetected_language); + $transactionConfig->set('system', 'relay_language_quality', $relay_language_quality); + $transactionConfig->set('system', 'relay_languages', max($relay_languages, 1)); + + $transactionConfig->set('channel', 'engagement_hours', $engagement_hours); + $transactionConfig->set('channel', 'engagement_post_limit', $engagement_post_limit); + $transactionConfig->set('channel', 'interaction_score_days', $interaction_score_days); + $transactionConfig->set('channel', 'max_posts_per_author', $max_posts_per_author); $transactionConfig->set('channel', 'sharer_interaction_days', $sharer_interaction_days); $transactionConfig->commit(); @@ -359,10 +356,10 @@ class Site extends BaseAdmin } /* Installed themes */ - $theme_choices = []; - $theme_choices_mobile = []; + $theme_choices = []; + $theme_choices_mobile = []; $theme_choices_mobile['---'] = DI::l10n()->t('No special theme for mobile devices'); - $files = glob('view/theme/*'); + $files = glob('view/theme/*'); if (is_array($files)) { $allowed_theme_list = DI::config()->get('system', 'allowed_themes'); @@ -399,7 +396,7 @@ class Site extends BaseAdmin /* get user names to make the install a personal install of X */ // @TODO Move to Model\User::getNames() - $user_names = []; + $user_names = []; $user_names['---'] = DI::l10n()->t('Multi user instance'); $usersStmt = DBA::select('user', ['username', 'nickname'], ['account_removed' => 0, 'account_expired' => 0]); @@ -423,20 +420,20 @@ class Site extends BaseAdmin /* Register policy */ $register_choices = [ - Register::CLOSED => DI::l10n()->t('Closed'), + Register::CLOSED => DI::l10n()->t('Closed'), Register::APPROVE => DI::l10n()->t('Requires approval'), - Register::OPEN => DI::l10n()->t('Open') + Register::OPEN => DI::l10n()->t('Open') ]; $check_git_version_choices = [ - 'none' => DI::l10n()->t('Don\'t check'), - 'stable' => DI::l10n()->t('check the stable version'), + 'none' => DI::l10n()->t('Don\'t check'), + 'stable' => DI::l10n()->t('check the stable version'), 'develop' => DI::l10n()->t('check the development version') ]; $discovery_choices = [ - Contact\Relation::DISCOVERY_NONE => DI::l10n()->t('none'), - Contact\Relation::DISCOVERY_LOCAL => DI::l10n()->t('Local contacts'), + Contact\Relation::DISCOVERY_NONE => DI::l10n()->t('none'), + Contact\Relation::DISCOVERY_LOCAL => DI::l10n()->t('Local contacts'), Contact\Relation::DISCOVERY_INTERACTOR => DI::l10n()->t('Interactors'), // "All" is deactivated until we are sure not to put too much stress on the fediverse with this // ContactRelation::DISCOVERY_ALL => DI::l10n()->t('All'), @@ -469,119 +466,119 @@ class Site extends BaseAdmin '$relocate_cmd' => DI::l10n()->t('(Friendica directory)# bin/console relocate https://newdomain.com'), // name, label, value, help string, extra data... - '$sitename' => ['sitename', DI::l10n()->t('Site name'), DI::config()->get('config', 'sitename'), !DI::config()->isWritable('config', 'sitename') ? DI::l10n()->t('Read-only because it is set by an environment variable') : '', '', !DI::config()->isWritable('config', 'sitename') ? 'disabled' : ''], - '$sender_email' => ['sender_email', DI::l10n()->t('Sender Email'), DI::config()->get('config', 'sender_email'), DI::l10n()->t('The email address your server shall use to send notification emails from.'), '', '', 'email'], + '$sitename' => ['sitename', DI::l10n()->t('Site name'), DI::config()->get('config', 'sitename'), !DI::config()->isWritable('config', 'sitename') ? DI::l10n()->t('Read-only because it is set by an environment variable') : '', '', !DI::config()->isWritable('config', 'sitename') ? 'disabled' : ''], + '$sender_email' => ['sender_email', DI::l10n()->t('Sender Email'), DI::config()->get('config', 'sender_email'), DI::l10n()->t('The email address your server shall use to send notification emails from.'), '', '', 'email'], '$system_actor_name' => ['system_actor_name', DI::l10n()->t('Name of the system actor'), User::getActorName(), DI::l10n()->t("Name of the internal system account that is used to perform ActivityPub requests. This must be an unused username. If set, this can't be changed again.")], - '$banner' => ['banner', DI::l10n()->t('Banner/Logo'), $banner, ''], - '$email_banner' => ['email_banner', DI::l10n()->t('Email Banner/Logo'), $email_banner, ''], - '$shortcut_icon' => ['shortcut_icon', DI::l10n()->t('Shortcut icon'), DI::config()->get('system', 'shortcut_icon'), DI::l10n()->t('Link to an icon that will be used for browsers.')], - '$touch_icon' => ['touch_icon', DI::l10n()->t('Touch icon'), DI::config()->get('system', 'touch_icon'), DI::l10n()->t('Link to an icon that will be used for tablets and mobiles.')], - '$additional_info' => ['additional_info', DI::l10n()->t('Additional Info'), $additional_info, DI::l10n()->t('For public servers: you can add additional information here that will be listed at %s/servers.', Search::getGlobalDirectory())], - '$language' => ['language', DI::l10n()->t('System language'), DI::config()->get('system', 'language'), !DI::config()->isWritable('system', 'language') ? DI::l10n()->t("Read-only because it is set by an environment variable") : '', $lang_choices, !DI::config()->isWritable('system', 'language') ? 'disabled' : ''], - '$theme' => ['theme', DI::l10n()->t('System theme'), DI::config()->get('system', 'theme'), DI::l10n()->t('Default system theme - may be over-ridden by user profiles - Change default theme settings', DI::baseUrl() . '/admin/themes'), $theme_choices], - '$theme_mobile' => ['theme_mobile', DI::l10n()->t('Mobile system theme'), DI::config()->get('system', 'mobile-theme', '---'), DI::l10n()->t('Theme for mobile devices'), $theme_choices_mobile], - '$force_ssl' => ['force_ssl', DI::l10n()->t('Force SSL'), DI::config()->get('system', 'force_ssl'), DI::l10n()->t('Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops.')], - '$show_help' => ['show_help', DI::l10n()->t('Show help entry from navigation menu'), !DI::config()->get('system', 'hide_help'), DI::l10n()->t('Displays the menu entry for the Help pages from the navigation menu. It is always accessible by calling /help directly.')], - '$singleuser' => ['singleuser', DI::l10n()->t('Single user instance'), DI::config()->get('system', 'singleuser', '---'), DI::l10n()->t('Make this instance multi-user or single-user for the named user'), $user_names], + '$banner' => ['banner', DI::l10n()->t('Banner/Logo'), $banner, ''], + '$email_banner' => ['email_banner', DI::l10n()->t('Email Banner/Logo'), $email_banner, ''], + '$shortcut_icon' => ['shortcut_icon', DI::l10n()->t('Shortcut icon'), DI::config()->get('system', 'shortcut_icon'), DI::l10n()->t('Link to an icon that will be used for browsers.')], + '$touch_icon' => ['touch_icon', DI::l10n()->t('Touch icon'), DI::config()->get('system', 'touch_icon'), DI::l10n()->t('Link to an icon that will be used for tablets and mobiles.')], + '$additional_info' => ['additional_info', DI::l10n()->t('Additional Info'), $additional_info, DI::l10n()->t('For public servers: you can add additional information here that will be listed at %s/servers.', Search::getGlobalDirectory())], + '$language' => ['language', DI::l10n()->t('System language'), DI::config()->get('system', 'language'), !DI::config()->isWritable('system', 'language') ? DI::l10n()->t("Read-only because it is set by an environment variable") : '', $lang_choices, !DI::config()->isWritable('system', 'language') ? 'disabled' : ''], + '$theme' => ['theme', DI::l10n()->t('System theme'), DI::config()->get('system', 'theme'), DI::l10n()->t('Default system theme - may be over-ridden by user profiles - Change default theme settings', DI::baseUrl() . '/admin/themes'), $theme_choices], + '$theme_mobile' => ['theme_mobile', DI::l10n()->t('Mobile system theme'), DI::config()->get('system', 'mobile-theme', '---'), DI::l10n()->t('Theme for mobile devices'), $theme_choices_mobile], + '$force_ssl' => ['force_ssl', DI::l10n()->t('Force SSL'), DI::config()->get('system', 'force_ssl'), DI::l10n()->t('Force all Non-SSL requests to SSL - Attention: on some systems it could lead to endless loops.')], + '$show_help' => ['show_help', DI::l10n()->t('Show help entry from navigation menu'), !DI::config()->get('system', 'hide_help'), DI::l10n()->t('Displays the menu entry for the Help pages from the navigation menu. It is always accessible by calling /help directly.')], + '$singleuser' => ['singleuser', DI::l10n()->t('Single user instance'), DI::config()->get('system', 'singleuser', '---'), DI::l10n()->t('Make this instance multi-user or single-user for the named user'), $user_names], - '$maximagesize' => ['maximagesize', DI::l10n()->t('Maximum image size'), DI::config()->get('system', 'maximagesize'), DI::l10n()->t('Maximum size in bytes of uploaded images. Default is 0, which means no limits. You can put k, m, or g behind the desired value for KiB, MiB, GiB, respectively. + '$maximagesize' => ['maximagesize', DI::l10n()->t('Maximum image size'), DI::config()->get('system', 'maximagesize'), DI::l10n()->t('Maximum size in bytes of uploaded images. Default is 0, which means no limits. You can put k, m, or g behind the desired value for KiB, MiB, GiB, respectively. The value of upload_max_filesize in your PHP.ini needs be set to at least the desired limit. Currently upload_max_filesize is set to %s (%s byte)', Strings::formatBytes(Strings::getBytesFromShorthand(ini_get('upload_max_filesize'))), Strings::getBytesFromShorthand(ini_get('upload_max_filesize'))), - '', 'pattern="\d+(?:\s*[kmg])?"'], + '', 'pattern="\d+(?:\s*[kmg])?"'], '$maximagelength' => ['maximagelength', DI::l10n()->t('Maximum image length'), DI::config()->get('system', 'max_image_length'), DI::l10n()->t('Maximum length in pixels of the longest side of uploaded images. Default is -1, which means no limits.')], '$jpegimagequality' => ['jpegimagequality', DI::l10n()->t('JPEG image quality'), DI::config()->get('system', 'jpeg_quality'), DI::l10n()->t('Uploaded JPEGS will be saved at this quality setting [0-100]. Default is 100, which is full quality.')], '$maxfilesize' => ['maxfilesize', DI::l10n()->t('Maximum media file size'), DI::config()->get('system', 'maxfilesize'), DI::l10n()->t('Maximum size in bytes of uploaded media files. Default is 0, which means no limits. You can put k, m, or g behind the desired value for KiB, MiB, GiB, respectively. The value of upload_max_filesize in your PHP.ini needs be set to at least the desired limit. Currently upload_max_filesize is set to %s (%s byte)', Strings::formatBytes(Strings::getBytesFromShorthand(ini_get('upload_max_filesize'))), Strings::getBytesFromShorthand(ini_get('upload_max_filesize'))), - '', 'pattern="\d+(?:\s*[kmg])?"'], + '', 'pattern="\d+(?:\s*[kmg])?"'], - '$register_policy' => ['register_policy', DI::l10n()->t('Register policy'), DI::config()->get('config', 'register_policy'), '', $register_choices], - '$max_registered_users' => ['max_registered_users', DI::l10n()->t('Maximum Users'), DI::config()->get('config', 'max_registered_users'), DI::l10n()->t('If defined, the register policy is automatically closed when the given number of users is reached and reopens the registry when the number drops below the limit. It only works when the policy is set to open or close, but not when the policy is set to approval.')], - '$daily_registrations' => ['max_daily_registrations', DI::l10n()->t('Maximum Daily Registrations'), DI::config()->get('system', 'max_daily_registrations'), DI::l10n()->t('If registration is permitted above, this sets the maximum number of new user registrations to accept per day. If register is set to closed, this setting has no effect.')], - '$register_text' => ['register_text', DI::l10n()->t('Register text'), DI::config()->get('config', 'register_text'), DI::l10n()->t('Will be displayed prominently on the registration page. You can use BBCode here.')], - '$forbidden_nicknames' => ['forbidden_nicknames', DI::l10n()->t('Forbidden Nicknames'), DI::config()->get('system', 'forbidden_nicknames'), DI::l10n()->t('Comma separated list of nicknames that are forbidden from registration. Preset is a list of role names according RFC 2142.')], - '$abandon_days' => ['abandon_days', DI::l10n()->t('Accounts abandoned after x days'), DI::config()->get('system', 'account_abandon_days'), DI::l10n()->t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')], - '$allowed_sites' => ['allowed_sites', DI::l10n()->t('Allowed friend domains'), DI::config()->get('system', 'allowed_sites'), DI::l10n()->t('Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains')], - '$allowed_email' => ['allowed_email', DI::l10n()->t('Allowed email domains'), DI::config()->get('system', 'allowed_email'), DI::l10n()->t('Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains')], - '$disallowed_email' => ['disallowed_email', DI::l10n()->t('Disallowed email domains'), DI::config()->get('system', 'disallowed_email'), DI::l10n()->t('Comma separated list of domains which are rejected as email addresses for registrations to this site. Wildcards are accepted.')], - '$no_oembed_rich_content' => ['no_oembed_rich_content', DI::l10n()->t('No OEmbed rich content'), DI::config()->get('system', 'no_oembed_rich_content'), DI::l10n()->t('Don\'t show the rich content (e.g. embedded PDF), except from the domains listed below.')], - '$allowed_oembed' => ['allowed_oembed', DI::l10n()->t('Trusted third-party domains'), DI::config()->get('system', 'allowed_oembed'), DI::l10n()->t('Comma separated list of domains from which content is allowed to be embedded in posts like with OEmbed. All sub-domains of the listed domains are allowed as well.')], - '$block_public' => ['block_public', DI::l10n()->t('Block public'), DI::config()->get('system', 'block_public'), DI::l10n()->t('Check to block public access to all otherwise public personal pages on this site unless you are currently logged in.')], - '$force_publish' => ['publish_all', DI::l10n()->t('Force publish'), DI::config()->get('system', 'publish_all'), DI::l10n()->t('Check to force all profiles on this site to be listed in the site directory.') . '' . DI::l10n()->t('Enabling this may violate privacy laws like the GDPR') . ''], - '$global_directory' => ['directory', DI::l10n()->t('Global directory URL'), DI::config()->get('system', 'directory'), DI::l10n()->t('URL to the global directory. If this is not set, the global directory is completely unavailable to the application.')], - '$newuser_private' => ['newuser_private', DI::l10n()->t('Private posts by default for new users'), DI::config()->get('system', 'newuser_private'), DI::l10n()->t('Set default post permissions for all new members to the default privacy circle rather than public.')], - '$enotify_no_content' => ['enotify_no_content', DI::l10n()->t('Don\'t include post content in email notifications'), DI::config()->get('system', 'enotify_no_content'), DI::l10n()->t('Don\'t include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure.')], - '$private_addons' => ['private_addons', DI::l10n()->t('Disallow public access to addons listed in the apps menu.'), DI::config()->get('config', 'private_addons'), DI::l10n()->t('Checking this box will restrict addons listed in the apps menu to members only.')], - '$disable_embedded' => ['disable_embedded', DI::l10n()->t('Don\'t embed private images in posts'), DI::config()->get('system', 'disable_embedded'), DI::l10n()->t('Don\'t replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while.')], - '$explicit_content' => ['explicit_content', DI::l10n()->t('Explicit Content'), DI::config()->get('system', 'explicit_content'), DI::l10n()->t('Set this to announce that your node is used mostly for explicit content that might not be suited for minors. This information will be published in the node information and might be used, e.g. by the global directory, to filter your node from listings of nodes to join. Additionally a note about this will be shown at the user registration page.')], - '$local_search' => ['local_search', DI::l10n()->t('Only local search'), DI::config()->get('system', 'local_search'), DI::l10n()->t('Blocks search for users who are not logged in to prevent crawlers from blocking your system.')], - '$blocked_tags' => ['blocked_tags', DI::l10n()->t('Blocked tags for trending tags'), DI::config()->get('system', 'blocked_tags'), DI::l10n()->t("Comma separated list of hashtags that shouldn't be displayed in the trending tags.")], - '$cache_contact_avatar' => ['cache_contact_avatar', DI::l10n()->t('Cache contact avatars'), DI::config()->get('system', 'cache_contact_avatar'), DI::l10n()->t('Locally store the avatar pictures of the contacts. This uses a lot of storage space but it increases the performance.')], - '$allow_users_remote_self'=> ['allow_users_remote_self', DI::l10n()->t('Allow Users to set remote_self'), DI::config()->get('system', 'allow_users_remote_self'), DI::l10n()->t('With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream.')], - '$allow_relay_channels' => ['allow_relay_channels', DI::l10n()->t('Allow Users to set up relay channels'), DI::config()->get('system', 'allow_relay_channels'), DI::l10n()->t('If enabled, it is possible to create relay users that are used to reshare content based on user defined channels.')], - '$adjust_poll_frequency' => ['adjust_poll_frequency', DI::l10n()->t('Adjust the feed poll frequency'), DI::config()->get('system', 'adjust_poll_frequency'), DI::l10n()->t('Automatically detect and set the best feed poll frequency.')], - '$min_poll_interval' => ['min_poll_interval', DI::l10n()->t('Minimum poll interval'), DI::config()->get('system', 'min_poll_interval'), DI::l10n()->t('Minimal distance in minutes between two polls for mail and feed contacts. Reasonable values are between 1 and 59.')], - '$enable_multi_reg' => ['enable_multi_reg', DI::l10n()->t('Enable multiple registrations'), !DI::config()->get('system', 'block_extended_register'), DI::l10n()->t('Enable users to register additional accounts for use as pages.')], - '$enable_openid' => ['enable_openid', DI::l10n()->t('Enable OpenID'), !DI::config()->get('system', 'no_openid'), DI::l10n()->t('Enable OpenID support for registration and logins.')], - '$enable_regfullname' => ['enable_regfullname', DI::l10n()->t('Enable full name check'), !DI::config()->get('system', 'no_regfullname'), DI::l10n()->t('Prevents users from registering with a display name with fewer than two parts separated by spaces.')], - '$register_notification' => ['register_notification', DI::l10n()->t('Email administrators on new registration'), DI::config()->get('system', 'register_notification'), DI::l10n()->t('If enabled and the system is set to an open registration, an email for each new registration is sent to the administrators.')], - '$community_page_style' => ['community_page_style', DI::l10n()->t('Community pages for visitors'), DI::config()->get('system', 'community_page_style'), DI::l10n()->t('Which community pages should be available for visitors. Local users always see both pages.'), $community_page_style_choices], + '$register_policy' => ['register_policy', DI::l10n()->t('Register policy'), DI::config()->get('config', 'register_policy'), '', $register_choices], + '$max_registered_users' => ['max_registered_users', DI::l10n()->t('Maximum Users'), DI::config()->get('config', 'max_registered_users'), DI::l10n()->t('If defined, the register policy is automatically closed when the given number of users is reached and reopens the registry when the number drops below the limit. It only works when the policy is set to open or close, but not when the policy is set to approval.')], + '$daily_registrations' => ['max_daily_registrations', DI::l10n()->t('Maximum Daily Registrations'), DI::config()->get('system', 'max_daily_registrations'), DI::l10n()->t('If registration is permitted above, this sets the maximum number of new user registrations to accept per day. If register is set to closed, this setting has no effect.')], + '$register_text' => ['register_text', DI::l10n()->t('Register text'), DI::config()->get('config', 'register_text'), DI::l10n()->t('Will be displayed prominently on the registration page. You can use BBCode here.')], + '$forbidden_nicknames' => ['forbidden_nicknames', DI::l10n()->t('Forbidden Nicknames'), DI::config()->get('system', 'forbidden_nicknames'), DI::l10n()->t('Comma separated list of nicknames that are forbidden from registration. Preset is a list of role names according RFC 2142.')], + '$abandon_days' => ['abandon_days', DI::l10n()->t('Accounts abandoned after x days'), DI::config()->get('system', 'account_abandon_days'), DI::l10n()->t('Will not waste system resources polling external sites for abandonded accounts. Enter 0 for no time limit.')], + '$allowed_sites' => ['allowed_sites', DI::l10n()->t('Allowed friend domains'), DI::config()->get('system', 'allowed_sites'), DI::l10n()->t('Comma separated list of domains which are allowed to establish friendships with this site. Wildcards are accepted. Empty to allow any domains')], + '$allowed_email' => ['allowed_email', DI::l10n()->t('Allowed email domains'), DI::config()->get('system', 'allowed_email'), DI::l10n()->t('Comma separated list of domains which are allowed in email addresses for registrations to this site. Wildcards are accepted. Empty to allow any domains')], + '$disallowed_email' => ['disallowed_email', DI::l10n()->t('Disallowed email domains'), DI::config()->get('system', 'disallowed_email'), DI::l10n()->t('Comma separated list of domains which are rejected as email addresses for registrations to this site. Wildcards are accepted.')], + '$no_oembed_rich_content' => ['no_oembed_rich_content', DI::l10n()->t('No OEmbed rich content'), DI::config()->get('system', 'no_oembed_rich_content'), DI::l10n()->t('Don\'t show the rich content (e.g. embedded PDF), except from the domains listed below.')], + '$allowed_oembed' => ['allowed_oembed', DI::l10n()->t('Trusted third-party domains'), DI::config()->get('system', 'allowed_oembed'), DI::l10n()->t('Comma separated list of domains from which content is allowed to be embedded in posts like with OEmbed. All sub-domains of the listed domains are allowed as well.')], + '$block_public' => ['block_public', DI::l10n()->t('Block public'), DI::config()->get('system', 'block_public'), DI::l10n()->t('Check to block public access to all otherwise public personal pages on this site unless you are currently logged in.')], + '$force_publish' => ['publish_all', DI::l10n()->t('Force publish'), DI::config()->get('system', 'publish_all'), DI::l10n()->t('Check to force all profiles on this site to be listed in the site directory.') . '' . DI::l10n()->t('Enabling this may violate privacy laws like the GDPR') . ''], + '$global_directory' => ['directory', DI::l10n()->t('Global directory URL'), DI::config()->get('system', 'directory'), DI::l10n()->t('URL to the global directory. If this is not set, the global directory is completely unavailable to the application.')], + '$newuser_private' => ['newuser_private', DI::l10n()->t('Private posts by default for new users'), DI::config()->get('system', 'newuser_private'), DI::l10n()->t('Set default post permissions for all new members to the default privacy circle rather than public.')], + '$enotify_no_content' => ['enotify_no_content', DI::l10n()->t('Don\'t include post content in email notifications'), DI::config()->get('system', 'enotify_no_content'), DI::l10n()->t('Don\'t include the content of a post/comment/private message/etc. in the email notifications that are sent out from this site, as a privacy measure.')], + '$private_addons' => ['private_addons', DI::l10n()->t('Disallow public access to addons listed in the apps menu.'), DI::config()->get('config', 'private_addons'), DI::l10n()->t('Checking this box will restrict addons listed in the apps menu to members only.')], + '$disable_embedded' => ['disable_embedded', DI::l10n()->t('Don\'t embed private images in posts'), DI::config()->get('system', 'disable_embedded'), DI::l10n()->t('Don\'t replace locally-hosted private photos in posts with an embedded copy of the image. This means that contacts who receive posts containing private photos will have to authenticate and load each image, which may take a while.')], + '$explicit_content' => ['explicit_content', DI::l10n()->t('Explicit Content'), DI::config()->get('system', 'explicit_content'), DI::l10n()->t('Set this to announce that your node is used mostly for explicit content that might not be suited for minors. This information will be published in the node information and might be used, e.g. by the global directory, to filter your node from listings of nodes to join. Additionally a note about this will be shown at the user registration page.')], + '$local_search' => ['local_search', DI::l10n()->t('Only local search'), DI::config()->get('system', 'local_search'), DI::l10n()->t('Blocks search for users who are not logged in to prevent crawlers from blocking your system.')], + '$blocked_tags' => ['blocked_tags', DI::l10n()->t('Blocked tags for trending tags'), DI::config()->get('system', 'blocked_tags'), DI::l10n()->t("Comma separated list of hashtags that shouldn't be displayed in the trending tags.")], + '$cache_contact_avatar' => ['cache_contact_avatar', DI::l10n()->t('Cache contact avatars'), DI::config()->get('system', 'cache_contact_avatar'), DI::l10n()->t('Locally store the avatar pictures of the contacts. This uses a lot of storage space but it increases the performance.')], + '$allow_users_remote_self' => ['allow_users_remote_self', DI::l10n()->t('Allow Users to set remote_self'), DI::config()->get('system', 'allow_users_remote_self'), DI::l10n()->t('With checking this, every user is allowed to mark every contact as a remote_self in the repair contact dialog. Setting this flag on a contact causes mirroring every posting of that contact in the users stream.')], + '$allow_relay_channels' => ['allow_relay_channels', DI::l10n()->t('Allow Users to set up relay channels'), DI::config()->get('system', 'allow_relay_channels'), DI::l10n()->t('If enabled, it is possible to create relay users that are used to reshare content based on user defined channels.')], + '$adjust_poll_frequency' => ['adjust_poll_frequency', DI::l10n()->t('Adjust the feed poll frequency'), DI::config()->get('system', 'adjust_poll_frequency'), DI::l10n()->t('Automatically detect and set the best feed poll frequency.')], + '$min_poll_interval' => ['min_poll_interval', DI::l10n()->t('Minimum poll interval'), DI::config()->get('system', 'min_poll_interval'), DI::l10n()->t('Minimal distance in minutes between two polls for mail and feed contacts. Reasonable values are between 1 and 59.')], + '$enable_multi_reg' => ['enable_multi_reg', DI::l10n()->t('Enable multiple registrations'), !DI::config()->get('system', 'block_extended_register'), DI::l10n()->t('Enable users to register additional accounts for use as pages.')], + '$enable_openid' => ['enable_openid', DI::l10n()->t('Enable OpenID'), !DI::config()->get('system', 'no_openid'), DI::l10n()->t('Enable OpenID support for registration and logins.')], + '$enable_regfullname' => ['enable_regfullname', DI::l10n()->t('Enable full name check'), !DI::config()->get('system', 'no_regfullname'), DI::l10n()->t('Prevents users from registering with a display name with fewer than two parts separated by spaces.')], + '$register_notification' => ['register_notification', DI::l10n()->t('Email administrators on new registration'), DI::config()->get('system', 'register_notification'), DI::l10n()->t('If enabled and the system is set to an open registration, an email for each new registration is sent to the administrators.')], + '$community_page_style' => ['community_page_style', DI::l10n()->t('Community pages for visitors'), DI::config()->get('system', 'community_page_style'), DI::l10n()->t('Which community pages should be available for visitors. Local users always see both pages.'), $community_page_style_choices], '$max_author_posts_community_page' => ['max_author_posts_community_page', DI::l10n()->t('Posts per user on community page'), DI::config()->get('system', 'max_author_posts_community_page'), DI::l10n()->t('The maximum number of posts per user on the local community page. This is useful, when a single user floods the local community page.')], '$max_server_posts_community_page' => ['max_server_posts_community_page', DI::l10n()->t('Posts per server on community page'), DI::config()->get('system', 'max_server_posts_community_page'), DI::l10n()->t('The maximum number of posts per server on the global community page. This is useful, when posts from a single server flood the global community page.')], - '$mail_able' => function_exists('imap_open'), - '$mail_enabled' => ['mail_enabled', DI::l10n()->t('Enable Mail support'), !DI::config()->get('system', 'imap_disabled', !function_exists('imap_open')), DI::l10n()->t('Enable built-in mail support to poll IMAP folders and to reply via mail.')], - '$mail_not_able' => DI::l10n()->t('Mail support can\'t be enabled because the PHP IMAP module is not installed.'), - '$diaspora_able' => $diaspora_able, - '$diaspora_not_able' => DI::l10n()->t('Diaspora support can\'t be enabled because Friendica was installed into a sub directory.'), - '$diaspora_enabled' => ['diaspora_enabled', DI::l10n()->t('Enable Diaspora support'), DI::config()->get('system', 'diaspora_enabled', $diaspora_able), DI::l10n()->t('Enable built-in Diaspora network compatibility for communicating with diaspora servers.')], - '$verifyssl' => ['verifyssl', DI::l10n()->t('Verify SSL'), DI::config()->get('system', 'verifyssl'), DI::l10n()->t('If you wish, you can turn on strict certificate checking. This will mean you cannot connect (at all) to self-signed SSL sites.')], - '$proxyuser' => ['proxyuser', DI::l10n()->t('Proxy user'), DI::config()->get('system', 'proxyuser'), DI::l10n()->t('User name for the proxy server.')], - '$proxy' => ['proxy', DI::l10n()->t('Proxy URL'), DI::config()->get('system', 'proxy'), DI::l10n()->t('If you want to use a proxy server that Friendica should use to connect to the network, put the URL of the proxy here.')], - '$timeout' => ['timeout', DI::l10n()->t('Network timeout'), DI::config()->get('system', 'curl_timeout'), DI::l10n()->t('Value is in seconds. Set to 0 for unlimited (not recommended).')], - '$maxloadavg' => ['maxloadavg', DI::l10n()->t('Maximum Load Average'), DI::config()->get('system', 'maxloadavg'), DI::l10n()->t('Maximum system load before delivery and poll processes are deferred - default %d.', 20)], - '$min_memory' => ['min_memory', DI::l10n()->t('Minimal Memory'), DI::config()->get('system', 'min_memory'), DI::l10n()->t('Minimal free memory in MB for the worker. Needs access to /proc/meminfo - default 0 (deactivated).')], - '$optimize_tables' => ['optimize_tables', DI::l10n()->t('Periodically optimize tables'), DI::config()->get('system', 'optimize_tables'), DI::l10n()->t('Periodically optimize tables like the cache and the workerqueue')], + '$mail_able' => function_exists('imap_open'), + '$mail_enabled' => ['mail_enabled', DI::l10n()->t('Enable Mail support'), !DI::config()->get('system', 'imap_disabled', !function_exists('imap_open')), DI::l10n()->t('Enable built-in mail support to poll IMAP folders and to reply via mail.')], + '$mail_not_able' => DI::l10n()->t('Mail support can\'t be enabled because the PHP IMAP module is not installed.'), + '$diaspora_able' => $diaspora_able, + '$diaspora_not_able' => DI::l10n()->t('Diaspora support can\'t be enabled because Friendica was installed into a sub directory.'), + '$diaspora_enabled' => ['diaspora_enabled', DI::l10n()->t('Enable Diaspora support'), DI::config()->get('system', 'diaspora_enabled', $diaspora_able), DI::l10n()->t('Enable built-in Diaspora network compatibility for communicating with diaspora servers.')], + '$verifyssl' => ['verifyssl', DI::l10n()->t('Verify SSL'), DI::config()->get('system', 'verifyssl'), DI::l10n()->t('If you wish, you can turn on strict certificate checking. This will mean you cannot connect (at all) to self-signed SSL sites.')], + '$proxyuser' => ['proxyuser', DI::l10n()->t('Proxy user'), DI::config()->get('system', 'proxyuser'), DI::l10n()->t('User name for the proxy server.')], + '$proxy' => ['proxy', DI::l10n()->t('Proxy URL'), DI::config()->get('system', 'proxy'), DI::l10n()->t('If you want to use a proxy server that Friendica should use to connect to the network, put the URL of the proxy here.')], + '$timeout' => ['timeout', DI::l10n()->t('Network timeout'), DI::config()->get('system', 'curl_timeout'), DI::l10n()->t('Value is in seconds. Set to 0 for unlimited (not recommended).')], + '$maxloadavg' => ['maxloadavg', DI::l10n()->t('Maximum Load Average'), DI::config()->get('system', 'maxloadavg'), DI::l10n()->t('Maximum system load before delivery and poll processes are deferred - default %d.', 20)], + '$min_memory' => ['min_memory', DI::l10n()->t('Minimal Memory'), DI::config()->get('system', 'min_memory'), DI::l10n()->t('Minimal free memory in MB for the worker. Needs access to /proc/meminfo - default 0 (deactivated).')], + '$optimize_tables' => ['optimize_tables', DI::l10n()->t('Periodically optimize tables'), DI::config()->get('system', 'optimize_tables'), DI::l10n()->t('Periodically optimize tables like the cache and the workerqueue')], - '$contact_discovery' => ['contact_discovery', DI::l10n()->t('Discover followers/followings from contacts'), DI::config()->get('system', 'contact_discovery'), DI::l10n()->t('If enabled, contacts are checked for their followers and following contacts.') . '
      ' . + '$contact_discovery' => ['contact_discovery', DI::l10n()->t('Discover followers/followings from contacts'), DI::config()->get('system', 'contact_discovery'), DI::l10n()->t('If enabled, contacts are checked for their followers and following contacts.') . '
        ' . '
      • ' . DI::l10n()->t('None - deactivated') . '
      • ' . '
      • ' . DI::l10n()->t('Local contacts - contacts of our local contacts are discovered for their followers/followings.') . '
      • ' . '
      • ' . DI::l10n()->t('Interactors - contacts of our local contacts and contacts who interacted on locally visible postings are discovered for their followers/followings.') . '
      ', $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_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.')], + '$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.')], - '$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_requery_days' => ['poco_requery_days', DI::l10n()->t('Days between requery'), DI::config()->get('system', 'poco_requery_days'), DI::l10n()->t('Number of days after which a server is requeried for their contacts and servers it knows of. This is only used when the discovery is activated.')], - '$poco_local_search' => ['poco_local_search', DI::l10n()->t('Search the local directory'), DI::config()->get('system', 'poco_local_search'), DI::l10n()->t('Search the local directory instead of the global directory. When searching locally, every search will be executed on the global directory in the background. This improves the search results when the search is repeated.')], + '$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_requery_days' => ['poco_requery_days', DI::l10n()->t('Days between requery'), DI::config()->get('system', 'poco_requery_days'), DI::l10n()->t('Number of days after which a server is requeried for their contacts and servers it knows of. This is only used when the discovery is activated.')], + '$poco_local_search' => ['poco_local_search', DI::l10n()->t('Search the local directory'), DI::config()->get('system', 'poco_local_search'), DI::l10n()->t('Search the local directory instead of the global directory. When searching locally, every search will be executed on the global directory in the background. This improves the search results when the search is repeated.')], - '$nodeinfo' => ['nodeinfo', DI::l10n()->t('Publish server information'), DI::config()->get('system', 'nodeinfo'), DI::l10n()->t('If enabled, general server and usage data will be published. The data contains the name and version of the server, number of users with public profiles, number of posts and the activated protocols and connectors. See the-federation.info for details.')], + '$nodeinfo' => ['nodeinfo', DI::l10n()->t('Publish server information'), DI::config()->get('system', 'nodeinfo'), DI::l10n()->t('If enabled, general server and usage data will be published. The data contains the name and version of the server, number of users with public profiles, number of posts and the activated protocols and connectors. See the-federation.info for details.')], - '$check_new_version_url' => ['check_new_version_url', DI::l10n()->t('Check upstream version'), DI::config()->get('system', 'check_new_version_url'), DI::l10n()->t('Enables checking for new Friendica versions at github. If there is a new version, you will be informed in the admin panel overview.'), $check_git_version_choices], - '$suppress_tags' => ['suppress_tags', DI::l10n()->t('Suppress Tags'), DI::config()->get('system', 'suppress_tags'), DI::l10n()->t('Suppress showing a list of hashtags at the end of the posting.')], - '$dbclean' => ['dbclean', DI::l10n()->t('Clean database'), DI::config()->get('system', 'dbclean'), DI::l10n()->t('Remove old remote items, orphaned database records and old content from some other helper tables.')], - '$dbclean_expire_days' => ['dbclean_expire_days', DI::l10n()->t('Lifespan of remote items'), DI::config()->get('system', 'dbclean-expire-days'), DI::l10n()->t('When the database cleanup is enabled, this defines the days after which remote items will be deleted. Own items, and marked or filed items are always kept. 0 disables this behaviour.')], - '$dbclean_unclaimed' => ['dbclean_unclaimed', DI::l10n()->t('Lifespan of unclaimed items'), DI::config()->get('system', 'dbclean-expire-unclaimed'), DI::l10n()->t('When the database cleanup is enabled, this defines the days after which unclaimed remote items (mostly content from the relay) will be deleted. Default value is 90 days. Defaults to the general lifespan value of remote items if set to 0.')], - '$dbclean_expire_conv' => ['dbclean_expire_conv', DI::l10n()->t('Lifespan of raw conversation data'), DI::config()->get('system', 'dbclean_expire_conversation'), DI::l10n()->t('The conversation data is used for ActivityPub, as well as for debug purposes. It should be safe to remove it after 14 days, default is 90 days.')], - '$max_comments' => ['max_comments', DI::l10n()->t('Maximum numbers of comments per post'), DI::config()->get('system', 'max_comments'), DI::l10n()->t('How much comments should be shown for each post? Default value is 100.')], - '$max_display_comments' => ['max_display_comments', DI::l10n()->t('Maximum numbers of comments per post on the display page'), DI::config()->get('system', 'max_display_comments'), DI::l10n()->t('How many comments should be shown on the single view for each post? Default value is 1000.')], - '$itemspage_network' => ['itemspage_network', DI::l10n()->t('Items per page'), DI::config()->get('system', 'itemspage_network'), DI::l10n()->t('Number of items per page in stream pages (network, community, profile/contact statuses, search).')], + '$check_new_version_url' => ['check_new_version_url', DI::l10n()->t('Check upstream version'), DI::config()->get('system', 'check_new_version_url'), DI::l10n()->t('Enables checking for new Friendica versions at github. If there is a new version, you will be informed in the admin panel overview.'), $check_git_version_choices], + '$suppress_tags' => ['suppress_tags', DI::l10n()->t('Suppress Tags'), DI::config()->get('system', 'suppress_tags'), DI::l10n()->t('Suppress showing a list of hashtags at the end of the posting.')], + '$dbclean' => ['dbclean', DI::l10n()->t('Clean database'), DI::config()->get('system', 'dbclean'), DI::l10n()->t('Remove old remote items, orphaned database records and old content from some other helper tables.')], + '$dbclean_expire_days' => ['dbclean_expire_days', DI::l10n()->t('Lifespan of remote items'), DI::config()->get('system', 'dbclean-expire-days'), DI::l10n()->t('When the database cleanup is enabled, this defines the days after which remote items will be deleted. Own items, and marked or filed items are always kept. 0 disables this behaviour.')], + '$dbclean_unclaimed' => ['dbclean_unclaimed', DI::l10n()->t('Lifespan of unclaimed items'), DI::config()->get('system', 'dbclean-expire-unclaimed'), DI::l10n()->t('When the database cleanup is enabled, this defines the days after which unclaimed remote items (mostly content from the relay) will be deleted. Default value is 90 days. Defaults to the general lifespan value of remote items if set to 0.')], + '$dbclean_expire_conv' => ['dbclean_expire_conv', DI::l10n()->t('Lifespan of raw conversation data'), DI::config()->get('system', 'dbclean_expire_conversation'), DI::l10n()->t('The conversation data is used for ActivityPub, as well as for debug purposes. It should be safe to remove it after 14 days, default is 90 days.')], + '$max_comments' => ['max_comments', DI::l10n()->t('Maximum numbers of comments per post'), DI::config()->get('system', 'max_comments'), DI::l10n()->t('How much comments should be shown for each post? Default value is 100.')], + '$max_display_comments' => ['max_display_comments', DI::l10n()->t('Maximum numbers of comments per post on the display page'), DI::config()->get('system', 'max_display_comments'), DI::l10n()->t('How many comments should be shown on the single view for each post? Default value is 1000.')], + '$itemspage_network' => ['itemspage_network', DI::l10n()->t('Items per page'), DI::config()->get('system', 'itemspage_network'), DI::l10n()->t('Number of items per page in stream pages (network, community, profile/contact statuses, search).')], '$itemspage_network_mobile' => ['itemspage_network_mobile', DI::l10n()->t('Items per page for mobile devices'), DI::config()->get('system', 'itemspage_network_mobile'), DI::l10n()->t('Number of items per page in stream pages (network, community, profile/contact statuses, search) for mobile devices.')], - '$temppath' => ['temppath', DI::l10n()->t('Temp path'), DI::config()->get('system', 'temppath'), DI::l10n()->t('If you have a restricted system where the webserver can\'t access the system temp path, enter another path here.')], - '$only_tag_search' => ['only_tag_search', DI::l10n()->t('Only search in tags'), DI::config()->get('system', 'only_tag_search'), DI::l10n()->t('On large systems the text search can slow down the system extremely.')], - '$limited_search_scope' => ['limited_search_scope', DI::l10n()->t('Limited search scope'), DI::config()->get('system', 'limited_search_scope'), DI::l10n()->t('If enabled, searches will only be performed in the data used for the channels and not in all posts.')], - '$search_age_days' => ['search_age_days', DI::l10n()->t('Maximum age of items in the search table'), DI::config()->get('system', 'search_age_days'), DI::l10n()->t('Maximum age of items in the search table in days. Lower values will increase the performance and reduce disk usage. 0 means no age restriction.')], - '$compute_circle_counts' => ['compute_circle_counts', DI::l10n()->t('Generate counts per contact circle when calculating network count'), DI::config()->get('system', 'compute_circle_counts'), DI::l10n()->t('On systems with users that heavily use contact circles the query can be very expensive.')], - '$process_view' => ['process_view', DI::l10n()->t('Process "view" activities'), DI::config()->get('system', 'process_view'), DI::l10n()->t('"view" activities are mostly geberated by Peertube systems. Per default they are not processed for performance reasons. Only activate this option on performant system.')], - '$archival_days' => ['archival_days', DI::l10n()->t('Days, after which a contact is archived'), DI::config()->get('system', 'archival_days'), DI::l10n()->t('Number of days that we try to deliver content or to update the contact data before we archive a contact.')], + '$temppath' => ['temppath', DI::l10n()->t('Temp path'), DI::config()->get('system', 'temppath'), DI::l10n()->t('If you have a restricted system where the webserver can\'t access the system temp path, enter another path here.')], + '$only_tag_search' => ['only_tag_search', DI::l10n()->t('Only search in tags'), DI::config()->get('system', 'only_tag_search'), DI::l10n()->t('On large systems the text search can slow down the system extremely.')], + '$limited_search_scope' => ['limited_search_scope', DI::l10n()->t('Limited search scope'), DI::config()->get('system', 'limited_search_scope'), DI::l10n()->t('If enabled, searches will only be performed in the data used for the channels and not in all posts.')], + '$search_age_days' => ['search_age_days', DI::l10n()->t('Maximum age of items in the search table'), DI::config()->get('system', 'search_age_days'), DI::l10n()->t('Maximum age of items in the search table in days. Lower values will increase the performance and reduce disk usage. 0 means no age restriction.')], + '$compute_circle_counts' => ['compute_circle_counts', DI::l10n()->t('Generate counts per contact circle when calculating network count'), DI::config()->get('system', 'compute_circle_counts'), DI::l10n()->t('On systems with users that heavily use contact circles the query can be very expensive.')], + '$process_view' => ['process_view', DI::l10n()->t('Process "view" activities'), DI::config()->get('system', 'process_view'), DI::l10n()->t('"view" activities are mostly geberated by Peertube systems. Per default they are not processed for performance reasons. Only activate this option on performant system.')], + '$archival_days' => ['archival_days', DI::l10n()->t('Days, after which a contact is archived'), DI::config()->get('system', 'archival_days'), DI::l10n()->t('Number of days that we try to deliver content or to update the contact data before we archive a contact.')], - '$worker_queues' => ['worker_queues', DI::l10n()->t('Maximum number of parallel workers'), DI::config()->get('system', 'worker_queues'), DI::l10n()->t('On shared hosters set this to %d. On larger systems, values of %d are great. Default value is %d.', 5, 20, 10)], - '$worker_load_cooldown' => ['worker_load_cooldown', DI::l10n()->t('Maximum load for workers'), DI::config()->get('system', 'worker_load_cooldown'), DI::l10n()->t('Maximum load that causes a cooldown before each worker function call.')], - '$worker_fastlane' => ['worker_fastlane', DI::l10n()->t('Enable fastlane'), DI::config()->get('system', 'worker_fastlane'), DI::l10n()->t('When enabed, the fastlane mechanism starts an additional worker if processes with higher priority are blocked by processes of lower priority.')], - '$decoupled_receiver' => ['decoupled_receiver', DI::l10n()->t('Decoupled receiver'), DI::config()->get('system', 'decoupled_receiver'), DI::l10n()->t('Decouple incoming ActivityPub posts by processing them in the background via a worker process. Only enable this on fast systems.')], - '$cron_interval' => ['cron_interval', DI::l10n()->t('Cron interval'), DI::config()->get('system', 'cron_interval'), DI::l10n()->t('Minimal period in minutes between two calls of the "Cron" worker job.')], - '$worker_defer_limit' => ['worker_defer_limit', DI::l10n()->t('Worker defer limit'), DI::config()->get('system', 'worker_defer_limit'), DI::l10n()->t('Per default the systems tries delivering for 15 times before dropping it.')], - '$worker_fetch_limit' => ['worker_fetch_limit', DI::l10n()->t('Worker fetch limit'), DI::config()->get('system', 'worker_fetch_limit'), DI::l10n()->t('Number of worker tasks that are fetched in a single query. Higher values should increase the performance, too high values will mostly likely decrease it. Only change it, when you know how to measure the performance of your system.')], + '$worker_queues' => ['worker_queues', DI::l10n()->t('Maximum number of parallel workers'), DI::config()->get('system', 'worker_queues'), DI::l10n()->t('On shared hosters set this to %d. On larger systems, values of %d are great. Default value is %d.', 5, 20, 10)], + '$worker_load_cooldown' => ['worker_load_cooldown', DI::l10n()->t('Maximum load for workers'), DI::config()->get('system', 'worker_load_cooldown'), DI::l10n()->t('Maximum load that causes a cooldown before each worker function call.')], + '$worker_fastlane' => ['worker_fastlane', DI::l10n()->t('Enable fastlane'), DI::config()->get('system', 'worker_fastlane'), DI::l10n()->t('When enabed, the fastlane mechanism starts an additional worker if processes with higher priority are blocked by processes of lower priority.')], + '$decoupled_receiver' => ['decoupled_receiver', DI::l10n()->t('Decoupled receiver'), DI::config()->get('system', 'decoupled_receiver'), DI::l10n()->t('Decouple incoming ActivityPub posts by processing them in the background via a worker process. Only enable this on fast systems.')], + '$cron_interval' => ['cron_interval', DI::l10n()->t('Cron interval'), DI::config()->get('system', 'cron_interval'), DI::l10n()->t('Minimal period in minutes between two calls of the "Cron" worker job.')], + '$worker_defer_limit' => ['worker_defer_limit', DI::l10n()->t('Worker defer limit'), DI::config()->get('system', 'worker_defer_limit'), DI::l10n()->t('Per default the systems tries delivering for 15 times before dropping it.')], + '$worker_fetch_limit' => ['worker_fetch_limit', DI::l10n()->t('Worker fetch limit'), DI::config()->get('system', 'worker_fetch_limit'), DI::l10n()->t('Number of worker tasks that are fetched in a single query. Higher values should increase the performance, too high values will mostly likely decrease it. Only change it, when you know how to measure the performance of your system.')], '$relay_directly' => ['relay_directly', DI::l10n()->t('Direct relay transfer'), DI::config()->get('system', 'relay_directly'), DI::l10n()->t('Enables the direct transfer to other servers without using the relay servers')], '$relay_scope' => ['relay_scope', DI::l10n()->t('Relay scope'), DI::config()->get('system', 'relay_scope'), DI::l10n()->t('Can be "all" or "tags". "all" means that every public post should be received. "tags" means that only posts with selected tags should be received.'), [Relay::SCOPE_NONE => DI::l10n()->t('Disabled'), Relay::SCOPE_ALL => DI::l10n()->t('all'), Relay::SCOPE_TAGS => DI::l10n()->t('tags')]], @@ -599,8 +596,8 @@ class Site extends BaseAdmin '$max_posts_per_author' => ['max_posts_per_author', DI::l10n()->t('Maximum number of posts per author'), DI::config()->get('channel', 'max_posts_per_author'), DI::l10n()->t('Maximum number of posts per page by author if the contact frequency is set to "Display only few posts". If there are more posts, then the post with the most interactions will be displayed.')], '$sharer_interaction_days' => ['sharer_interaction_days', DI::l10n()->t('Sharer interaction days'), DI::config()->get('channel', 'sharer_interaction_days'), DI::l10n()->t('Number of days of the last interaction that are used to define which sharers are used for the "sharers of sharers" channel.')], - '$form_security_token' => self::getFormSecurityToken('admin_site'), - '$relocate_button' => DI::l10n()->t('Start Relocation'), + '$form_security_token' => self::getFormSecurityToken('admin_site'), + '$relocate_button' => DI::l10n()->t('Start Relocation'), ]); } } diff --git a/static/settings.config.php b/static/settings.config.php index 869065ce6e..59507690e3 100644 --- a/static/settings.config.php +++ b/static/settings.config.php @@ -74,7 +74,7 @@ return [ // curl_timeout (Integer) // Value is in seconds. Set to 0 for unlimited (not recommended). - 'curl_timeout' => 60, + 'curl_timeout' => 60, // dbclean (Boolean) // Remove old remote items, orphaned database records and old content from some other helper tables. From 3da2a3ef3d89340387dc8fa8943ef2894cef855c Mon Sep 17 00:00:00 2001 From: Michael Date: Wed, 22 Jan 2025 21:02:15 +0000 Subject: [PATCH 87/91] Fix logger calls --- src/Worker/UpdateContact.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Worker/UpdateContact.php b/src/Worker/UpdateContact.php index 24c65a3d3c..6928b0c2f2 100644 --- a/src/Worker/UpdateContact.php +++ b/src/Worker/UpdateContact.php @@ -69,22 +69,22 @@ class UpdateContact } if (DI::config()->get('system', 'update_known_contacts') && ($contact['uid'] == 0) && !Contact::hasRelations($contact_id)) { - Logger::debug('No local relations, contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + DI::logger()->debug('No local relations, contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); return false; } if (DI::config()->get('system', 'update_active_contacts') && $contact['local-data']) { - Logger::debug('No local data, contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + DI::logger()->debug('No local data, contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); return false; } if (Contact::isLocal($contact['url'])) { - Logger::debug('Local contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + DI::logger()->debug('Local contact will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); return false; } if (!Protocol::supportsProbe($contact['network'])) { - Logger::debug('Contact does not support probe, it will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); + DI::logger()->debug('Contact does not support probe, it will not be updated', ['id' => $contact_id, 'url' => $contact['url'], 'network' => $contact['network']]); return false; } From 3e465cb76177c53389c2a01d9ac17ed301b00242 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Wed, 22 Jan 2025 21:36:32 -0500 Subject: [PATCH 88/91] Partially revert "Improve search for user in Modration module" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 78444ff25cfb0e30d79b78e4744a8b84aa06c52a. ↪️ When the uid parameter isn't set, the regular list should be shown instead of throwing an error. --- src/Module/Moderation/Users/Active.php | 15 ++++++--------- src/Module/Moderation/Users/Blocked.php | 15 ++++++--------- src/Module/Moderation/Users/Index.php | 15 ++++++--------- 3 files changed, 18 insertions(+), 27 deletions(-) diff --git a/src/Module/Moderation/Users/Active.php b/src/Module/Moderation/Users/Active.php index b16efa46ae..f25bb40ed2 100644 --- a/src/Module/Moderation/Users/Active.php +++ b/src/Module/Moderation/Users/Active.php @@ -51,15 +51,12 @@ class Active extends BaseUsers $action = (string) $this->parameters['action'] ?? ''; $uid = (int) $this->parameters['uid'] ?? 0; - if ($uid === 0) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); - } - - $user = User::getById($uid, ['username', 'blocked']); - if (!is_array($user)) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); + if ($uid !== 0) { + $user = User::getById($uid, ['username', 'blocked']); + if (!$user) { + $this->systemMessages->addNotice($this->t('User not found')); + $this->baseUrl->redirect('moderation/users'); + } } switch ($action) { diff --git a/src/Module/Moderation/Users/Blocked.php b/src/Module/Moderation/Users/Blocked.php index 6eeb11549f..6d4d1cce16 100644 --- a/src/Module/Moderation/Users/Blocked.php +++ b/src/Module/Moderation/Users/Blocked.php @@ -51,15 +51,12 @@ class Blocked extends BaseUsers $action = (string) $this->parameters['action'] ?? ''; $uid = (int) $this->parameters['uid'] ?? 0; - if ($uid === 0) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); - } - - $user = User::getById($uid, ['username', 'blocked']); - if (!is_array($user)) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); + if ($uid !== 0) { + $user = User::getById($uid, ['username', 'blocked']); + if (!$user) { + $this->systemMessages->addNotice($this->t('User not found')); + $this->baseUrl->redirect('moderation/users'); + } } switch ($action) { diff --git a/src/Module/Moderation/Users/Index.php b/src/Module/Moderation/Users/Index.php index 1a7d8f1721..61208d3403 100644 --- a/src/Module/Moderation/Users/Index.php +++ b/src/Module/Moderation/Users/Index.php @@ -58,15 +58,12 @@ class Index extends BaseUsers $action = (string) $this->parameters['action'] ?? ''; $uid = (int) $this->parameters['uid'] ?? 0; - if ($uid === 0) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); - } - - $user = User::getById($uid, ['username', 'blocked']); - if (!is_array($user)) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); + if ($uid !== 0) { + $user = User::getById($uid, ['username', 'blocked']); + if (!$user) { + $this->systemMessages->addNotice($this->t('User not found')); + $this->baseUrl->redirect('moderation/users'); + } } switch ($action) { From cbb6b7819a312502278c3b19313a7599169c472b Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Wed, 22 Jan 2025 21:51:03 -0500 Subject: [PATCH 89/91] Extract GET action processing in Moderation modules --- src/Module/Moderation/Users/Active.php | 76 ++++++++++++--------- src/Module/Moderation/Users/Blocked.php | 75 ++++++++++++--------- src/Module/Moderation/Users/Index.php | 88 ++++++++++++++----------- 3 files changed, 139 insertions(+), 100 deletions(-) diff --git a/src/Module/Moderation/Users/Active.php b/src/Module/Moderation/Users/Active.php index f25bb40ed2..1b11685f64 100644 --- a/src/Module/Moderation/Users/Active.php +++ b/src/Module/Moderation/Users/Active.php @@ -48,38 +48,8 @@ class Active extends BaseUsers { parent::content(); - $action = (string) $this->parameters['action'] ?? ''; - $uid = (int) $this->parameters['uid'] ?? 0; + $this->processGetActions(); - if ($uid !== 0) { - $user = User::getById($uid, ['username', 'blocked']); - if (!$user) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); - } - } - - switch ($action) { - case 'delete': - if ($this->session->getLocalUserId() != $uid) { - self::checkFormSecurityTokenRedirectOnError('moderation/users/active', 'moderation_users_active', 't'); - // delete user - User::remove($uid); - - $this->systemMessages->addNotice($this->t('User "%s" deleted', $user['username'])); - } else { - $this->systemMessages->addNotice($this->t('You can\'t remove yourself')); - } - - $this->baseUrl->redirect('moderation/users/active'); - break; - case 'block': - self::checkFormSecurityTokenRedirectOnError('moderation/users/active', 'moderation_users_active', 't'); - User::block($uid); - $this->systemMessages->addNotice($this->t('User "%s" blocked', $user['username'])); - $this->baseUrl->redirect('moderation/users/active'); - break; - } $pager = new Pager($this->l10n, $this->args->getQueryString(), 100); $valid_orders = [ @@ -143,4 +113,48 @@ class Active extends BaseUsers '$pager' => $pager->renderFull($count), ]); } + + /** + * @return void + * @throws \Friendica\Network\HTTPException\FoundException + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws \Friendica\Network\HTTPException\MovedPermanentlyException + * @throws \Friendica\Network\HTTPException\NotFoundException + * @throws \Friendica\Network\HTTPException\TemporaryRedirectException + */ + private function processGetActions(): void + { + $action = (string)$this->parameters['action'] ?? ''; + $uid = (int)$this->parameters['uid'] ?? 0; + + if ($uid === 0) { + return; + } + + $user = User::getById($uid, ['username']); + if (!$user) { + $this->systemMessages->addNotice($this->t('User not found')); + $this->baseUrl->redirect('moderation/users'); + } + + switch ($action) { + case 'delete': + if ($this->session->getLocalUserId() != $uid) { + self::checkFormSecurityTokenRedirectOnError('moderation/users/active', 'moderation_users_active', 't'); + // delete user + User::remove($uid); + + $this->systemMessages->addNotice($this->t('User "%s" deleted', $user['username'])); + } else { + $this->systemMessages->addNotice($this->t('You can\'t remove yourself')); + } + + $this->baseUrl->redirect('moderation/users/active'); + case 'block': + self::checkFormSecurityTokenRedirectOnError('moderation/users/active', 'moderation_users_active', 't'); + User::block($uid); + $this->systemMessages->addNotice($this->t('User "%s" blocked', $user['username'])); + $this->baseUrl->redirect('moderation/users/active'); + } + } } diff --git a/src/Module/Moderation/Users/Blocked.php b/src/Module/Moderation/Users/Blocked.php index 6d4d1cce16..fbdbc8d8c7 100644 --- a/src/Module/Moderation/Users/Blocked.php +++ b/src/Module/Moderation/Users/Blocked.php @@ -48,37 +48,7 @@ class Blocked extends BaseUsers { parent::content(); - $action = (string) $this->parameters['action'] ?? ''; - $uid = (int) $this->parameters['uid'] ?? 0; - - if ($uid !== 0) { - $user = User::getById($uid, ['username', 'blocked']); - if (!$user) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); - } - } - - switch ($action) { - case 'delete': - if ($this->session->getLocalUserId() != $uid) { - self::checkFormSecurityTokenRedirectOnError('/moderation/users/blocked', 'moderation_users_blocked', 't'); - // delete user - User::remove($uid); - - $this->systemMessages->addNotice($this->t('User "%s" deleted', $user['username'])); - } else { - $this->systemMessages->addNotice($this->t('You can\'t remove yourself')); - } - $this->baseUrl->redirect('moderation/users/blocked'); - break; - case 'unblock': - self::checkFormSecurityTokenRedirectOnError('/moderation/users/blocked', 'moderation_users_blocked', 't'); - User::block($uid, false); - $this->systemMessages->addNotice($this->t('User "%s" unblocked', $user['username'])); - $this->baseUrl->redirect('moderation/users/blocked'); - break; - } + $this->processGetActions(); $pager = new Pager($this->l10n, $this->args->getQueryString(), 100); @@ -142,4 +112,47 @@ class Blocked extends BaseUsers '$pager' => $pager->renderFull($count) ]); } + + /** + * @return void + * @throws \Friendica\Network\HTTPException\FoundException + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws \Friendica\Network\HTTPException\MovedPermanentlyException + * @throws \Friendica\Network\HTTPException\NotFoundException + * @throws \Friendica\Network\HTTPException\TemporaryRedirectException + */ + private function processGetActions(): void + { + $action = (string)$this->parameters['action'] ?? ''; + $uid = (int)$this->parameters['uid'] ?? 0; + + if ($uid === 0) { + return; + } + + $user = User::getById($uid, ['username']); + if (!$user) { + $this->systemMessages->addNotice($this->t('User not found')); + $this->baseUrl->redirect('moderation/users'); + } + + switch ($action) { + case 'delete': + if ($this->session->getLocalUserId() != $uid) { + self::checkFormSecurityTokenRedirectOnError('/moderation/users/blocked', 'moderation_users_blocked', 't'); + // delete user + User::remove($uid); + + $this->systemMessages->addNotice($this->t('User "%s" deleted', $user['username'])); + } else { + $this->systemMessages->addNotice($this->t('You can\'t remove yourself')); + } + $this->baseUrl->redirect('moderation/users/blocked'); + case 'unblock': + self::checkFormSecurityTokenRedirectOnError('/moderation/users/blocked', 'moderation_users_blocked', 't'); + User::block($uid, false); + $this->systemMessages->addNotice($this->t('User "%s" unblocked', $user['username'])); + $this->baseUrl->redirect('moderation/users/blocked'); + } + } } diff --git a/src/Module/Moderation/Users/Index.php b/src/Module/Moderation/Users/Index.php index 61208d3403..7d195c1096 100644 --- a/src/Module/Moderation/Users/Index.php +++ b/src/Module/Moderation/Users/Index.php @@ -55,44 +55,7 @@ class Index extends BaseUsers { parent::content(); - $action = (string) $this->parameters['action'] ?? ''; - $uid = (int) $this->parameters['uid'] ?? 0; - - if ($uid !== 0) { - $user = User::getById($uid, ['username', 'blocked']); - if (!$user) { - $this->systemMessages->addNotice($this->t('User not found')); - $this->baseUrl->redirect('moderation/users'); - } - } - - switch ($action) { - case 'delete': - if ($this->session->getLocalUserId() != $uid) { - self::checkFormSecurityTokenRedirectOnError($this->baseUrl, 'moderation_users', 't'); - // delete user - User::remove($uid); - - $this->systemMessages->addNotice($this->t('User "%s" deleted', $user['username'])); - } else { - $this->systemMessages->addNotice($this->t('You can\'t remove yourself')); - } - - $this->baseUrl->redirect('moderation/users'); - break; - case 'block': - self::checkFormSecurityTokenRedirectOnError('moderation/users', 'moderation_users', 't'); - User::block($uid); - $this->systemMessages->addNotice($this->t('User "%s" blocked', $user['username'])); - $this->baseUrl->redirect('moderation/users'); - break; - case 'unblock': - self::checkFormSecurityTokenRedirectOnError('moderation/users', 'moderation_users', 't'); - User::block($uid, false); - $this->systemMessages->addNotice($this->t('User "%s" unblocked', $user['username'])); - $this->baseUrl->redirect('moderation/users'); - break; - } + $this->processGetActions(); $pager = new Pager($this->l10n, $this->args->getQueryString(), 100); @@ -161,4 +124,53 @@ class Index extends BaseUsers '$pager' => $pager->renderFull($count), ]); } + + /** + * @return void + * @throws \Friendica\Network\HTTPException\FoundException + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + * @throws \Friendica\Network\HTTPException\MovedPermanentlyException + * @throws \Friendica\Network\HTTPException\NotFoundException + * @throws \Friendica\Network\HTTPException\TemporaryRedirectException + */ + private function processGetActions(): void + { + $action = (string) $this->parameters['action'] ?? ''; + $uid = (int) $this->parameters['uid'] ?? 0; + + if ($uid === 0) { + return; + } + + $user = User::getById($uid, ['username']); + if (!$user) { + $this->systemMessages->addNotice($this->t('User not found')); + $this->baseUrl->redirect('moderation/users'); + } + + switch ($action) { + case 'delete': + if ($this->session->getLocalUserId() != $uid) { + self::checkFormSecurityTokenRedirectOnError($this->baseUrl, 'moderation_users', 't'); + // delete user + User::remove($uid); + + $this->systemMessages->addNotice($this->t('User "%s" deleted', $user['username'])); + } else { + $this->systemMessages->addNotice($this->t('You can\'t remove yourself')); + } + + $this->baseUrl->redirect('moderation/users'); + case 'block': + self::checkFormSecurityTokenRedirectOnError('moderation/users', 'moderation_users', 't'); + User::block($uid); + $this->systemMessages->addNotice($this->t('User "%s" blocked', $user['username'])); + $this->baseUrl->redirect('moderation/users'); + case 'unblock': + self::checkFormSecurityTokenRedirectOnError('moderation/users', 'moderation_users', 't'); + User::block($uid, false); + $this->systemMessages->addNotice($this->t('User "%s" unblocked', $user['username'])); + $this->baseUrl->redirect('moderation/users'); + } + } } From 354e3adc040a2d30b3627fd523b244b5c2672da3 Mon Sep 17 00:00:00 2001 From: Hypolite Petovan Date: Wed, 22 Jan 2025 22:14:38 -0500 Subject: [PATCH 90/91] Show Create new Group link in widget even if there's no group membership to display --- src/Content/GroupManager.php | 69 +++++++++++------------ view/templates/widget/group_list.tpl | 84 +++++++++++++++------------- 2 files changed, 76 insertions(+), 77 deletions(-) diff --git a/src/Content/GroupManager.php b/src/Content/GroupManager.php index 61b9d99053..f6762bc28b 100644 --- a/src/Content/GroupManager.php +++ b/src/Content/GroupManager.php @@ -97,52 +97,47 @@ class GroupManager * @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \ImagickException */ - public static function widget(int $uid) + public static function widget(int $uid): string { - $o = ''; - //sort by last updated item - $lastitem = true; - - $contacts = self::getList($uid, $lastitem, true, true); - $total = count($contacts); + $contacts = self::getList($uid, true, true, true); + $total = count($contacts); $visibleGroups = 10; - if (DBA::isResult($contacts)) { - $id = 0; + $id = 0; - $entries = []; + $entries = []; - foreach ($contacts as $contact) { - $entry = [ - 'url' => 'contact/' . $contact['id'] . '/conversations', - 'external_url' => Contact::magicLinkByContact($contact), - 'name' => $contact['name'], - 'cid' => $contact['id'], - 'micro' => DI::baseUrl()->remove(Contact::getMicro($contact)), - 'id' => ++$id, - ]; - $entries[] = $entry; - } + $contacts = []; - $tpl = Renderer::getMarkupTemplate('widget/group_list.tpl'); - - $o .= Renderer::replaceMacros( - $tpl, - [ - '$title' => DI::l10n()->t('Groups'), - '$groups' => $entries, - '$link_desc' => DI::l10n()->t('External link to group'), - '$new_group_page' => 'register/', - '$total' => $total, - '$visible_groups' => $visibleGroups, - '$showless' => DI::l10n()->t('show less'), - '$showmore' => DI::l10n()->t('show more'), - '$create_new_group' => DI::l10n()->t('Create new group')] - ); + foreach ($contacts as $contact) { + $entry = [ + 'url' => 'contact/' . $contact['id'] . '/conversations', + 'external_url' => Contact::magicLinkByContact($contact), + 'name' => $contact['name'], + 'cid' => $contact['id'], + 'micro' => DI::baseUrl()->remove(Contact::getMicro($contact)), + 'id' => ++$id, + ]; + $entries[] = $entry; } - return $o; + $tpl = Renderer::getMarkupTemplate('widget/group_list.tpl'); + + return Renderer::replaceMacros( + $tpl, + [ + '$title' => DI::l10n()->t('Groups'), + '$groups' => $entries, + '$link_desc' => DI::l10n()->t('External link to group'), + '$new_group_page' => 'register/', + '$total' => $total, + '$visible_groups' => $visibleGroups, + '$showless' => DI::l10n()->t('show less'), + '$showmore' => DI::l10n()->t('show more'), + '$create_new_group' => DI::l10n()->t('Create new group') + ], + ); } /** diff --git a/view/templates/widget/group_list.tpl b/view/templates/widget/group_list.tpl index 962f477ad4..b42041a7b6 100644 --- a/view/templates/widget/group_list.tpl +++ b/view/templates/widget/group_list.tpl @@ -18,49 +18,53 @@ function showHideGroupList() { } - -

      {{$title}}

      -
      -
      -