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/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..162a92948f 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,11 +24,15 @@ 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);
+
+// 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..c97557dbb0 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,11 +19,15 @@ 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);
+
+// 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..f319bd766f 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,11 +21,15 @@ 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);
+
+// 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/composer.json b/composer.json
index c94a3e8aef..2fa4ee40e9 100644
--- a/composer.json
+++ b/composer.json
@@ -173,6 +173,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"
}
}
diff --git a/doc/Developers-Intro.md b/doc/Developers-Intro.md
index c500b27741..99e84739d0 100644
--- a/doc/Developers-Intro.md
+++ b/doc/Developers-Intro.md
@@ -156,3 +156,97 @@ 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 compatibility
+
+### Backward Compatibility Promise
+
+Friendica can be extended by addons.
+These addons relies on many classes and conventions from Friendica.
+As developers our work on Friendica should not break things in the addons without giving the addon maintainers a chance to fix their addons.
+Our goal is to build trust for the addon maintainers but also allow Friendica developers to move on.
+This is called the Backward Compatibility Promise.
+
+Inspired by the [Symonfy BC promise](https://symfony.com/doc/current/contributing/code/bc.html) we promise BC for every class, interface, trait, enum, function, constant, etc., but with the exception of:
+
+- Classes, interfaces, traits, enums, functions, methods, properties and constants marked as `@internal` or `@private`
+- Extending or modifying a `final` class or method in any way
+- Calling `private` methods (via Reflection)
+- Accessing `private` properties (via Reflection)
+- Accessing `private` methods (via Reflection)
+- Accessing `private` constants (via Reflection)
+- New properties on overridden `protected` methods
+- Possible name collisions with new methods in an extended class (addon developers should prefix their custom methods in the extending classes in an appropriate way)
+- Dropping support for every PHP version that has reached end of life
+
+### Deprecation and removing features
+
+As the development goes by Friendica needs to get rid of old code and concepts.
+This will be done in 3 steps to give addon maintainers a chance to adjust their addons.
+
+**1. Label deprecation**
+
+If we as the Friendica maintainers decide to remove some functions, classes, interface, etc. we start this by adding a `@deprecated` PHPDoc note on the code.
+For instance the class `Friendica\Core\Logger` should be removed, so we add the following note with a possible replacement:
+
+```php
+/**
+ * Logger functions
+ *
+ * @deprecated 2025.02 Use constructor injection or `DI::logger()` instead
+ */
+class Logger {/* ... */}
+```
+
+This way addon developers might be notified early by their IDE or other tools that the usage of the class is deprecated.
+In Friendica we can now start to replace all occurrences and usage of this class with the alternative.
+
+The deprecation label COULD be remain over multiple releases.
+As long as the code that is labeled with `@deprecated` is used inside Friendica or the official addon repository, it SHOULD NOT be hard deprecated.
+
+**2. Hard deprecation**
+
+If the deprecated code is no longer used inside Friendica or the official addons it MUST be hard deprecated.
+The code MUST NOT be deleted.
+Starting from the next release, it MUST be stay for at least 5 months.
+Hard deprecated code COULD remain longer than 5 months, depending on when a release appears.
+Addon developer MUST NOT consider that they have more than 5 months to adjust their code.
+
+Hard deprecation code means that the code triggers an `E_USER_DEPRECATION` error if it is called.
+For instance with the deprecated class `Friendica\Core\Logger` the call of every method should trigger an error:
+
+```php
+/**
+ * Logger functions
+ *
+ * @deprecated 2025.02 Use constructor injection or `DI::logger()` instead
+ */
+class Logger {
+ public static function info(string $message, array $context = [])
+ {
+ trigger_error('Class `' . __CLASS__ . '` is deprecated since 2025.05 and will be removed after 5 months, use constructor injection or `DI::logger()` instead.', E_USER_DEPRECATED);
+
+ self::getInstance()->info($message, $context);
+ }
+
+ /* ... */
+}
+```
+
+This way the maintainer or users of addons will be notified that the addon will stop working in one of the next releases.
+The addon maintainer now has at least 5 months or at least one release to fix the deprecations.
+
+Please note that the deprecation message contains the release that will be released next.
+In the example the code was hard deprecated with release `2025.05`, so it COULD be removed earliest with the `2025.11` release.
+
+**3. Code Removing**
+
+We promise BC for deprecated code for at least 5 months, starting from the release the deprecation was announced.
+After this time the deprecated code COULD be remove within the next release.
+
+Breaking changes MUST be happen only in a new release but MUST be hard deprecated first.
+The BC promise refers only to releases, respective the `stable` branch.
+Deprecated code on other branches like `develop` or RC branches could be removed earlier.
+This is not a BC break as long as the release will be published 5 months after the hard deprecation.
+
+If a release breaks BC without deprecation or earlier than 5 months, this SHOULD considered as a bug and BC SHOULD be restored in a bugfix release.
diff --git a/mod/item.php b/mod/item.php
index c47dbac44d..de9a51915a 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;
@@ -56,7 +55,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']);
@@ -132,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'] = '';
@@ -165,18 +164,18 @@ 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'];
- $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);
@@ -197,7 +196,7 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat
$post = Post::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
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 +212,7 @@ function item_insert(int $uid, array $request, bool $preview, string $return_pat
DI::contentItem()->copyPermissions($post['thr-parent-id'], $post['uri-id'], $post['parent-uri-id']);
}
- Logger::debug('post_complete');
+ DI::logger()->debug('post_complete');
item_post_return(DI::baseUrl(), $return_path);
// NOTREACHED
@@ -297,7 +296,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 +323,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 +443,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..c2831270ab 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;
@@ -115,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]);
@@ -125,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) {
@@ -142,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'] ?? '';
@@ -152,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
@@ -277,7 +276,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);
@@ -318,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]
@@ -333,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;
@@ -357,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);
}
@@ -371,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);
@@ -380,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;
@@ -454,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);
@@ -553,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 {
@@ -583,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;
}
}
@@ -644,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'),
]);
@@ -676,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(),
@@ -713,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,
@@ -749,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'),
@@ -769,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')
]);
}
@@ -783,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'];
}
@@ -799,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'],
@@ -818,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),
]);
@@ -849,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'),
@@ -951,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')];
}
@@ -974,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?
@@ -990,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']]);
@@ -1022,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)) {
@@ -1077,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),
]);
}
}
@@ -1133,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();
@@ -1182,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'),
@@ -1190,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'],
@@ -1213,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),
]);
}
}
@@ -1244,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(),
]);
}
@@ -1263,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.php b/src/App.php
index 73f2913b1a..5623f9a413 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, [
@@ -158,16 +165,18 @@ class App
$this->session = $this->container->create(IHandleUserSessions::class);
$this->appHelper = $this->container->create(AppHelper::class);
- $this->loadSetupForFrontend(
- $request,
+ $this->load(
+ $request->getServerParams(),
$this->container->create(DbaDefinition::class),
$this->container->create(ViewDefinition::class),
+ $this->mode,
+ $this->config,
+ $this->profiler,
+ $this->appHelper,
);
$this->registerTemplateEngine();
- $this->mode->setExecutor(Mode::INDEX);
-
$this->runFrontend(
$this->container->create(IManagePersonalConfigValues::class),
$this->container->create(Page::class),
@@ -178,8 +187,13 @@ class App
);
}
- public function processConsole(array $argv): void
+ /**
+ * @internal
+ */
+ public function processConsole(array $serverParams): void
{
+ $argv = $serverParams['argv'] ?? [];
+
$this->setupContainerForAddons();
$this->setupLogChannel($this->determineLogChannel($argv));
@@ -188,12 +202,25 @@ 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
+ /**
+ * @internal
+ */
+ public function processEjabberd(array $serverParams): void
{
$this->setupContainerForAddons();
@@ -203,6 +230,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);
@@ -272,14 +309,21 @@ class App
/**
* Load the whole app instance
*/
- private function loadSetupForFrontend(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'));
+ private function load(
+ array $serverParams,
+ DbaDefinition $dbaDefinition,
+ ViewDefinition $viewDefinition,
+ Mode $mode,
+ IManageConfigValues $config,
+ Profiler $profiler,
+ AppHelper $appHelper
+ ): void {
+ if ($config->get('system', 'ini_max_execution_time') !== false) {
+ set_time_limit((int) $config->get('system', 'ini_max_execution_time'));
}
- if ($this->config->get('system', 'ini_pcre_backtrack_limit') !== false) {
- 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
@@ -290,11 +334,11 @@ class App
// Ensure that all "strtotime" operations do run timezone independent
date_default_timezone_set('UTC');
- $this->profiler->reset();
+ $profiler->reset();
- if ($this->mode->has(Mode::DBAVAILABLE)) {
+ if ($mode->has(Mode::DBAVAILABLE)) {
Core\Hook::loadHooks();
- $loader = (new Config())->createConfigFileManager($this->appHelper->getBasePath(), $request->getServerParams());
+ $loader = (new Config())->createConfigFileManager($appHelper->getBasePath(), $serverParams);
Core\Hook::callAll('load_config', $loader);
// Hooks are now working, reload the whole definitions with hook enabled
@@ -302,7 +346,7 @@ class App
$viewDefinition->load(true);
}
- $this->loadDefaultTimezone();
+ $this->loadDefaultTimezone($config, $appHelper);
}
/**
@@ -312,16 +356,16 @@ class App
*
* @global string $default_timezone
*/
- private function loadDefaultTimezone()
+ private function loadDefaultTimezone(IManageConfigValues $config, AppHelper $appHelper)
{
- 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';
}
- $this->appHelper->setTimeZone($timezone);
+ $appHelper->setTimeZone($timezone);
}
/**
@@ -348,6 +392,8 @@ class App
float $start_time,
ServerRequestInterface $request
) {
+ $this->mode->setExecutor(Mode::INDEX);
+
$httpInput = new HTTPInputData($request->getServerParams());
$serverVars = $request->getServerParams();
$queryVars = $request->getQueryParams();
diff --git a/src/App/Page.php b/src/App/Page.php
index 2fb18c4c5d..87493a67e4 100644
--- a/src/App/Page.php
+++ b/src/App/Page.php
@@ -16,12 +16,12 @@ 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;
use Friendica\Core\System;
use Friendica\Core\Theme;
+use Friendica\DI;
use Friendica\Network\HTTPException;
use Friendica\Util\Images;
use Friendica\Util\Network;
@@ -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)
@@ -102,7 +102,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'] ?? '']);
}
}
@@ -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/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/BaseModule.php b/src/BaseModule.php
index 908f750ba9..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;
@@ -412,8 +411,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 +421,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();
}
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 c8165a1d9b..a21ff26fc6 100644
--- a/src/Console/Daemon.php
+++ b/src/Console/Daemon.php
@@ -10,10 +10,10 @@ 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;
-use Friendica\Core\Logger\Capability\LogChannel;
use Friendica\Core\System;
use Friendica\Core\Update;
use Friendica\Core\Worker;
@@ -27,10 +27,8 @@ 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;
-
private Mode $mode;
private IManageConfigValues $config;
private IManageKeyValuePairs $keyValue;
@@ -93,8 +91,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..8bb1e7e106 100644
--- a/src/Console/JetstreamDaemon.php
+++ b/src/Console/JetstreamDaemon.php
@@ -9,12 +9,12 @@ 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;
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;
@@ -22,10 +22,8 @@ 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;
-
private Mode $mode;
private IManageConfigValues $config;
private IManageKeyValuePairs $keyValue;
@@ -79,8 +77,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..97b7160d03 100644
--- a/src/Console/Worker.php
+++ b/src/Console/Worker.php
@@ -9,8 +9,8 @@ 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;
use Friendica\Core\Worker as CoreWorker;
use Friendica\Core\Worker\Repository\Process as ProcessRepository;
@@ -19,10 +19,8 @@ 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;
-
private Mode $mode;
private BasePath $basePath;
private ProcessRepository $processRepo;
@@ -69,8 +67,6 @@ HELP;
protected function doExecute()
{
- $this->checkDeprecated('worker');
-
$this->mode->setExecutor(Mode::WORKER);
// Check the database structure and possibly fixes it
diff --git a/src/Contact/Avatar.php b/src/Contact/Avatar.php
index 04f8778a59..677ab8e048 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;
@@ -47,36 +46,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 +88,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 +154,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 '';
}
@@ -216,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 '';
}
@@ -257,7 +256,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 +276,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 '';
}
}
diff --git a/src/Content/GroupManager.php b/src/Content/GroupManager.php
index 61b9d99053..a484ba73ce 100644
--- a/src/Content/GroupManager.php
+++ b/src/Content/GroupManager.php
@@ -45,11 +45,11 @@ class GroupManager
$condition = [
'contact-type' => Contact::TYPE_COMMUNITY,
- 'network' => [Protocol::DFRN, Protocol::ACTIVITYPUB],
- 'uid' => $uid,
- 'blocked' => false,
- 'pending' => false,
- 'archive' => false,
+ 'network' => [Protocol::DFRN, Protocol::ACTIVITYPUB],
+ 'uid' => $uid,
+ 'blocked' => false,
+ 'pending' => false,
+ 'archive' => false,
];
$condition = DBA::mergeConditions($condition, ["`platform` NOT IN (?, ?)", 'peertube', 'wordpress']);
@@ -64,7 +64,7 @@ class GroupManager
$groupList = [];
- $fields = ['id', 'url', 'alias', 'name', 'micro', 'thumb', 'avatar', 'network', 'uid'];
+ $fields = ['id', 'url', 'alias', 'name', 'micro', 'thumb', 'avatar', 'network', 'uid'];
$contacts = DBA::select('account-user-view', $fields, $condition, $params);
if (!$contacts) {
return $groupList;
@@ -72,10 +72,10 @@ class GroupManager
while ($contact = DBA::fetch($contacts)) {
$groupList[] = [
- 'url' => $contact['url'],
- 'alias' => $contact['alias'],
- 'name' => $contact['name'],
- 'id' => $contact['id'],
+ 'url' => $contact['url'],
+ 'alias' => $contact['alias'],
+ 'name' => $contact['name'],
+ 'id' => $contact['id'],
'micro' => $contact['micro'],
'thumb' => $contact['thumb'],
];
@@ -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')
+ ],
+ );
}
/**
@@ -206,7 +201,11 @@ class GroupManager
AND NOT `contact`.`pending` AND NOT `contact`.`archive`
AND `contact`.`uid` = ?
GROUP BY `contact`.`id`",
- DI::userSession()->getLocalUserId(), Protocol::DFRN, Protocol::ACTIVITYPUB, Contact::TYPE_COMMUNITY, DI::userSession()->getLocalUserId()
+ DI::userSession()->getLocalUserId(),
+ Protocol::DFRN,
+ Protocol::ACTIVITYPUB,
+ Contact::TYPE_COMMUNITY,
+ DI::userSession()->getLocalUserId()
);
return DBA::toArray($stmtContacts);
diff --git a/src/Content/Item.php b/src/Content/Item.php
index 7343c06aff..943bda4591 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;
@@ -117,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;
@@ -133,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;
}
@@ -149,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;
}
@@ -198,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);
}
}
@@ -263,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);
}
}
@@ -304,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,
@@ -313,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:
@@ -341,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);
}
}
@@ -359,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']) {
@@ -380,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)) {
@@ -416,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,
];
@@ -518,20 +517,20 @@ 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;
- 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'];
+ $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
@@ -562,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'];
}
@@ -606,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)) {
@@ -635,10 +634,10 @@ 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)) {
- 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;
}
@@ -650,11 +649,11 @@ 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)) {
- Logger::notice('Post does not exist.', ['guid' => $guid]);
+ DI::logger()->notice('Post does not exist.', ['guid' => $guid]);
return '';
}
@@ -801,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
@@ -816,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'] = [
@@ -843,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)) {
@@ -859,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;
}
@@ -879,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
@@ -908,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;
}
@@ -926,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'])) {
@@ -990,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) {
@@ -1084,10 +1083,10 @@ 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) {
- 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..93d2e46750 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) {
@@ -60,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;
}
@@ -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;
}
@@ -216,8 +215,11 @@ class PageInfo
$taglist = [];
foreach ($data['keywords'] as $keyword) {
- $hashtag = str_replace([' ', '+', '/', '.', '#', "'"],
- ['', '', '', '', '', ''], $keyword);
+ $hashtag = str_replace(
+ [' ', '+', '/', '.', '#', "'"],
+ ['', '', '', '', '', ''],
+ $keyword
+ );
$taglist[] = $hashtag;
}
@@ -271,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 900032c33e..f03dfa84be 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;
@@ -131,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;
@@ -290,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);
@@ -328,15 +328,15 @@ 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 = '';
- $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
@@ -348,9 +348,9 @@ 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;
+ $textlen = $maxlen;
}
} else {
$new_body = $new_body . substr($orig_body, 0, $img_start);
@@ -362,9 +362,9 @@ 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;
+ $textlen = $maxlen;
}
} else {
$new_body = $new_body . substr($orig_body, 0, $img_end);
@@ -378,18 +378,18 @@ 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) {
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;
}
@@ -434,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 = '';
@@ -507,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'];
}
@@ -585,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 . ']')
],
];
@@ -615,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);
}
@@ -637,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;
@@ -651,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 {
@@ -665,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;
@@ -737,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;
@@ -797,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);
@@ -832,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');
@@ -908,7 +908,7 @@ class BBCode
break;
case self::ACTIVITYPUB:
$author = '@' . $author_contact['addr'] . ':';
- $text = '
' . "\n";
+ $text = '' . "\n";
break;
default:
$text = ($is_quote_share ? "\n" : '');
@@ -917,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'],
@@ -939,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]);
@@ -964,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 = [];
@@ -1035,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;
}
@@ -1067,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) {
@@ -1135,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;
}
@@ -1171,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;
}
@@ -1311,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 {
@@ -1326,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
@@ -1475,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");
@@ -1498,7 +1498,7 @@ class BBCode
];
do {
$oldtext = $text;
- $text = str_replace($search, $replace, $text);
+ $text = str_replace($search, $replace, $text);
} while ($oldtext != $text);
}
@@ -1635,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) {
@@ -1750,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 ',
@@ -1796,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
",
@@ -1830,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 '
';
@@ -2044,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:
@@ -2107,7 +2107,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;
}
}
@@ -2219,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;
}
@@ -2319,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]);
@@ -2368,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
@@ -2572,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 211369f712..8aa9453041 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;
@@ -25,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;
@@ -97,7 +97,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 '';
}
@@ -122,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 7feac4403c..173a91d017 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,17 +33,17 @@ 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);
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 = '';
@@ -54,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())) {
@@ -69,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])) {
@@ -92,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 1119f2d392..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'
];
}
@@ -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')) {
@@ -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,14 +182,14 @@ 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
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);
@@ -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/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
{
diff --git a/src/Core/Protocol.php b/src/Core/Protocol.php
index e723b13d45..53f69bc509 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;
@@ -56,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
@@ -73,7 +74,7 @@ class Protocol
$hook_data = [
'protocol' => $protocol,
- 'result' => null
+ 'result' => null
];
Hook::callAll('support_follow', $hook_data);
@@ -95,7 +96,7 @@ class Protocol
$hook_data = [
'protocol' => $protocol,
- 'result' => null
+ 'result' => null
];
Hook::callAll('support_revoke_follow', $hook_data);
@@ -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;
}
@@ -241,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);
@@ -280,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);
@@ -308,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 776a0a0e50..0abd808377 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;
/**
@@ -118,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(
@@ -138,7 +137,7 @@ class Search
Protocol::DFRN,
$contactDetails['cid'] ?? 0,
$contactDetails['zid'] ?? 0,
- $profile['tags'] ?? ''
+ $profile['tags'] ?? ''
);
$resultList->addResult($result);
@@ -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()) {
@@ -232,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/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..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,13 +185,13 @@ class Theme
$func();
}
- $allowed_themes = Theme::getAllowedList();
+ $allowed_themes = Theme::getAllowedList();
$allowed_themes[] = $theme;
Theme::setAllowedList($allowed_themes);
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;
}
}
@@ -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 b6bf0e5a2d..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();
@@ -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,15 @@ 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::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing pre update %d',
- DateTimeFormat::utcNow() . ' ' . date('e'), $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 +219,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 +233,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 +242,20 @@ 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::config()->set('system', 'maintenance_reason', DI::l10n()->t('%s: executing post update %d',
- DateTimeFormat::utcNow() . ' ' . date('e'), $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 +265,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 +277,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 +303,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 +316,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 +328,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,20 +358,22 @@ 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;
}
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()
@@ -376,7 +384,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]);
}
/**
@@ -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()
@@ -404,6 +415,6 @@ class Update
DI::emailer()->send($email);
}
- Logger::debug('Database structure update successful.');
+ DI::logger()->debug('Database structure update successful.');
}
}
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..a4184caf70 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.
@@ -113,10 +112,13 @@ 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 {
- Logger::info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
+ DI::logger()->info('Process runtime is okay', ['duration' => number_format($duration, 3), 'max' => $max_duration, 'id' => $entry["id"], 'pid' => $entry["pid"], 'command' => $command]);
}
}
}
@@ -156,12 +158,12 @@ class Cron
$deliveries = DBA::p("SELECT `item-uri`.`uri` AS `inbox`, MAX(`gsid`) AS `gsid`, MAX(`shared`) AS `shared`, MAX(`failed`) AS `failed` FROM `post-delivery` INNER JOIN `item-uri` ON `item-uri`.`id` = `post-delivery`.`inbox-id` LEFT JOIN `inbox-status` ON `inbox-status`.`url` = `item-uri`.`uri` GROUP BY `inbox` ORDER BY RAND()");
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 +176,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 +184,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 +197,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 +212,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 +239,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');
}
}
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
*/
diff --git a/src/Database/DBStructure.php b/src/Database/DBStructure.php
index 098a47d675..6809838b96 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;
@@ -74,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.');
@@ -144,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 . '
';
}
@@ -238,7 +243,7 @@ class DBStructure
$errors = '';
- Logger::info('updating structure');
+ DI::logger()->info('updating structure');
// Get the current structure
$database = [];
@@ -251,7 +256,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);
}
}
@@ -523,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;
}
}
@@ -574,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'];
@@ -597,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
];
@@ -732,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]
+ );
}
/**
@@ -807,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);
@@ -884,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);
@@ -914,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 65c8e98c22..a4db193752 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;
@@ -36,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;
@@ -139,24 +138,24 @@ 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;
- 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,24 +172,31 @@ class PostUpdate
return true;
}
- Logger::info('Start');
+ DI::logger()->info('Start');
- $contacts = DBA::p("SELECT `nurl`, `uid` FROM `contact`
+ $contacts = DBA::p(
+ "SELECT `nurl`, `uid` FROM `contact`
WHERE EXISTS (SELECT `nurl` FROM `contact` AS `c2`
WHERE `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)) {
- 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,16 +221,16 @@ 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;
+ $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) {
- 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 +245,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 +276,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 +285,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 +301,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,35 +334,41 @@ 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;
- $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) {
- Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
+ DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false;
}
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']);
@@ -371,13 +383,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 +416,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 +427,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 +441,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;
}
@@ -455,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'] . '>';
@@ -487,16 +499,19 @@ 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;
- $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) {
- 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 +536,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,10 +570,10 @@ 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;
+ $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`
@@ -566,12 +581,12 @@ 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;
}
while ($item = DBA::fetch($items)) {
- $id = $item['id'];
+ $id = $item['id'];
$verb = $item['item-verb'];
if (empty($verb)) {
$verb = $item['verb'];
@@ -590,11 +605,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,25 +632,27 @@ 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;
+ $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) {
- Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
+ DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false;
}
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;
}
@@ -643,11 +660,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,25 +687,27 @@ 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;
- $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) {
- Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
+ DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false;
}
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;
}
@@ -696,11 +715,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,10 +740,10 @@ class PostUpdate
return true;
}
- Logger::info('Start');
+ 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)) {
@@ -744,7 +763,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 +782,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;
+ $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 +801,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 +832,13 @@ class PostUpdate
}
$condition = ["`extid` != ? AND EXISTS(SELECT `id` FROM `post-user` WHERE `uri-id` = `item`.`uri-id` AND `uid` = `item`.`uid` AND `external-id` IS NULL)", ''];
- Logger::info('Start', ['rest' => DBA::count('item', $condition)]);
+ DI::logger()->info('Start', ['rest' => DBA::count('item', $condition)]);
- $rows = 0;
+ $rows = 0;
$items = DBA::select('item', ['uri-id', 'uid', 'extid'], $condition, ['order' => ['id'], 'limit' => 10000]);
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 +848,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 +874,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;
+ $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 +890,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 +921,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;
+ $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 +942,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 +968,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;
+ $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 +989,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 +1015,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;
+ $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 +1036,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,18 +1068,22 @@ 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 = '';
- $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) {
- 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 +1111,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 +1137,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 +1150,7 @@ class PostUpdate
DBA::close($posts);
DI::keyValue()->set('post_update_version', 1483);
- Logger::info('Done');
+ DI::logger()->info('Done');
return true;
}
@@ -1147,14 +1170,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 +1194,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,16 +1221,16 @@ 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;
+ $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) {
- Logger::error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
+ DI::logger()->error('Database error', ['no' => DBA::errorNo(), 'message' => DBA::errorMessage()]);
return false;
}
@@ -1218,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;
}
@@ -1228,11 +1253,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,16 +1280,16 @@ 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;
- $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) {
- 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 +1308,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;
}
@@ -1311,17 +1336,17 @@ 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);
}
- 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 +1359,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 +1393,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);
@@ -1376,10 +1401,10 @@ 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);
}
- Logger::info('Start', ['uri-id' => $id]);
+ DI::logger()->info('Start', ['uri-id' => $id]);
$rows = 0;
@@ -1393,7 +1418,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 +1431,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;
}
diff --git a/src/Factory/Api/Mastodon/Status.php b/src/Factory/Api/Mastodon/Status.php
index 8cf9f3d8e7..8eba9221e7 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;
@@ -222,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);
@@ -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 {
@@ -350,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 {
@@ -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 {
diff --git a/src/Model/APContact.php b/src/Model/APContact.php
index bfb80686b4..9c20b5b283 100644
--- a/src/Model/APContact.php
+++ b/src/Model/APContact.php
@@ -9,12 +9,10 @@ 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;
use Friendica\DI;
-use Friendica\Model\Item;
use Friendica\Network\HTTPException;
use Friendica\Network\Probe;
use Friendica\Protocol\ActivityNamespace;
@@ -95,12 +93,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 [];
}
@@ -154,9 +152,9 @@ 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)) {
- 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;
}
@@ -168,7 +166,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;
@@ -180,11 +178,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);
}
@@ -194,7 +192,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;
}
@@ -218,13 +216,13 @@ class APContact
*/
private static function compactProfile(array $apcontact, array $compacted, string $url, $fetched_contact, bool $webfinger, $local_owner): array
{
- $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'])) {
@@ -302,7 +300,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'] = '';
}
}
@@ -315,12 +313,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');
}
@@ -360,7 +358,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)) {
@@ -382,7 +380,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'] = '';
}
}
@@ -468,9 +466,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']]);
}
}
}
@@ -479,7 +477,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]);
}
@@ -492,7 +490,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']]) ?: [];
}
@@ -543,7 +541,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']);
}
@@ -553,7 +551,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']);
}
}
@@ -568,11 +566,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..f9323897e9 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;
@@ -24,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
@@ -164,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`
@@ -231,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) {
@@ -411,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) {
@@ -432,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) {
@@ -479,8 +479,8 @@ class Circle
{
$display_circles = [
[
- 'name' => '',
- 'id' => '0',
+ 'name' => '',
+ 'id' => '0',
'selected' => ''
]
];
@@ -488,18 +488,18 @@ 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' : ''
];
}
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,
- '$label' => $label,
+ '$id' => $id,
+ '$label' => $label,
'$circles' => $display_circles
]);
return $o;
@@ -527,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,
]
];
@@ -545,7 +545,7 @@ class Circle
if ($editmode == 'full') {
$circleedit = [
- 'href' => 'circle/' . $circle['id'],
+ 'href' => 'circle/' . $circle['id'],
'title' => DI::l10n()->t('edit'),
];
} else {
@@ -553,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),
];
@@ -582,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'),
]);
@@ -608,7 +608,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 +638,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 +673,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/Contact.php b/src/Model/Contact.php
index a0e186b40e..a7dfa08dcf 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;
@@ -75,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;
/**
* @}
*/
@@ -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]);
}
@@ -336,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;
}
}
@@ -354,23 +353,21 @@ 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)) {
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) {
- Logger::notice($e->getMessage(), ['contact' => $contact]);
+ DI::logger()->notice($e->getMessage(), ['contact' => $contact]);
}
}
@@ -538,6 +535,17 @@ class Contact
return DBA::exists('account-user-view', ["`pid` = ? AND `uid` != ? AND `rel` IN (?, ?)", $cid, 0, self::SHARING, self::FRIEND]);
}
+ /**
+ * 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
*
@@ -567,11 +575,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'];
}
@@ -838,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;
}
@@ -869,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]);
@@ -898,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;
@@ -1084,16 +1092,16 @@ 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;
}
} 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']) {
@@ -1136,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);
@@ -1150,14 +1158,14 @@ 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;
}
}
- 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];
@@ -1206,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';
@@ -1310,7 +1318,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;
}
@@ -1319,25 +1327,23 @@ 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) {
- 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,11 +1375,11 @@ 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]);
- $data = $personal_contact;
- $data['photo'] = $personal_contact['avatar'];
+ 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'];
- $data['hide'] = $personal_contact['unsearchable'];
+ $data['hide'] = $personal_contact['unsearchable'];
unset($data['avatar']);
unset($data['contact-type']);
unset($data['unsearchable']);
@@ -1381,12 +1387,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,24 +1404,24 @@ 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]);
}
}
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];
@@ -1424,37 +1430,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 +1469,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;
}
@@ -1628,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);
@@ -1691,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 = '';
}
@@ -1707,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()]);
@@ -1716,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);
@@ -1812,16 +1818,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;
}
@@ -1907,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;
@@ -1965,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 = '';
@@ -2010,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;
}
@@ -2030,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;
}
@@ -2147,7 +2153,7 @@ class Contact
return DI::baseUrl() . $default;
}
- $avatar['url'] = '';
+ $avatar['url'] = '';
$avatar['success'] = false;
Hook::callAll('avatar_lookup', $avatar);
@@ -2175,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);
@@ -2243,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);
@@ -2303,7 +2309,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 +2333,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 +2343,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 +2352,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;
}
@@ -2374,13 +2380,13 @@ 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)
];
- Logger::debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
+ DI::logger()->debug('Use default avatar', ['id' => $cid, 'uid' => $uid]);
}
$local_uid = 0;
@@ -2390,7 +2396,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 +2413,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;
}
}
@@ -2417,15 +2423,15 @@ 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;
- 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 +2472,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]);
}
@@ -2474,9 +2480,9 @@ 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)) {
- 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 +2514,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 +2523,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 +2570,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]);
}
}
@@ -2601,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;
}
@@ -2613,10 +2619,10 @@ 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];
+ $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)) {
@@ -2626,7 +2632,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 +2655,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;
}
@@ -2687,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;
@@ -2698,17 +2704,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 +2795,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 +2803,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 +2850,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 +2863,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 +2880,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);
}
}
@@ -2884,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'];
}
}
@@ -2904,11 +2910,11 @@ 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;
- $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'];
@@ -2975,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;
}
@@ -3006,7 +3012,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]);
}
}
@@ -3107,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) {
@@ -3125,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']);
@@ -3204,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'],
@@ -3224,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) {
@@ -3243,7 +3249,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]);
}
}
@@ -3269,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
@@ -3281,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
@@ -3297,7 +3303,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 +3336,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;
}
@@ -3362,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)) {
@@ -3396,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;
}
@@ -3492,7 +3498,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);
@@ -3501,7 +3507,7 @@ class Contact
DBA::update(
'contact',
['bdyear' => substr($nextbd, 0, 4), 'bd' => $nextbd],
- ['id' => $contact['id']]
+ ['id' => $contact['id']]
);
}
}
@@ -3656,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;
}
@@ -3676,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;
}
@@ -3707,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) {
@@ -3756,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)) {
@@ -3774,7 +3780,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..5172d87c70 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]);
- $followers = self::getContacts($uid, [Contact::FOLLOWER, Contact::FRIEND]);
+ 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,8 +116,8 @@ class Relation
$followings = [];
}
} else {
- Logger::warning('Contact seems to be local but could not be found here', ['url' => $url]);
- $followers = [];
+ 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;
}
@@ -159,10 +158,10 @@ class Relation
}
$contacts = array_unique($contacts);
- $follower_counter = 0;
+ $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;
}
@@ -200,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;
@@ -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;
}
}
@@ -301,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();
}
@@ -312,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;
@@ -335,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;
@@ -356,33 +355,37 @@ 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 = [];
- 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;
// 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,
]
@@ -394,7 +397,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);
@@ -402,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]
);
@@ -419,19 +424,21 @@ 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);
}
// 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]
);
@@ -440,19 +447,21 @@ 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);
}
// 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]
);
@@ -461,7 +470,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);
}
@@ -477,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;
@@ -496,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]);
@@ -515,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;
@@ -534,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]);
@@ -554,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++;
}
@@ -583,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]);
@@ -606,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++;
}
@@ -635,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]);
@@ -660,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++;
}
@@ -691,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]);
@@ -713,10 +722,11 @@ 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`)
+ $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);
@@ -736,13 +746,17 @@ class Relation
*/
public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
{
- $condition = DBA::mergeConditions($condition,
- ["`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
+ $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']]
);
}
@@ -758,10 +772,11 @@ 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`)
+ $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);
@@ -781,13 +796,17 @@ class Relation
*/
public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
{
- $condition = DBA::mergeConditions($condition,
- ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
+ $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']]
);
}
@@ -800,84 +819,162 @@ 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);
- 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);
- $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
+ );
- Logger::debug('Calculate relation-score', ['uid' => $uid, 'total' => $total['activity']]);
+ DI::logger()->debug('Calculate relation-score', ['uid' => $uid, 'total' => $total['activity']]);
- $interactions = DBA::p("SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows`
+ $interactions = DBA::p(
+ "SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows`
FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`thr-parent-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`",
- $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
+ );
- Logger::debug('Calculate relation-thread-score', ['uid' => $uid, 'total' => $total['activity']]);
+ DI::logger()->debug('Calculate relation-thread-score', ['uid' => $uid, 'total' => $total['activity']]);
- $interactions = DBA::p("SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows`
+ $interactions = DBA::p(
+ "SELECT `post`.`author-id`, count(*) AS `activity`, EXISTS(SELECT `pid` FROM `account-user-view` WHERE `pid` = `post`.`author-id` AND `uid` = ? AND `rel` IN (?, ?)) AS `follows`
FROM `post-user` INNER JOIN `post` ON `post`.`uri-id` = `post-user`.`parent-uri-id` WHERE `post-user`.`author-id` = ? AND `post-user`.`received` >= ? AND `post-user`.`uid` = ? AND `post`.`author-id` != ? AND NOT `post`.`vid` IN (?, ?, ?) GROUP BY `post`.`author-id`",
- $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
+ );
- 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);
+ $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
+ );
- 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);
+ $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')
+ );
- 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'));
+ $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']]);
}
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..17663e233b 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,18 +52,18 @@ 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;
}
- $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);
- 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;
}
@@ -90,8 +89,8 @@ class User
continue;
}
$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]);
+ $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]);
}
DBA::close($contacts);
diff --git a/src/Model/Event.php b/src/Model/Event.php
index f98c8cdd0c..6cb73f4c37 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;
@@ -30,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)) {
@@ -219,7 +217,7 @@ class Event
}
DBA::delete('event', ['id' => $event_id]);
- Logger::info("Deleted event", ['id' => $event_id]);
+ DI::logger()->info("Deleted event", ['id' => $event_id]);
}
/**
@@ -233,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),
];
@@ -358,7 +356,7 @@ class Event
$item['body'] = self::getBBCode($event);
$item['event-id'] = $event['id'];
- $item['object'] = '