Replace Logger with DI::logger() in Util classes

This commit is contained in:
Art4 2025-01-13 12:53:09 +00:00
parent 9306a56da0
commit 0ce0aa4d2c
10 changed files with 101 additions and 107 deletions

View file

@ -8,7 +8,6 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use phpseclib3\Crypt\PublicKeyLoader; use phpseclib3\Crypt\PublicKeyLoader;
@ -27,7 +26,7 @@ class Crypto
public static function rsaSign($data, $key, $alg = 'sha256') public static function rsaSign($data, $key, $alg = 'sha256')
{ {
if (empty($key)) { if (empty($key)) {
Logger::warning('Empty key parameter'); DI::logger()->warning('Empty key parameter');
} }
openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg)); openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
return $sig; return $sig;
@ -43,7 +42,7 @@ class Crypto
public static function rsaVerify($data, $sig, $key, $alg = 'sha256') public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
{ {
if (empty($key)) { if (empty($key)) {
Logger::warning('Empty key parameter'); DI::logger()->warning('Empty key parameter');
} }
return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg)); return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
} }
@ -80,7 +79,7 @@ class Crypto
$result = openssl_pkey_new($openssl_options); $result = openssl_pkey_new($openssl_options);
if (empty($result)) { if (empty($result)) {
Logger::notice('new_keypair: failed'); DI::logger()->notice('new_keypair: failed');
return false; return false;
} }
@ -161,7 +160,7 @@ class Crypto
private static function encapsulateOther($data, $pubkey, $alg) private static function encapsulateOther($data, $pubkey, $alg)
{ {
if (!$pubkey) { if (!$pubkey) {
Logger::notice('no key. data: '.$data); DI::logger()->notice('no key. data: '.$data);
} }
$fn = 'encrypt' . strtoupper($alg); $fn = 'encrypt' . strtoupper($alg);
if (method_exists(__CLASS__, $fn)) { if (method_exists(__CLASS__, $fn)) {
@ -173,7 +172,7 @@ class Crypto
// log the offending call so we can track it down // log the offending call so we can track it down
if (!openssl_public_encrypt($key, $k, $pubkey)) { if (!openssl_public_encrypt($key, $k, $pubkey)) {
$x = debug_backtrace(); $x = debug_backtrace();
Logger::notice('RSA failed', ['trace' => $x[0]]); DI::logger()->notice('RSA failed', ['trace' => $x[0]]);
} }
$result['alg'] = $alg; $result['alg'] = $alg;
@ -203,7 +202,7 @@ class Crypto
private static function encapsulateAes($data, $pubkey) private static function encapsulateAes($data, $pubkey)
{ {
if (!$pubkey) { if (!$pubkey) {
Logger::notice('aes_encapsulate: no key. data: ' . $data); DI::logger()->notice('aes_encapsulate: no key. data: ' . $data);
} }
$key = random_bytes(32); $key = random_bytes(32);
@ -214,7 +213,7 @@ class Crypto
// log the offending call so we can track it down // log the offending call so we can track it down
if (!openssl_public_encrypt($key, $k, $pubkey)) { if (!openssl_public_encrypt($key, $k, $pubkey)) {
$x = debug_backtrace(); $x = debug_backtrace();
Logger::notice('aes_encapsulate: RSA failed.', ['data' => $x[0]]); DI::logger()->notice('aes_encapsulate: RSA failed.', ['data' => $x[0]]);
} }
$result['alg'] = 'aes256cbc'; $result['alg'] = 'aes256cbc';

View file

@ -7,10 +7,10 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Logger;
use DateTime; use DateTime;
use DateTimeZone; use DateTimeZone;
use Exception; use Exception;
use Friendica\DI;
/** /**
* Temporal class * Temporal class
@ -140,7 +140,7 @@ class DateTimeFormat
try { try {
$d = new DateTime(self::fix($s), $from_obj); $d = new DateTime(self::fix($s), $from_obj);
} catch (\Throwable $e) { } catch (\Throwable $e) {
Logger::warning('DateTimeFormat::convert: exception: ' . $e->getMessage()); DI::logger()->warning('DateTimeFormat::convert: exception: ' . $e->getMessage());
$d = new DateTime('now', $from_obj); $d = new DateTime('now', $from_obj);
} }
} }

View file

@ -7,7 +7,6 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -72,7 +71,7 @@ class HTTPSignature
$sig_block = self::parseSigheader($headers['authorization']); $sig_block = self::parseSigheader($headers['authorization']);
if (!$sig_block) { if (!$sig_block) {
Logger::notice('no signature provided.'); DI::logger()->notice('no signature provided.');
return $result; return $result;
} }
@ -102,7 +101,7 @@ class HTTPSignature
$key = $key($sig_block['keyId']); $key = $key($sig_block['keyId']);
} }
Logger::info('Got keyID ' . $sig_block['keyId']); DI::logger()->info('Got keyID ' . $sig_block['keyId']);
if (!$key) { if (!$key) {
return $result; return $result;
@ -110,7 +109,7 @@ class HTTPSignature
$x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm); $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
Logger::info('verified: ' . $x); DI::logger()->info('verified: ' . $x);
if (!$x) { if (!$x) {
return $result; return $result;
@ -293,7 +292,7 @@ class HTTPSignature
$postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'), HttpClientRequest::ACTIVITYPUB); $postResult = DI::httpClient()->post($target, $content, $headers, DI::config()->get('system', 'curl_timeout'), HttpClientRequest::ACTIVITYPUB);
$return_code = $postResult->getReturnCode(); $return_code = $postResult->getReturnCode();
Logger::info('Transmit to ' . $target . ' returned ' . $return_code); DI::logger()->info('Transmit to ' . $target . ' returned ' . $return_code);
self::setInboxStatus($target, ($return_code >= 200) && ($return_code <= 299)); self::setInboxStatus($target, ($return_code >= 200) && ($return_code <= 299));
@ -327,7 +326,7 @@ class HTTPSignature
return false; return false;
} }
Logger::debug('Process directly', ['uid' => $uid, 'target' => $target, 'type' => $type]); DI::logger()->debug('Process directly', ['uid' => $uid, 'target' => $target, 'type' => $type]);
return Receiver::routeActivities($object_data, $type, true, true, $uid); return Receiver::routeActivities($object_data, $type, true, true, $uid);
} }
@ -371,7 +370,7 @@ class HTTPSignature
try { try {
$postResult = self::post($data, $target, $owner); $postResult = self::post($data, $target, $owner);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return false; return false;
} }
$return_code = $postResult->getReturnCode(); $return_code = $postResult->getReturnCode();
@ -402,7 +401,7 @@ class HTTPSignature
$status = DBA::selectFirst('inbox-status', [], ['url' => $url]); $status = DBA::selectFirst('inbox-status', [], ['url' => $url]);
if (empty($status)) { if (empty($status)) {
Logger::warning('Unable to insert inbox-status row', $insertFields); DI::logger()->warning('Unable to insert inbox-status row', $insertFields);
return; return;
} }
} }
@ -476,12 +475,12 @@ class HTTPSignature
try { try {
$curlResult = self::fetchRaw($request, $uid); $curlResult = self::fetchRaw($request, $uid);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::notice('Error fetching url', ['url' => $request, 'exception' => $exception]); DI::logger()->notice('Error fetching url', ['url' => $request, 'exception' => $exception]);
return []; return [];
} }
if (!$curlResult->isSuccess() || empty($curlResult->getBodyString())) { if (!$curlResult->isSuccess() || empty($curlResult->getBodyString())) {
Logger::debug('Fetching was unsuccessful', ['url' => $request, 'return-code' => $curlResult->getReturnCode(), 'error-number' => $curlResult->getErrorNumber(), 'error' => $curlResult->getError()]); DI::logger()->debug('Fetching was unsuccessful', ['url' => $request, 'return-code' => $curlResult->getReturnCode(), 'error-number' => $curlResult->getErrorNumber(), 'error' => $curlResult->getError()]);
return []; return [];
} }
@ -510,7 +509,7 @@ class HTTPSignature
} }
if (current(explode(';', $contentType)) == 'application/json') { if (current(explode(';', $contentType)) == 'application/json') {
Logger::notice('Unexpected content type, possibly from a remote system that is not standard compliant.', ['content-type' => $contentType, 'url' => $url]); DI::logger()->notice('Unexpected content type, possibly from a remote system that is not standard compliant.', ['content-type' => $contentType, 'url' => $url]);
} }
return false; return false;
} }
@ -572,7 +571,7 @@ class HTTPSignature
} }
$return_code = $curlResult->getReturnCode(); $return_code = $curlResult->getReturnCode();
Logger::info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code); DI::logger()->info('Fetched for user ' . $uid . ' from ' . $request . ' returned ' . $return_code);
return $curlResult; return $curlResult;
} }
@ -587,14 +586,14 @@ class HTTPSignature
public static function getKeyIdContact(array $http_headers): array public static function getKeyIdContact(array $http_headers): array
{ {
if (empty($http_headers['HTTP_SIGNATURE'])) { if (empty($http_headers['HTTP_SIGNATURE'])) {
Logger::debug('No HTTP_SIGNATURE header', ['header' => $http_headers]); DI::logger()->debug('No HTTP_SIGNATURE header', ['header' => $http_headers]);
return []; return [];
} }
$sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']); $sig_block = self::parseSigHeader($http_headers['HTTP_SIGNATURE']);
if (empty($sig_block['keyId'])) { if (empty($sig_block['keyId'])) {
Logger::debug('No keyId', ['sig_block' => $sig_block]); DI::logger()->debug('No keyId', ['sig_block' => $sig_block]);
return []; return [];
} }
@ -614,14 +613,14 @@ class HTTPSignature
public static function getSigner(string $content, array $http_headers) public static function getSigner(string $content, array $http_headers)
{ {
if (empty($http_headers['HTTP_SIGNATURE'])) { if (empty($http_headers['HTTP_SIGNATURE'])) {
Logger::debug('No HTTP_SIGNATURE header'); DI::logger()->debug('No HTTP_SIGNATURE header');
return false; return false;
} }
if (!empty($content)) { if (!empty($content)) {
$object = json_decode($content, true); $object = json_decode($content, true);
if (empty($object)) { if (empty($object)) {
Logger::info('No object'); DI::logger()->info('No object');
return false; return false;
} }
@ -659,7 +658,7 @@ class HTTPSignature
} }
if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) { if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
Logger::info('No headers or keyId'); DI::logger()->info('No headers or keyId');
return false; return false;
} }
@ -668,13 +667,13 @@ class HTTPSignature
if (array_key_exists($h, $headers)) { if (array_key_exists($h, $headers)) {
$signed_data .= $h . ': ' . $headers[$h] . "\n"; $signed_data .= $h . ': ' . $headers[$h] . "\n";
} else { } else {
Logger::info('Requested header field not found', ['field' => $h, 'header' => $headers]); DI::logger()->info('Requested header field not found', ['field' => $h, 'header' => $headers]);
} }
} }
$signed_data = rtrim($signed_data, "\n"); $signed_data = rtrim($signed_data, "\n");
if (empty($signed_data)) { if (empty($signed_data)) {
Logger::info('Signed data is empty'); DI::logger()->info('Signed data is empty');
return false; return false;
} }
@ -697,18 +696,18 @@ class HTTPSignature
} }
if (empty($algorithm)) { if (empty($algorithm)) {
Logger::info('No algorithm'); DI::logger()->info('No algorithm');
return false; return false;
} }
$key = self::fetchKey($sig_block['keyId'], $actor); $key = self::fetchKey($sig_block['keyId'], $actor);
if (empty($key)) { if (empty($key)) {
Logger::info('Empty key'); DI::logger()->info('Empty key');
return false; return false;
} }
if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) { if (!empty($key['url']) && !empty($key['type']) && ($key['type'] == 'Tombstone')) {
Logger::info('Actor is a tombstone', ['key' => $key]); DI::logger()->info('Actor is a tombstone', ['key' => $key]);
if (!Contact::isLocal($key['url'])) { if (!Contact::isLocal($key['url'])) {
// We now delete everything that we possibly knew from this actor // We now delete everything that we possibly knew from this actor
@ -718,12 +717,12 @@ class HTTPSignature
} }
if (empty($key['pubkey'])) { if (empty($key['pubkey'])) {
Logger::info('Empty pubkey'); DI::logger()->info('Empty pubkey');
return false; return false;
} }
if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) { if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key['pubkey'], $algorithm)) {
Logger::info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]); DI::logger()->info('Verification failed', ['signed_data' => $signed_data, 'algorithm' => $algorithm, 'header' => $sig_block['headers'], 'http_headers' => $http_headers]);
return false; return false;
} }
@ -742,7 +741,7 @@ class HTTPSignature
/// @todo add all hashes from the rfc /// @todo add all hashes from the rfc
if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) { if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
Logger::info('Digest does not match'); DI::logger()->info('Digest does not match');
return false; return false;
} }
@ -769,23 +768,23 @@ class HTTPSignature
// Calculate with a grace period of 60 seconds to avoid slight time differences between the servers // Calculate with a grace period of 60 seconds to avoid slight time differences between the servers
if (($created - 60) > $current) { if (($created - 60) > $current) {
Logger::notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); DI::logger()->notice('Signature created in the future', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
return false; return false;
} }
if ($current > $expired) { if ($current > $expired) {
Logger::notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); DI::logger()->notice('Signature expired', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
return false; return false;
} }
Logger::debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]); DI::logger()->debug('Valid creation date', ['created' => date(DateTimeFormat::MYSQL, $created), 'expired' => date(DateTimeFormat::MYSQL, $expired), 'current' => date(DateTimeFormat::MYSQL, $current)]);
$hasGoodSignedContent = true; $hasGoodSignedContent = true;
} }
// Check the content-length when it is part of the signed data // Check the content-length when it is part of the signed data
if (in_array('content-length', $sig_block['headers'])) { if (in_array('content-length', $sig_block['headers'])) {
if (strlen($content) != $headers['content-length']) { if (strlen($content) != $headers['content-length']) {
Logger::info('Content length does not match'); DI::logger()->info('Content length does not match');
return false; return false;
} }
} }
@ -793,7 +792,7 @@ class HTTPSignature
// Ensure that the authentication had been done with some content // Ensure that the authentication had been done with some content
// Without this check someone could authenticate with fakeable data // Without this check someone could authenticate with fakeable data
if (!$hasGoodSignedContent) { if (!$hasGoodSignedContent) {
Logger::info('No good signed content'); DI::logger()->info('No good signed content');
return false; return false;
} }
@ -815,17 +814,17 @@ class HTTPSignature
$profile = APContact::getByURL($url); $profile = APContact::getByURL($url);
if (!empty($profile)) { if (!empty($profile)) {
Logger::info('Taking key from id', ['id' => $id]); DI::logger()->info('Taking key from id', ['id' => $id]);
return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']]; return ['url' => $url, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
} elseif ($url != $actor) { } elseif ($url != $actor) {
$profile = APContact::getByURL($actor); $profile = APContact::getByURL($actor);
if (!empty($profile)) { if (!empty($profile)) {
Logger::info('Taking key from actor', ['actor' => $actor]); DI::logger()->info('Taking key from actor', ['actor' => $actor]);
return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']]; return ['url' => $actor, 'pubkey' => $profile['pubkey'], 'type' => $profile['type']];
} }
} }
Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]); DI::logger()->notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);
return []; return [];
} }
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Photo; use Friendica\Model\Photo;
use Friendica\Network\HTTPClient\Client\HttpClientAccept; use Friendica\Network\HTTPClient\Client\HttpClientAccept;
@ -103,7 +102,7 @@ class Images
} }
} }
Logger::debug('Undetected mimetype', ['mimetype' => $mimetype]); DI::logger()->debug('Undetected mimetype', ['mimetype' => $mimetype]);
return 0; return 0;
} }
@ -116,7 +115,7 @@ class Images
public static function getExtensionByImageType(int $type): string public static function getExtensionByImageType(int $type): string
{ {
if (empty($type)) { if (empty($type)) {
Logger::debug('Invalid image type', ['type' => $type]); DI::logger()->debug('Invalid image type', ['type' => $type]);
return ''; return '';
} }
@ -201,7 +200,7 @@ class Images
return $image['mime']; return $image['mime'];
} }
Logger::debug('Undetected mime type', ['image' => $image, 'size' => strlen($image_data)]); DI::logger()->debug('Undetected mime type', ['image' => $image, 'size' => strlen($image_data)]);
return ''; return '';
} }
@ -284,7 +283,7 @@ class Images
} }
} }
Logger::debug('Unhandled extension', ['filename' => $filename, 'extension' => $ext]); DI::logger()->debug('Unhandled extension', ['filename' => $filename, 'extension' => $ext]);
return ''; return '';
} }
@ -345,7 +344,7 @@ class Images
try { try {
$img_str = DI::httpClient()->fetch($url, HttpClientAccept::IMAGE, 4, '', HttpClientRequest::MEDIAVERIFIER); $img_str = DI::httpClient()->fetch($url, HttpClientAccept::IMAGE, 4, '', HttpClientRequest::MEDIAVERIFIER);
} catch (\Exception $exception) { } catch (\Exception $exception) {
Logger::notice('Image is invalid', ['url' => $url, 'exception' => $exception]); DI::logger()->notice('Image is invalid', ['url' => $url, 'exception' => $exception]);
return []; return [];
} }
} }

View file

@ -8,7 +8,6 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Cache\Enum\Duration; use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Logger;
use Exception; use Exception;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\DI; use Friendica\DI;
@ -72,7 +71,7 @@ class JsonLD
$url = DI::basePath() . '/static/apschema.jsonld'; $url = DI::basePath() . '/static/apschema.jsonld';
break; break;
default: default:
Logger::info('Got url', ['url' => $url]); DI::logger()->info('Got url', ['url' => $url]);
break; break;
} }
} }
@ -89,7 +88,7 @@ class JsonLD
} }
if ($recursion > 5) { if ($recursion > 5) {
Logger::error('jsonld bomb detected at: ' . $url); DI::logger()->error('jsonld bomb detected at: ' . $url);
System::exit(); System::exit();
} }
@ -127,9 +126,9 @@ class JsonLD
$messages[] = $currentException->getMessage(); $messages[] = $currentException->getMessage();
} while ($currentException = $currentException->getPrevious()); } while ($currentException = $currentException->getPrevious());
Logger::notice('JsonLD normalize error', ['messages' => $messages]); DI::logger()->notice('JsonLD normalize error', ['messages' => $messages]);
Logger::info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]); DI::logger()->info('JsonLD normalize error', ['trace' => $e->getTraceAsString()]);
Logger::debug('JsonLD normalize error', ['jsonobj' => $jsonobj]); DI::logger()->debug('JsonLD normalize error', ['jsonobj' => $jsonobj]);
} }
return $normalized; return $normalized;
@ -176,18 +175,18 @@ class JsonLD
$compacted = jsonld_compact($jsonobj, $context); $compacted = jsonld_compact($jsonobj, $context);
} catch (Exception $e) { } catch (Exception $e) {
$compacted = false; $compacted = false;
Logger::notice('compacting error', ['msg' => $e->getMessage(), 'previous' => $e->getPrevious(), 'line' => $e->getLine()]); DI::logger()->notice('compacting error', ['msg' => $e->getMessage(), 'previous' => $e->getPrevious(), 'line' => $e->getLine()]);
if ($logfailed && DI::config()->get('debug', 'ap_log_failure')) { if ($logfailed && DI::config()->get('debug', 'ap_log_failure')) {
$tempfile = tempnam(System::getTempPath(), 'failed-jsonld'); $tempfile = tempnam(System::getTempPath(), 'failed-jsonld');
file_put_contents($tempfile, json_encode(['json' => $orig_json, 'msg' => $e->getMessage(), 'previous' => $e->getPrevious()], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); file_put_contents($tempfile, json_encode(['json' => $orig_json, 'msg' => $e->getMessage(), 'previous' => $e->getPrevious()], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
Logger::notice('Failed message stored', ['file' => $tempfile]); DI::logger()->notice('Failed message stored', ['file' => $tempfile]);
} }
} }
$json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true); $json = json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);
if ($json === false) { if ($json === false) {
Logger::notice('JSON encode->decode failed', ['orig_json' => $orig_json, 'compacted' => $compacted]); DI::logger()->notice('JSON encode->decode failed', ['orig_json' => $orig_json, 'compacted' => $compacted]);
$json = []; $json = [];
} }
@ -212,7 +211,7 @@ class JsonLD
// Workaround for servers with missing context // Workaround for servers with missing context
// See issue https://github.com/nextcloud/social/issues/330 // See issue https://github.com/nextcloud/social/issues/330
if (!in_array('https://w3id.org/security/v1', $json['@context'])) { if (!in_array('https://w3id.org/security/v1', $json['@context'])) {
Logger::debug('Missing security context'); DI::logger()->debug('Missing security context');
$json['@context'][] = 'https://w3id.org/security/v1'; $json['@context'][] = 'https://w3id.org/security/v1';
} }
} }
@ -220,16 +219,16 @@ class JsonLD
// Issue 14448: Peertube transmits an unexpected type and schema URL. // Issue 14448: Peertube transmits an unexpected type and schema URL.
array_walk_recursive($json['@context'], function (&$value, $key) { array_walk_recursive($json['@context'], function (&$value, $key) {
if ($key == '@type' && $value == '@json') { if ($key == '@type' && $value == '@json') {
Logger::debug('"@json" converted to "@id"'); DI::logger()->debug('"@json" converted to "@id"');
$value = '@id'; $value = '@id';
} }
if ($key == 'sc' && $value == 'http://schema.org/') { if ($key == 'sc' && $value == 'http://schema.org/') {
Logger::debug('schema.org path fixed'); DI::logger()->debug('schema.org path fixed');
$value = 'http://schema.org#'; $value = 'http://schema.org#';
} }
// Issue 14630: Wordpress Event Bridge uses a URL that cannot be retrieved // Issue 14630: Wordpress Event Bridge uses a URL that cannot be retrieved
if (is_int($key) && $value == 'https://schema.org/') { if (is_int($key) && $value == 'https://schema.org/') {
Logger::debug('https schema.org path fixed'); DI::logger()->debug('https schema.org path fixed');
$value = 'https://schema.org/docs/jsonldcontext.json#'; $value = 'https://schema.org/docs/jsonldcontext.json#';
} }
}); });
@ -237,7 +236,7 @@ class JsonLD
// Bookwyrm transmits "id" fields with "null", which isn't allowed. // Bookwyrm transmits "id" fields with "null", which isn't allowed.
array_walk_recursive($json, function (&$value, $key) { array_walk_recursive($json, function (&$value, $key) {
if ($key == 'id' && is_null($value)) { if ($key == 'id' && is_null($value)) {
Logger::debug('Fixed null id'); DI::logger()->debug('Fixed null id');
$value = ''; $value = '';
} }
}); });

View file

@ -7,7 +7,7 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Logger; use Friendica\DI;
use Friendica\Model\APContact; use Friendica\Model\APContact;
/** /**
@ -55,7 +55,7 @@ class LDSignature
$dhash = self::hash(self::signableData($data)); $dhash = self::hash(self::signableData($data));
$x = Crypto::rsaVerify($ohash . $dhash, base64_decode($data['signature']['signatureValue']), $pubkey); $x = Crypto::rsaVerify($ohash . $dhash, base64_decode($data['signature']['signatureValue']), $pubkey);
Logger::info('LD-verify', ['verified' => (int)$x, 'actor' => $profile['url']]); DI::logger()->info('LD-verify', ['verified' => (int)$x, 'actor' => $profile['url']]);
if (empty($x)) { if (empty($x)) {
return false; return false;

View file

@ -8,7 +8,6 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\DI; use Friendica\DI;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Network\HTTPClient\Client\HttpClientAccept; use Friendica\Network\HTTPClient\Client\HttpClientAccept;
@ -79,13 +78,13 @@ class Network
try { try {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::DEFAULT, $options); $curlResult = DI::httpClient()->get($url, HttpClientAccept::DEFAULT, $options);
} catch (\Exception $e) { } catch (\Exception $e) {
Logger::notice('Got exception', ['code' => $e->getCode(), 'message' => $e->getMessage()]); DI::logger()->notice('Got exception', ['code' => $e->getCode(), 'message' => $e->getMessage()]);
return false; return false;
} }
} }
if (!$curlResult->isSuccess()) { if (!$curlResult->isSuccess()) {
Logger::notice('Url not reachable', ['host' => $host, 'url' => $url]); DI::logger()->notice('Url not reachable', ['host' => $host, 'url' => $url]);
return false; return false;
} elseif ($curlResult->isRedirectUrl()) { } elseif ($curlResult->isRedirectUrl()) {
$url = $curlResult->getRedirectUrl(); $url = $curlResult->getRedirectUrl();
@ -184,7 +183,7 @@ class Network
try { try {
return self::isUriBlocked(new Uri($url)); return self::isUriBlocked(new Uri($url));
} catch (\Throwable $e) { } catch (\Throwable $e) {
Logger::warning('Invalid URL', ['url' => $url]); DI::logger()->warning('Invalid URL', ['url' => $url]);
return false; return false;
} }
} }
@ -310,7 +309,7 @@ class Network
$avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO; $avatar['url'] = DI::baseUrl() . Contact::DEFAULT_AVATAR_PHOTO;
} }
Logger::info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']); DI::logger()->info('Avatar: ' . $avatar['email'] . ' ' . $avatar['url']);
return $avatar['url']; return $avatar['url'];
} }
@ -508,7 +507,7 @@ class Network
private static function idnToAscii(string $uri): string private static function idnToAscii(string $uri): string
{ {
if (!function_exists('idn_to_ascii')) { if (!function_exists('idn_to_ascii')) {
Logger::error('IDN functions are missing.'); DI::logger()->error('IDN functions are missing.');
return $uri; return $uri;
} }
return idn_to_ascii($uri); return idn_to_ascii($uri);
@ -634,7 +633,7 @@ class Network
} }
if ($sanitized != $url) { if ($sanitized != $url) {
Logger::debug('Link got sanitized', ['url' => $url, 'sanitzed' => $sanitized]); DI::logger()->debug('Link got sanitized', ['url' => $url, 'sanitzed' => $sanitized]);
} }
return $sanitized; return $sanitized;
} }
@ -654,7 +653,7 @@ class Network
try { try {
return new Uri($uri); return new Uri($uri);
} catch (\Exception $e) { } catch (\Exception $e) {
Logger::debug('Invalid URI', ['code' => $e->getCode(), 'message' => $e->getMessage(), 'uri' => $uri]); DI::logger()->debug('Invalid URI', ['code' => $e->getCode(), 'message' => $e->getMessage(), 'uri' => $uri]);
return null; return null;
} }
} }
@ -662,10 +661,10 @@ class Network
/** /**
* Remove an Url parameter * Remove an Url parameter
* *
* @param string $url * @param string $url
* @param string $parameter * @param string $parameter
* @return string * @return string
* @throws MalformedUriException * @throws MalformedUriException
*/ */
public static function removeUrlParameter(string $url, string $parameter): string public static function removeUrlParameter(string $url, string $parameter): string
{ {

View file

@ -12,7 +12,6 @@ use DOMXPath;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Protocol\HTTP\MediaType; use Friendica\Protocol\HTTP\MediaType;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
@ -68,13 +67,13 @@ class ParseUrl
try { try {
$curlResult = DI::httpClient()->get($url, $accept, array_merge([HttpClientOptions::CONTENT_LENGTH => 1000000], $options)); $curlResult = DI::httpClient()->get($url, $accept, array_merge([HttpClientOptions::CONTENT_LENGTH => 1000000], $options));
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->notice('Got exception', ['code' => $th->getCode(), 'message' => $th->getMessage()]);
return []; return [];
} }
} }
if (!$curlResult->isSuccess()) { if (!$curlResult->isSuccess()) {
Logger::debug('Got HTTP Error', ['http error' => $curlResult->getReturnCode(), 'url' => $url]); DI::logger()->debug('Got HTTP Error', ['http error' => $curlResult->getReturnCode(), 'url' => $url]);
return []; return [];
} }
@ -210,7 +209,7 @@ class ParseUrl
]; ];
if ($count > 10) { if ($count > 10) {
Logger::warning('Endless loop detected', ['url' => $url]); DI::logger()->warning('Endless loop detected', ['url' => $url]);
return $siteinfo; return $siteinfo;
} }
@ -219,25 +218,25 @@ class ParseUrl
} else { } else {
$type = self::getContentType($url); $type = self::getContentType($url);
} }
Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]); DI::logger()->info('Got content-type', ['content-type' => $type, 'url' => $url]);
if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) { if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
$siteinfo['type'] = $type[0]; $siteinfo['type'] = $type[0];
return $siteinfo; return $siteinfo;
} }
if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) { if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]); DI::logger()->info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
return $siteinfo; return $siteinfo;
} }
try { try {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::REQUEST => HttpClientRequest::SITEINFO]); $curlResult = DI::httpClient()->get($url, HttpClientAccept::HTML, [HttpClientOptions::CONTENT_LENGTH => 1000000, HttpClientOptions::REQUEST => HttpClientRequest::SITEINFO]);
} catch (\Throwable $th) { } catch (\Throwable $th) {
Logger::info('Exception when fetching', ['url' => $url, 'code' => $th->getCode(), 'message' => $th->getMessage()]); DI::logger()->info('Exception when fetching', ['url' => $url, 'code' => $th->getCode(), 'message' => $th->getMessage()]);
return $siteinfo; return $siteinfo;
} }
if (!$curlResult->isSuccess() || empty($curlResult->getBodyString())) { if (!$curlResult->isSuccess() || empty($curlResult->getBodyString())) {
Logger::info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]); DI::logger()->info('Empty body or error when fetching', ['url' => $url, 'success' => $curlResult->isSuccess(), 'code' => $curlResult->getReturnCode()]);
return $siteinfo; return $siteinfo;
} }
@ -268,7 +267,7 @@ class ParseUrl
// See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
$charset = str_ireplace('latin-1', 'latin1', $charset); $charset = str_ireplace('latin-1', 'latin1', $charset);
Logger::info('detected charset', ['charset' => $charset]); DI::logger()->info('detected charset', ['charset' => $charset]);
$body = iconv($charset, 'UTF-8//TRANSLIT', $body); $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
} }
@ -494,7 +493,7 @@ class ParseUrl
} }
} }
Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]); DI::logger()->info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
Hook::callAll('getsiteinfo', $siteinfo); Hook::callAll('getsiteinfo', $siteinfo);
@ -746,7 +745,7 @@ class ParseUrl
{ {
$type = JsonLD::fetchElement($jsonld, '@type'); $type = JsonLD::fetchElement($jsonld, '@type');
if (empty($type)) { if (empty($type)) {
Logger::info('Empty type', ['url' => $siteinfo['url']]); DI::logger()->info('Empty type', ['url' => $siteinfo['url']]);
return $siteinfo; return $siteinfo;
} }
@ -823,7 +822,7 @@ class ParseUrl
case 'ImageObject': case 'ImageObject':
return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images'); return self::parseJsonLdMediaObject($siteinfo, $jsonld, 'images');
default: default:
Logger::info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]); DI::logger()->info('Unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
return $siteinfo; return $siteinfo;
} }
} }
@ -907,7 +906,7 @@ class ParseUrl
$jsonldinfo['author_name'] = trim($jsonld['author']); $jsonldinfo['author_name'] = trim($jsonld['author']);
} }
Logger::info('Fetched Author information', ['fetched' => $jsonldinfo]); DI::logger()->info('Fetched Author information', ['fetched' => $jsonldinfo]);
return array_merge($siteinfo, $jsonldinfo); return array_merge($siteinfo, $jsonldinfo);
} }
@ -978,7 +977,7 @@ class ParseUrl
$jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld); $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); DI::logger()->info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
return array_merge($siteinfo, $jsonldinfo); return array_merge($siteinfo, $jsonldinfo);
} }
@ -1018,7 +1017,7 @@ class ParseUrl
$jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld); $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
Logger::info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); DI::logger()->info('Fetched WebPage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
return array_merge($siteinfo, $jsonldinfo); return array_merge($siteinfo, $jsonldinfo);
} }
@ -1058,7 +1057,7 @@ class ParseUrl
$jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld); $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); DI::logger()->info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
return array_merge($siteinfo, $jsonldinfo); return array_merge($siteinfo, $jsonldinfo);
} }
@ -1107,7 +1106,7 @@ class ParseUrl
$jsonldinfo['publisher_url'] = Network::sanitizeUrl($content); $jsonldinfo['publisher_url'] = Network::sanitizeUrl($content);
} }
Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); DI::logger()->info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
return array_merge($siteinfo, $jsonldinfo); return array_merge($siteinfo, $jsonldinfo);
} }
@ -1146,14 +1145,14 @@ class ParseUrl
$content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject'); $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
if (!empty($content) && !is_string($content)) { if (!empty($content) && !is_string($content)) {
Logger::notice('Unexpected return value for the author image', ['content' => $content]); DI::logger()->notice('Unexpected return value for the author image', ['content' => $content]);
} }
if (!empty($content) && is_string($content)) { if (!empty($content) && is_string($content)) {
$jsonldinfo['author_img'] = trim($content); $jsonldinfo['author_img'] = trim($content);
} }
Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]); DI::logger()->info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
return array_merge($siteinfo, $jsonldinfo); return array_merge($siteinfo, $jsonldinfo);
} }
@ -1229,7 +1228,7 @@ class ParseUrl
} }
} }
Logger::info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]); DI::logger()->info('Fetched Media information', ['url' => $siteinfo['url'], 'fetched' => $media]);
$siteinfo[$name][] = $media; $siteinfo[$name][] = $media;
return $siteinfo; return $siteinfo;
} }

View file

@ -8,7 +8,7 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Content\ContactSelector; use Friendica\Content\ContactSelector;
use Friendica\Core\Logger; use Friendica\DI;
use ParagonIE\ConstantTime\Base64; use ParagonIE\ConstantTime\Base64;
/** /**
@ -498,7 +498,7 @@ class Strings
); );
if (is_null($return)) { if (is_null($return)) {
Logger::notice('Received null value from preg_replace_callback', ['text' => $text, 'regex' => $regex, 'blocks' => $blocks, 'executionId' => $executionId]); DI::logger()->notice('Received null value from preg_replace_callback', ['text' => $text, 'regex' => $regex, 'blocks' => $blocks, 'executionId' => $executionId]);
} }
$text = $callback($return ?? $text) ?? ''; $text = $callback($return ?? $text) ?? '';

View file

@ -11,7 +11,7 @@ use DOMDocument;
use DOMElement; use DOMElement;
use DOMNode; use DOMNode;
use DOMXPath; use DOMXPath;
use Friendica\Core\Logger; use Friendica\DI;
use SimpleXMLElement; use SimpleXMLElement;
/** /**
@ -256,7 +256,7 @@ class XML
} }
if (!function_exists('xml_parser_create')) { if (!function_exists('xml_parser_create')) {
Logger::error('Xml::toArray: parser function missing'); DI::logger()->error('Xml::toArray: parser function missing');
return []; return [];
} }
@ -272,7 +272,7 @@ class XML
} }
if (!$parser) { if (!$parser) {
Logger::warning('Xml::toArray: xml_parser_create: no resource'); DI::logger()->warning('Xml::toArray: xml_parser_create: no resource');
return []; return [];
} }
@ -284,9 +284,9 @@ class XML
@xml_parser_free($parser); @xml_parser_free($parser);
if (! $xml_values) { if (! $xml_values) {
Logger::debug('Xml::toArray: libxml: parse error: ' . $contents); DI::logger()->debug('Xml::toArray: libxml: parse error: ' . $contents);
foreach (libxml_get_errors() as $err) { foreach (libxml_get_errors() as $err) {
Logger::debug('libxml: parse: ' . $err->code . ' at ' . $err->line . ':' . $err->column . ' : ' . $err->message); DI::logger()->debug('libxml: parse: ' . $err->code . ' at ' . $err->line . ':' . $err->column . ' : ' . $err->message);
} }
libxml_clear_errors(); libxml_clear_errors();
return []; return [];
@ -436,11 +436,11 @@ class XML
$x = @simplexml_load_string($s); $x = @simplexml_load_string($s);
if (!$x) { if (!$x) {
if (!$suppress_log) { if (!$suppress_log) {
Logger::error('Error(s) while parsing XML string.'); DI::logger()->error('Error(s) while parsing XML string.');
foreach (libxml_get_errors() as $err) { foreach (libxml_get_errors() as $err) {
Logger::info('libxml error', ['code' => $err->code, 'position' => $err->line . ':' . $err->column, 'message' => $err->message]); DI::logger()->info('libxml error', ['code' => $err->code, 'position' => $err->line . ':' . $err->column, 'message' => $err->message]);
} }
Logger::debug('Erroring XML string', ['xml' => $s]); DI::logger()->debug('Erroring XML string', ['xml' => $s]);
} }
libxml_clear_errors(); libxml_clear_errors();
} }