Merge pull request #6046 from zeroadam/CoreLogger

Split functions from text.php to new Logger class
This commit is contained in:
Hypolite Petovan 2018-10-30 12:32:33 -04:00 committed by GitHub
commit 2f28c2ebbf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
123 changed files with 1425 additions and 1319 deletions

View file

@ -9,6 +9,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -97,7 +98,7 @@ if ($mode == "stop") {
unlink($pidfile); unlink($pidfile);
logger("Worker daemon process $pid was killed.", LOGGER_DEBUG); Logger::log("Worker daemon process $pid was killed.", Logger::DEBUG);
Config::set('system', 'worker_daemon_mode', false); Config::set('system', 'worker_daemon_mode', false);
die("Worker daemon process $pid was killed.\n"); die("Worker daemon process $pid was killed.\n");
@ -107,7 +108,7 @@ if (!empty($pid) && posix_kill($pid, 0)) {
die("Daemon process $pid is already running.\n"); die("Daemon process $pid is already running.\n");
} }
logger('Starting worker daemon.', LOGGER_DEBUG); Logger::log('Starting worker daemon.', Logger::DEBUG);
if (!$foreground) { if (!$foreground) {
echo "Starting worker daemon.\n"; echo "Starting worker daemon.\n";
@ -155,7 +156,7 @@ $last_cron = 0;
// Now running as a daemon. // Now running as a daemon.
while (true) { while (true) {
if (!$do_cron && ($last_cron + $wait_interval) < time()) { if (!$do_cron && ($last_cron + $wait_interval) < time()) {
logger('Forcing cron worker call.', LOGGER_DEBUG); Logger::log('Forcing cron worker call.', Logger::DEBUG);
$do_cron = true; $do_cron = true;
} }
@ -169,7 +170,7 @@ while (true) {
$last_cron = time(); $last_cron = time();
} }
logger("Sleeping", LOGGER_DEBUG); Logger::log("Sleeping", Logger::DEBUG);
$start = time(); $start = time();
do { do {
$seconds = (time() - $start); $seconds = (time() - $start);
@ -186,10 +187,10 @@ while (true) {
if ($timeout) { if ($timeout) {
$do_cron = true; $do_cron = true;
logger("Woke up after $wait_interval seconds.", LOGGER_DEBUG); Logger::log("Woke up after $wait_interval seconds.", Logger::DEBUG);
} else { } else {
$do_cron = false; $do_cron = false;
logger("Worker jobs are calling to be forked.", LOGGER_DEBUG); Logger::log("Worker jobs are calling to be forked.", Logger::DEBUG);
} }
} }

View file

@ -106,20 +106,6 @@ define('SSL_POLICY_FULL', 1);
define('SSL_POLICY_SELFSIGN', 2); define('SSL_POLICY_SELFSIGN', 2);
/* @}*/ /* @}*/
/**
* @name Logger
*
* log levels
* @{
*/
define('LOGGER_WARNING', 0);
define('LOGGER_INFO', 1);
define('LOGGER_TRACE', 2);
define('LOGGER_DEBUG', 3);
define('LOGGER_DATA', 4);
define('LOGGER_ALL', 5);
/* @}*/
/** /**
* @name Register * @name Register
* *

View file

@ -15,6 +15,7 @@ use Friendica\Core\Addon;
use Friendica\Core\Authentication; use Friendica\Core\Authentication;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\NotificationsManager; use Friendica\Core\NotificationsManager;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
@ -96,9 +97,9 @@ function api_source()
return "Twidere"; return "Twidere";
} }
logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG); Logger::log("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], Logger::DEBUG);
} else { } else {
logger("Empty user-agent", LOGGER_DEBUG); Logger::log("Empty user-agent", Logger::DEBUG);
} }
return "api"; return "api";
@ -180,7 +181,7 @@ function api_login(App $a)
var_dump($consumer, $token); var_dump($consumer, $token);
die(); die();
} catch (Exception $e) { } catch (Exception $e) {
logger($e); Logger::log($e);
} }
// workaround for HTTP-auth in CGI mode // workaround for HTTP-auth in CGI mode
@ -194,7 +195,7 @@ function api_login(App $a)
} }
if (!x($_SERVER, 'PHP_AUTH_USER')) { if (!x($_SERVER, 'PHP_AUTH_USER')) {
logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG); Logger::log('API_login: ' . print_r($_SERVER, true), Logger::DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"'); header('WWW-Authenticate: Basic realm="Friendica"');
throw new UnauthorizedException("This API requires login"); throw new UnauthorizedException("This API requires login");
} }
@ -235,7 +236,7 @@ function api_login(App $a)
} }
if (!DBA::isResult($record)) { if (!DBA::isResult($record)) {
logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG); Logger::log('API_login failure: ' . print_r($_SERVER, true), Logger::DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"'); header('WWW-Authenticate: Basic realm="Friendica"');
//header('HTTP/1.0 401 Unauthorized'); //header('HTTP/1.0 401 Unauthorized');
//die('This api requires login'); //die('This api requires login');
@ -308,19 +309,19 @@ function api_call(App $a)
api_login($a); api_login($a);
} }
logger('API call for ' . $a->user['username'] . ': ' . $a->query_string); Logger::log('API call for ' . $a->user['username'] . ': ' . $a->query_string);
logger('API parameters: ' . print_r($_REQUEST, true)); Logger::log('API parameters: ' . print_r($_REQUEST, true));
$stamp = microtime(true); $stamp = microtime(true);
$return = call_user_func($info['func'], $type); $return = call_user_func($info['func'], $type);
$duration = (float) (microtime(true) - $stamp); $duration = (float) (microtime(true) - $stamp);
logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG); Logger::log("API call duration: " . round($duration, 2) . "\t" . $a->query_string, Logger::DEBUG);
if (Config::get("system", "profiler")) { if (Config::get("system", "profiler")) {
$duration = microtime(true)-$a->performance["start"]; $duration = microtime(true)-$a->performance["start"];
/// @TODO round() really everywhere? /// @TODO round() really everywhere?
logger( Logger::log(
parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf( parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
"Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s", "Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
round($a->performance["database"] - $a->performance["database_write"], 3), round($a->performance["database"] - $a->performance["database_write"], 3),
@ -334,7 +335,7 @@ function api_call(App $a)
+ $a->performance["network"] + $a->performance["file"]), 2), + $a->performance["network"] + $a->performance["file"]), 2),
round($duration, 2) round($duration, 2)
), ),
LOGGER_DEBUG Logger::DEBUG
); );
if (Config::get("rendertime", "callstack")) { if (Config::get("rendertime", "callstack")) {
@ -375,7 +376,7 @@ function api_call(App $a)
$o .= $func . ": " . $time . "\n"; $o .= $func . ": " . $time . "\n";
} }
} }
logger($o, LOGGER_DEBUG); Logger::log($o, Logger::DEBUG);
} }
} }
@ -412,7 +413,7 @@ function api_call(App $a)
} }
} }
logger('API call not implemented: ' . $a->query_string); Logger::log('API call not implemented: ' . $a->query_string);
throw new NotImplementedException(); throw new NotImplementedException();
} catch (HTTPException $e) { } catch (HTTPException $e) {
header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}"); header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
@ -521,7 +522,7 @@ function api_get_user(App $a, $contact_id = null)
$extra_query = ""; $extra_query = "";
$url = ""; $url = "";
logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG); Logger::log("api_get_user: Fetching user data for user ".$contact_id, Logger::DEBUG);
// Searching for contact URL // Searching for contact URL
if (!is_null($contact_id) && (intval($contact_id) == 0)) { if (!is_null($contact_id) && (intval($contact_id) == 0)) {
@ -605,7 +606,7 @@ function api_get_user(App $a, $contact_id = null)
} }
} }
logger("api_get_user: user ".$user, LOGGER_DEBUG); Logger::log("api_get_user: user ".$user, Logger::DEBUG);
if (!$user) { if (!$user) {
if (api_user() === false) { if (api_user() === false) {
@ -617,7 +618,7 @@ function api_get_user(App $a, $contact_id = null)
} }
} }
logger('api_user: ' . $extra_query . ', user: ' . $user); Logger::log('api_user: ' . $extra_query . ', user: ' . $user);
// user info // user info
$uinfo = q( $uinfo = q(
@ -1033,7 +1034,7 @@ function api_statuses_mediap($type)
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
logger('api_statuses_update: no user'); Logger::log('api_statuses_update: no user');
throw new ForbiddenException(); throw new ForbiddenException();
} }
$user_info = api_get_user($a); $user_info = api_get_user($a);
@ -1081,7 +1082,7 @@ function api_statuses_update($type)
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
logger('api_statuses_update: no user'); Logger::log('api_statuses_update: no user');
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -1135,7 +1136,7 @@ function api_statuses_update($type)
$posts_day = DBA::count('thread', $condition); $posts_day = DBA::count('thread', $condition);
if ($posts_day > $throttle_day) { if ($posts_day > $throttle_day) {
logger('Daily posting limit reached for user '.api_user(), LOGGER_DEBUG); Logger::log('Daily posting limit reached for user '.api_user(), Logger::DEBUG);
// die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day)); // die(api_error($type, L10n::t("Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day)); throw new TooManyRequestsException(L10n::tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day));
} }
@ -1149,7 +1150,7 @@ function api_statuses_update($type)
$posts_week = DBA::count('thread', $condition); $posts_week = DBA::count('thread', $condition);
if ($posts_week > $throttle_week) { if ($posts_week > $throttle_week) {
logger('Weekly posting limit reached for user '.api_user(), LOGGER_DEBUG); Logger::log('Weekly posting limit reached for user '.api_user(), Logger::DEBUG);
// die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week))); // die(api_error($type, L10n::t("Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)));
throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week)); throw new TooManyRequestsException(L10n::tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week));
} }
@ -1163,7 +1164,7 @@ function api_statuses_update($type)
$posts_month = DBA::count('thread', $condition); $posts_month = DBA::count('thread', $condition);
if ($posts_month > $throttle_month) { if ($posts_month > $throttle_month) {
logger('Monthly posting limit reached for user '.api_user(), LOGGER_DEBUG); Logger::log('Monthly posting limit reached for user '.api_user(), Logger::DEBUG);
// die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month)); // die(api_error($type, L10n::t("Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month)); throw new TooManyRequestsException(L10n::t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month));
} }
@ -1223,7 +1224,7 @@ function api_media_upload()
$a = get_app(); $a = get_app();
if (api_user() === false) { if (api_user() === false) {
logger('no user'); Logger::log('no user');
throw new ForbiddenException(); throw new ForbiddenException();
} }
@ -1248,7 +1249,7 @@ function api_media_upload()
"h" => $media["height"], "h" => $media["height"],
"image_type" => $media["type"]]; "image_type" => $media["type"]];
logger("Media uploaded: " . print_r($returndata, true), LOGGER_DEBUG); Logger::log("Media uploaded: " . print_r($returndata, true), Logger::DEBUG);
return ["media" => $returndata]; return ["media" => $returndata];
} }
@ -1268,7 +1269,7 @@ function api_status_show($type, $item_id = 0)
$user_info = api_get_user($a); $user_info = api_get_user($a);
logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG); Logger::log('api_status_show: user_info: '.print_r($user_info, true), Logger::DEBUG);
if ($type == "raw") { if ($type == "raw") {
$privacy_sql = "AND NOT `private`"; $privacy_sql = "AND NOT `private`";
@ -1344,7 +1345,7 @@ function api_status_show($type, $item_id = 0)
unset($status_info["user"]["uid"]); unset($status_info["user"]["uid"]);
unset($status_info["user"]["self"]); unset($status_info["user"]["self"]);
logger('status_info: '.print_r($status_info, true), LOGGER_DEBUG); Logger::log('status_info: '.print_r($status_info, true), Logger::DEBUG);
if ($type == "raw") { if ($type == "raw") {
return $status_info; return $status_info;
@ -1824,7 +1825,7 @@ function api_statuses_show($type)
$id = intval(defaults($a->argv, 4, 0)); $id = intval(defaults($a->argv, 4, 0));
} }
logger('API: api_statuses_show: ' . $id); Logger::log('API: api_statuses_show: ' . $id);
$conversation = !empty($_REQUEST['conversation']); $conversation = !empty($_REQUEST['conversation']);
@ -1906,7 +1907,7 @@ function api_conversation_show($type)
$id = intval(defaults($a->argv, 4, 0)); $id = intval(defaults($a->argv, 4, 0));
} }
logger('API: api_conversation_show: '.$id); Logger::log('API: api_conversation_show: '.$id);
// try to fetch the item for the local user - or the public item, if there is no local one // try to fetch the item for the local user - or the public item, if there is no local one
$item = Item::selectFirst(['parent-uri'], ['id' => $id]); $item = Item::selectFirst(['parent-uri'], ['id' => $id]);
@ -1977,7 +1978,7 @@ function api_statuses_repeat($type)
$id = intval(defaults($a->argv, 4, 0)); $id = intval(defaults($a->argv, 4, 0));
} }
logger('API: api_statuses_repeat: '.$id); Logger::log('API: api_statuses_repeat: '.$id);
$fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink']; $fields = ['body', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
$item = Item::selectFirst($fields, ['id' => $id, 'private' => false]); $item = Item::selectFirst($fields, ['id' => $id, 'private' => false]);
@ -2042,7 +2043,7 @@ function api_statuses_destroy($type)
$id = intval(defaults($a->argv, 4, 0)); $id = intval(defaults($a->argv, 4, 0));
} }
logger('API: api_statuses_destroy: '.$id); Logger::log('API: api_statuses_destroy: '.$id);
$ret = api_statuses_show($type); $ret = api_statuses_show($type);
@ -2137,11 +2138,11 @@ function api_statuses_user_timeline($type)
throw new ForbiddenException(); throw new ForbiddenException();
} }
logger( Logger::log(
"api_statuses_user_timeline: api_user: ". api_user() . "api_statuses_user_timeline: api_user: ". api_user() .
"\nuser_info: ".print_r($user_info, true) . "\nuser_info: ".print_r($user_info, true) .
"\n_REQUEST: ".print_r($_REQUEST, true), "\n_REQUEST: ".print_r($_REQUEST, true),
LOGGER_DEBUG Logger::DEBUG
); );
$since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0; $since_id = x($_REQUEST, 'since_id') ? $_REQUEST['since_id'] : 0;
@ -2294,7 +2295,7 @@ function api_favorites($type)
// in friendica starred item are private // in friendica starred item are private
// return favorites only for self // return favorites only for self
logger('api_favorites: self:' . $user_info['self']); Logger::log('api_favorites: self:' . $user_info['self']);
if ($user_info['self'] == 0) { if ($user_info['self'] == 0) {
$ret = []; $ret = [];
@ -3649,7 +3650,7 @@ function api_friendships_destroy($type)
$contact_id = defaults($_REQUEST, 'user_id'); $contact_id = defaults($_REQUEST, 'user_id');
if (empty($contact_id)) { if (empty($contact_id)) {
logger("No user_id specified", LOGGER_DEBUG); Logger::log("No user_id specified", Logger::DEBUG);
throw new BadRequestException("no user_id specified"); throw new BadRequestException("no user_id specified");
} }
@ -3657,7 +3658,7 @@ function api_friendships_destroy($type)
$contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]); $contact = DBA::selectFirst('contact', ['url'], ['id' => $contact_id, 'uid' => 0, 'self' => false]);
if(!DBA::isResult($contact)) { if(!DBA::isResult($contact)) {
logger("No contact found for ID" . $contact_id, LOGGER_DEBUG); Logger::log("No contact found for ID" . $contact_id, Logger::DEBUG);
throw new NotFoundException("no contact found to given ID"); throw new NotFoundException("no contact found to given ID");
} }
@ -3669,12 +3670,12 @@ function api_friendships_destroy($type)
$contact = DBA::selectFirst('contact', [], $condition); $contact = DBA::selectFirst('contact', [], $condition);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
logger("Not following Contact", LOGGER_DEBUG); Logger::log("Not following Contact", Logger::DEBUG);
throw new NotFoundException("Not following Contact"); throw new NotFoundException("Not following Contact");
} }
if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) { if (!in_array($contact['network'], Protocol::NATIVE_SUPPORT)) {
logger("Not supported", LOGGER_DEBUG); Logger::log("Not supported", Logger::DEBUG);
throw new ExpectationFailedException("Not supported"); throw new ExpectationFailedException("Not supported");
} }
@ -3685,7 +3686,7 @@ function api_friendships_destroy($type)
Contact::terminateFriendship($owner, $contact, $dissolve); Contact::terminateFriendship($owner, $contact, $dissolve);
} }
else { else {
logger("No owner found", LOGGER_DEBUG); Logger::log("No owner found", Logger::DEBUG);
throw new NotFoundException("Error Processing Request"); throw new NotFoundException("Error Processing Request");
} }
@ -4485,10 +4486,10 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
if ($imagedata) { if ($imagedata) {
$filetype = $imagedata['mime']; $filetype = $imagedata['mime'];
} }
logger( Logger::log(
"File upload src: " . $src . " - filename: " . $filename . "File upload src: " . $src . " - filename: " . $filename .
" - size: " . $filesize . " - type: " . $filetype, " - size: " . $filesize . " - type: " . $filetype,
LOGGER_DEBUG Logger::DEBUG
); );
// check if there was a php upload error // check if there was a php upload error
@ -4520,7 +4521,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
} }
if ($max_length > 0) { if ($max_length > 0) {
$Image->scaleDown($max_length); $Image->scaleDown($max_length);
logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG); Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
} }
$width = $Image->getWidth(); $width = $Image->getWidth();
$height = $Image->getHeight(); $height = $Image->getHeight();
@ -4530,17 +4531,17 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
if ($mediatype == "photo") { if ($mediatype == "photo") {
// upload normal image (scales 0, 1, 2) // upload normal image (scales 0, 1, 2)
logger("photo upload: starting new photo upload", LOGGER_DEBUG); Logger::log("photo upload: starting new photo upload", Logger::DEBUG);
$r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 0, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) { if (!$r) {
logger("photo upload: image upload with scale 0 (original size) failed"); Logger::log("photo upload: image upload with scale 0 (original size) failed");
} }
if ($width > 640 || $height > 640) { if ($width > 640 || $height > 640) {
$Image->scaleDown(640); $Image->scaleDown(640);
$r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 1, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) { if (!$r) {
logger("photo upload: image upload with scale 1 (640x640) failed"); Logger::log("photo upload: image upload with scale 1 (640x640) failed");
} }
} }
@ -4548,19 +4549,19 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
$Image->scaleDown(320); $Image->scaleDown(320);
$r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 2, 0, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) { if (!$r) {
logger("photo upload: image upload with scale 2 (320x320) failed"); Logger::log("photo upload: image upload with scale 2 (320x320) failed");
} }
} }
logger("photo upload: new photo upload ended", LOGGER_DEBUG); Logger::log("photo upload: new photo upload ended", Logger::DEBUG);
} elseif ($mediatype == "profileimage") { } elseif ($mediatype == "profileimage") {
// upload profile image (scales 4, 5, 6) // upload profile image (scales 4, 5, 6)
logger("photo upload: starting new profile image upload", LOGGER_DEBUG); Logger::log("photo upload: starting new profile image upload", Logger::DEBUG);
if ($width > 300 || $height > 300) { if ($width > 300 || $height > 300) {
$Image->scaleDown(300); $Image->scaleDown(300);
$r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 4, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) { if (!$r) {
logger("photo upload: profile image upload with scale 4 (300x300) failed"); Logger::log("photo upload: profile image upload with scale 4 (300x300) failed");
} }
} }
@ -4568,7 +4569,7 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
$Image->scaleDown(80); $Image->scaleDown(80);
$r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 5, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) { if (!$r) {
logger("photo upload: profile image upload with scale 5 (80x80) failed"); Logger::log("photo upload: profile image upload with scale 5 (80x80) failed");
} }
} }
@ -4576,11 +4577,11 @@ function save_media_to_database($mediatype, $media, $type, $album, $allow_cid, $
$Image->scaleDown(48); $Image->scaleDown(48);
$r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc); $r = Photo::store($Image, local_user(), $visitor, $hash, $filename, $album, 6, $profile, $allow_cid, $allow_gid, $deny_cid, $deny_gid, $desc);
if (!$r) { if (!$r) {
logger("photo upload: profile image upload with scale 6 (48x48) failed"); Logger::log("photo upload: profile image upload with scale 6 (48x48) failed");
} }
} }
$Image->__destruct(); $Image->__destruct();
logger("photo upload: new profile image upload ended", LOGGER_DEBUG); Logger::log("photo upload: new profile image upload ended", Logger::DEBUG);
} }
if (isset($r) && $r) { if (isset($r) && $r) {
@ -4807,7 +4808,7 @@ function api_friendica_remoteauth()
'sec' => $sec, 'expire' => time() + 45]; 'sec' => $sec, 'expire' => time() + 45];
DBA::insert('profile_check', $fields); DBA::insert('profile_check', $fields);
logger($contact['name'] . ' ' . $sec, LOGGER_DEBUG); Logger::log($contact['name'] . ' ' . $sec, Logger::DEBUG);
$dest = ($url ? '&destination_url=' . $url : ''); $dest = ($url ? '&destination_url=' . $url : '');
System::externalRedirect( System::externalRedirect(
@ -5055,7 +5056,7 @@ function api_in_reply_to($item)
// https://github.com/friendica/friendica/issues/1010 // https://github.com/friendica/friendica/issues/1010
// This is a bugfix for that. // This is a bugfix for that.
if (intval($in_reply_to['status_id']) == intval($item['id'])) { if (intval($in_reply_to['status_id']) == intval($item['id'])) {
logger('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], LOGGER_DEBUG); Logger::log('this message should never appear: id: '.$item['id'].' similar to reply-to: '.$in_reply_to['status_id'], Logger::DEBUG);
$in_reply_to['status_id'] = null; $in_reply_to['status_id'] = null;
$in_reply_to['user_id'] = null; $in_reply_to['user_id'] = null;
$in_reply_to['status_id_str'] = null; $in_reply_to['status_id_str'] = null;

View file

@ -11,6 +11,7 @@ use Friendica\Content\Text\BBCode;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
@ -751,7 +752,7 @@ function conversation(App $a, array $items, Pager $pager, $mode, $update, $previ
$threads = $conv->getTemplateData($conv_responses); $threads = $conv->getTemplateData($conv_responses);
if (!$threads) { if (!$threads) {
logger('[ERROR] conversation : Failed to get template data.', LOGGER_DEBUG); Logger::log('[ERROR] conversation : Failed to get template data.', Logger::DEBUG);
$threads = []; $threads = [];
} }
} }

View file

@ -7,6 +7,7 @@ use Friendica\Content\Text\BBCode;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -29,7 +30,7 @@ function notification($params)
// Temporary logging for finding the origin // Temporary logging for finding the origin
if (!isset($params['language']) || !isset($params['uid'])) { if (!isset($params['language']) || !isset($params['uid'])) {
logger('Missing parameters.' . System::callstack()); Logger::log('Missing parameters.' . System::callstack());
} }
// Ensure that the important fields are set at any time // Ensure that the important fields are set at any time
@ -37,7 +38,7 @@ function notification($params)
$user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]); $user = DBA::selectFirst('user', $fields, ['uid' => $params['uid']]);
if (!DBA::isResult($user)) { if (!DBA::isResult($user)) {
logger('Unknown user ' . $params['uid']); Logger::log('Unknown user ' . $params['uid']);
return; return;
} }
@ -133,7 +134,7 @@ function notification($params)
if ($params['type'] == NOTIFY_COMMENT) { if ($params['type'] == NOTIFY_COMMENT) {
$thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]); $thread = Item::selectFirstThreadForUser($params['uid'] ,['ignored'], ['iid' => $parent_id]);
if (DBA::isResult($thread) && $thread["ignored"]) { if (DBA::isResult($thread) && $thread["ignored"]) {
logger("Thread ".$parent_id." will be ignored", LOGGER_DEBUG); Logger::log("Thread ".$parent_id." will be ignored", Logger::DEBUG);
L10n::popLang(); L10n::popLang();
return; return;
} }
@ -452,7 +453,7 @@ function notification($params)
$itemlink = $h['itemlink']; $itemlink = $h['itemlink'];
if ($show_in_notification_page) { if ($show_in_notification_page) {
logger("adding notification entry", LOGGER_DEBUG); Logger::log("adding notification entry", Logger::DEBUG);
do { do {
$dups = false; $dups = false;
$hash = random_string(); $hash = random_string();
@ -529,14 +530,14 @@ function notification($params)
|| $params['type'] == NOTIFY_SYSTEM || $params['type'] == NOTIFY_SYSTEM
|| $params['type'] == SYSTEM_EMAIL) { || $params['type'] == SYSTEM_EMAIL) {
logger('sending notification email'); Logger::log('sending notification email');
if (isset($params['parent']) && (intval($params['parent']) != 0)) { if (isset($params['parent']) && (intval($params['parent']) != 0)) {
$id_for_parent = $params['parent']."@".$hostname; $id_for_parent = $params['parent']."@".$hostname;
// Is this the first email notification for this parent item and user? // Is this the first email notification for this parent item and user?
if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) { if (!DBA::exists('notify-threads', ['master-parent-item' => $params['parent'], 'receiver-uid' => $params['uid']])) {
logger("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), LOGGER_DEBUG); Logger::log("notify_id:".intval($notify_id).", parent: ".intval($params['parent'])."uid: ".intval($params['uid']), Logger::DEBUG);
$fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'], $fields = ['notify-id' => $notify_id, 'master-parent-item' => $params['parent'],
'receiver-uid' => $params['uid'], 'parent-item' => 0]; 'receiver-uid' => $params['uid'], 'parent-item' => 0];
@ -545,11 +546,11 @@ function notification($params)
$additional_mail_header .= "Message-ID: <${id_for_parent}>\n"; $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
$log_msg = "include/enotify: No previous notification found for this parent:\n". $log_msg = "include/enotify: No previous notification found for this parent:\n".
" parent: ${params['parent']}\n"." uid : ${params['uid']}\n"; " parent: ${params['parent']}\n"." uid : ${params['uid']}\n";
logger($log_msg, LOGGER_DEBUG); Logger::log($log_msg, Logger::DEBUG);
} else { } else {
// If not, just "follow" the thread. // If not, just "follow" the thread.
$additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n"; $additional_mail_header .= "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
logger("There's already a notification for this parent.", LOGGER_DEBUG); Logger::log("There's already a notification for this parent.", Logger::DEBUG);
} }
} }

View file

@ -8,6 +8,7 @@ use Friendica\Content\Feature;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
@ -109,7 +110,7 @@ function query_page_info($url, $photo = "", $keywords = false, $keyword_blacklis
$data["images"][0]["src"] = $photo; $data["images"][0]["src"] = $photo;
} }
logger('fetch page info for ' . $url . ' ' . print_r($data, true), LOGGER_DEBUG); Logger::log('fetch page info for ' . $url . ' ' . print_r($data, true), Logger::DEBUG);
if (!$keywords && isset($data["keywords"])) { if (!$keywords && isset($data["keywords"])) {
unset($data["keywords"]); unset($data["keywords"]);
@ -167,7 +168,7 @@ function add_page_info($url, $no_photos = false, $photo = "", $keywords = false,
function add_page_info_to_body($body, $texturl = false, $no_photos = false) function add_page_info_to_body($body, $texturl = false, $no_photos = false)
{ {
logger('add_page_info_to_body: fetch page info for body ' . $body, LOGGER_DEBUG); Logger::log('add_page_info_to_body: fetch page info for body ' . $body, Logger::DEBUG);
$URLSearchString = "^\[\]"; $URLSearchString = "^\[\]";
@ -251,7 +252,7 @@ function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0
// Test - remove before flight // Test - remove before flight
//$tempfile = tempnam(get_temppath(), "ostatus2"); //$tempfile = tempnam(get_temppath(), "ostatus2");
//file_put_contents($tempfile, $xml); //file_put_contents($tempfile, $xml);
logger("Consume OStatus messages ", LOGGER_DEBUG); Logger::log("Consume OStatus messages ", Logger::DEBUG);
OStatus::import($xml, $importer, $contact, $hub); OStatus::import($xml, $importer, $contact, $hub);
} }
@ -260,7 +261,7 @@ function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0
if ($contact['network'] === Protocol::FEED) { if ($contact['network'] === Protocol::FEED) {
if ($pass < 2) { if ($pass < 2) {
logger("Consume feeds", LOGGER_DEBUG); Logger::log("Consume feeds", Logger::DEBUG);
Feed::import($xml, $importer, $contact, $hub); Feed::import($xml, $importer, $contact, $hub);
} }
@ -268,10 +269,10 @@ function consume_feed($xml, array $importer, array $contact, &$hub, $datedir = 0
} }
if ($contact['network'] === Protocol::DFRN) { if ($contact['network'] === Protocol::DFRN) {
logger("Consume DFRN messages", LOGGER_DEBUG); Logger::log("Consume DFRN messages", Logger::DEBUG);
$dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]); $dfrn_importer = DFRN::getImporter($contact["id"], $importer["uid"]);
if (!empty($dfrn_importer)) { if (!empty($dfrn_importer)) {
logger("Now import the DFRN feed"); Logger::log("Now import the DFRN feed");
DFRN::import($xml, $dfrn_importer, true); DFRN::import($xml, $dfrn_importer, true);
return; return;
} }
@ -310,7 +311,7 @@ function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'sub
$params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token; $params= 'hub.mode=' . $hubmode . '&hub.callback=' . urlencode($push_url) . '&hub.topic=' . urlencode($contact['poll']) . '&hub.verify=async&hub.verify_token=' . $verify_token;
logger('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token); Logger::log('subscribe_to_hub: ' . $hubmode . ' ' . $contact['name'] . ' to hub ' . $url . ' endpoint: ' . $push_url . ' with verifier ' . $verify_token);
if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) { if (!strlen($contact['hub-verify']) || ($contact['hub-verify'] != $verify_token)) {
DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]); DBA::update('contact', ['hub-verify' => $verify_token], ['id' => $contact['id']]);
@ -318,7 +319,7 @@ function subscribe_to_hub($url, array $importer, array $contact, $hubmode = 'sub
$postResult = Network::post($url, $params); $postResult = Network::post($url, $params);
logger('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), LOGGER_DEBUG); Logger::log('subscribe_to_hub: returns: ' . $postResult->getReturnCode(), Logger::DEBUG);
return; return;

View file

@ -23,6 +23,8 @@ use Friendica\Util\DateTimeFormat;
use Friendica\Util\Map; use Friendica\Util\Map;
use Friendica\Util\Proxy as ProxyUtils; use Friendica\Util\Proxy as ProxyUtils;
use Friendica\Core\Logger;
require_once "include/conversation.php"; require_once "include/conversation.php";
/** /**
@ -379,139 +381,6 @@ function attribute_contains($attr, $s) {
return (count($a) && in_array($s,$a)); return (count($a) && in_array($s,$a));
} }
/* setup int->string log level map */
$LOGGER_LEVELS = [];
/**
* @brief Logs the given message at the given log level
*
* log levels:
* LOGGER_WARNING
* LOGGER_INFO (default)
* LOGGER_TRACE
* LOGGER_DEBUG
* LOGGER_DATA
* LOGGER_ALL
*
* @global array $LOGGER_LEVELS
* @param string $msg
* @param int $level
*/
function logger($msg, $level = LOGGER_INFO) {
$a = get_app();
global $LOGGER_LEVELS;
$debugging = Config::get('system', 'debugging');
$logfile = Config::get('system', 'logfile');
$loglevel = intval(Config::get('system', 'loglevel'));
if (
!$debugging
|| !$logfile
|| $level > $loglevel
) {
return;
}
if (count($LOGGER_LEVELS) == 0) {
foreach (get_defined_constants() as $k => $v) {
if (substr($k, 0, 7) == "LOGGER_") {
$LOGGER_LEVELS[$v] = substr($k, 7, 7);
}
}
}
$process_id = session_id();
if ($process_id == '') {
$process_id = get_app()->process_id;
}
$callers = debug_backtrace();
if (count($callers) > 1) {
$function = $callers[1]['function'];
} else {
$function = '';
}
$logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
DateTimeFormat::utcNow(DateTimeFormat::ATOM),
$process_id,
$LOGGER_LEVELS[$level],
basename($callers[0]['file']),
$callers[0]['line'],
$function,
$msg
);
$stamp1 = microtime(true);
@file_put_contents($logfile, $logline, FILE_APPEND);
$a->saveTimestamp($stamp1, "file");
}
/**
* @brief An alternative logger for development.
* Works largely as logger() but allows developers
* to isolate particular elements they are targetting
* personally without background noise
*
* log levels:
* LOGGER_WARNING
* LOGGER_INFO (default)
* LOGGER_TRACE
* LOGGER_DEBUG
* LOGGER_DATA
* LOGGER_ALL
*
* @global array $LOGGER_LEVELS
* @param string $msg
* @param int $level
*/
function dlogger($msg, $level = LOGGER_INFO) {
$a = get_app();
$logfile = Config::get('system', 'dlogfile');
if (!$logfile) {
return;
}
$dlogip = Config::get('system', 'dlogip');
if (!is_null($dlogip) && $_SERVER['REMOTE_ADDR'] != $dlogip) {
return;
}
if (count($LOGGER_LEVELS) == 0) {
foreach (get_defined_constants() as $k => $v) {
if (substr($k, 0, 7) == "LOGGER_") {
$LOGGER_LEVELS[$v] = substr($k, 7, 7);
}
}
}
$process_id = session_id();
if ($process_id == '') {
$process_id = $a->process_id;
}
$callers = debug_backtrace();
$logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
DateTimeFormat::utcNow(),
$process_id,
basename($callers[0]['file']),
$callers[0]['line'],
$callers[1]['function'],
$msg
);
$stamp1 = microtime(true);
@file_put_contents($logfile, $logline, FILE_APPEND);
$a->saveTimestamp($stamp1, "file");
}
/** /**
* Compare activity uri. Knows about activity namespace. * Compare activity uri. Knows about activity namespace.
* *
@ -1353,7 +1222,7 @@ function base64url_encode($s, $strip_padding = false) {
function base64url_decode($s) { function base64url_decode($s) {
if (is_array($s)) { if (is_array($s)) {
logger('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true)); Logger::log('base64url_decode: illegal input: ' . print_r(debug_backtrace(), true));
return $s; return $s;
} }

View file

@ -6,6 +6,7 @@ use Friendica\App;
use Friendica\Content\Widget; use Friendica\Content\Widget;
use Friendica\Core\ACL; use Friendica\Core\ACL;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -34,7 +35,7 @@ function acl_content(App $a)
$search = $_REQUEST['query']; $search = $_REQUEST['query'];
} }
logger("Searching for ".$search." - type ".$type." conversation ".$conv_id, LOGGER_DEBUG); Logger::log("Searching for ".$search." - type ".$type." conversation ".$conv_id, Logger::DEBUG);
if ($search != '') { if ($search != '') {
$sql_extra = "AND `name` LIKE '%%" . DBA::escape($search) . "%%'"; $sql_extra = "AND `name` LIKE '%%" . DBA::escape($search) . "%%'";

View file

@ -13,6 +13,7 @@ use Friendica\Content\Text\Markdown;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Theme; use Friendica\Core\Theme;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -910,7 +911,7 @@ function admin_page_summary(App $a)
$users+= $u['count']; $users+= $u['count'];
} }
logger('accounts: ' . print_r($accounts, true), LOGGER_DATA); Logger::log('accounts: ' . print_r($accounts, true), Logger::DATA);
$pending = Register::getPendingCount(); $pending = Register::getPendingCount();
@ -2399,12 +2400,12 @@ function admin_page_logs_post(App $a)
function admin_page_logs(App $a) function admin_page_logs(App $a)
{ {
$log_choices = [ $log_choices = [
LOGGER_WARNING => 'Warning', Logger::WARNING => 'Warning',
LOGGER_INFO => 'Info', Logger::INFO => 'Info',
LOGGER_TRACE => 'Trace', Logger::TRACE => 'Trace',
LOGGER_DEBUG => 'Debug', Logger::DEBUG => 'Debug',
LOGGER_DATA => 'Data', Logger::DATA => 'Data',
LOGGER_ALL => 'All' Logger::ALL => 'All'
]; ];
if (ini_get('log_errors')) { if (ini_get('log_errors')) {
@ -2499,7 +2500,7 @@ function admin_page_features_post(App $a)
{ {
BaseModule::checkFormSecurityTokenRedirectOnError('/admin/features', 'admin_manage_features'); BaseModule::checkFormSecurityTokenRedirectOnError('/admin/features', 'admin_manage_features');
logger('postvars: ' . print_r($_POST, true), LOGGER_DATA); Logger::log('postvars: ' . print_r($_POST, true), Logger::DATA);
$features = Feature::get(false); $features = Feature::get(false);

View file

@ -6,6 +6,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model; use Friendica\Model;
@ -78,7 +79,7 @@ function crepair_post(App $a)
); );
if ($photo) { if ($photo) {
logger('mod-crepair: updating photo from ' . $photo); Logger::log('mod-crepair: updating photo from ' . $photo);
Model\Contact::updateAvatar($photo, local_user(), $contact['id']); Model\Contact::updateAvatar($photo, local_user(), $contact['id']);
} }

View file

@ -20,6 +20,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -76,7 +77,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
// These data elements may come from either the friend request notification form or $handsfree array. // These data elements may come from either the friend request notification form or $handsfree array.
if (is_array($handsfree)) { if (is_array($handsfree)) {
logger('Confirm in handsfree mode'); Logger::log('Confirm in handsfree mode');
$dfrn_id = $handsfree['dfrn_id']; $dfrn_id = $handsfree['dfrn_id'];
$intro_id = $handsfree['intro_id']; $intro_id = $handsfree['intro_id'];
$duplex = $handsfree['duplex']; $duplex = $handsfree['duplex'];
@ -99,9 +100,9 @@ function dfrn_confirm_post(App $a, $handsfree = null)
$cid = 0; $cid = 0;
} }
logger('Confirming request for dfrn_id (issued) ' . $dfrn_id); Logger::log('Confirming request for dfrn_id (issued) ' . $dfrn_id);
if ($cid) { if ($cid) {
logger('Confirming follower with contact_id: ' . $cid); Logger::log('Confirming follower with contact_id: ' . $cid);
} }
/* /*
@ -124,7 +125,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
intval($uid) intval($uid)
); );
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
logger('Contact not found in DB.'); Logger::log('Contact not found in DB.');
notice(L10n::t('Contact not found.') . EOL); notice(L10n::t('Contact not found.') . EOL);
notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL); notice(L10n::t('This may occasionally happen if contact was requested by both persons and it has already been approved.') . EOL);
return; return;
@ -211,7 +212,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
$params['page'] = 2; $params['page'] = 2;
} }
logger('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), LOGGER_DATA); Logger::log('Confirm: posting data to ' . $dfrn_confirm . ': ' . print_r($params, true), Logger::DATA);
/* /*
* *
@ -223,7 +224,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
$res = Network::post($dfrn_confirm, $params, null, $redirects, 120)->getBody(); $res = Network::post($dfrn_confirm, $params, null, $redirects, 120)->getBody();
logger(' Confirm: received data: ' . $res, LOGGER_DATA); Logger::log(' Confirm: received data: ' . $res, Logger::DATA);
// Now figure out what they responded. Try to be robust if the remote site is // Now figure out what they responded. Try to be robust if the remote site is
// having difficulty and throwing up errors of some kind. // having difficulty and throwing up errors of some kind.
@ -248,7 +249,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
if (stristr($res, "<status") === false) { if (stristr($res, "<status") === false) {
// wrong xml! stop here! // wrong xml! stop here!
logger('Unexpected response posting to ' . $dfrn_confirm); Logger::log('Unexpected response posting to ' . $dfrn_confirm);
notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL); notice(L10n::t('Unexpected response from remote site: ') . EOL . htmlspecialchars($res) . EOL);
return; return;
} }
@ -305,7 +306,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
*/ */
Contact::updateAvatar($contact['photo'], $uid, $contact_id); Contact::updateAvatar($contact['photo'], $uid, $contact_id);
logger('dfrn_confirm: confirm - imported photos'); Logger::log('dfrn_confirm: confirm - imported photos');
if ($network === Protocol::DFRN) { if ($network === Protocol::DFRN) {
$new_relation = Contact::FOLLOWER; $new_relation = Contact::FOLLOWER;
@ -387,7 +388,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
if ((isset($new_relation) && $new_relation == Contact::FRIEND)) { if ((isset($new_relation) && $new_relation == Contact::FRIEND)) {
if (DBA::isResult($contact) && ($contact['network'] === Protocol::DIASPORA)) { if (DBA::isResult($contact) && ($contact['network'] === Protocol::DIASPORA)) {
$ret = Diaspora::sendShare($user, $contact); $ret = Diaspora::sendShare($user, $contact);
logger('share returns: ' . $ret); Logger::log('share returns: ' . $ret);
} }
} }
@ -427,9 +428,9 @@ function dfrn_confirm_post(App $a, $handsfree = null)
$forum = (($page == 1) ? 1 : 0); $forum = (($page == 1) ? 1 : 0);
$prv = (($page == 2) ? 1 : 0); $prv = (($page == 2) ? 1 : 0);
logger('dfrn_confirm: requestee contacted: ' . $node); Logger::log('dfrn_confirm: requestee contacted: ' . $node);
logger('dfrn_confirm: request: POST=' . print_r($_POST, true), LOGGER_DATA); Logger::log('dfrn_confirm: request: POST=' . print_r($_POST, true), Logger::DATA);
// If $aes_key is set, both of these items require unpacking from the hex transport encoding. // If $aes_key is set, both of these items require unpacking from the hex transport encoding.
@ -542,7 +543,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
Contact::updateAvatar($photo, $local_uid, $dfrn_record); Contact::updateAvatar($photo, $local_uid, $dfrn_record);
logger('dfrn_confirm: request - photos imported'); Logger::log('dfrn_confirm: request - photos imported');
$new_relation = Contact::SHARING; $new_relation = Contact::SHARING;
@ -582,7 +583,7 @@ function dfrn_confirm_post(App $a, $handsfree = null)
// Otherwise everything seems to have worked and we are almost done. Yay! // Otherwise everything seems to have worked and we are almost done. Yay!
// Send an email notification // Send an email notification
logger('dfrn_confirm: request: info updated'); Logger::log('dfrn_confirm: request: info updated');
$combined = null; $combined = null;
$r = q("SELECT `contact`.*, `user`.* $r = q("SELECT `contact`.*, `user`.*

View file

@ -8,6 +8,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -17,7 +18,7 @@ use Friendica\Protocol\Diaspora;
require_once 'include/items.php'; require_once 'include/items.php';
function dfrn_notify_post(App $a) { function dfrn_notify_post(App $a) {
logger(__function__, LOGGER_TRACE); Logger::log(__function__, Logger::TRACE);
$postdata = file_get_contents('php://input'); $postdata = file_get_contents('php://input');
@ -63,7 +64,7 @@ function dfrn_notify_post(App $a) {
} }
if (!DBA::exists('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge])) { if (!DBA::exists('challenge', ['dfrn-id' => $dfrn_id, 'challenge' => $challenge])) {
logger('could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge); Logger::log('could not match challenge to dfrn_id ' . $dfrn_id . ' challenge=' . $challenge);
System::xmlExit(3, 'Could not match challenge'); System::xmlExit(3, 'Could not match challenge');
} }
@ -71,7 +72,7 @@ function dfrn_notify_post(App $a) {
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]); $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
if (!DBA::isResult($user)) { if (!DBA::isResult($user)) {
logger('User not found for nickname ' . $a->argv[1]); Logger::log('User not found for nickname ' . $a->argv[1]);
System::xmlExit(3, 'User not found'); System::xmlExit(3, 'User not found');
} }
@ -94,7 +95,7 @@ function dfrn_notify_post(App $a) {
$contact = DBA::selectFirst('contact', ['id'], $condition); $contact = DBA::selectFirst('contact', ['id'], $condition);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
logger('contact not found for dfrn_id ' . $dfrn_id); Logger::log('contact not found for dfrn_id ' . $dfrn_id);
System::xmlExit(3, 'Contact not found'); System::xmlExit(3, 'Contact not found');
} }
@ -117,12 +118,12 @@ function dfrn_notify_post(App $a) {
$importer = Contact::updateSslPolicy($importer, $ssl_policy); $importer = Contact::updateSslPolicy($importer, $ssl_policy);
logger('data: ' . $data, LOGGER_DATA); Logger::log('data: ' . $data, Logger::DATA);
if ($dissolve == 1) { if ($dissolve == 1) {
// Relationship is dissolved permanently // Relationship is dissolved permanently
Contact::remove($importer['id']); Contact::remove($importer['id']);
logger('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']); Logger::log('relationship dissolved : ' . $importer['name'] . ' dissolved ' . $importer['username']);
System::xmlExit(0, 'relationship dissolved'); System::xmlExit(0, 'relationship dissolved');
} }
@ -134,12 +135,12 @@ function dfrn_notify_post(App $a) {
// if local rino is lower than remote rino, abort: should not happen! // if local rino is lower than remote rino, abort: should not happen!
// but only for $remote_rino > 1, because old code did't send rino version // but only for $remote_rino > 1, because old code did't send rino version
if ($rino_remote > 1 && $rino < $rino_remote) { if ($rino_remote > 1 && $rino < $rino_remote) {
logger("rino version '$rino_remote' is lower than supported '$rino'"); Logger::log("rino version '$rino_remote' is lower than supported '$rino'");
System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'"); System::xmlExit(0, "rino version '$rino_remote' is lower than supported '$rino'");
} }
$rawkey = hex2bin(trim($key)); $rawkey = hex2bin(trim($key));
logger('rino: md5 raw key: ' . md5($rawkey), LOGGER_DATA); Logger::log('rino: md5 raw key: ' . md5($rawkey), Logger::DATA);
$final_key = ''; $final_key = '';
@ -165,14 +166,14 @@ function dfrn_notify_post(App $a) {
$data = DFRN::aesDecrypt(hex2bin($data), $final_key); $data = DFRN::aesDecrypt(hex2bin($data), $final_key);
break; break;
default: default:
logger("rino: invalid sent version '$rino_remote'"); Logger::log("rino: invalid sent version '$rino_remote'");
System::xmlExit(0, "Invalid sent version '$rino_remote'"); System::xmlExit(0, "Invalid sent version '$rino_remote'");
} }
logger('rino: decrypted data: ' . $data, LOGGER_DATA); Logger::log('rino: decrypted data: ' . $data, Logger::DATA);
} }
logger('Importing post from ' . $importer['addr'] . ' to ' . $importer['nickname'] . ' with the RINO ' . $rino_remote . ' encryption.', LOGGER_DEBUG); Logger::log('Importing post from ' . $importer['addr'] . ' to ' . $importer['nickname'] . ' with the RINO ' . $rino_remote . ' encryption.', Logger::DEBUG);
$ret = DFRN::import($data, $importer); $ret = DFRN::import($data, $importer);
System::xmlExit($ret, 'Processed'); System::xmlExit($ret, 'Processed');
@ -191,7 +192,7 @@ function dfrn_dispatch_public($postdata)
// Fetch the corresponding public contact // Fetch the corresponding public contact
$contact = Contact::getDetailsByAddr($msg['author'], 0); $contact = Contact::getDetailsByAddr($msg['author'], 0);
if (!$contact) { if (!$contact) {
logger('Contact not found for address ' . $msg['author']); Logger::log('Contact not found for address ' . $msg['author']);
System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found'); System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
} }
@ -199,11 +200,11 @@ function dfrn_dispatch_public($postdata)
// This should never fail // This should never fail
if (empty($importer)) { if (empty($importer)) {
logger('Contact not found for address ' . $msg['author']); Logger::log('Contact not found for address ' . $msg['author']);
System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found'); System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
} }
logger('Importing post from ' . $msg['author'] . ' with the public envelope.', LOGGER_DEBUG); Logger::log('Importing post from ' . $msg['author'] . ' with the public envelope.', Logger::DEBUG);
// Now we should be able to import it // Now we should be able to import it
$ret = DFRN::import($msg['message'], $importer); $ret = DFRN::import($msg['message'], $importer);
@ -223,7 +224,7 @@ function dfrn_dispatch_private($user, $postdata)
// Otherwise there should be a public contact // Otherwise there should be a public contact
$cid = Contact::getIdForURL($msg['author']); $cid = Contact::getIdForURL($msg['author']);
if (!$cid) { if (!$cid) {
logger('Contact not found for address ' . $msg['author']); Logger::log('Contact not found for address ' . $msg['author']);
System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found'); System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
} }
} }
@ -232,11 +233,11 @@ function dfrn_dispatch_private($user, $postdata)
// This should never fail // This should never fail
if (empty($importer)) { if (empty($importer)) {
logger('Contact not found for address ' . $msg['author']); Logger::log('Contact not found for address ' . $msg['author']);
System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found'); System::xmlExit(3, 'Contact ' . $msg['author'] . ' not found');
} }
logger('Importing post from ' . $msg['author'] . ' to ' . $user['nickname'] . ' with the private envelope.', LOGGER_DEBUG); Logger::log('Importing post from ' . $msg['author'] . ' to ' . $user['nickname'] . ' with the private envelope.', Logger::DEBUG);
// Now we should be able to import it // Now we should be able to import it
$ret = DFRN::import($msg['message'], $importer); $ret = DFRN::import($msg['message'], $importer);
@ -258,7 +259,7 @@ function dfrn_notify_content(App $a) {
$type = ""; $type = "";
$last_update = ""; $last_update = "";
logger('new notification dfrn_id=' . $dfrn_id); Logger::log('new notification dfrn_id=' . $dfrn_id);
$direction = (-1); $direction = (-1);
if (strpos($dfrn_id,':') == 1) { if (strpos($dfrn_id,':') == 1) {
@ -276,11 +277,11 @@ function dfrn_notify_content(App $a) {
'type' => $type, 'last_update' => $last_update]; 'type' => $type, 'last_update' => $last_update];
DBA::insert('challenge', $fields); DBA::insert('challenge', $fields);
logger('challenge=' . $hash, LOGGER_DATA); Logger::log('challenge=' . $hash, Logger::DATA);
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]); $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
if (!DBA::isResult($user)) { if (!DBA::isResult($user)) {
logger('User not found for nickname ' . $a->argv[1]); Logger::log('User not found for nickname ' . $a->argv[1]);
killme(); killme();
} }
@ -305,18 +306,18 @@ function dfrn_notify_content(App $a) {
$contact = DBA::selectFirst('contact', ['id'], $condition); $contact = DBA::selectFirst('contact', ['id'], $condition);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
logger('contact not found for dfrn_id ' . $dfrn_id); Logger::log('contact not found for dfrn_id ' . $dfrn_id);
System::xmlExit(3, 'Contact not found'); System::xmlExit(3, 'Contact not found');
} }
// $importer in this case contains the contact record for the remote contact joined with the user record of our user. // $importer in this case contains the contact record for the remote contact joined with the user record of our user.
$importer = DFRN::getImporter($contact['id'], $user['uid']); $importer = DFRN::getImporter($contact['id'], $user['uid']);
if (empty($importer)) { if (empty($importer)) {
logger('No importer data found for user ' . $a->argv[1] . ' and contact ' . $dfrn_id); Logger::log('No importer data found for user ' . $a->argv[1] . ' and contact ' . $dfrn_id);
killme(); killme();
} }
logger("Remote rino version: ".$rino_remote." for ".$importer["url"], LOGGER_DATA); Logger::log("Remote rino version: ".$rino_remote." for ".$importer["url"], Logger::DATA);
$challenge = ''; $challenge = '';
$encrypted_id = ''; $encrypted_id = '';
@ -344,7 +345,7 @@ function dfrn_notify_content(App $a) {
$rino = Config::get('system', 'rino_encrypt'); $rino = Config::get('system', 'rino_encrypt');
$rino = intval($rino); $rino = intval($rino);
logger("Local rino version: ". $rino, LOGGER_DATA); Logger::log("Local rino version: ". $rino, Logger::DATA);
// if requested rino is lower than enabled local rino, lower local rino version // if requested rino is lower than enabled local rino, lower local rino version
// if requested rino is higher than enabled local rino, reply with local rino // if requested rino is higher than enabled local rino, reply with local rino

View file

@ -7,6 +7,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Module\Login; use Friendica\Module\Login;
@ -68,7 +69,7 @@ function dfrn_poll_init(App $a)
$user = $r[0]['nickname']; $user = $r[0]['nickname'];
} }
logger('dfrn_poll: public feed request from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $user); Logger::log('dfrn_poll: public feed request from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $user);
header("Content-type: application/atom+xml"); header("Content-type: application/atom+xml");
echo DFRN::feed('', $user, $last_update, 0, $hidewall); echo DFRN::feed('', $user, $last_update, 0, $hidewall);
killme(); killme();
@ -104,7 +105,7 @@ function dfrn_poll_init(App $a)
if (DBA::isResult($r)) { if (DBA::isResult($r)) {
$s = Network::fetchUrl($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check'); $s = Network::fetchUrl($r[0]['poll'] . '?dfrn_id=' . $my_id . '&type=profile-check');
logger("dfrn_poll: old profile returns " . $s, LOGGER_DATA); Logger::log("dfrn_poll: old profile returns " . $s, Logger::DATA);
if (strlen($s)) { if (strlen($s)) {
$xml = XML::parseString($s); $xml = XML::parseString($s);
@ -191,7 +192,7 @@ function dfrn_poll_init(App $a)
} }
if ($final_dfrn_id != $orig_id) { if ($final_dfrn_id != $orig_id) {
logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG); Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
// did not decode properly - cannot trust this site // did not decode properly - cannot trust this site
System::xmlExit(3, 'Bad decryption'); System::xmlExit(3, 'Bad decryption');
} }
@ -238,7 +239,7 @@ function dfrn_poll_post(App $a)
if ($ptype === 'profile-check') { if ($ptype === 'profile-check') {
if (strlen($challenge) && strlen($sec)) { if (strlen($challenge) && strlen($sec)) {
logger('dfrn_poll: POST: profile-check'); Logger::log('dfrn_poll: POST: profile-check');
DBA::delete('profile_check', ["`expire` < ?", time()]); DBA::delete('profile_check', ["`expire` < ?", time()]);
$r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1", $r = q("SELECT * FROM `profile_check` WHERE `sec` = '%s' ORDER BY `expire` DESC LIMIT 1",
@ -283,7 +284,7 @@ function dfrn_poll_post(App $a)
} }
if ($final_dfrn_id != $orig_id) { if ($final_dfrn_id != $orig_id) {
logger('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, LOGGER_DEBUG); Logger::log('profile_check: ' . $final_dfrn_id . ' != ' . $orig_id, Logger::DEBUG);
// did not decode properly - cannot trust this site // did not decode properly - cannot trust this site
System::xmlExit(3, 'Bad decryption'); System::xmlExit(3, 'Bad decryption');
} }
@ -372,7 +373,7 @@ function dfrn_poll_post(App $a)
// NOTREACHED // NOTREACHED
} else { } else {
// Update the writable flag if it changed // Update the writable flag if it changed
logger('dfrn_poll: post request feed: ' . print_r($_POST, true), LOGGER_DATA); Logger::log('dfrn_poll: post request feed: ' . print_r($_POST, true), Logger::DATA);
if ($dfrn_version >= 2.21) { if ($dfrn_version >= 2.21) {
if ($perm === 'rw') { if ($perm === 'rw') {
$writable = 1; $writable = 1;
@ -510,15 +511,15 @@ function dfrn_poll_content(App $a)
])->getBody(); ])->getBody();
} }
logger("dfrn_poll: sec profile: " . $s, LOGGER_DATA); Logger::log("dfrn_poll: sec profile: " . $s, Logger::DATA);
if (strlen($s) && strstr($s, '<?xml')) { if (strlen($s) && strstr($s, '<?xml')) {
$xml = XML::parseString($s); $xml = XML::parseString($s);
logger('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), LOGGER_DATA); Logger::log('dfrn_poll: profile: parsed xml: ' . print_r($xml, true), Logger::DATA);
logger('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash); Logger::log('dfrn_poll: secure profile: challenge: ' . $xml->challenge . ' expecting ' . $hash);
logger('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec); Logger::log('dfrn_poll: secure profile: sec: ' . $xml->sec . ' expecting ' . $sec);
if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) { if (((int) $xml->status == 0) && ($xml->challenge == $hash) && ($xml->sec == $sec)) {
$_SESSION['authenticated'] = 1; $_SESSION['authenticated'] = 1;

View file

@ -15,6 +15,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -57,7 +58,7 @@ function dfrn_request_init(App $a)
function dfrn_request_post(App $a) function dfrn_request_post(App $a)
{ {
if (($a->argc != 2) || (!count($a->profile))) { if (($a->argc != 2) || (!count($a->profile))) {
logger('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile)); Logger::log('Wrong count of argc or profiles: argc=' . $a->argc . ',profile()=' . count($a->profile));
return; return;
} }
@ -297,7 +298,7 @@ function dfrn_request_post(App $a)
$network = Protocol::DFRN; $network = Protocol::DFRN;
} }
logger('dfrn_request: url: ' . $url . ',network=' . $network, LOGGER_DEBUG); Logger::log('dfrn_request: url: ' . $url . ',network=' . $network, Logger::DEBUG);
if ($network === Protocol::DFRN) { if ($network === Protocol::DFRN) {
$ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1", $ret = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' AND `self` = 0 LIMIT 1",

View file

@ -10,6 +10,7 @@ use Friendica\Content\Text\HTML;
use Friendica\Core\ACL; use Friendica\Core\ACL;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -74,7 +75,7 @@ function display_init(App $a)
} }
if (!empty($_SERVER['HTTP_ACCEPT']) && strstr($_SERVER['HTTP_ACCEPT'], 'application/atom+xml')) { if (!empty($_SERVER['HTTP_ACCEPT']) && strstr($_SERVER['HTTP_ACCEPT'], 'application/atom+xml')) {
logger('Directly serving XML for id '.$item["id"], LOGGER_DEBUG); Logger::log('Directly serving XML for id '.$item["id"], Logger::DEBUG);
displayShowFeed($item["id"], false); displayShowFeed($item["id"], false);
} }

View file

@ -9,6 +9,7 @@ use Friendica\Content\Nav;
use Friendica\Content\Widget\CalendarExport; use Friendica\Content\Widget\CalendarExport;
use Friendica\Core\ACL; use Friendica\Core\ACL;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -47,7 +48,7 @@ function events_init(App $a)
function events_post(App $a) function events_post(App $a)
{ {
logger('post: ' . print_r($_REQUEST, true), LOGGER_DATA); Logger::log('post: ' . print_r($_REQUEST, true), Logger::DATA);
if (!local_user()) { if (!local_user()) {
return; return;

View file

@ -4,6 +4,7 @@
*/ */
use Friendica\App; use Friendica\App;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
require_once 'include/items.php'; require_once 'include/items.php';
@ -17,7 +18,7 @@ function filer_content(App $a)
$term = unxmlify(trim(defaults($_GET, 'term', ''))); $term = unxmlify(trim(defaults($_GET, 'term', '')));
$item_id = (($a->argc > 1) ? intval($a->argv[1]) : 0); $item_id = (($a->argc > 1) ? intval($a->argv[1]) : 0);
logger('filer: tag ' . $term . ' item ' . $item_id); Logger::log('filer: tag ' . $term . ' item ' . $item_id);
if ($item_id && strlen($term)) { if ($item_id && strlen($term)) {
// file item // file item

View file

@ -1,6 +1,7 @@
<?php <?php
use Friendica\App; use Friendica\App;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
function filerm_content(App $a) { function filerm_content(App $a) {
@ -19,7 +20,7 @@ function filerm_content(App $a) {
$item_id = (($a->argc > 1) ? intval($a->argv[1]) : 0); $item_id = (($a->argc > 1) ? intval($a->argv[1]) : 0);
logger('filerm: tag ' . $term . ' item ' . $item_id); Logger::log('filerm: tag ' . $term . ' item ' . $item_id);
if ($item_id && strlen($term)) { if ($item_id && strlen($term)) {
file_tag_unsave_file(local_user(),$item_id,$term, $category); file_tag_unsave_file(local_user(),$item_id,$term, $category);

View file

@ -22,6 +22,7 @@ use Friendica\Content\Text\HTML;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -56,7 +57,7 @@ function item_post(App $a) {
Addon::callHooks('post_local_start', $_REQUEST); Addon::callHooks('post_local_start', $_REQUEST);
logger('postvars ' . print_r($_REQUEST, true), LOGGER_DATA); Logger::log('postvars ' . print_r($_REQUEST, true), Logger::DATA);
$api_source = defaults($_REQUEST, 'api_source', false); $api_source = defaults($_REQUEST, 'api_source', false);
@ -72,7 +73,7 @@ function item_post(App $a) {
*/ */
if (!$preview && !empty($_REQUEST['post_id_random'])) { if (!$preview && !empty($_REQUEST['post_id_random'])) {
if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) { if (!empty($_SESSION['post-random']) && $_SESSION['post-random'] == $_REQUEST['post_id_random']) {
logger("item post: duplicate post", LOGGER_DEBUG); Logger::log("item post: duplicate post", Logger::DEBUG);
item_post_return(System::baseUrl(), $api_source, $return_path); item_post_return(System::baseUrl(), $api_source, $return_path);
} else { } else {
$_SESSION['post-random'] = $_REQUEST['post_id_random']; $_SESSION['post-random'] = $_REQUEST['post_id_random'];
@ -130,7 +131,7 @@ function item_post(App $a) {
} }
if ($parent) { if ($parent) {
logger('mod_item: item_post parent=' . $parent); Logger::log('mod_item: item_post parent=' . $parent);
} }
$post_id = intval(defaults($_REQUEST, 'post_id', 0)); $post_id = intval(defaults($_REQUEST, 'post_id', 0));
@ -153,7 +154,7 @@ function item_post(App $a) {
// Check for multiple posts with the same message id (when the post was created via API) // Check for multiple posts with the same message id (when the post was created via API)
if (($message_id != '') && ($profile_uid != 0)) { if (($message_id != '') && ($profile_uid != 0)) {
if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) { if (Item::exists(['uri' => $message_id, 'uid' => $profile_uid])) {
logger("Message with URI ".$message_id." already exists for user ".$profile_uid, LOGGER_DEBUG); Logger::log("Message with URI ".$message_id." already exists for user ".$profile_uid, Logger::DEBUG);
return 0; return 0;
} }
} }
@ -669,7 +670,7 @@ function item_post(App $a) {
$datarray["author-network"] = Protocol::DFRN; $datarray["author-network"] = Protocol::DFRN;
$o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true); $o = conversation($a, [array_merge($contact_record, $datarray)], new Pager($a->query_string), 'search', false, true);
logger('preview: ' . $o); Logger::log('preview: ' . $o);
echo json_encode(['preview' => $o]); echo json_encode(['preview' => $o]);
exit(); exit();
} }
@ -677,7 +678,7 @@ function item_post(App $a) {
Addon::callHooks('post_local',$datarray); Addon::callHooks('post_local',$datarray);
if (!empty($datarray['cancel'])) { if (!empty($datarray['cancel'])) {
logger('mod_item: post cancelled by addon.'); Logger::log('mod_item: post cancelled by addon.');
if ($return_path) { if ($return_path) {
$a->internalRedirect($return_path); $a->internalRedirect($return_path);
} }
@ -714,7 +715,7 @@ function item_post(App $a) {
file_tag_update_pconfig($uid,$categories_old,$categories_new,'category'); file_tag_update_pconfig($uid,$categories_old,$categories_new,'category');
if (!empty($_REQUEST['return']) && strlen($return_path)) { if (!empty($_REQUEST['return']) && strlen($return_path)) {
logger('return: ' . $return_path); Logger::log('return: ' . $return_path);
$a->internalRedirect($return_path); $a->internalRedirect($return_path);
} }
killme(); killme();
@ -736,14 +737,14 @@ function item_post(App $a) {
$post_id = Item::insert($datarray); $post_id = Item::insert($datarray);
if (!$post_id) { if (!$post_id) {
logger("Item wasn't stored."); Logger::log("Item wasn't stored.");
$a->internalRedirect($return_path); $a->internalRedirect($return_path);
} }
$datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]); $datarray = Item::selectFirst(Item::ITEM_FIELDLIST, ['id' => $post_id]);
if (!DBA::isResult($datarray)) { if (!DBA::isResult($datarray)) {
logger("Item with id ".$post_id." couldn't be fetched."); Logger::log("Item with id ".$post_id." couldn't be fetched.");
$a->internalRedirect($return_path); $a->internalRedirect($return_path);
} }
@ -833,7 +834,7 @@ function item_post(App $a) {
// We don't fork a new process since this is done anyway with the following command // We don't fork a new process since this is done anyway with the following command
Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id); Worker::add(['priority' => PRIORITY_HIGH, 'dont_fork' => true], "CreateShadowEntry", $post_id);
logger('post_complete'); Logger::log('post_complete');
if ($api_source) { if ($api_source) {
return $post_id; return $post_id;
@ -861,7 +862,7 @@ function item_post_return($baseurl, $api_source, $return_path)
$json['reload'] = $baseurl . '/' . $_REQUEST['jsreload']; $json['reload'] = $baseurl . '/' . $_REQUEST['jsreload'];
} }
logger('post_json: ' . print_r($json, true), LOGGER_DEBUG); Logger::log('post_json: ' . print_r($json, true), Logger::DEBUG);
echo json_encode($json); echo json_encode($json);
killme(); killme();

View file

@ -15,6 +15,7 @@ use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -871,7 +872,7 @@ function networkThreadedView(App $a, $update, $parent)
$_SESSION['network_last_date'] = $tag_top_limit; $_SESSION['network_last_date'] = $tag_top_limit;
} }
logger('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update); Logger::log('Tagged items: ' . count($data) . ' - ' . $bottom_limit . ' - ' . $top_limit . ' - ' . local_user().' - '.(int)$update);
$s = []; $s = [];
foreach ($r as $item) { foreach ($r as $item) {
$s[$item['uri']] = $item; $s[$item['uri']] = $item;

View file

@ -8,6 +8,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\Network; use Friendica\Util\Network;
@ -172,7 +173,7 @@ function nodeinfo_cron() {
return; return;
} }
logger('cron_start'); Logger::log('cron_start');
$users = q("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item` $users = q("SELECT `user`.`uid`, `user`.`login_date`, `contact`.`last-item`
FROM `user` FROM `user`
@ -203,22 +204,22 @@ function nodeinfo_cron() {
Config::set('nodeinfo', 'active_users_halfyear', $active_users_halfyear); Config::set('nodeinfo', 'active_users_halfyear', $active_users_halfyear);
Config::set('nodeinfo', 'active_users_monthly', $active_users_monthly); Config::set('nodeinfo', 'active_users_monthly', $active_users_monthly);
logger('total_users: ' . $total_users . '/' . $active_users_halfyear. '/' . $active_users_monthly, LOGGER_DEBUG); Logger::log('total_users: ' . $total_users . '/' . $active_users_halfyear. '/' . $active_users_monthly, Logger::DEBUG);
} }
$local_posts = DBA::count('thread', ["`wall` AND NOT `deleted` AND `uid` != 0"]); $local_posts = DBA::count('thread', ["`wall` AND NOT `deleted` AND `uid` != 0"]);
Config::set('nodeinfo', 'local_posts', $local_posts); Config::set('nodeinfo', 'local_posts', $local_posts);
logger('local_posts: ' . $local_posts, LOGGER_DEBUG); Logger::log('local_posts: ' . $local_posts, Logger::DEBUG);
$local_comments = DBA::count('item', ["`origin` AND `id` != `parent` AND NOT `deleted` AND `uid` != 0"]); $local_comments = DBA::count('item', ["`origin` AND `id` != `parent` AND NOT `deleted` AND `uid` != 0"]);
Config::set('nodeinfo', 'local_comments', $local_comments); Config::set('nodeinfo', 'local_comments', $local_comments);
logger('local_comments: ' . $local_comments, LOGGER_DEBUG); Logger::log('local_comments: ' . $local_comments, Logger::DEBUG);
// Now trying to register // Now trying to register
$url = 'http://the-federation.info/register/'.$a->getHostName(); $url = 'http://the-federation.info/register/'.$a->getHostName();
logger('registering url: '.$url, LOGGER_DEBUG); Logger::log('registering url: '.$url, Logger::DEBUG);
$ret = Network::fetchUrl($url); $ret = Network::fetchUrl($url);
logger('registering answer: '.$ret, LOGGER_DEBUG); Logger::log('registering answer: '.$ret, Logger::DEBUG);
logger('cron_end'); Logger::log('cron_end');
} }

View file

@ -7,6 +7,7 @@ use Friendica\App;
use Friendica\Core\Authentication; use Friendica\Core\Authentication;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -16,7 +17,7 @@ function openid_content(App $a) {
if($noid) if($noid)
$a->internalRedirect(); $a->internalRedirect();
logger('mod_openid ' . print_r($_REQUEST,true), LOGGER_DATA); Logger::log('mod_openid ' . print_r($_REQUEST,true), Logger::DATA);
if((x($_GET,'openid_mode')) && (x($_SESSION,'openid'))) { if((x($_GET,'openid_mode')) && (x($_SESSION,'openid'))) {
@ -27,7 +28,7 @@ function openid_content(App $a) {
$authid = $_REQUEST['openid_identity']; $authid = $_REQUEST['openid_identity'];
if(! strlen($authid)) { if(! strlen($authid)) {
logger(L10n::t('OpenID protocol error. No ID returned.') . EOL); Logger::log(L10n::t('OpenID protocol error. No ID returned.') . EOL);
$a->internalRedirect(); $a->internalRedirect();
} }

View file

@ -11,6 +11,7 @@
*/ */
use Friendica\App; use Friendica\App;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Logger;
use Friendica\Util\Network; use Friendica\Util\Network;
use Friendica\Util\ParseUrl; use Friendica\Util\ParseUrl;
@ -54,7 +55,7 @@ function parse_url_content(App $a)
} }
} }
logger($url); Logger::log($url);
// Check if the URL is an image, video or audio file. If so format // Check if the URL is an image, video or audio file. If so format
// the URL with the corresponding BBCode media tag // the URL with the corresponding BBCode media tag
@ -114,7 +115,7 @@ function parse_url_content(App $a)
$result = sprintf($template, $url, ($title) ? $title : $url, $text) . $str_tags; $result = sprintf($template, $url, ($title) ? $title : $url, $text) . $str_tags;
logger('(unparsed): returns: ' . $result); Logger::log('(unparsed): returns: ' . $result);
echo $result; echo $result;
exit(); exit();

View file

@ -12,6 +12,7 @@ use Friendica\Core\ACL;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -141,9 +142,9 @@ function photos_init(App $a) {
function photos_post(App $a) function photos_post(App $a)
{ {
logger('mod-photos: photos_post: begin' , LOGGER_DEBUG); Logger::log('mod-photos: photos_post: begin' , Logger::DEBUG);
logger('mod_photos: REQUEST ' . print_r($_REQUEST, true), LOGGER_DATA); Logger::log('mod_photos: REQUEST ' . print_r($_REQUEST, true), Logger::DATA);
logger('mod_photos: FILES ' . print_r($_FILES, true), LOGGER_DATA); Logger::log('mod_photos: FILES ' . print_r($_FILES, true), Logger::DATA);
$phototypes = Image::supportedTypes(); $phototypes = Image::supportedTypes();
@ -189,7 +190,7 @@ function photos_post(App $a)
if (!$owner_record) { if (!$owner_record) {
notice(L10n::t('Contact information unavailable') . EOL); notice(L10n::t('Contact information unavailable') . EOL);
logger('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid); Logger::log('photos_post: unable to locate contact record for page owner. uid=' . $page_owner_uid);
killme(); killme();
} }
@ -379,7 +380,7 @@ function photos_post(App $a)
} }
if (!empty($_POST['rotate']) && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) { if (!empty($_POST['rotate']) && (intval($_POST['rotate']) == 1 || intval($_POST['rotate']) == 2)) {
logger('rotate'); Logger::log('rotate');
$r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d AND `scale` = 0 LIMIT 1", $r = q("SELECT * FROM `photo` WHERE `resource-id` = '%s' AND `uid` = %d AND `scale` = 0 LIMIT 1",
DBA::escape($resource_id), DBA::escape($resource_id),
@ -706,7 +707,7 @@ function photos_post(App $a)
$album = !empty($_REQUEST['album']) ? notags(trim($_REQUEST['album'])) : ''; $album = !empty($_REQUEST['album']) ? notags(trim($_REQUEST['album'])) : '';
$newalbum = !empty($_REQUEST['newalbum']) ? notags(trim($_REQUEST['newalbum'])) : ''; $newalbum = !empty($_REQUEST['newalbum']) ? notags(trim($_REQUEST['newalbum'])) : '';
logger('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , LOGGER_DEBUG); Logger::log('mod/photos.php: photos_post(): album= ' . $album . ' newalbum= ' . $newalbum , Logger::DEBUG);
if (!strlen($album)) { if (!strlen($album)) {
if (strlen($newalbum)) { if (strlen($newalbum)) {
@ -799,7 +800,7 @@ function photos_post(App $a)
$type = Image::guessType($filename); $type = Image::guessType($filename);
} }
logger('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', LOGGER_DEBUG); Logger::log('photos: upload: received file: ' . $filename . ' as ' . $src . ' ('. $type . ') ' . $filesize . ' bytes', Logger::DEBUG);
$maximagesize = Config::get('system', 'maximagesize'); $maximagesize = Config::get('system', 'maximagesize');
@ -819,14 +820,14 @@ function photos_post(App $a)
return; return;
} }
logger('mod/photos.php: photos_post(): loading the contents of ' . $src , LOGGER_DEBUG); Logger::log('mod/photos.php: photos_post(): loading the contents of ' . $src , Logger::DEBUG);
$imagedata = @file_get_contents($src); $imagedata = @file_get_contents($src);
$image = new Image($imagedata, $type); $image = new Image($imagedata, $type);
if (!$image->isValid()) { if (!$image->isValid()) {
logger('mod/photos.php: photos_post(): unable to process image' , LOGGER_DEBUG); Logger::log('mod/photos.php: photos_post(): unable to process image' , Logger::DEBUG);
notice(L10n::t('Unable to process image.') . EOL); notice(L10n::t('Unable to process image.') . EOL);
@unlink($src); @unlink($src);
$foo = 0; $foo = 0;
@ -855,7 +856,7 @@ function photos_post(App $a)
$r = Photo::store($image, $page_owner_uid, $visitor, $photo_hash, $filename, $album, 0 , 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny); $r = Photo::store($image, $page_owner_uid, $visitor, $photo_hash, $filename, $album, 0 , 0, $str_contact_allow, $str_group_allow, $str_contact_deny, $str_group_deny);
if (!$r) { if (!$r) {
logger('mod/photos.php: photos_post(): image store failed', LOGGER_DEBUG); Logger::log('mod/photos.php: photos_post(): image store failed', Logger::DEBUG);
notice(L10n::t('Image upload failed.') . EOL); notice(L10n::t('Image upload failed.') . EOL);
killme(); killme();
} }

View file

@ -8,6 +8,7 @@ use Friendica\App;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -121,7 +122,7 @@ function poco_init(App $a) {
$itemsPerPage = ((x($_GET, 'count') && intval($_GET['count'])) ? intval($_GET['count']) : $totalResults); $itemsPerPage = ((x($_GET, 'count') && intval($_GET['count'])) ? intval($_GET['count']) : $totalResults);
if ($global) { if ($global) {
logger("Start global query", LOGGER_DEBUG); Logger::log("Start global query", Logger::DEBUG);
$contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure` $contacts = q("SELECT * FROM `gcontact` WHERE `updated` > '%s' AND NOT `hide` AND `network` IN ('%s', '%s', '%s') AND `updated` > `last_failure`
ORDER BY `updated` DESC LIMIT %d, %d", ORDER BY `updated` DESC LIMIT %d, %d",
DBA::escape($update_limit), DBA::escape($update_limit),
@ -132,7 +133,7 @@ function poco_init(App $a) {
intval($itemsPerPage) intval($itemsPerPage)
); );
} elseif ($system_mode) { } elseif ($system_mode) {
logger("Start system mode query", LOGGER_DEBUG); Logger::log("Start system mode query", Logger::DEBUG);
$contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`, $contacts = q("SELECT `contact`.*, `profile`.`about` AS `pabout`, `profile`.`locality` AS `plocation`, `profile`.`pub_keywords`,
`profile`.`gender` AS `pgender`, `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`, `profile`.`gender` AS `pgender`, `profile`.`address` AS `paddress`, `profile`.`region` AS `pregion`,
`profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type` `profile`.`postal-code` AS `ppostalcode`, `profile`.`country-name` AS `pcountry`, `user`.`account-type`
@ -144,7 +145,7 @@ function poco_init(App $a) {
intval($itemsPerPage) intval($itemsPerPage)
); );
} else { } else {
logger("Start query for user " . $user['nickname'], LOGGER_DEBUG); Logger::log("Start query for user " . $user['nickname'], Logger::DEBUG);
$contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0 $contacts = q("SELECT * FROM `contact` WHERE `uid` = %d AND `blocked` = 0 AND `pending` = 0 AND `hidden` = 0 AND `archive` = 0
AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`) AND (`success_update` >= `failure_update` OR `last-item` >= `failure_update`)
AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d", AND `network` IN ('%s', '%s', '%s', '%s') $sql_extra LIMIT %d, %d",
@ -157,7 +158,7 @@ function poco_init(App $a) {
intval($itemsPerPage) intval($itemsPerPage)
); );
} }
logger("Query done", LOGGER_DEBUG); Logger::log("Query done", Logger::DEBUG);
$ret = []; $ret = [];
if (x($_GET, 'sorted')) { if (x($_GET, 'sorted')) {
@ -369,7 +370,7 @@ function poco_init(App $a) {
} else { } else {
System::httpExit(500); System::httpExit(500);
} }
logger("End of poco", LOGGER_DEBUG); Logger::log("End of poco", Logger::DEBUG);
if ($format === 'xml') { if ($format === 'xml') {
header('Content-type: text/xml'); header('Content-type: text/xml');

View file

@ -16,6 +16,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -53,7 +54,7 @@ function poke_init(App $a)
$parent = (x($_GET,'parent') ? intval($_GET['parent']) : 0); $parent = (x($_GET,'parent') ? intval($_GET['parent']) : 0);
logger('poke: verb ' . $verb . ' contact ' . $contact_id, LOGGER_DEBUG); Logger::log('poke: verb ' . $verb . ' contact ' . $contact_id, Logger::DEBUG);
$r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1", $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
@ -62,7 +63,7 @@ function poke_init(App $a)
); );
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
logger('poke: no contact ' . $contact_id); Logger::log('poke: no contact ' . $contact_id);
return; return;
} }

View file

@ -11,6 +11,7 @@ use Friendica\Core\ACL;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -37,7 +38,7 @@ function profile_init(App $a)
if (DBA::isResult($r)) { if (DBA::isResult($r)) {
$a->internalRedirect('profile/' . $r[0]['nickname']); $a->internalRedirect('profile/' . $r[0]['nickname']);
} else { } else {
logger('profile error: mod_profile ' . $a->query_string, LOGGER_DEBUG); Logger::log('profile error: mod_profile ' . $a->query_string, Logger::DEBUG);
notice(L10n::t('Requested profile is not available.') . EOL); notice(L10n::t('Requested profile is not available.') . EOL);
$a->error = 404; $a->error = 404;
return; return;

View file

@ -1,6 +1,7 @@
<?php <?php
use Friendica\App; use Friendica\App;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -39,14 +40,14 @@ function pubsub_init(App $a)
$hub_lease = notags(trim(defaults($_GET, 'hub_lease_seconds', ''))); $hub_lease = notags(trim(defaults($_GET, 'hub_lease_seconds', '')));
$hub_verify = notags(trim(defaults($_GET, 'hub_verify_token', ''))); $hub_verify = notags(trim(defaults($_GET, 'hub_verify_token', '')));
logger('Subscription from ' . $_SERVER['REMOTE_ADDR'] . ' Mode: ' . $hub_mode . ' Nick: ' . $nick); Logger::log('Subscription from ' . $_SERVER['REMOTE_ADDR'] . ' Mode: ' . $hub_mode . ' Nick: ' . $nick);
logger('Data: ' . print_r($_GET,true), LOGGER_DATA); Logger::log('Data: ' . print_r($_GET,true), Logger::DATA);
$subscribe = (($hub_mode === 'subscribe') ? 1 : 0); $subscribe = (($hub_mode === 'subscribe') ? 1 : 0);
$owner = DBA::selectFirst('user', ['uid'], ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]); $owner = DBA::selectFirst('user', ['uid'], ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]);
if (!DBA::isResult($owner)) { if (!DBA::isResult($owner)) {
logger('Local account not found: ' . $nick); Logger::log('Local account not found: ' . $nick);
hub_return(false, ''); hub_return(false, '');
} }
@ -58,12 +59,12 @@ function pubsub_init(App $a)
$contact = DBA::selectFirst('contact', ['id', 'poll'], $condition); $contact = DBA::selectFirst('contact', ['id', 'poll'], $condition);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
logger('Contact ' . $contact_id . ' not found.'); Logger::log('Contact ' . $contact_id . ' not found.');
hub_return(false, ''); hub_return(false, '');
} }
if (!empty($hub_topic) && !link_compare($hub_topic, $contact['poll'])) { if (!empty($hub_topic) && !link_compare($hub_topic, $contact['poll'])) {
logger('Hub topic ' . $hub_topic . ' != ' . $contact['poll']); Logger::log('Hub topic ' . $hub_topic . ' != ' . $contact['poll']);
hub_return(false, ''); hub_return(false, '');
} }
@ -71,13 +72,13 @@ function pubsub_init(App $a)
// Don't allow outsiders to unsubscribe us. // Don't allow outsiders to unsubscribe us.
if (($hub_mode === 'unsubscribe') && empty($hub_verify)) { if (($hub_mode === 'unsubscribe') && empty($hub_verify)) {
logger('Bogus unsubscribe'); Logger::log('Bogus unsubscribe');
hub_return(false, ''); hub_return(false, '');
} }
if (!empty($hub_mode)) { if (!empty($hub_mode)) {
DBA::update('contact', ['subhub' => $subscribe], ['id' => $contact['id']]); DBA::update('contact', ['subhub' => $subscribe], ['id' => $contact['id']]);
logger($hub_mode . ' success for contact ' . $contact_id . '.'); Logger::log($hub_mode . ' success for contact ' . $contact_id . '.');
} }
hub_return(true, $hub_challenge); hub_return(true, $hub_challenge);
} }
@ -87,8 +88,8 @@ function pubsub_post(App $a)
{ {
$xml = file_get_contents('php://input'); $xml = file_get_contents('php://input');
logger('Feed arrived from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $a->cmd . ' with user-agent: ' . $_SERVER['HTTP_USER_AGENT']); Logger::log('Feed arrived from ' . $_SERVER['REMOTE_ADDR'] . ' for ' . $a->cmd . ' with user-agent: ' . $_SERVER['HTTP_USER_AGENT']);
logger('Data: ' . $xml, LOGGER_DATA); Logger::log('Data: ' . $xml, Logger::DATA);
$nick = (($a->argc > 1) ? notags(trim($a->argv[1])) : ''); $nick = (($a->argc > 1) ? notags(trim($a->argv[1])) : '');
$contact_id = (($a->argc > 2) ? intval($a->argv[2]) : 0 ); $contact_id = (($a->argc > 2) ? intval($a->argv[2]) : 0 );
@ -106,16 +107,16 @@ function pubsub_post(App $a)
if (!empty($author['contact-id'])) { if (!empty($author['contact-id'])) {
$condition = ['id' => $author['contact-id'], 'uid' => $importer['uid'], 'subhub' => true, 'blocked' => false]; $condition = ['id' => $author['contact-id'], 'uid' => $importer['uid'], 'subhub' => true, 'blocked' => false];
$contact = DBA::selectFirst('contact', [], $condition); $contact = DBA::selectFirst('contact', [], $condition);
logger('No record for ' . $nick .' with contact id ' . $contact_id . ' - using '.$author['contact-id'].' instead.'); Logger::log('No record for ' . $nick .' with contact id ' . $contact_id . ' - using '.$author['contact-id'].' instead.');
} }
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
logger('Contact ' . $author["author-link"] . ' (' . $contact_id . ') for user ' . $nick . " wasn't found - ignored. XML: " . $xml); Logger::log('Contact ' . $author["author-link"] . ' (' . $contact_id . ') for user ' . $nick . " wasn't found - ignored. XML: " . $xml);
hub_post_return(); hub_post_return();
} }
} }
if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND]) && ($contact['network'] != Protocol::FEED)) { if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND]) && ($contact['network'] != Protocol::FEED)) {
logger('Contact ' . $contact['id'] . ' is not expected to share with us - ignored.'); Logger::log('Contact ' . $contact['id'] . ' is not expected to share with us - ignored.');
hub_post_return(); hub_post_return();
} }
@ -125,7 +126,7 @@ function pubsub_post(App $a)
hub_post_return(); hub_post_return();
} }
logger('Import item for ' . $nick . ' from ' . $contact['nick'] . ' (' . $contact['id'] . ')'); Logger::log('Import item for ' . $nick . ' from ' . $contact['nick'] . ' (' . $contact['id'] . ')');
$feedhub = ''; $feedhub = '';
consume_feed($xml, $importer, $contact, $feedhub); consume_feed($xml, $importer, $contact, $feedhub);

View file

@ -2,6 +2,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\PushSubscriber; use Friendica\Model\PushSubscriber;
@ -42,11 +43,11 @@ function pubsubhubbub_init(App $a) {
} elseif ($hub_mode === 'unsubscribe') { } elseif ($hub_mode === 'unsubscribe') {
$subscribe = 0; $subscribe = 0;
} else { } else {
logger("Invalid hub_mode=$hub_mode, ignoring."); Logger::log("Invalid hub_mode=$hub_mode, ignoring.");
System::httpExit(404); System::httpExit(404);
} }
logger("$hub_mode request from " . $_SERVER['REMOTE_ADDR']); Logger::log("$hub_mode request from " . $_SERVER['REMOTE_ADDR']);
// get the nick name from the topic, a bit hacky but needed as a fallback // get the nick name from the topic, a bit hacky but needed as a fallback
$nick = substr(strrchr($hub_topic, "/"), 1); $nick = substr(strrchr($hub_topic, "/"), 1);
@ -57,7 +58,7 @@ function pubsubhubbub_init(App $a) {
} }
if (!$nick) { if (!$nick) {
logger('Bad hub_topic=$hub_topic, ignoring.'); Logger::log('Bad hub_topic=$hub_topic, ignoring.');
System::httpExit(404); System::httpExit(404);
} }
@ -65,13 +66,13 @@ function pubsubhubbub_init(App $a) {
$condition = ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false]; $condition = ['nickname' => $nick, 'account_expired' => false, 'account_removed' => false];
$owner = DBA::selectFirst('user', ['uid', 'hidewall'], $condition); $owner = DBA::selectFirst('user', ['uid', 'hidewall'], $condition);
if (!DBA::isResult($owner)) { if (!DBA::isResult($owner)) {
logger('Local account not found: ' . $nick . ' - topic: ' . $hub_topic . ' - callback: ' . $hub_callback); Logger::log('Local account not found: ' . $nick . ' - topic: ' . $hub_topic . ' - callback: ' . $hub_callback);
System::httpExit(404); System::httpExit(404);
} }
// abort if user's wall is supposed to be private // abort if user's wall is supposed to be private
if ($owner['hidewall']) { if ($owner['hidewall']) {
logger('Local user ' . $nick . 'has chosen to hide wall, ignoring.'); Logger::log('Local user ' . $nick . 'has chosen to hide wall, ignoring.');
System::httpExit(403); System::httpExit(403);
} }
@ -80,14 +81,14 @@ function pubsubhubbub_init(App $a) {
'pending' => false, 'self' => true]; 'pending' => false, 'self' => true];
$contact = DBA::selectFirst('contact', ['poll'], $condition); $contact = DBA::selectFirst('contact', ['poll'], $condition);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
logger('Self contact for user ' . $owner['uid'] . ' not found.'); Logger::log('Self contact for user ' . $owner['uid'] . ' not found.');
System::httpExit(404); System::httpExit(404);
} }
// sanity check that topic URLs are the same // sanity check that topic URLs are the same
$hub_topic2 = str_replace('/feed/', '/dfrn_poll/', $hub_topic); $hub_topic2 = str_replace('/feed/', '/dfrn_poll/', $hub_topic);
if (!link_compare($hub_topic, $contact['poll']) && !link_compare($hub_topic2, $contact['poll'])) { if (!link_compare($hub_topic, $contact['poll']) && !link_compare($hub_topic2, $contact['poll'])) {
logger('Hub topic ' . $hub_topic . ' != ' . $contact['poll']); Logger::log('Hub topic ' . $hub_topic . ' != ' . $contact['poll']);
System::httpExit(404); System::httpExit(404);
} }
@ -110,14 +111,14 @@ function pubsubhubbub_init(App $a) {
// give up if the HTTP return code wasn't a success (2xx) // give up if the HTTP return code wasn't a success (2xx)
if ($ret < 200 || $ret > 299) { if ($ret < 200 || $ret > 299) {
logger("Subscriber verification for $hub_topic at $hub_callback returned $ret, ignoring."); Logger::log("Subscriber verification for $hub_topic at $hub_callback returned $ret, ignoring.");
System::httpExit(404); System::httpExit(404);
} }
// check that the correct hub_challenge code was echoed back // check that the correct hub_challenge code was echoed back
if (trim($body) !== $hub_challenge) { if (trim($body) !== $hub_challenge) {
logger("Subscriber did not echo back hub.challenge, ignoring."); Logger::log("Subscriber did not echo back hub.challenge, ignoring.");
logger("\"$hub_challenge\" != \"".trim($body)."\""); Logger::log("\"$hub_challenge\" != \"".trim($body)."\"");
System::httpExit(404); System::httpExit(404);
} }

View file

@ -6,6 +6,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Protocol\Diaspora; use Friendica\Protocol\Diaspora;
@ -18,7 +19,7 @@ function receive_post(App $a)
{ {
$enabled = intval(Config::get('system', 'diaspora_enabled')); $enabled = intval(Config::get('system', 'diaspora_enabled'));
if (!$enabled) { if (!$enabled) {
logger('mod-diaspora: disabled'); Logger::log('mod-diaspora: disabled');
System::httpExit(500); System::httpExit(500);
} }
@ -41,7 +42,7 @@ function receive_post(App $a)
// It is an application/x-www-form-urlencoded // It is an application/x-www-form-urlencoded
logger('mod-diaspora: receiving post', LOGGER_DEBUG); Logger::log('mod-diaspora: receiving post', Logger::DEBUG);
if (empty($_POST['xml'])) { if (empty($_POST['xml'])) {
$postdata = file_get_contents("php://input"); $postdata = file_get_contents("php://input");
@ -49,29 +50,29 @@ function receive_post(App $a)
System::httpExit(500); System::httpExit(500);
} }
logger('mod-diaspora: message is in the new format', LOGGER_DEBUG); Logger::log('mod-diaspora: message is in the new format', Logger::DEBUG);
$msg = Diaspora::decodeRaw($importer, $postdata); $msg = Diaspora::decodeRaw($importer, $postdata);
} else { } else {
$xml = urldecode($_POST['xml']); $xml = urldecode($_POST['xml']);
logger('mod-diaspora: decode message in the old format', LOGGER_DEBUG); Logger::log('mod-diaspora: decode message in the old format', Logger::DEBUG);
$msg = Diaspora::decode($importer, $xml); $msg = Diaspora::decode($importer, $xml);
if ($public && !$msg) { if ($public && !$msg) {
logger('mod-diaspora: decode message in the new format', LOGGER_DEBUG); Logger::log('mod-diaspora: decode message in the new format', Logger::DEBUG);
$msg = Diaspora::decodeRaw($importer, $xml); $msg = Diaspora::decodeRaw($importer, $xml);
} }
} }
logger('mod-diaspora: decoded', LOGGER_DEBUG); Logger::log('mod-diaspora: decoded', Logger::DEBUG);
logger('mod-diaspora: decoded msg: ' . print_r($msg, true), LOGGER_DATA); Logger::log('mod-diaspora: decoded msg: ' . print_r($msg, true), Logger::DATA);
if (!is_array($msg)) { if (!is_array($msg)) {
System::httpExit(500); System::httpExit(500);
} }
logger('mod-diaspora: dispatching', LOGGER_DEBUG); Logger::log('mod-diaspora: dispatching', Logger::DEBUG);
$ret = true; $ret = true;
if ($public) { if ($public) {

View file

@ -2,6 +2,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -51,7 +52,7 @@ function redir_init(App $a) {
if (!empty($a->contact['id']) && $a->contact['id'] == $cid) { if (!empty($a->contact['id']) && $a->contact['id'] == $cid) {
// Local user is already authenticated. // Local user is already authenticated.
$target_url = defaults($url, $contact_url); $target_url = defaults($url, $contact_url);
logger($contact['name'] . " is already authenticated. Redirecting to " . $target_url, LOGGER_DEBUG); Logger::log($contact['name'] . " is already authenticated. Redirecting to " . $target_url, Logger::DEBUG);
$a->redirect($target_url); $a->redirect($target_url);
} }
} }
@ -72,7 +73,7 @@ function redir_init(App $a) {
if ($v['uid'] == $_SESSION['visitor_visiting'] && $v['cid'] == $_SESSION['visitor_id']) { if ($v['uid'] == $_SESSION['visitor_visiting'] && $v['cid'] == $_SESSION['visitor_id']) {
// Remote user is already authenticated. // Remote user is already authenticated.
$target_url = defaults($url, $contact_url); $target_url = defaults($url, $contact_url);
logger($contact['name'] . " is already authenticated. Redirecting to " . $target_url, LOGGER_DEBUG); Logger::log($contact['name'] . " is already authenticated. Redirecting to " . $target_url, Logger::DEBUG);
$a->redirect($target_url); $a->redirect($target_url);
} }
} }
@ -98,7 +99,7 @@ function redir_init(App $a) {
'sec' => $sec, 'expire' => time() + 45]; 'sec' => $sec, 'expire' => time() + 45];
DBA::insert('profile_check', $fields); DBA::insert('profile_check', $fields);
logger('mod_redir: ' . $contact['name'] . ' ' . $sec, LOGGER_DEBUG); Logger::log('mod_redir: ' . $contact['name'] . ' ' . $sec, Logger::DEBUG);
$dest = (!empty($url) ? '&destination_url=' . $url : ''); $dest = (!empty($url) ? '&destination_url=' . $url : '');
@ -120,7 +121,7 @@ function redir_init(App $a) {
$url .= $separator . 'zrl=' . urlencode($my_profile); $url .= $separator . 'zrl=' . urlencode($my_profile);
} }
logger('redirecting to ' . $url, LOGGER_DEBUG); Logger::log('redirecting to ' . $url, Logger::DEBUG);
$a->redirect($url); $a->redirect($url);
} }

View file

@ -9,6 +9,7 @@ use Friendica\Content\Text\BBCode;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -186,7 +187,7 @@ function register_content(App $a)
if ($max_dailies) { if ($max_dailies) {
$r = q("select count(*) as total from user where register_date > UTC_TIMESTAMP - INTERVAL 1 day"); $r = q("select count(*) as total from user where register_date > UTC_TIMESTAMP - INTERVAL 1 day");
if ($r && $r[0]['total'] >= $max_dailies) { if ($r && $r[0]['total'] >= $max_dailies) {
logger('max daily registrations exceeded.'); Logger::log('max daily registrations exceeded.');
notice(L10n::t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.') . EOL); notice(L10n::t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.') . EOL);
return; return;
} }

View file

@ -3,6 +3,7 @@
* @file mod/salmon.php * @file mod/salmon.php
*/ */
use Friendica\App; use Friendica\App;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
@ -20,7 +21,7 @@ function salmon_post(App $a, $xml = '') {
$xml = file_get_contents('php://input'); $xml = file_get_contents('php://input');
} }
logger('new salmon ' . $xml, LOGGER_DATA); Logger::log('new salmon ' . $xml, Logger::DATA);
$nick = (($a->argc > 1) ? notags(trim($a->argv[1])) : ''); $nick = (($a->argc > 1) ? notags(trim($a->argv[1])) : '');
$mentions = (($a->argc > 2 && $a->argv[2] === 'mention') ? true : false); $mentions = (($a->argc > 2 && $a->argv[2] === 'mention') ? true : false);
@ -49,7 +50,7 @@ function salmon_post(App $a, $xml = '') {
$base = $dom; $base = $dom;
if (empty($base)) { if (empty($base)) {
logger('unable to locate salmon data in xml '); Logger::log('unable to locate salmon data in xml ');
System::httpExit(400); System::httpExit(400);
} }
@ -87,18 +88,18 @@ function salmon_post(App $a, $xml = '') {
$author_link = $author["author-link"]; $author_link = $author["author-link"];
if(! $author_link) { if(! $author_link) {
logger('Could not retrieve author URI.'); Logger::log('Could not retrieve author URI.');
System::httpExit(400); System::httpExit(400);
} }
// Once we have the author URI, go to the web and try to find their public key // Once we have the author URI, go to the web and try to find their public key
logger('Fetching key for ' . $author_link); Logger::log('Fetching key for ' . $author_link);
$key = Salmon::getKey($author_link, $keyhash); $key = Salmon::getKey($author_link, $keyhash);
if(! $key) { if(! $key) {
logger('Could not retrieve author key.'); Logger::log('Could not retrieve author key.');
System::httpExit(400); System::httpExit(400);
} }
@ -107,7 +108,7 @@ function salmon_post(App $a, $xml = '') {
$m = base64url_decode($key_info[1]); $m = base64url_decode($key_info[1]);
$e = base64url_decode($key_info[2]); $e = base64url_decode($key_info[2]);
logger('key details: ' . print_r($key_info,true), LOGGER_DEBUG); Logger::log('key details: ' . print_r($key_info,true), Logger::DEBUG);
$pubkey = Crypto::meToPem($m, $e); $pubkey = Crypto::meToPem($m, $e);
@ -118,23 +119,23 @@ function salmon_post(App $a, $xml = '') {
$mode = 1; $mode = 1;
if (! $verify) { if (! $verify) {
logger('message did not verify using protocol. Trying compliant format.'); Logger::log('message did not verify using protocol. Trying compliant format.');
$verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey); $verify = Crypto::rsaVerify($compliant_format, $signature, $pubkey);
$mode = 2; $mode = 2;
} }
if (! $verify) { if (! $verify) {
logger('message did not verify using padding. Trying old statusnet format.'); Logger::log('message did not verify using padding. Trying old statusnet format.');
$verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey); $verify = Crypto::rsaVerify($stnet_signed_data, $signature, $pubkey);
$mode = 3; $mode = 3;
} }
if (! $verify) { if (! $verify) {
logger('Message did not verify. Discarding.'); Logger::log('Message did not verify. Discarding.');
System::httpExit(400); System::httpExit(400);
} }
logger('Message verified with mode '.$mode); Logger::log('Message verified with mode '.$mode);
/* /*
@ -155,7 +156,7 @@ function salmon_post(App $a, $xml = '') {
); );
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
logger('Author ' . $author_link . ' unknown to user ' . $importer['uid'] . '.'); Logger::log('Author ' . $author_link . ' unknown to user ' . $importer['uid'] . '.');
if (PConfig::get($importer['uid'], 'system', 'ostatus_autofriend')) { if (PConfig::get($importer['uid'], 'system', 'ostatus_autofriend')) {
$result = Contact::createFromProbe($importer['uid'], $author_link); $result = Contact::createFromProbe($importer['uid'], $author_link);
@ -177,7 +178,7 @@ function salmon_post(App $a, $xml = '') {
//if((DBA::isResult($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == Contact::FOLLOWER) || ($r[0]['blocked']))) { //if((DBA::isResult($r)) && (($r[0]['readonly']) || ($r[0]['rel'] == Contact::FOLLOWER) || ($r[0]['blocked']))) {
if (DBA::isResult($r) && $r[0]['blocked']) { if (DBA::isResult($r) && $r[0]['blocked']) {
logger('Ignoring this author.'); Logger::log('Ignoring this author.');
System::httpExit(202); System::httpExit(202);
// NOTREACHED // NOTREACHED
} }

View file

@ -10,6 +10,7 @@ use Friendica\Content\Pager;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Item; use Friendica\Model\Item;
@ -204,7 +205,7 @@ function search_content(App $a) {
$pager = new Pager($a->query_string); $pager = new Pager($a->query_string);
if ($tag) { if ($tag) {
logger("Start tag search for '".$search."'", LOGGER_DEBUG); Logger::log("Start tag search for '".$search."'", Logger::DEBUG);
$condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`)) $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
AND `otype` = ? AND `type` = ? AND `term` = ?", AND `otype` = ? AND `type` = ? AND `term` = ?",
@ -227,7 +228,7 @@ function search_content(App $a) {
$r = []; $r = [];
} }
} else { } else {
logger("Start fulltext search for '".$search."'", LOGGER_DEBUG); Logger::log("Start fulltext search for '".$search."'", Logger::DEBUG);
$condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`)) $condition = ["(`uid` = 0 OR (`uid` = ? AND NOT `global`))
AND `body` LIKE CONCAT('%',?,'%')", AND `body` LIKE CONCAT('%',?,'%')",
@ -254,12 +255,12 @@ function search_content(App $a) {
'$title' => $title '$title' => $title
]); ]);
logger("Start Conversation for '".$search."'", LOGGER_DEBUG); Logger::log("Start Conversation for '".$search."'", Logger::DEBUG);
$o .= conversation($a, $r, $pager, 'search', false, false, 'commented', local_user()); $o .= conversation($a, $r, $pager, 'search', false, false, 'commented', local_user());
$o .= $pager->renderMinimal(count($r)); $o .= $pager->renderMinimal(count($r));
logger("Done '".$search."'", LOGGER_DEBUG); Logger::log("Done '".$search."'", Logger::DEBUG);
return $o; return $o;
} }

View file

@ -11,6 +11,7 @@ use Friendica\Core\ACL;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Theme; use Friendica\Core\Theme;
@ -269,7 +270,7 @@ function settings_post(App $a)
intval($mail_pubmail), intval($mail_pubmail),
intval(local_user()) intval(local_user())
); );
logger("mail: updating mailaccount. Response: ".print_r($r, true)); Logger::log("mail: updating mailaccount. Response: ".print_r($r, true));
$r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1", $r = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
intval(local_user()) intval(local_user())
); );
@ -547,7 +548,7 @@ function settings_post(App $a)
// If openid has changed or if there's an openid but no openidserver, try and discover it. // If openid has changed or if there's an openid but no openidserver, try and discover it.
if ($openid != $a->user['openid'] || (strlen($openid) && (!strlen($openidserver)))) { if ($openid != $a->user['openid'] || (strlen($openid) && (!strlen($openidserver)))) {
if (Network::isUrlValid($openid)) { if (Network::isUrlValid($openid)) {
logger('updating openidserver'); Logger::log('updating openidserver');
$open_id_obj = new LightOpenID($a->getHostName()); $open_id_obj = new LightOpenID($a->getHostName());
$open_id_obj->identity = $openid; $open_id_obj->identity = $openid;
$openidserver = $open_id_obj->discover($open_id_obj->identity); $openidserver = $open_id_obj->discover($open_id_obj->identity);

View file

@ -7,6 +7,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
function statistics_json_init(App $a) { function statistics_json_init(App $a) {
@ -56,6 +57,6 @@ function statistics_json_init(App $a) {
header("Content-Type: application/json"); header("Content-Type: application/json");
echo json_encode($statistics, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); echo json_encode($statistics, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
logger("statistics_init: printed " . print_r($statistics, true), LOGGER_DATA); Logger::log("statistics_init: printed " . print_r($statistics, true), Logger::DATA);
killme(); killme();
} }

View file

@ -5,6 +5,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Item; use Friendica\Model\Item;
@ -26,7 +27,7 @@ function subthread_content(App $a) {
$item = Item::selectFirst([], $condition); $item = Item::selectFirst([], $condition);
if (empty($item_id) || !DBA::isResult($item)) { if (empty($item_id) || !DBA::isResult($item)) {
logger('subthread: no item ' . $item_id); Logger::log('subthread: no item ' . $item_id);
return; return;
} }
@ -62,7 +63,7 @@ function subthread_content(App $a) {
} }
if (!$owner) { if (!$owner) {
logger('like: no owner'); Logger::log('like: no owner');
return; return;
} }

View file

@ -5,6 +5,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -28,13 +29,13 @@ function tagger_content(App $a) {
$item_id = (($a->argc > 1) ? notags(trim($a->argv[1])) : 0); $item_id = (($a->argc > 1) ? notags(trim($a->argv[1])) : 0);
logger('tagger: tag ' . $term . ' item ' . $item_id); Logger::log('tagger: tag ' . $term . ' item ' . $item_id);
$item = Item::selectFirst([], ['id' => $item_id]); $item = Item::selectFirst([], ['id' => $item_id]);
if (!$item_id || !DBA::isResult($item)) { if (!$item_id || !DBA::isResult($item)) {
logger('tagger: no item ' . $item_id); Logger::log('tagger: no item ' . $item_id);
return; return;
} }
@ -60,7 +61,7 @@ function tagger_content(App $a) {
if (DBA::isResult($r)) { if (DBA::isResult($r)) {
$contact = $r[0]; $contact = $r[0];
} else { } else {
logger('tagger: no contact_id'); Logger::log('tagger: no contact_id');
return; return;
} }

View file

@ -7,6 +7,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\UserImport; use Friendica\Core\UserImport;
function uimport_post(App $a) function uimport_post(App $a)
@ -33,7 +34,7 @@ function uimport_content(App $a)
if ($max_dailies) { if ($max_dailies) {
$r = q("select count(*) as total from user where register_date > UTC_TIMESTAMP - INTERVAL 1 day"); $r = q("select count(*) as total from user where register_date > UTC_TIMESTAMP - INTERVAL 1 day");
if ($r && $r[0]['total'] >= $max_dailies) { if ($r && $r[0]['total'] >= $max_dailies) {
logger('max daily registrations exceeded.'); Logger::log('max daily registrations exceeded.');
notice(L10n::t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.') . EOL); notice(L10n::t('This site has exceeded the number of allowed daily account registrations. Please try again tomorrow.') . EOL);
return; return;
} }

View file

@ -10,6 +10,7 @@
use Friendica\App; use Friendica\App;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -19,7 +20,7 @@ use Friendica\Object\Image;
function wall_upload_post(App $a, $desktopmode = true) function wall_upload_post(App $a, $desktopmode = true)
{ {
logger("wall upload: starting new upload", LOGGER_DEBUG); Logger::log("wall upload: starting new upload", Logger::DEBUG);
$r_json = (x($_GET, 'response') && $_GET['response'] == 'json'); $r_json = (x($_GET, 'response') && $_GET['response'] == 'json');
$album = (x($_GET, 'album') ? notags(trim($_GET['album'])) : ''); $album = (x($_GET, 'album') ? notags(trim($_GET['album'])) : '');
@ -186,8 +187,8 @@ function wall_upload_post(App $a, $desktopmode = true)
$filetype = $imagedata['mime']; $filetype = $imagedata['mime'];
} }
logger("File upload src: " . $src . " - filename: " . $filename . Logger::log("File upload src: " . $src . " - filename: " . $filename .
" - size: " . $filesize . " - type: " . $filetype, LOGGER_DEBUG); " - size: " . $filesize . " - type: " . $filetype, Logger::DEBUG);
$maximagesize = Config::get('system', 'maximagesize'); $maximagesize = Config::get('system', 'maximagesize');
@ -225,7 +226,7 @@ function wall_upload_post(App $a, $desktopmode = true)
} }
if ($max_length > 0) { if ($max_length > 0) {
$Image->scaleDown($max_length); $Image->scaleDown($max_length);
logger("File upload: Scaling picture to new size " . $max_length, LOGGER_DEBUG); Logger::log("File upload: Scaling picture to new size " . $max_length, Logger::DEBUG);
} }
$width = $Image->getWidth(); $width = $Image->getWidth();
@ -300,11 +301,11 @@ function wall_upload_post(App $a, $desktopmode = true)
echo json_encode(['picture' => $picture]); echo json_encode(['picture' => $picture]);
killme(); killme();
} }
logger("upload done", LOGGER_DEBUG); Logger::log("upload done", Logger::DEBUG);
return $picture; return $picture;
} }
logger("upload done", LOGGER_DEBUG); Logger::log("upload done", Logger::DEBUG);
if ($r_json) { if ($r_json) {
echo json_encode(['ok' => true]); echo json_encode(['ok' => true]);

View file

@ -4,6 +4,7 @@
*/ */
use Friendica\App; use Friendica\App;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Mail; use Friendica\Model\Mail;
@ -30,7 +31,7 @@ function wallmessage_post(App $a) {
); );
if (! DBA::isResult($r)) { if (! DBA::isResult($r)) {
logger('wallmessage: no recipient'); Logger::log('wallmessage: no recipient');
return; return;
} }
@ -93,7 +94,7 @@ function wallmessage_content(App $a) {
if (! DBA::isResult($r)) { if (! DBA::isResult($r)) {
notice(L10n::t('No recipient.') . EOL); notice(L10n::t('No recipient.') . EOL);
logger('wallmessage: no recipient'); Logger::log('wallmessage: no recipient');
return; return;
} }

View file

@ -5,6 +5,7 @@
*/ */
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -33,7 +34,7 @@ function worker_init()
Worker::startProcess(); Worker::startProcess();
logger("Front end worker started: ".getmypid()); Logger::log("Front end worker started: ".getmypid());
Worker::callWorker(); Worker::callWorker();
@ -55,7 +56,7 @@ function worker_init()
Worker::endProcess(); Worker::endProcess();
logger("Front end worker ended: ".getmypid()); Logger::log("Front end worker ended: ".getmypid());
killme(); killme();
} }

View file

@ -1101,10 +1101,10 @@ class App
$processlist = DBA::processlist(); $processlist = DBA::processlist();
if ($processlist['list'] != '') { if ($processlist['list'] != '') {
logger('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], LOGGER_DEBUG); Core\Logger::log('Processcheck: Processes: ' . $processlist['amount'] . ' - Processlist: ' . $processlist['list'], Core\Logger::DEBUG);
if ($processlist['amount'] > $max_processes) { if ($processlist['amount'] > $max_processes) {
logger('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', LOGGER_DEBUG); Core\Logger::log('Processcheck: Maximum number of processes for ' . $process . ' tasks (' . $max_processes . ') reached.', Core\Logger::DEBUG);
return true; return true;
} }
} }
@ -1150,7 +1150,7 @@ class App
$reached = ($free < $min_memory); $reached = ($free < $min_memory);
if ($reached) { if ($reached) {
logger('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, LOGGER_DEBUG); Core\Logger::log('Minimal memory reached: ' . $free . '/' . $meminfo['MemTotal'] . ' - limit ' . $min_memory, Core\Logger::DEBUG);
} }
return $reached; return $reached;
@ -1180,7 +1180,7 @@ class App
$load = Core\System::currentLoad(); $load = Core\System::currentLoad();
if ($load) { if ($load) {
if (intval($load) > $maxsysload) { if (intval($load) > $maxsysload) {
logger('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.'); Core\Logger::log('system: load ' . $load . ' for ' . $process . ' tasks (' . $maxsysload . ') too high.');
return true; return true;
} }
} }
@ -1222,7 +1222,7 @@ class App
$resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath()); $resource = proc_open($cmdline . ' &', [], $foo, $this->getBasePath());
} }
if (!is_resource($resource)) { if (!is_resource($resource)) {
logger('We got no resource for command ' . $cmdline, LOGGER_DEBUG); Core\Logger::log('We got no resource for command ' . $cmdline, Core\Logger::DEBUG);
return; return;
} }
proc_close($resource); proc_close($resource);
@ -1253,27 +1253,27 @@ class App
public static function isDirectoryUsable($directory, $check_writable = true) public static function isDirectoryUsable($directory, $check_writable = true)
{ {
if ($directory == '') { if ($directory == '') {
logger('Directory is empty. This shouldn\'t happen.', LOGGER_DEBUG); Core\Logger::log('Directory is empty. This shouldn\'t happen.', Core\Logger::DEBUG);
return false; return false;
} }
if (!file_exists($directory)) { if (!file_exists($directory)) {
logger('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), LOGGER_DEBUG); Core\Logger::log('Path "' . $directory . '" does not exist for user ' . self::getSystemUser(), Core\Logger::DEBUG);
return false; return false;
} }
if (is_file($directory)) { if (is_file($directory)) {
logger('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), LOGGER_DEBUG); Core\Logger::log('Path "' . $directory . '" is a file for user ' . self::getSystemUser(), Core\Logger::DEBUG);
return false; return false;
} }
if (!is_dir($directory)) { if (!is_dir($directory)) {
logger('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), LOGGER_DEBUG); Core\Logger::log('Path "' . $directory . '" is not a directory for user ' . self::getSystemUser(), Core\Logger::DEBUG);
return false; return false;
} }
if ($check_writable && !is_writable($directory)) { if ($check_writable && !is_writable($directory)) {
logger('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), LOGGER_DEBUG); Core\Logger::log('Path "' . $directory . '" is not writable for user ' . self::getSystemUser(), Core\Logger::DEBUG);
return false; return false;
} }
@ -1646,7 +1646,7 @@ class App
} else { } else {
// Someone came with an invalid parameter, maybe as a DDoS attempt // Someone came with an invalid parameter, maybe as a DDoS attempt
// We simply stop processing here // We simply stop processing here
logger("Invalid ZRL parameter " . $_GET['zrl'], LOGGER_DEBUG); Core\Logger::log("Invalid ZRL parameter " . $_GET['zrl'], Core\Logger::DEBUG);
Core\System::httpExit(403, ['title' => '403 Forbidden']); Core\System::httpExit(403, ['title' => '403 Forbidden']);
} }
} }
@ -1785,11 +1785,11 @@ class App
} }
if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) { if (!empty($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] === 'q=internal_error.html') && isset($dreamhost_error_hack)) {
logger('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']); Core\Logger::log('index.php: dreamhost_error_hack invoked. Original URI =' . $_SERVER['REQUEST_URI']);
$this->internalRedirect($_SERVER['REQUEST_URI']); $this->internalRedirect($_SERVER['REQUEST_URI']);
} }
logger('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], LOGGER_DEBUG); Core\Logger::log('index.php: page not found: ' . $_SERVER['REQUEST_URI'] . ' ADDRESS: ' . $_SERVER['REMOTE_ADDR'] . ' QUERY: ' . $_SERVER['QUERY_STRING'], Core\Logger::DEBUG);
header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found')); header($_SERVER["SERVER_PROTOCOL"] . ' 404 ' . Core\L10n::t('Not Found'));
$tpl = get_markup_template("404.tpl"); $tpl = get_markup_template("404.tpl");

View file

@ -3,6 +3,7 @@
namespace Friendica; namespace Friendica;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
/** /**
@ -136,8 +137,8 @@ abstract class BaseModule extends BaseObject
{ {
if (!self::checkFormSecurityToken($typename, $formname)) { if (!self::checkFormSecurityToken($typename, $formname)) {
$a = get_app(); $a = get_app();
logger('checkFormSecurityToken failed: user ' . $a->user['guid'] . ' - form element ' . $typename); Logger::log('checkFormSecurityToken failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
logger('checkFormSecurityToken failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA); Logger::log('checkFormSecurityToken failed: _REQUEST data: ' . print_r($_REQUEST, true), Logger::DATA);
notice(self::getFormSecurityStandardErrorMessage()); notice(self::getFormSecurityStandardErrorMessage());
$a->internalRedirect($err_redirect); $a->internalRedirect($err_redirect);
} }
@ -147,8 +148,8 @@ abstract class BaseModule extends BaseObject
{ {
if (!self::checkFormSecurityToken($typename, $formname)) { if (!self::checkFormSecurityToken($typename, $formname)) {
$a = get_app(); $a = get_app();
logger('checkFormSecurityToken failed: user ' . $a->user['guid'] . ' - form element ' . $typename); Logger::log('checkFormSecurityToken failed: user ' . $a->user['guid'] . ' - form element ' . $typename);
logger('checkFormSecurityToken failed: _REQUEST data: ' . print_r($_REQUEST, true), LOGGER_DATA); Logger::log('checkFormSecurityToken failed: _REQUEST data: ' . print_r($_REQUEST, true), Logger::DATA);
header('HTTP/1.1 403 Forbidden'); header('HTTP/1.1 403 Forbidden');
killme(); killme();
} }

View file

@ -15,6 +15,7 @@ use Friendica\Core\Addon;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -379,7 +380,7 @@ class BBCode extends BaseObject
$c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER); $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
if ($c) { if ($c) {
foreach ($matches as $mtch) { foreach ($matches as $mtch) {
logger('scale_external_image: ' . $mtch[1]); Logger::log('scale_external_image: ' . $mtch[1]);
$hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3)); $hostname = str_replace('www.', '', substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3));
if (stristr($mtch[1], $hostname)) { if (stristr($mtch[1], $hostname)) {
@ -414,7 +415,7 @@ class BBCode extends BaseObject
$Image->scaleDown(640); $Image->scaleDown(640);
$new_width = $Image->getWidth(); $new_width = $Image->getWidth();
$new_height = $Image->getHeight(); $new_height = $Image->getHeight();
logger('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], LOGGER_DEBUG); Logger::log('scale_external_images: ' . $orig_width . '->' . $new_width . 'w ' . $orig_height . '->' . $new_height . 'h' . ' match: ' . $mtch[0], Logger::DEBUG);
$s = str_replace( $s = str_replace(
$mtch[0], $mtch[0],
'[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]' '[img=' . $new_width . 'x' . $new_height. ']' . $scaled . '[/img]'
@ -423,7 +424,7 @@ class BBCode extends BaseObject
: ''), : ''),
$s $s
); );
logger('scale_external_images: new string: ' . $s, LOGGER_DEBUG); Logger::log('scale_external_images: new string: ' . $s, Logger::DEBUG);
} }
} }
} }
@ -451,7 +452,7 @@ class BBCode extends BaseObject
// than the maximum, then don't waste time looking for the images // than the maximum, then don't waste time looking for the images
if ($maxlen && (strlen($body) > $maxlen)) { if ($maxlen && (strlen($body) > $maxlen)) {
logger('the total body length exceeds the limit', LOGGER_DEBUG); Logger::log('the total body length exceeds the limit', Logger::DEBUG);
$orig_body = $body; $orig_body = $body;
$new_body = ''; $new_body = '';
@ -471,7 +472,7 @@ class BBCode extends BaseObject
if (($textlen + $img_start) > $maxlen) { if (($textlen + $img_start) > $maxlen) {
if ($textlen < $maxlen) { if ($textlen < $maxlen) {
logger('the limit happens before an embedded image', LOGGER_DEBUG); Logger::log('the limit happens before an embedded image', Logger::DEBUG);
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
$textlen = $maxlen; $textlen = $maxlen;
} }
@ -485,7 +486,7 @@ class BBCode extends BaseObject
if (($textlen + $img_end) > $maxlen) { if (($textlen + $img_end) > $maxlen) {
if ($textlen < $maxlen) { if ($textlen < $maxlen) {
logger('the limit happens before the end of a non-embedded image', LOGGER_DEBUG); Logger::log('the limit happens before the end of a non-embedded image', Logger::DEBUG);
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
$textlen = $maxlen; $textlen = $maxlen;
} }
@ -508,11 +509,11 @@ class BBCode extends BaseObject
if (($textlen + strlen($orig_body)) > $maxlen) { if (($textlen + strlen($orig_body)) > $maxlen) {
if ($textlen < $maxlen) { if ($textlen < $maxlen) {
logger('the limit happens after the end of the last image', LOGGER_DEBUG); Logger::log('the limit happens after the end of the last image', Logger::DEBUG);
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen); $new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
} }
} else { } else {
logger('the text size with embedded images extracted did not violate the limit', LOGGER_DEBUG); Logger::log('the text size with embedded images extracted did not violate the limit', Logger::DEBUG);
$new_body = $new_body . $orig_body; $new_body = $new_body . $orig_body;
} }

View file

@ -6,6 +6,7 @@ namespace Friendica\Core;
use Friendica\App; use Friendica\App;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
/** /**
@ -75,7 +76,7 @@ class Addon extends BaseObject
*/ */
public static function uninstall($addon) public static function uninstall($addon)
{ {
logger("Addons: uninstalling " . $addon); Logger::log("Addons: uninstalling " . $addon);
DBA::delete('addon', ['name' => $addon]); DBA::delete('addon', ['name' => $addon]);
@include_once('addon/' . $addon . '/' . $addon . '.php'); @include_once('addon/' . $addon . '/' . $addon . '.php');
@ -100,7 +101,7 @@ class Addon extends BaseObject
if (!file_exists('addon/' . $addon . '/' . $addon . '.php')) { if (!file_exists('addon/' . $addon . '/' . $addon . '.php')) {
return false; return false;
} }
logger("Addons: installing " . $addon); Logger::log("Addons: installing " . $addon);
$t = @filemtime('addon/' . $addon . '/' . $addon . '.php'); $t = @filemtime('addon/' . $addon . '/' . $addon . '.php');
@include_once('addon/' . $addon . '/' . $addon . '.php'); @include_once('addon/' . $addon . '/' . $addon . '.php');
if (function_exists($addon . '_install')) { if (function_exists($addon . '_install')) {
@ -125,7 +126,7 @@ class Addon extends BaseObject
} }
return true; return true;
} else { } else {
logger("Addons: FAILED installing " . $addon); Logger::log("Addons: FAILED installing " . $addon);
return false; return false;
} }
} }
@ -155,7 +156,7 @@ class Addon extends BaseObject
$t = @filemtime($fname); $t = @filemtime($fname);
foreach ($installed as $i) { foreach ($installed as $i) {
if (($i['name'] == $addon) && ($i['timestamp'] != $t)) { if (($i['name'] == $addon) && ($i['timestamp'] != $t)) {
logger('Reloading addon: ' . $i['name']); Logger::log('Reloading addon: ' . $i['name']);
@include_once($fname); @include_once($fname);
if (function_exists($addon . '_uninstall')) { if (function_exists($addon . '_uninstall')) {

View file

@ -9,6 +9,7 @@ use Friendica\BaseObject;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -153,10 +154,10 @@ class Authentication extends BaseObject
} }
if ($login_initial) { if ($login_initial) {
logger('auth_identities: ' . print_r($a->identities, true), LOGGER_DEBUG); Logger::log('auth_identities: ' . print_r($a->identities, true), Logger::DEBUG);
} }
if ($login_refresh) { if ($login_refresh) {
logger('auth_identities refresh: ' . print_r($a->identities, true), LOGGER_DEBUG); Logger::log('auth_identities refresh: ' . print_r($a->identities, true), Logger::DEBUG);
} }
$contact = DBA::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]); $contact = DBA::selectFirst('contact', [], ['uid' => $_SESSION['uid'], 'self' => true]);
@ -184,7 +185,7 @@ class Authentication extends BaseObject
* The week ensures that sessions will expire after some inactivity. * The week ensures that sessions will expire after some inactivity.
*/ */
if (!empty($_SESSION['remember'])) { if (!empty($_SESSION['remember'])) {
logger('Injecting cookie for remembered user ' . $a->user['nickname']); Logger::log('Injecting cookie for remembered user ' . $a->user['nickname']);
self::setCookie(604800, $user_record); self::setCookie(604800, $user_record);
unset($_SESSION['remember']); unset($_SESSION['remember']);
} }

View file

@ -3,6 +3,7 @@
namespace Friendica\Core\Cache; namespace Friendica\Core\Cache;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Logger;
use Exception; use Exception;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
@ -64,7 +65,7 @@ class MemcachedCacheDriver extends AbstractCacheDriver implements IMemoryCacheDr
if ($this->memcached->getResultCode() == Memcached::RES_SUCCESS) { if ($this->memcached->getResultCode() == Memcached::RES_SUCCESS) {
return $this->filterArrayKeysByPrefix($keys, $prefix); return $this->filterArrayKeysByPrefix($keys, $prefix);
} else { } else {
logger('Memcached \'getAllKeys\' failed with ' . $this->memcached->getResultMessage(), LOGGER_ALL); Logger::log('Memcached \'getAllKeys\' failed with ' . $this->memcached->getResultMessage(), Logger::ALL);
return []; return [];
} }
} }
@ -83,7 +84,7 @@ class MemcachedCacheDriver extends AbstractCacheDriver implements IMemoryCacheDr
if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) { if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
$return = $value; $return = $value;
} else { } else {
logger('Memcached \'get\' failed with ' . $this->memcached->getResultMessage(), LOGGER_ALL); Logger::log('Memcached \'get\' failed with ' . $this->memcached->getResultMessage(), Logger::ALL);
} }
return $return; return $return;

View file

@ -6,6 +6,7 @@ namespace Friendica\Core;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
require_once 'boot.php'; require_once 'boot.php';
@ -271,7 +272,7 @@ class L10n extends BaseObject
public static function tt($singular, $plural, $count) public static function tt($singular, $plural, $count)
{ {
if (!is_numeric($count)) { if (!is_numeric($count)) {
logger('Non numeric count called by ' . System::callstack(20)); Logger::log('Non numeric count called by ' . System::callstack(20));
} }
if (!self::$lang) { if (!self::$lang) {

View file

@ -7,6 +7,7 @@ namespace Friendica\Core;
* @brief Functions for preventing parallel execution of functions * @brief Functions for preventing parallel execution of functions
*/ */
use Friendica\Core\Logger;
use Friendica\Core\Cache\CacheDriverFactory; use Friendica\Core\Cache\CacheDriverFactory;
use Friendica\Core\Cache\IMemoryCacheDriver; use Friendica\Core\Cache\IMemoryCacheDriver;
@ -83,7 +84,7 @@ class Lock
} }
return; return;
} catch (\Exception $exception) { } catch (\Exception $exception) {
logger('Using Cache driver for locking failed: ' . $exception->getMessage()); Logger::log('Using Cache driver for locking failed: ' . $exception->getMessage());
} }
} }

132
src/Core/Logger.php Normal file
View file

@ -0,0 +1,132 @@
<?php
/**
* @file src/Core/Logger.php
*/
namespace Friendica\Core;
use Friendica\BaseObject;
use Friendica\Core\Config;
use Friendica\Util\DateTimeFormat;
use ReflectionClass;
/**
* @brief Logger functions
*/
class Logger extends BaseObject
{
// Log levels:
const WARNING = 0;
const INFO = 1;
const TRACE = 2;
const DEBUG = 3;
const DATA = 4;
const ALL = 5;
public static $levels = [
self::WARNING => 'Warning',
self::INFO => 'Info',
self::TRACE => 'Trace',
self::DEBUG => 'Debug',
self::DATA => 'Data',
self::ALL => 'All',
];
/**
* @brief Logs the given message at the given log level
*
* @param string $msg
* @param int $level
*/
public static function log($msg, $level = self::INFO)
{
$a = self::getApp();
$debugging = Config::get('system', 'debugging');
$logfile = Config::get('system', 'logfile');
$loglevel = intval(Config::get('system', 'loglevel'));
if (
!$debugging
|| !$logfile
|| $level > $loglevel
) {
return;
}
$processId = session_id();
if ($processId == '')
{
$processId = $a->process_id;
}
$callers = debug_backtrace();
if (count($callers) > 1) {
$function = $callers[1]['function'];
} else {
$function = '';
}
$logline = sprintf("%s@%s\t[%s]:%s:%s:%s\t%s\n",
DateTimeFormat::utcNow(DateTimeFormat::ATOM),
$processId,
self::$levels[$level],
basename($callers[0]['file']),
$callers[0]['line'],
$function,
$msg
);
$stamp1 = microtime(true);
@file_put_contents($logfile, $logline, FILE_APPEND);
$a->saveTimestamp($stamp1, "file");
}
/**
* @brief An alternative logger for development.
* Works largely as log() but allows developers
* to isolate particular elements they are targetting
* personally without background noise
*
* @param string $msg
*/
public static function devLog($msg)
{
$a = self::getApp();
$logfile = Config::get('system', 'dlogfile');
if (!$logfile) {
return;
}
$dlogip = Config::get('system', 'dlogip');
if (!is_null($dlogip) && $_SERVER['REMOTE_ADDR'] != $dlogip)
{
return;
}
$processId = session_id();
if ($processId == '')
{
$processId = $a->process_id;
}
$callers = debug_backtrace();
$logline = sprintf("%s@\t%s:\t%s:\t%s\t%s\t%s\n",
DateTimeFormat::utcNow(),
$processId,
basename($callers[0]['file']),
$callers[0]['line'],
$callers[1]['function'],
$msg
);
$stamp1 = microtime(true);
@file_put_contents($logfile, $logline, FILE_APPEND);
$a->saveTimestamp($stamp1, "file");
}
}

View file

@ -9,6 +9,7 @@ namespace Friendica\Core;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -358,7 +359,7 @@ class NotificationsManager extends BaseObject
break; break;
} }
/// @todo Check if this part here is used at all /// @todo Check if this part here is used at all
logger('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), LOGGER_DEBUG); Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG);
$xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">"; $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
$obj = XML::parseString($xmlhead . $it['object']); $obj = XML::parseString($xmlhead . $it['object']);

View file

@ -4,6 +4,7 @@ namespace Friendica\Core\Session;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Logger;
use Friendica\Core\Session; use Friendica\Core\Session;
use SessionHandlerInterface; use SessionHandlerInterface;
@ -33,7 +34,7 @@ class CacheSessionHandler extends BaseObject implements SessionHandlerInterface
Session::$exists = true; Session::$exists = true;
return $data; return $data;
} }
logger("no data for session $session_id", LOGGER_TRACE); Logger::log("no data for session $session_id", Logger::TRACE);
return ''; return '';
} }

View file

@ -3,6 +3,7 @@
namespace Friendica\Core\Session; namespace Friendica\Core\Session;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Core\Session; use Friendica\Core\Session;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use SessionHandlerInterface; use SessionHandlerInterface;
@ -34,7 +35,7 @@ class DatabaseSessionHandler extends BaseObject implements SessionHandlerInterfa
Session::$exists = true; Session::$exists = true;
return $session['data']; return $session['data'];
} }
logger("no data for session $session_id", LOGGER_TRACE); Logger::log("no data for session $session_id", Logger::TRACE);
return ''; return '';
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Util\XML; use Friendica\Util\XML;
@ -100,7 +101,7 @@ class System extends BaseObject
} }
if ($st) { if ($st) {
logger('xml_status returning non_zero: ' . $st . " message=" . $message); Logger::log('xml_status returning non_zero: ' . $st . " message=" . $message);
} }
header("Content-type: text/xml"); header("Content-type: text/xml");
@ -134,7 +135,7 @@ class System extends BaseObject
$err = 'OK'; $err = 'OK';
} }
logger('http_status_exit ' . $val); Logger::log('http_status_exit ' . $val);
header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err); header($_SERVER["SERVER_PROTOCOL"] . ' ' . $val . ' ' . $err);
if (isset($description["title"])) { if (isset($description["title"])) {

View file

@ -6,6 +6,7 @@
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
require_once 'boot.php'; require_once 'boot.php';
@ -106,7 +107,7 @@ class Theme
// install and uninstall theme // install and uninstall theme
public static function uninstall($theme) public static function uninstall($theme)
{ {
logger("Addons: uninstalling theme " . $theme); Logger::log("Addons: uninstalling theme " . $theme);
include_once "view/theme/$theme/theme.php"; include_once "view/theme/$theme/theme.php";
if (function_exists("{$theme}_uninstall")) { if (function_exists("{$theme}_uninstall")) {
@ -123,7 +124,7 @@ class Theme
return false; return false;
} }
logger("Addons: installing theme $theme"); Logger::log("Addons: installing theme $theme");
include_once "view/theme/$theme/theme.php"; include_once "view/theme/$theme/theme.php";
@ -132,7 +133,7 @@ class Theme
$func(); $func();
return true; return true;
} else { } else {
logger("Addons: FAILED installing theme $theme"); Logger::log("Addons: FAILED installing theme $theme");
return false; return false;
} }
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\App; use Friendica\App;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Photo; use Friendica\Model\Photo;
@ -37,7 +38,7 @@ class UserImport
private static function checkCols($table, &$arr) private static function checkCols($table, &$arr)
{ {
$query = sprintf("SHOW COLUMNS IN `%s`", DBA::escape($table)); $query = sprintf("SHOW COLUMNS IN `%s`", DBA::escape($table));
logger("uimport: $query", LOGGER_DEBUG); Logger::log("uimport: $query", Logger::DEBUG);
$r = q($query); $r = q($query);
$tcols = []; $tcols = [];
// get a plain array of column names // get a plain array of column names
@ -68,7 +69,7 @@ class UserImport
$cols = implode("`,`", array_map(['Friendica\Database\DBA', 'escape'], array_keys($arr))); $cols = implode("`,`", array_map(['Friendica\Database\DBA', 'escape'], array_keys($arr)));
$vals = implode("','", array_map(['Friendica\Database\DBA', 'escape'], array_values($arr))); $vals = implode("','", array_map(['Friendica\Database\DBA', 'escape'], array_values($arr)));
$query = "INSERT INTO `$table` (`$cols`) VALUES ('$vals')"; $query = "INSERT INTO `$table` (`$cols`) VALUES ('$vals')";
logger("uimport: $query", LOGGER_TRACE); Logger::log("uimport: $query", Logger::TRACE);
if (self::IMPORT_DEBUG) { if (self::IMPORT_DEBUG) {
return true; return true;
@ -85,7 +86,7 @@ class UserImport
*/ */
public static function importAccount(App $a, $file) public static function importAccount(App $a, $file)
{ {
logger("Start user import from " . $file['tmp_name']); Logger::log("Start user import from " . $file['tmp_name']);
/* /*
STEPS STEPS
1. checks 1. checks
@ -143,7 +144,7 @@ class UserImport
// import user // import user
$r = self::dbImportAssoc('user', $account['user']); $r = self::dbImportAssoc('user', $account['user']);
if ($r === false) { if ($r === false) {
logger("uimport:insert user : ERROR : " . DBA::errorMessage(), LOGGER_INFO); Logger::log("uimport:insert user : ERROR : " . DBA::errorMessage(), Logger::INFO);
notice(L10n::t("User creation error")); notice(L10n::t("User creation error"));
return; return;
} }
@ -161,7 +162,7 @@ class UserImport
$profile['uid'] = $newuid; $profile['uid'] = $newuid;
$r = self::dbImportAssoc('profile', $profile); $r = self::dbImportAssoc('profile', $profile);
if ($r === false) { if ($r === false) {
logger("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . DBA::errorMessage(), LOGGER_INFO); Logger::log("uimport:insert profile " . $profile['profile-name'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
info(L10n::t("User profile creation error")); info(L10n::t("User profile creation error"));
DBA::delete('user', ['uid' => $newuid]); DBA::delete('user', ['uid' => $newuid]);
return; return;
@ -199,7 +200,7 @@ class UserImport
$contact['uid'] = $newuid; $contact['uid'] = $newuid;
$r = self::dbImportAssoc('contact', $contact); $r = self::dbImportAssoc('contact', $contact);
if ($r === false) { if ($r === false) {
logger("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . DBA::errorMessage(), LOGGER_INFO); Logger::log("uimport:insert contact " . $contact['nick'] . "," . $contact['network'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
$errorcount++; $errorcount++;
} else { } else {
$contact['newid'] = self::lastInsertId(); $contact['newid'] = self::lastInsertId();
@ -213,7 +214,7 @@ class UserImport
$group['uid'] = $newuid; $group['uid'] = $newuid;
$r = self::dbImportAssoc('group', $group); $r = self::dbImportAssoc('group', $group);
if ($r === false) { if ($r === false) {
logger("uimport:insert group " . $group['name'] . " : ERROR : " . DBA::errorMessage(), LOGGER_INFO); Logger::log("uimport:insert group " . $group['name'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
} else { } else {
$group['newid'] = self::lastInsertId(); $group['newid'] = self::lastInsertId();
} }
@ -238,7 +239,7 @@ class UserImport
if ($import == 2) { if ($import == 2) {
$r = self::dbImportAssoc('group_member', $group_member); $r = self::dbImportAssoc('group_member', $group_member);
if ($r === false) { if ($r === false) {
logger("uimport:insert group member " . $group_member['id'] . " : ERROR : " . DBA::errorMessage(), LOGGER_INFO); Logger::log("uimport:insert group member " . $group_member['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
} }
} }
} }
@ -256,7 +257,7 @@ class UserImport
); );
if ($r === false) { if ($r === false) {
logger("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . DBA::errorMessage(), LOGGER_INFO); Logger::log("uimport:insert photo " . $photo['resource-id'] . "," . $photo['scale'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
} }
} }
@ -264,7 +265,7 @@ class UserImport
$pconfig['uid'] = $newuid; $pconfig['uid'] = $newuid;
$r = self::dbImportAssoc('pconfig', $pconfig); $r = self::dbImportAssoc('pconfig', $pconfig);
if ($r === false) { if ($r === false) {
logger("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . DBA::errorMessage(), LOGGER_INFO); Logger::log("uimport:insert pconfig " . $pconfig['id'] . " : ERROR : " . DBA::errorMessage(), Logger::INFO);
} }
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Core; namespace Friendica\Core;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Process; use Friendica\Model\Process;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -42,7 +43,7 @@ class Worker
// At first check the maximum load. We shouldn't continue with a high load // At first check the maximum load. We shouldn't continue with a high load
if ($a->isMaxLoadReached()) { if ($a->isMaxLoadReached()) {
logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG); Logger::log('Pre check: maximum load reached, quitting.', Logger::DEBUG);
return; return;
} }
@ -58,25 +59,25 @@ class Worker
// Count active workers and compare them with a maximum value that depends on the load // Count active workers and compare them with a maximum value that depends on the load
if (self::tooMuchWorkers()) { if (self::tooMuchWorkers()) {
logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG); Logger::log('Pre check: Active worker limit reached, quitting.', Logger::DEBUG);
return; return;
} }
// Do we have too few memory? // Do we have too few memory?
if ($a->isMinMemoryReached()) { if ($a->isMinMemoryReached()) {
logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG); Logger::log('Pre check: Memory limit reached, quitting.', Logger::DEBUG);
return; return;
} }
// Possibly there are too much database connections // Possibly there are too much database connections
if (self::maxConnectionsReached()) { if (self::maxConnectionsReached()) {
logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG); Logger::log('Pre check: maximum connections reached, quitting.', Logger::DEBUG);
return; return;
} }
// Possibly there are too much database processes that block the system // Possibly there are too much database processes that block the system
if ($a->isMaxProcessesReached()) { if ($a->isMaxProcessesReached()) {
logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG); Logger::log('Pre check: maximum processes reached, quitting.', Logger::DEBUG);
return; return;
} }
@ -99,7 +100,7 @@ class Worker
// The work will be done // The work will be done
if (!self::execute($entry)) { if (!self::execute($entry)) {
logger('Process execution failed, quitting.', LOGGER_DEBUG); Logger::log('Process execution failed, quitting.', Logger::DEBUG);
return; return;
} }
@ -117,14 +118,14 @@ class Worker
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
// Count active workers and compare them with a maximum value that depends on the load // Count active workers and compare them with a maximum value that depends on the load
if (self::tooMuchWorkers()) { if (self::tooMuchWorkers()) {
logger('Active worker limit reached, quitting.', LOGGER_DEBUG); Logger::log('Active worker limit reached, quitting.', Logger::DEBUG);
Lock::release('worker'); Lock::release('worker');
return; return;
} }
// Check free memory // Check free memory
if ($a->isMinMemoryReached()) { if ($a->isMinMemoryReached()) {
logger('Memory limit reached, quitting.', LOGGER_DEBUG); Logger::log('Memory limit reached, quitting.', Logger::DEBUG);
Lock::release('worker'); Lock::release('worker');
return; return;
} }
@ -134,7 +135,7 @@ class Worker
// Quit the worker once every 5 minutes // Quit the worker once every 5 minutes
if (time() > ($starttime + 300)) { if (time() > ($starttime + 300)) {
logger('Process lifetime reached, quitting.', LOGGER_DEBUG); Logger::log('Process lifetime reached, quitting.', Logger::DEBUG);
return; return;
} }
} }
@ -143,7 +144,7 @@ class Worker
if (Config::get('system', 'worker_daemon_mode', false)) { if (Config::get('system', 'worker_daemon_mode', false)) {
self::IPCSetJobState(false); self::IPCSetJobState(false);
} }
logger("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", LOGGER_DEBUG); Logger::log("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", Logger::DEBUG);
} }
/** /**
@ -213,19 +214,19 @@ class Worker
// Quit when in maintenance // Quit when in maintenance
if (Config::get('system', 'maintenance', false, true)) { if (Config::get('system', 'maintenance', false, true)) {
logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG); Logger::log("Maintenance mode - quit process ".$mypid, Logger::DEBUG);
return false; return false;
} }
// Constantly check the number of parallel database processes // Constantly check the number of parallel database processes
if ($a->isMaxProcessesReached()) { if ($a->isMaxProcessesReached()) {
logger("Max processes reached for process ".$mypid, LOGGER_DEBUG); Logger::log("Max processes reached for process ".$mypid, Logger::DEBUG);
return false; return false;
} }
// Constantly check the number of available database connections to let the frontend be accessible at any time // Constantly check the number of available database connections to let the frontend be accessible at any time
if (self::maxConnectionsReached()) { if (self::maxConnectionsReached()) {
logger("Max connection reached for process ".$mypid, LOGGER_DEBUG); Logger::log("Max connection reached for process ".$mypid, Logger::DEBUG);
return false; return false;
} }
@ -270,7 +271,7 @@ class Worker
} }
if (!validate_include($include)) { if (!validate_include($include)) {
logger("Include file ".$argv[0]." is not valid!"); Logger::log("Include file ".$argv[0]." is not valid!");
DBA::delete('workerqueue', ['id' => $queue["id"]]); DBA::delete('workerqueue', ['id' => $queue["id"]]);
return true; return true;
} }
@ -302,7 +303,7 @@ class Worker
} }
self::$db_duration = (microtime(true) - $stamp); self::$db_duration = (microtime(true) - $stamp);
} else { } else {
logger("Function ".$funcname." does not exist"); Logger::log("Function ".$funcname." does not exist");
DBA::delete('workerqueue', ['id' => $queue["id"]]); DBA::delete('workerqueue', ['id' => $queue["id"]]);
} }
@ -328,7 +329,7 @@ class Worker
$new_process_id = System::processID("wrk"); $new_process_id = System::processID("wrk");
logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id); Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
@ -378,27 +379,27 @@ class Worker
* The execution time is the productive time. * The execution time is the productive time.
* By changing parameters like the maximum number of workers we can check the effectivness. * By changing parameters like the maximum number of workers we can check the effectivness.
*/ */
logger( Logger::log(
'DB: '.number_format(self::$db_duration, 2). 'DB: '.number_format(self::$db_duration, 2).
' - Lock: '.number_format(self::$lock_duration, 2). ' - Lock: '.number_format(self::$lock_duration, 2).
' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2). ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
' - Execution: '.number_format($duration, 2), ' - Execution: '.number_format($duration, 2),
LOGGER_DEBUG Logger::DEBUG
); );
self::$lock_duration = 0; self::$lock_duration = 0;
if ($duration > 3600) { if ($duration > 3600) {
logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG); Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", Logger::DEBUG);
} elseif ($duration > 600) { } elseif ($duration > 600) {
logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG); Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", Logger::DEBUG);
} elseif ($duration > 300) { } elseif ($duration > 300) {
logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG); Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", Logger::DEBUG);
} elseif ($duration > 120) { } elseif ($duration > 120) {
logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG); Logger::log("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", Logger::DEBUG);
} }
logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id); Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
// Write down the performance values into the log // Write down the performance values into the log
if (Config::get("system", "profiler")) { if (Config::get("system", "profiler")) {
@ -453,7 +454,7 @@ class Worker
} }
} }
logger( Logger::log(
"ID ".$queue["id"].": ".$funcname.": ".sprintf( "ID ".$queue["id"].": ".$funcname.": ".sprintf(
"DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o, "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
number_format($a->performance["database"] - $a->performance["database_write"], 2), number_format($a->performance["database"] - $a->performance["database_write"], 2),
@ -467,14 +468,14 @@ class Worker
+ $a->performance["network"] + $a->performance["file"]), 2), + $a->performance["network"] + $a->performance["file"]), 2),
number_format($duration, 2) number_format($duration, 2)
), ),
LOGGER_DEBUG Logger::DEBUG
); );
} }
$cooldown = Config::get("system", "worker_cooldown", 0); $cooldown = Config::get("system", "worker_cooldown", 0);
if ($cooldown > 0) { if ($cooldown > 0) {
logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds"); Logger::log("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
sleep($cooldown); sleep($cooldown);
} }
} }
@ -518,12 +519,12 @@ class Worker
$used = DBA::numRows($r); $used = DBA::numRows($r);
DBA::close($r); DBA::close($r);
logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG); Logger::log("Connection usage (user values): ".$used."/".$max, Logger::DEBUG);
$level = ($used / $max) * 100; $level = ($used / $max) * 100;
if ($level >= $maxlevel) { if ($level >= $maxlevel) {
logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max); Logger::log("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
return true; return true;
} }
} }
@ -546,14 +547,14 @@ class Worker
if ($used == 0) { if ($used == 0) {
return false; return false;
} }
logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG); Logger::log("Connection usage (system values): ".$used."/".$max, Logger::DEBUG);
$level = $used / $max * 100; $level = $used / $max * 100;
if ($level < $maxlevel) { if ($level < $maxlevel) {
return false; return false;
} }
logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max); Logger::log("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
return true; return true;
} }
@ -594,7 +595,7 @@ class Worker
// How long is the process already running? // How long is the process already running?
$duration = (time() - strtotime($entry["executed"])) / 60; $duration = (time() - strtotime($entry["executed"])) / 60;
if ($duration > $max_duration) { if ($duration > $max_duration) {
logger("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now."); Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") took more than ".$max_duration." minutes. It will be killed now.");
posix_kill($entry["pid"], SIGTERM); posix_kill($entry["pid"], SIGTERM);
// We killed the stale process. // We killed the stale process.
@ -614,7 +615,7 @@ class Worker
['id' => $entry["id"]] ['id' => $entry["id"]]
); );
} else { } else {
logger("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG); Logger::log("Worker process ".$entry["pid"]." (".substr(json_encode($argv), 0, 50).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", Logger::DEBUG);
} }
} }
} }
@ -697,16 +698,16 @@ class Worker
$high_running = self::processWithPriorityActive($top_priority); $high_running = self::processWithPriorityActive($top_priority);
if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) { if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG); Logger::log("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", Logger::DEBUG);
$queues = $active + 1; $queues = $active + 1;
} }
} }
logger("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $entries . $processlist . " - maximum: " . $queues . "/" . $maxqueues, LOGGER_DEBUG); Logger::log("Load: " . $load ."/" . $maxsysload . " - processes: " . $deferred . "/" . $active . "/" . $entries . $processlist . " - maximum: " . $queues . "/" . $maxqueues, Logger::DEBUG);
// Are there fewer workers running as possible? Then fork a new one. // Are there fewer workers running as possible? Then fork a new one.
if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) { if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG); Logger::log("Active workers: ".$active."/".$queues." Fork a new worker.", Logger::DEBUG);
if (Config::get('system', 'worker_daemon_mode', false)) { if (Config::get('system', 'worker_daemon_mode', false)) {
self::IPCSetJobState(true); self::IPCSetJobState(true);
} else { } else {
@ -779,11 +780,11 @@ class Worker
++$high; ++$high;
} }
} }
logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG); Logger::log("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, Logger::DEBUG);
$passing_slow = (($high/count($priorities)) > (2/3)); $passing_slow = (($high/count($priorities)) > (2/3));
if ($passing_slow) { if ($passing_slow) {
logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG); Logger::log("Passing slower processes than priority ".$highest_priority, Logger::DEBUG);
} }
return $passing_slow; return $passing_slow;
} }
@ -816,7 +817,7 @@ class Worker
$slope = $queue_length / pow($lower_job_limit, $exponent); $slope = $queue_length / pow($lower_job_limit, $exponent);
$limit = min($queue_length, ceil($slope * pow($jobs, $exponent))); $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
logger('Deferred: ' . $deferred . ' - Total: ' . $jobs . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, LOGGER_DEBUG); Logger::log('Deferred: ' . $deferred . ' - Total: ' . $jobs . ' - Maximum: ' . $queue_length . ' - jobs per queue: ' . $limit, Logger::DEBUG);
$ids = []; $ids = [];
if (self::passingSlow($highest_priority)) { if (self::passingSlow($highest_priority)) {
// Are there waiting processes with a higher priority than the currently highest? // Are there waiting processes with a higher priority than the currently highest?
@ -975,7 +976,7 @@ class Worker
self::runCron(); self::runCron();
logger('Call worker', LOGGER_DEBUG); Logger::log('Call worker', Logger::DEBUG);
self::spawnWorker(); self::spawnWorker();
return; return;
} }
@ -1014,7 +1015,7 @@ class Worker
*/ */
private static function runCron() private static function runCron()
{ {
logger('Add cron entries', LOGGER_DEBUG); Logger::log('Add cron entries', Logger::DEBUG);
// Check for spooled items // Check for spooled items
self::add(PRIORITY_HIGH, "SpoolPost"); self::add(PRIORITY_HIGH, "SpoolPost");
@ -1152,7 +1153,7 @@ class Worker
$id = $queue['id']; $id = $queue['id'];
if ($retrial > 14) { if ($retrial > 14) {
logger('Id ' . $id . ' had been tried 14 times. We stop now.', LOGGER_DEBUG); Logger::log('Id ' . $id . ' had been tried 14 times. We stop now.', Logger::DEBUG);
return; return;
} }
@ -1160,7 +1161,7 @@ class Worker
$delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1)); $delay = (($retrial + 3) ** 4) + (rand(1, 30) * ($retrial + 1));
$next = DateTimeFormat::utc('now + ' . $delay . ' seconds'); $next = DateTimeFormat::utc('now + ' . $delay . ' seconds');
logger('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next, LOGGER_DEBUG); Logger::log('Defer execution ' . $retrial . ' of id ' . $id . ' to ' . $next, Logger::DEBUG);
$fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0]; $fields = ['retrial' => $retrial + 1, 'next_try' => $next, 'executed' => DBA::NULL_DATETIME, 'pid' => 0];
DBA::update('workerqueue', $fields, ['id' => $id]); DBA::update('workerqueue', $fields, ['id' => $id]);

View file

@ -6,6 +6,7 @@ namespace Friendica\Database;
// Please use App->getConfigVariable() instead. // Please use App->getConfigVariable() instead.
//use Friendica\Core\Config; //use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
use mysqli; use mysqli;
@ -412,7 +413,7 @@ class DBA
if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) { if ((substr_count($sql, '?') != count($args)) && (count($args) > 0)) {
// Question: Should we continue or stop the query here? // Question: Should we continue or stop the query here?
logger('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), LOGGER_DEBUG); Logger::log('Parameter mismatch. Query "'.$sql.'" - Parameters '.print_r($args, true), Logger::DEBUG);
} }
$sql = self::cleanQuery($sql); $sql = self::cleanQuery($sql);
@ -552,7 +553,7 @@ class DBA
$error = self::$error; $error = self::$error;
$errorno = self::$errorno; $errorno = self::$errorno;
logger('DB Error '.self::$errorno.': '.self::$error."\n". Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
System::callstack(8)."\n".self::replaceParameters($sql, $args)); System::callstack(8)."\n".self::replaceParameters($sql, $args));
// On a lost connection we try to reconnect - but only once. // On a lost connection we try to reconnect - but only once.
@ -560,14 +561,14 @@ class DBA
if (self::$in_retrial || !self::reconnect()) { if (self::$in_retrial || !self::reconnect()) {
// It doesn't make sense to continue when the database connection was lost // It doesn't make sense to continue when the database connection was lost
if (self::$in_retrial) { if (self::$in_retrial) {
logger('Giving up retrial because of database error '.$errorno.': '.$error); Logger::log('Giving up retrial because of database error '.$errorno.': '.$error);
} else { } else {
logger("Couldn't reconnect after database error ".$errorno.': '.$error); Logger::log("Couldn't reconnect after database error ".$errorno.': '.$error);
} }
exit(1); exit(1);
} else { } else {
// We try it again // We try it again
logger('Reconnected after database error '.$errorno.': '.$error); Logger::log('Reconnected after database error '.$errorno.': '.$error);
self::$in_retrial = true; self::$in_retrial = true;
$ret = self::p($sql, $args); $ret = self::p($sql, $args);
self::$in_retrial = false; self::$in_retrial = false;
@ -636,13 +637,13 @@ class DBA
$error = self::$error; $error = self::$error;
$errorno = self::$errorno; $errorno = self::$errorno;
logger('DB Error '.self::$errorno.': '.self::$error."\n". Logger::log('DB Error '.self::$errorno.': '.self::$error."\n".
System::callstack(8)."\n".self::replaceParameters($sql, $params)); System::callstack(8)."\n".self::replaceParameters($sql, $params));
// On a lost connection we simply quit. // On a lost connection we simply quit.
// A reconnect like in self::p could be dangerous with modifications // A reconnect like in self::p could be dangerous with modifications
if ($errorno == 2006) { if ($errorno == 2006) {
logger('Giving up because of database error '.$errorno.': '.$error); Logger::log('Giving up because of database error '.$errorno.': '.$error);
exit(1); exit(1);
} }
@ -835,7 +836,7 @@ class DBA
public static function insert($table, $param, $on_duplicate_update = false) { public static function insert($table, $param, $on_duplicate_update = false) {
if (empty($table) || empty($param)) { if (empty($table) || empty($param)) {
logger('Table and fields have to be set'); Logger::log('Table and fields have to be set');
return false; return false;
} }
@ -1051,7 +1052,7 @@ class DBA
public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = []) public static function delete($table, array $conditions, array $options = [], $in_process = false, array &$callstack = [])
{ {
if (empty($table) || empty($conditions)) { if (empty($table) || empty($conditions)) {
logger('Table and conditions have to be set'); Logger::log('Table and conditions have to be set');
return false; return false;
} }
@ -1142,7 +1143,7 @@ class DBA
if ((count($command['conditions']) > 1) || is_int($first_key)) { if ((count($command['conditions']) > 1) || is_int($first_key)) {
$sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string; $sql = "DELETE FROM `" . $command['table'] . "`" . $condition_string;
logger(self::replaceParameters($sql, $conditions), LOGGER_DATA); Logger::log(self::replaceParameters($sql, $conditions), Logger::DATA);
if (!self::e($sql, $conditions)) { if (!self::e($sql, $conditions)) {
if ($do_transaction) { if ($do_transaction) {
@ -1172,7 +1173,7 @@ class DBA
$sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" . $sql = "DELETE FROM `" . $table . "` WHERE `" . $field . "` IN (" .
substr(str_repeat("?, ", count($field_values)), 0, -2) . ");"; substr(str_repeat("?, ", count($field_values)), 0, -2) . ");";
logger(self::replaceParameters($sql, $field_values), LOGGER_DATA); Logger::log(self::replaceParameters($sql, $field_values), Logger::DATA);
if (!self::e($sql, $field_values)) { if (!self::e($sql, $field_values)) {
if ($do_transaction) { if ($do_transaction) {
@ -1223,7 +1224,7 @@ class DBA
public static function update($table, $fields, $condition, $old_fields = []) { public static function update($table, $fields, $condition, $old_fields = []) {
if (empty($table) || empty($fields) || empty($condition)) { if (empty($table) || empty($fields) || empty($condition)) {
logger('Table, fields and condition have to be set'); Logger::log('Table, fields and condition have to be set');
return false; return false;
} }

View file

@ -8,6 +8,7 @@ use Exception;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Hook; use Friendica\Core\Hook;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
require_once 'boot.php'; require_once 'boot.php';
@ -69,7 +70,7 @@ class DBStructure
// No valid result? // No valid result?
if (!DBA::isResult($adminlist)) { if (!DBA::isResult($adminlist)) {
logger(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), LOGGER_INFO); Logger::log(sprintf('Cannot notify administrators about update_id=%d, error_message=%s', $update_id, $error_message), Logger::INFO);
// Don't continue // Don't continue
return; return;
@ -100,7 +101,7 @@ class DBStructure
} }
//try the logger //try the logger
logger("CRITICAL: Database structure update failed: ".$error_message); Logger::log("CRITICAL: Database structure update failed: ".$error_message);
} }
@ -221,7 +222,7 @@ class DBStructure
$errors = ''; $errors = '';
logger('updating structure', LOGGER_DEBUG); Logger::log('updating structure', Logger::DEBUG);
// Get the current structure // Get the current structure
$database = []; $database = [];
@ -234,7 +235,7 @@ class DBStructure
foreach ($tables AS $table) { foreach ($tables AS $table) {
$table = current($table); $table = current($table);
logger(sprintf('updating structure for table %s ...', $table), LOGGER_DEBUG); Logger::log(sprintf('updating structure for table %s ...', $table), Logger::DEBUG);
$database[$table] = self::tableStructure($table); $database[$table] = self::tableStructure($table);
} }
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Database; namespace Friendica\Database;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\Item; use Friendica\Model\Item;
@ -52,7 +53,7 @@ class PostUpdate
return true; return true;
} }
logger("Start", LOGGER_DEBUG); Logger::log("Start", Logger::DEBUG);
$end_id = Config::get("system", "post_update_1194_end"); $end_id = Config::get("system", "post_update_1194_end");
if (!$end_id) { if (!$end_id) {
@ -63,7 +64,7 @@ class PostUpdate
} }
} }
logger("End ID: ".$end_id, LOGGER_DEBUG); Logger::log("End ID: ".$end_id, Logger::DEBUG);
$start_id = Config::get("system", "post_update_1194_start"); $start_id = Config::get("system", "post_update_1194_start");
@ -82,14 +83,14 @@ class PostUpdate
DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS)); DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
if (!$r) { if (!$r) {
Config::set("system", "post_update_version", 1194); Config::set("system", "post_update_version", 1194);
logger("Update is done", LOGGER_DEBUG); Logger::log("Update is done", Logger::DEBUG);
return true; return true;
} else { } else {
Config::set("system", "post_update_1194_start", $r[0]["id"]); Config::set("system", "post_update_1194_start", $r[0]["id"]);
$start_id = Config::get("system", "post_update_1194_start"); $start_id = Config::get("system", "post_update_1194_start");
} }
logger("Start ID: ".$start_id, LOGGER_DEBUG); Logger::log("Start ID: ".$start_id, Logger::DEBUG);
$r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1000,1", $r = q($query1.$query2.$query3." ORDER BY `item`.`id` LIMIT 1000,1",
intval($start_id), intval($end_id), intval($start_id), intval($end_id),
@ -99,13 +100,13 @@ class PostUpdate
} else { } else {
$pos_id = $end_id; $pos_id = $end_id;
} }
logger("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, LOGGER_DEBUG); Logger::log("Progress: Start: ".$start_id." position: ".$pos_id." end: ".$end_id, Logger::DEBUG);
q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3, q("UPDATE `item` ".$query2." SET `item`.`global` = 1 ".$query3,
intval($start_id), intval($pos_id), intval($start_id), intval($pos_id),
DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS)); DBA::escape(Protocol::DFRN), DBA::escape(Protocol::DIASPORA), DBA::escape(Protocol::OSTATUS));
logger("Done", LOGGER_DEBUG); Logger::log("Done", Logger::DEBUG);
} }
/** /**
@ -122,7 +123,7 @@ class PostUpdate
return true; return true;
} }
logger("Start", LOGGER_DEBUG); Logger::log("Start", Logger::DEBUG);
$r = q("SELECT `contact`.`id`, `contact`.`last-item`, $r = q("SELECT `contact`.`id`, `contact`.`last-item`,
(SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date` (SELECT MAX(`changed`) FROM `item` USE INDEX (`uid_wall_changed`) WHERE `wall` AND `uid` = `user`.`uid`) AS `lastitem_date`
FROM `user` FROM `user`
@ -138,7 +139,7 @@ class PostUpdate
} }
Config::set("system", "post_update_version", 1206); Config::set("system", "post_update_version", 1206);
logger("Done", LOGGER_DEBUG); Logger::log("Done", Logger::DEBUG);
return true; return true;
} }
@ -156,7 +157,7 @@ class PostUpdate
$id = Config::get("system", "post_update_version_1279_id", 0); $id = Config::get("system", "post_update_version_1279_id", 0);
logger("Start from item " . $id, LOGGER_DEBUG); Logger::log("Start from item " . $id, Logger::DEBUG);
$fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file', $fields = array_merge(Item::MIXED_CONTENT_FIELDLIST, ['network', 'author-id', 'owner-id', 'tag', 'file',
'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id', 'author-name', 'author-avatar', 'author-link', 'owner-name', 'owner-avatar', 'owner-link', 'id',
@ -170,7 +171,7 @@ class PostUpdate
$items = Item::select($fields, $condition, $params); $items = Item::select($fields, $condition, $params);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
logger('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage()); Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
return false; return false;
} }
@ -225,7 +226,7 @@ class PostUpdate
Config::set("system", "post_update_version_1279_id", $id); Config::set("system", "post_update_version_1279_id", $id);
logger("Processed rows: " . $rows . " - last processed item: " . $id, LOGGER_DEBUG); Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
if ($start_id == $id) { if ($start_id == $id) {
// Set all deprecated fields to "null" if they contain an empty string // Set all deprecated fields to "null" if they contain an empty string
@ -237,13 +238,13 @@ class PostUpdate
foreach ($nullfields as $field) { foreach ($nullfields as $field) {
$fields = [$field => null]; $fields = [$field => null];
$condition = [$field => '']; $condition = [$field => ''];
logger("Setting '" . $field . "' to null if empty.", LOGGER_DEBUG); Logger::log("Setting '" . $field . "' to null if empty.", Logger::DEBUG);
// Important: This has to be a "DBA::update", not a "Item::update" // Important: This has to be a "DBA::update", not a "Item::update"
DBA::update('item', $fields, $condition); DBA::update('item', $fields, $condition);
} }
Config::set("system", "post_update_version", 1279); Config::set("system", "post_update_version", 1279);
logger("Done", LOGGER_DEBUG); Logger::log("Done", Logger::DEBUG);
return true; return true;
} }
@ -306,7 +307,7 @@ class PostUpdate
$id = Config::get("system", "post_update_version_1281_id", 0); $id = Config::get("system", "post_update_version_1281_id", 0);
logger("Start from item " . $id, LOGGER_DEBUG); Logger::log("Start from item " . $id, Logger::DEBUG);
$fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id']; $fields = ['id', 'guid', 'uri', 'uri-id', 'parent-uri', 'parent-uri-id', 'thr-parent', 'thr-parent-id'];
@ -317,7 +318,7 @@ class PostUpdate
$items = DBA::select('item', $fields, $condition, $params); $items = DBA::select('item', $fields, $condition, $params);
if (DBA::errorNo() != 0) { if (DBA::errorNo() != 0) {
logger('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage()); Logger::log('Database error ' . DBA::errorNo() . ':' . DBA::errorMessage());
return false; return false;
} }
@ -358,17 +359,17 @@ class PostUpdate
Config::set("system", "post_update_version_1281_id", $id); Config::set("system", "post_update_version_1281_id", $id);
logger("Processed rows: " . $rows . " - last processed item: " . $id, LOGGER_DEBUG); Logger::log("Processed rows: " . $rows . " - last processed item: " . $id, Logger::DEBUG);
if ($start_id == $id) { if ($start_id == $id) {
logger("Updating item-uri in item-activity", LOGGER_DEBUG); Logger::log("Updating item-uri in item-activity", Logger::DEBUG);
DBA::e("UPDATE `item-activity` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-activity`.`uri` SET `item-activity`.`uri-id` = `item-uri`.`id` WHERE `item-activity`.`uri-id` IS NULL"); DBA::e("UPDATE `item-activity` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-activity`.`uri` SET `item-activity`.`uri-id` = `item-uri`.`id` WHERE `item-activity`.`uri-id` IS NULL");
logger("Updating item-uri in item-content", LOGGER_DEBUG); Logger::log("Updating item-uri in item-content", Logger::DEBUG);
DBA::e("UPDATE `item-content` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-content`.`uri` SET `item-content`.`uri-id` = `item-uri`.`id` WHERE `item-content`.`uri-id` IS NULL"); DBA::e("UPDATE `item-content` INNER JOIN `item-uri` ON `item-uri`.`uri` = `item-content`.`uri` SET `item-content`.`uri-id` = `item-uri`.`id` WHERE `item-content`.`uri-id` IS NULL");
Config::set("system", "post_update_version", 1281); Config::set("system", "post_update_version", 1281);
logger("Done", LOGGER_DEBUG); Logger::log("Done", Logger::DEBUG);
return true; return true;
} }

View file

@ -7,6 +7,7 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Protocol\ActivityPub; use Friendica\Protocol\ActivityPub;
use Friendica\Util\Network; use Friendica\Util\Network;
@ -192,7 +193,7 @@ class APContact extends BaseObject
// Update the gcontact table // Update the gcontact table
DBA::update('gcontact', $contact_fields, ['nurl' => normalise_link($url)]); DBA::update('gcontact', $contact_fields, ['nurl' => normalise_link($url)]);
logger('Updated profile for ' . $url, LOGGER_DEBUG); Logger::log('Updated profile for ' . $url, Logger::DEBUG);
return $apcontact; return $apcontact;
} }

View file

@ -9,6 +9,7 @@ use Friendica\Content\Pager;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -586,7 +587,7 @@ class Contact extends BaseObject
return; return;
} }
} elseif (!isset($contact['url'])) { } elseif (!isset($contact['url'])) {
logger('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), LOGGER_DEBUG); Logger::log('Empty contact: ' . json_encode($contact) . ' - ' . System::callstack(20), Logger::DEBUG);
} }
// Contact already archived or "self" contact? => nothing to do // Contact already archived or "self" contact? => nothing to do
@ -1027,7 +1028,7 @@ class Contact extends BaseObject
*/ */
public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false) public static function getIdForURL($url, $uid = 0, $no_update = false, $default = [], $in_loop = false)
{ {
logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG); Logger::log("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), Logger::DEBUG);
$contact_id = 0; $contact_id = 0;
@ -1618,7 +1619,7 @@ class Contact extends BaseObject
} }
if (($network != '') && ($ret['network'] != $network)) { if (($network != '') && ($ret['network'] != $network)) {
logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']); Logger::log('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
return $result; return $result;
} }
@ -1770,10 +1771,10 @@ class Contact extends BaseObject
} }
} elseif ($contact['network'] == Protocol::DIASPORA) { } elseif ($contact['network'] == Protocol::DIASPORA) {
$ret = Diaspora::sendShare($a->user, $contact); $ret = Diaspora::sendShare($a->user, $contact);
logger('share returns: ' . $ret); Logger::log('share returns: ' . $ret);
} elseif ($contact['network'] == Protocol::ACTIVITYPUB) { } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
$ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid); $ret = ActivityPub\Transmitter::sendActivity('Follow', $contact['url'], $uid);
logger('Follow returns: ' . $ret); Logger::log('Follow returns: ' . $ret);
} }
} }
@ -1855,7 +1856,7 @@ class Contact extends BaseObject
// send email notification to owner? // send email notification to owner?
} else { } else {
if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) { if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
logger('ignoring duplicated connection request from pending contact ' . $url); Logger::log('ignoring duplicated connection request from pending contact ' . $url);
return; return;
} }
// create contact record // create contact record
@ -1961,7 +1962,7 @@ class Contact extends BaseObject
$r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` "); $r = q("SELECT * FROM `contact` WHERE `bd` != '' AND `bd` > '0001-01-01' AND SUBSTRING(`bd`, 1, 4) != `bdyear` ");
if (DBA::isResult($r)) { if (DBA::isResult($r)) {
foreach ($r as $rr) { foreach ($r as $rr) {
logger('update_contact_birthday: ' . $rr['bd']); Logger::log('update_contact_birthday: ' . $rr['bd']);
$nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4); $nextbd = DateTimeFormat::utcNow('Y') . substr($rr['bd'], 4);

View file

@ -5,6 +5,7 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -82,13 +83,13 @@ class Conversation
unset($conversation['source']); unset($conversation['source']);
} }
if (!DBA::update('conversation', $conversation, ['item-uri' => $conversation['item-uri']], $old_conv)) { if (!DBA::update('conversation', $conversation, ['item-uri' => $conversation['item-uri']], $old_conv)) {
logger('Conversation: update for ' . $conversation['item-uri'] . ' from ' . $old_conv['protocol'] . ' to ' . $conversation['protocol'] . ' failed', Logger::log('Conversation: update for ' . $conversation['item-uri'] . ' from ' . $old_conv['protocol'] . ' to ' . $conversation['protocol'] . ' failed',
LOGGER_DEBUG); Logger::DEBUG);
} }
} else { } else {
if (!DBA::insert('conversation', $conversation, true)) { if (!DBA::insert('conversation', $conversation, true)) {
logger('Conversation: insert for ' . $conversation['item-uri'] . ' (protocol ' . $conversation['protocol'] . ') failed', Logger::log('Conversation: insert for ' . $conversation['item-uri'] . ' (protocol ' . $conversation['protocol'] . ') failed',
LOGGER_DEBUG); Logger::DEBUG);
} }
} }
} }

View file

@ -9,6 +9,7 @@ use Friendica\BaseObject;
use Friendica\Content\Text\BBCode; use Friendica\Content\Text\BBCode;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -224,7 +225,7 @@ class Event extends BaseObject
} }
DBA::delete('event', ['id' => $event_id]); DBA::delete('event', ['id' => $event_id]);
logger("Deleted event ".$event_id, LOGGER_DEBUG); Logger::log("Deleted event ".$event_id, Logger::DEBUG);
} }
/** /**

View file

@ -8,6 +8,7 @@ namespace Friendica\Model;
use Exception; use Exception;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
@ -256,7 +257,7 @@ class GContact
intval($cid) intval($cid)
); );
// logger("countCommonFriends: $uid $cid {$r[0]['total']}"); // Logger::log("countCommonFriends: $uid $cid {$r[0]['total']}");
if (DBA::isResult($r)) { if (DBA::isResult($r)) {
return $r[0]['total']; return $r[0]['total'];
} }
@ -588,7 +589,7 @@ class GContact
} }
if ($new_url != $url) { if ($new_url != $url) {
logger("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), LOGGER_DEBUG); Logger::log("Cleaned contact url ".$url." to ".$new_url." - Called by: ".System::callstack(), Logger::DEBUG);
} }
return $new_url; return $new_url;
@ -605,7 +606,7 @@ class GContact
if (($contact["network"] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) { if (($contact["network"] == Protocol::OSTATUS) && PortableContact::alternateOStatusUrl($contact["url"])) {
$data = Probe::uri($contact["url"]); $data = Probe::uri($contact["url"]);
if ($contact["network"] == Protocol::OSTATUS) { if ($contact["network"] == Protocol::OSTATUS) {
logger("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG); Logger::log("Fix primary url from ".$contact["url"]." to ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
$contact["url"] = $data["url"]; $contact["url"] = $data["url"];
$contact["addr"] = $data["addr"]; $contact["addr"] = $data["addr"];
$contact["alias"] = $data["alias"]; $contact["alias"] = $data["alias"];
@ -629,12 +630,12 @@ class GContact
$last_contact_str = ''; $last_contact_str = '';
if (empty($contact["network"])) { if (empty($contact["network"])) {
logger("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG); Logger::log("Empty network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
return false; return false;
} }
if (in_array($contact["network"], [Protocol::PHANTOM])) { if (in_array($contact["network"], [Protocol::PHANTOM])) {
logger("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG); Logger::log("Invalid network for contact url ".$contact["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
return false; return false;
} }
@ -702,7 +703,7 @@ class GContact
DBA::unlock(); DBA::unlock();
if ($doprobing) { if ($doprobing) {
logger("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], LOGGER_DEBUG); Logger::log("Last Contact: ". $last_contact_str." - Last Failure: ".$last_failure_str." - Checking: ".$contact["url"], Logger::DEBUG);
Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]); Worker::add(PRIORITY_LOW, 'GProbe', $contact["url"]);
} }
@ -807,19 +808,19 @@ class GContact
if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) { if ((($contact["generation"] > 0) && ($contact["generation"] <= $public_contact[0]["generation"])) || ($public_contact[0]["generation"] == 0)) {
foreach ($fields as $field => $data) { foreach ($fields as $field => $data) {
if ($contact[$field] != $public_contact[0][$field]) { if ($contact[$field] != $public_contact[0][$field]) {
logger("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", LOGGER_DEBUG); Logger::log("Difference for contact ".$contact["url"]." in field '".$field."'. New value: '".$contact[$field]."', old value '".$public_contact[0][$field]."'", Logger::DEBUG);
$update = true; $update = true;
} }
} }
if ($contact["generation"] < $public_contact[0]["generation"]) { if ($contact["generation"] < $public_contact[0]["generation"]) {
logger("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", LOGGER_DEBUG); Logger::log("Difference for contact ".$contact["url"]." in field 'generation'. new value: '".$contact["generation"]."', old value '".$public_contact[0]["generation"]."'", Logger::DEBUG);
$update = true; $update = true;
} }
} }
if ($update) { if ($update) {
logger("Update gcontact for ".$contact["url"], LOGGER_DEBUG); Logger::log("Update gcontact for ".$contact["url"], Logger::DEBUG);
$condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)', $condition = ['`nurl` = ? AND (`generation` = 0 OR `generation` >= ?)',
normalise_link($contact["url"]), $contact["generation"]]; normalise_link($contact["url"]), $contact["generation"]];
$contact["updated"] = DateTimeFormat::utc($contact["updated"]); $contact["updated"] = DateTimeFormat::utc($contact["updated"]);
@ -843,7 +844,7 @@ class GContact
// The quality of the gcontact table is mostly lower than the public contact // The quality of the gcontact table is mostly lower than the public contact
$public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => normalise_link($contact["url"]), 'uid' => 0]); $public_contact = DBA::selectFirst('contact', ['id'], ['nurl' => normalise_link($contact["url"]), 'uid' => 0]);
if (DBA::isResult($public_contact)) { if (DBA::isResult($public_contact)) {
logger("Update public contact ".$public_contact["id"], LOGGER_DEBUG); Logger::log("Update public contact ".$public_contact["id"], Logger::DEBUG);
Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]); Contact::updateAvatar($contact["photo"], 0, $public_contact["id"]);
@ -885,7 +886,7 @@ class GContact
$data = Probe::uri($url); $data = Probe::uri($url);
if (in_array($data["network"], [Protocol::PHANTOM])) { if (in_array($data["network"], [Protocol::PHANTOM])) {
logger("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), LOGGER_DEBUG); Logger::log("Invalid network for contact url ".$data["url"]." - Called by: ".System::callstack(), Logger::DEBUG);
return; return;
} }
@ -916,7 +917,7 @@ class GContact
); );
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
logger('Cannot find user with uid=' . $uid, LOGGER_INFO); Logger::log('Cannot find user with uid=' . $uid, Logger::INFO);
return false; return false;
} }
@ -953,7 +954,7 @@ class GContact
*/ */
public static function fetchGsUsers($server) public static function fetchGsUsers($server)
{ {
logger("Fetching users from GNU Social server ".$server, LOGGER_DEBUG); Logger::log("Fetching users from GNU Social server ".$server, Logger::DEBUG);
$url = $server."/main/statistics"; $url = $server."/main/statistics";

View file

@ -7,6 +7,7 @@ namespace Friendica\Model;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\Security; use Friendica\Util\Security;
@ -325,7 +326,7 @@ class Group extends BaseObject
'selected' => $gid == $group['id'] ? 'true' : '' 'selected' => $gid == $group['id'] ? 'true' : ''
]; ];
} }
logger('groups: ' . print_r($display_groups, true)); Logger::log('groups: ' . print_r($display_groups, true));
if ($label == '') { if ($label == '') {
$label = L10n::t('Default privacy group for new contacts'); $label = L10n::t('Default privacy group for new contacts');

View file

@ -11,6 +11,7 @@ use Friendica\Content\Text\BBCode;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Lock; use Friendica\Core\Lock;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
@ -960,7 +961,7 @@ class Item extends BaseObject
} elseif ($item['uid'] == $uid) { } elseif ($item['uid'] == $uid) {
self::deleteById($item['id'], PRIORITY_HIGH); self::deleteById($item['id'], PRIORITY_HIGH);
} else { } else {
logger('Wrong ownership. Not deleting item ' . $item['id']); Logger::log('Wrong ownership. Not deleting item ' . $item['id']);
} }
} }
DBA::close($items); DBA::close($items);
@ -983,12 +984,12 @@ class Item extends BaseObject
'icid', 'iaid', 'psid']; 'icid', 'iaid', 'psid'];
$item = self::selectFirst($fields, ['id' => $item_id]); $item = self::selectFirst($fields, ['id' => $item_id]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
logger('Item with ID ' . $item_id . " hasn't been found.", LOGGER_DEBUG); Logger::log('Item with ID ' . $item_id . " hasn't been found.", Logger::DEBUG);
return false; return false;
} }
if ($item['deleted']) { if ($item['deleted']) {
logger('Item with ID ' . $item_id . ' has already been deleted.', LOGGER_DEBUG); Logger::log('Item with ID ' . $item_id . ' has already been deleted.', Logger::DEBUG);
return false; return false;
} }
@ -1089,7 +1090,7 @@ class Item extends BaseObject
} }
} }
logger('Item with ID ' . $item_id . " has been deleted.", LOGGER_DEBUG); Logger::log('Item with ID ' . $item_id . " has been deleted.", Logger::DEBUG);
return true; return true;
} }
@ -1192,7 +1193,7 @@ class Item extends BaseObject
if (!empty($contact_id)) { if (!empty($contact_id)) {
return $contact_id; return $contact_id;
} }
logger('Missing contact-id. Called by: '.System::callstack(), LOGGER_DEBUG); Logger::log('Missing contact-id. Called by: '.System::callstack(), Logger::DEBUG);
/* /*
* First we are looking for a suitable contact that matches with the author of the post * First we are looking for a suitable contact that matches with the author of the post
* This is done only for comments * This is done only for comments
@ -1213,7 +1214,7 @@ class Item extends BaseObject
$contact_id = $self["id"]; $contact_id = $self["id"];
} }
} }
logger("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, LOGGER_DEBUG); Logger::log("Contact-id was missing for post ".$item['guid']." from user id ".$item['uid']." - now set to ".$contact_id, Logger::DEBUG);
return $contact_id; return $contact_id;
} }
@ -1298,7 +1299,7 @@ class Item extends BaseObject
$item['gravity'] = GRAVITY_COMMENT; $item['gravity'] = GRAVITY_COMMENT;
} else { } else {
$item['gravity'] = GRAVITY_UNKNOWN; // Should not happen $item['gravity'] = GRAVITY_UNKNOWN; // Should not happen
logger('Unknown gravity for verb: ' . $item['verb'], LOGGER_DEBUG); Logger::log('Unknown gravity for verb: ' . $item['verb'], Logger::DEBUG);
} }
$uid = intval($item['uid']); $uid = intval($item['uid']);
@ -1315,7 +1316,7 @@ class Item extends BaseObject
$expire_date = time() - ($expire_interval * 86400); $expire_date = time() - ($expire_interval * 86400);
$created_date = strtotime($item['created']); $created_date = strtotime($item['created']);
if ($created_date < $expire_date) { if ($created_date < $expire_date) {
logger('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), LOGGER_DEBUG); Logger::log('item-store: item created ('.date('c', $created_date).') before expiration time ('.date('c', $expire_date).'). ignored. ' . print_r($item,true), Logger::DEBUG);
return 0; return 0;
} }
} }
@ -1333,7 +1334,7 @@ class Item extends BaseObject
if (DBA::isResult($existing)) { if (DBA::isResult($existing)) {
// We only log the entries with a different user id than 0. Otherwise we would have too many false positives // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
if ($uid != 0) { if ($uid != 0) {
logger("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']); Logger::log("Item with uri ".$item['uri']." already existed for user ".$uid." with id ".$existing["id"]." target network ".$existing["network"]." - new network: ".$item['network']);
} }
return $existing["id"]; return $existing["id"];
@ -1384,7 +1385,7 @@ class Item extends BaseObject
// When there is no content then we don't post it // When there is no content then we don't post it
if ($item['body'].$item['title'] == '') { if ($item['body'].$item['title'] == '') {
logger('No body, no title.'); Logger::log('No body, no title.');
return 0; return 0;
} }
@ -1411,7 +1412,7 @@ class Item extends BaseObject
$item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default)); $item['author-id'] = defaults($item, 'author-id', Contact::getIdForURL($item["author-link"], 0, false, $default));
if (Contact::isBlocked($item["author-id"])) { if (Contact::isBlocked($item["author-id"])) {
logger('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored'); Logger::log('Contact '.$item["author-id"].' is blocked, item '.$item["uri"].' will not be stored');
return 0; return 0;
} }
@ -1421,22 +1422,22 @@ class Item extends BaseObject
$item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default)); $item['owner-id'] = defaults($item, 'owner-id', Contact::getIdForURL($item["owner-link"], 0, false, $default));
if (Contact::isBlocked($item["owner-id"])) { if (Contact::isBlocked($item["owner-id"])) {
logger('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored'); Logger::log('Contact '.$item["owner-id"].' is blocked, item '.$item["uri"].' will not be stored');
return 0; return 0;
} }
if ($item['network'] == Protocol::PHANTOM) { if ($item['network'] == Protocol::PHANTOM) {
logger('Missing network. Called by: '.System::callstack(), LOGGER_DEBUG); Logger::log('Missing network. Called by: '.System::callstack(), Logger::DEBUG);
$item['network'] = Protocol::DFRN; $item['network'] = Protocol::DFRN;
logger("Set network to " . $item["network"] . " for " . $item["uri"], LOGGER_DEBUG); Logger::log("Set network to " . $item["network"] . " for " . $item["uri"], Logger::DEBUG);
} }
// Checking if there is already an item with the same guid // Checking if there is already an item with the same guid
logger('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], LOGGER_DEBUG); Logger::log('Checking for an item for user '.$item['uid'].' on network '.$item['network'].' with the guid '.$item['guid'], Logger::DEBUG);
$condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']]; $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
if (self::exists($condition)) { if (self::exists($condition)) {
logger('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], LOGGER_DEBUG); Logger::log('found item with guid '.$item['guid'].' for user '.$item['uid'].' on network '.$item['network'], Logger::DEBUG);
return 0; return 0;
} }
@ -1517,15 +1518,15 @@ class Item extends BaseObject
} }
// If its a post from myself then tag the thread as "mention" // If its a post from myself then tag the thread as "mention"
logger("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], LOGGER_DEBUG); Logger::log("Checking if parent ".$parent_id." has to be tagged as mention for user ".$item['uid'], Logger::DEBUG);
$user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]); $user = DBA::selectFirst('user', ['nickname'], ['uid' => $item['uid']]);
if (DBA::isResult($user)) { if (DBA::isResult($user)) {
$self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']); $self = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
$self_id = Contact::getIdForURL($self, 0, true); $self_id = Contact::getIdForURL($self, 0, true);
logger("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], LOGGER_DEBUG); Logger::log("'myself' is ".$self_id." for parent ".$parent_id." checking against ".$item['author-id']." and ".$item['owner-id'], Logger::DEBUG);
if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) { if (($item['author-id'] == $self_id) || ($item['owner-id'] == $self_id)) {
DBA::update('thread', ['mention' => true], ['iid' => $parent_id]); DBA::update('thread', ['mention' => true], ['iid' => $parent_id]);
logger("tagged thread ".$parent_id." as mention for user ".$self, LOGGER_DEBUG); Logger::log("tagged thread ".$parent_id." as mention for user ".$self, Logger::DEBUG);
} }
} }
} else { } else {
@ -1534,12 +1535,12 @@ class Item extends BaseObject
* we don't have or can't see the original post. * we don't have or can't see the original post.
*/ */
if ($force_parent) { if ($force_parent) {
logger('$force_parent=true, reply converted to top-level post.'); Logger::log('$force_parent=true, reply converted to top-level post.');
$parent_id = 0; $parent_id = 0;
$item['parent-uri'] = $item['uri']; $item['parent-uri'] = $item['uri'];
$item['gravity'] = GRAVITY_PARENT; $item['gravity'] = GRAVITY_PARENT;
} else { } else {
logger('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item'); Logger::log('item parent '.$item['parent-uri'].' for '.$item['uid'].' was not found - ignoring item');
return 0; return 0;
} }
@ -1553,7 +1554,7 @@ class Item extends BaseObject
$condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?", $condition = ["`uri` = ? AND `network` IN (?, ?) AND `uid` = ?",
$item['uri'], $item['network'], Protocol::DFRN, $item['uid']]; $item['uri'], $item['network'], Protocol::DFRN, $item['uid']];
if (self::exists($condition)) { if (self::exists($condition)) {
logger('duplicated item with the same uri found. '.print_r($item,true)); Logger::log('duplicated item with the same uri found. '.print_r($item,true));
return 0; return 0;
} }
@ -1561,7 +1562,7 @@ class Item extends BaseObject
if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) { if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
$condition = ['guid' => $item['guid'], 'uid' => $item['uid']]; $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
if (self::exists($condition)) { if (self::exists($condition)) {
logger('duplicated item with the same guid found. '.print_r($item,true)); Logger::log('duplicated item with the same guid found. '.print_r($item,true));
return 0; return 0;
} }
} else { } else {
@ -1569,7 +1570,7 @@ class Item extends BaseObject
$condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?", $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
$item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']]; $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
if (self::exists($condition)) { if (self::exists($condition)) {
logger('duplicated item with the same body found. '.print_r($item,true)); Logger::log('duplicated item with the same body found. '.print_r($item,true));
return 0; return 0;
} }
} }
@ -1616,7 +1617,7 @@ class Item extends BaseObject
unset($item['api_source']); unset($item['api_source']);
if (x($item, 'cancel')) { if (x($item, 'cancel')) {
logger('post cancelled by addon.'); Logger::log('post cancelled by addon.');
return 0; return 0;
} }
@ -1627,12 +1628,12 @@ class Item extends BaseObject
*/ */
if ($item["uid"] == 0) { if ($item["uid"] == 0) {
if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) { if (self::exists(['uri' => trim($item['uri']), 'uid' => 0])) {
logger('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], LOGGER_DEBUG); Logger::log('Global item already stored. URI: '.$item['uri'].' on network '.$item['network'], Logger::DEBUG);
return 0; return 0;
} }
} }
logger('' . print_r($item,true), LOGGER_DATA); Logger::log('' . print_r($item,true), Logger::DATA);
if (array_key_exists('tag', $item)) { if (array_key_exists('tag', $item)) {
$tags = $item['tag']; $tags = $item['tag'];
@ -1700,14 +1701,14 @@ class Item extends BaseObject
$item = array_merge($item, $delivery_data); $item = array_merge($item, $delivery_data);
file_put_contents($spool, json_encode($item)); file_put_contents($spool, json_encode($item));
logger("Item wasn't stored - Item was spooled into file ".$file, LOGGER_DEBUG); Logger::log("Item wasn't stored - Item was spooled into file ".$file, Logger::DEBUG);
} }
return 0; return 0;
} }
if ($current_post == 0) { if ($current_post == 0) {
// This is one of these error messages that never should occur. // This is one of these error messages that never should occur.
logger("couldn't find created item - we better quit now."); Logger::log("couldn't find created item - we better quit now.");
DBA::rollback(); DBA::rollback();
return 0; return 0;
} }
@ -1718,7 +1719,7 @@ class Item extends BaseObject
if ($entries > 1) { if ($entries > 1) {
// There are duplicates. We delete our just created entry. // There are duplicates. We delete our just created entry.
logger('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']); Logger::log('Duplicated post occurred. uri = ' . $item['uri'] . ' uid = ' . $item['uid']);
// Yes, we could do a rollback here - but we are having many users with MyISAM. // Yes, we could do a rollback here - but we are having many users with MyISAM.
DBA::delete('item', ['id' => $current_post]); DBA::delete('item', ['id' => $current_post]);
@ -1726,12 +1727,12 @@ class Item extends BaseObject
return 0; return 0;
} elseif ($entries == 0) { } elseif ($entries == 0) {
// This really should never happen since we quit earlier if there were problems. // This really should never happen since we quit earlier if there were problems.
logger("Something is terribly wrong. We haven't found our created entry."); Logger::log("Something is terribly wrong. We haven't found our created entry.");
DBA::rollback(); DBA::rollback();
return 0; return 0;
} }
logger('created item '.$current_post); Logger::log('created item '.$current_post);
self::updateContact($item); self::updateContact($item);
if (!$parent_id || ($item['parent-uri'] === $item['uri'])) { if (!$parent_id || ($item['parent-uri'] === $item['uri'])) {
@ -1759,7 +1760,7 @@ class Item extends BaseObject
*/ */
if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) { if (base64_encode(base64_decode(base64_decode($dsprsig->signature))) == base64_decode($dsprsig->signature)) {
$dsprsig->signature = base64_decode($dsprsig->signature); $dsprsig->signature = base64_decode($dsprsig->signature);
logger("Repaired double encoded signature from handle ".$dsprsig->signer, LOGGER_DEBUG); Logger::log("Repaired double encoded signature from handle ".$dsprsig->signer, Logger::DEBUG);
} }
if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) { if (!empty($dsprsig->signed_text) && empty($dsprsig->signature) && empty($dsprsig->signer)) {
@ -1790,7 +1791,7 @@ class Item extends BaseObject
Addon::callHooks('post_remote_end', $posted_item); Addon::callHooks('post_remote_end', $posted_item);
} }
} else { } else {
logger('new item not found in DB, id ' . $current_post); Logger::log('new item not found in DB, id ' . $current_post);
} }
} }
@ -1895,20 +1896,20 @@ class Item extends BaseObject
// To avoid timing problems, we are using locks. // To avoid timing problems, we are using locks.
$locked = Lock::acquire('item_insert_activity'); $locked = Lock::acquire('item_insert_activity');
if (!$locked) { if (!$locked) {
logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway."); Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
} }
// Do we already have this content? // Do we already have this content?
$item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]); $item_activity = DBA::selectFirst('item-activity', ['id'], ['uri-id' => $item['uri-id']]);
if (DBA::isResult($item_activity)) { if (DBA::isResult($item_activity)) {
$item['iaid'] = $item_activity['id']; $item['iaid'] = $item_activity['id'];
logger('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')'); Logger::log('Fetched activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
} elseif (DBA::insert('item-activity', $fields)) { } elseif (DBA::insert('item-activity', $fields)) {
$item['iaid'] = DBA::lastInsertId(); $item['iaid'] = DBA::lastInsertId();
logger('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')'); Logger::log('Inserted activity for URI ' . $item['uri'] . ' (' . $item['iaid'] . ')');
} else { } else {
// This shouldn't happen. // This shouldn't happen.
logger('Could not insert activity for URI ' . $item['uri'] . ' - should not happen'); Logger::log('Could not insert activity for URI ' . $item['uri'] . ' - should not happen');
Lock::release('item_insert_activity'); Lock::release('item_insert_activity');
return false; return false;
} }
@ -1937,20 +1938,20 @@ class Item extends BaseObject
// To avoid timing problems, we are using locks. // To avoid timing problems, we are using locks.
$locked = Lock::acquire('item_insert_content'); $locked = Lock::acquire('item_insert_content');
if (!$locked) { if (!$locked) {
logger("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway."); Logger::log("Couldn't acquire lock for URI " . $item['uri'] . " - proceeding anyway.");
} }
// Do we already have this content? // Do we already have this content?
$item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]); $item_content = DBA::selectFirst('item-content', ['id'], ['uri-id' => $item['uri-id']]);
if (DBA::isResult($item_content)) { if (DBA::isResult($item_content)) {
$item['icid'] = $item_content['id']; $item['icid'] = $item_content['id'];
logger('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')'); Logger::log('Fetched content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
} elseif (DBA::insert('item-content', $fields)) { } elseif (DBA::insert('item-content', $fields)) {
$item['icid'] = DBA::lastInsertId(); $item['icid'] = DBA::lastInsertId();
logger('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')'); Logger::log('Inserted content for URI ' . $item['uri'] . ' (' . $item['icid'] . ')');
} else { } else {
// This shouldn't happen. // This shouldn't happen.
logger('Could not insert content for URI ' . $item['uri'] . ' - should not happen'); Logger::log('Could not insert content for URI ' . $item['uri'] . ' - should not happen');
} }
if ($locked) { if ($locked) {
Lock::release('item_insert_content'); Lock::release('item_insert_content');
@ -1976,7 +1977,7 @@ class Item extends BaseObject
$fields = ['activity' => $activity_index]; $fields = ['activity' => $activity_index];
logger('Update activity for ' . json_encode($condition)); Logger::log('Update activity for ' . json_encode($condition));
DBA::update('item-activity', $fields, $condition, true); DBA::update('item-activity', $fields, $condition, true);
@ -2005,7 +2006,7 @@ class Item extends BaseObject
$fields = $condition; $fields = $condition;
} }
logger('Update content for ' . json_encode($condition)); Logger::log('Update content for ' . json_encode($condition));
DBA::update('item-content', $fields, $condition, true); DBA::update('item-content', $fields, $condition, true);
} }
@ -2144,9 +2145,9 @@ class Item extends BaseObject
$distributed = self::insert($item, false, $notify, true); $distributed = self::insert($item, false, $notify, true);
if (!$distributed) { if (!$distributed) {
logger("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", LOGGER_DEBUG); Logger::log("Distributed public item " . $itemid . " for user " . $uid . " wasn't stored", Logger::DEBUG);
} else { } else {
logger("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, LOGGER_DEBUG); Logger::log("Distributed public item " . $itemid . " for user " . $uid . " with id " . $distributed, Logger::DEBUG);
} }
} }
@ -2209,7 +2210,7 @@ class Item extends BaseObject
$public_shadow = self::insert($item, false, false, true); $public_shadow = self::insert($item, false, false, true);
logger("Stored public shadow for thread ".$itemid." under id ".$public_shadow, LOGGER_DEBUG); Logger::log("Stored public shadow for thread ".$itemid." under id ".$public_shadow, Logger::DEBUG);
} }
} }
@ -2266,7 +2267,7 @@ class Item extends BaseObject
$public_shadow = self::insert($item, false, false, true); $public_shadow = self::insert($item, false, false, true);
logger("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, LOGGER_DEBUG); Logger::log("Stored public shadow for comment ".$item['uri']." under id ".$public_shadow, Logger::DEBUG);
// If this was a comment to a Diaspora post we don't get our comment back. // If this was a comment to a Diaspora post we don't get our comment back.
// This means that we have to distribute the comment by ourselves. // This means that we have to distribute the comment by ourselves.
@ -2543,7 +2544,7 @@ class Item extends BaseObject
foreach ($matches as $mtch) { foreach ($matches as $mtch) {
if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) { if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
$mention = true; $mention = true;
logger('mention found: ' . $mtch[2]); Logger::log('mention found: ' . $mtch[2]);
} }
} }
} }
@ -2553,7 +2554,7 @@ class Item extends BaseObject
!$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) { !$item['wall'] && !$item['origin'] && ($item['id'] == $item['parent'])) {
// mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment) // mmh.. no mention.. community page or private group... no wall.. no origin.. top-post (not a comment)
// delete it! // delete it!
logger("no-mention top-level post to community or private group. delete."); Logger::log("no-mention top-level post to community or private group. delete.");
DBA::delete('item', ['id' => $item_id]); DBA::delete('item', ['id' => $item_id]);
return true; return true;
} }
@ -2612,29 +2613,29 @@ class Item extends BaseObject
// Prevent the forwarding of posts that are forwarded // Prevent the forwarding of posts that are forwarded
if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) { if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
logger('Already forwarded', LOGGER_DEBUG); Logger::log('Already forwarded', Logger::DEBUG);
return false; return false;
} }
// Prevent to forward already forwarded posts // Prevent to forward already forwarded posts
if ($datarray["app"] == $a->getHostName()) { if ($datarray["app"] == $a->getHostName()) {
logger('Already forwarded (second test)', LOGGER_DEBUG); Logger::log('Already forwarded (second test)', Logger::DEBUG);
return false; return false;
} }
// Only forward posts // Only forward posts
if ($datarray["verb"] != ACTIVITY_POST) { if ($datarray["verb"] != ACTIVITY_POST) {
logger('No post', LOGGER_DEBUG); Logger::log('No post', Logger::DEBUG);
return false; return false;
} }
if (($contact['network'] != Protocol::FEED) && $datarray['private']) { if (($contact['network'] != Protocol::FEED) && $datarray['private']) {
logger('Not public', LOGGER_DEBUG); Logger::log('Not public', Logger::DEBUG);
return false; return false;
} }
$datarray2 = $datarray; $datarray2 = $datarray;
logger('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), LOGGER_DEBUG); Logger::log('remote-self start - Contact '.$contact['url'].' - '.$contact['remote_self'].' Item '.print_r($datarray, true), Logger::DEBUG);
if ($contact['remote_self'] == 2) { if ($contact['remote_self'] == 2) {
$self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'], $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
['uid' => $contact['uid'], 'self' => true]); ['uid' => $contact['uid'], 'self' => true]);
@ -2674,7 +2675,7 @@ class Item extends BaseObject
if ($contact['network'] != Protocol::FEED) { if ($contact['network'] != Protocol::FEED) {
// Store the original post // Store the original post
$result = self::insert($datarray2, false, false); $result = self::insert($datarray2, false, false);
logger('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), LOGGER_DEBUG); Logger::log('remote-self post original item - Contact '.$contact['url'].' return '.$result.' Item '.print_r($datarray2, true), Logger::DEBUG);
} else { } else {
$datarray["app"] = "Feed"; $datarray["app"] = "Feed";
$result = true; $result = true;
@ -2704,7 +2705,7 @@ class Item extends BaseObject
return $s; return $s;
} }
logger('check for photos', LOGGER_DEBUG); Logger::log('check for photos', Logger::DEBUG);
$site = substr(System::baseUrl(), strpos(System::baseUrl(), '://')); $site = substr(System::baseUrl(), strpos(System::baseUrl(), '://'));
$orig_body = $s; $orig_body = $s;
@ -2718,7 +2719,7 @@ class Item extends BaseObject
$img_st_close++; // make it point to AFTER the closing bracket $img_st_close++; // make it point to AFTER the closing bracket
$image = substr($orig_body, $img_start + $img_st_close, $img_len); $image = substr($orig_body, $img_start + $img_st_close, $img_len);
logger('found photo ' . $image, LOGGER_DEBUG); Logger::log('found photo ' . $image, Logger::DEBUG);
if (stristr($image, $site . '/photo/')) { if (stristr($image, $site . '/photo/')) {
// Only embed locally hosted photos // Only embed locally hosted photos
@ -2760,7 +2761,7 @@ class Item extends BaseObject
// If a custom width and height were specified, apply before embedding // If a custom width and height were specified, apply before embedding
if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) { if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
logger('scaling photo', LOGGER_DEBUG); Logger::log('scaling photo', Logger::DEBUG);
$width = intval($match[1]); $width = intval($match[1]);
$height = intval($match[2]); $height = intval($match[2]);
@ -2773,9 +2774,9 @@ class Item extends BaseObject
} }
} }
logger('replacing photo', LOGGER_DEBUG); Logger::log('replacing photo', Logger::DEBUG);
$image = 'data:' . $type . ';base64,' . base64_encode($data); $image = 'data:' . $type . ';base64,' . base64_encode($data);
logger('replaced: ' . $image, LOGGER_DATA); Logger::log('replaced: ' . $image, Logger::DATA);
} }
} }
} }
@ -2938,7 +2939,7 @@ class Item extends BaseObject
++$expired; ++$expired;
} }
DBA::close($items); DBA::close($items);
logger('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos"); Logger::log('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
} }
public static function firstPostDate($uid, $wall = false) public static function firstPostDate($uid, $wall = false)
@ -2994,18 +2995,18 @@ class Item extends BaseObject
$activity = ACTIVITY_ATTENDMAYBE; $activity = ACTIVITY_ATTENDMAYBE;
break; break;
default: default:
logger('like: unknown verb ' . $verb . ' for item ' . $item_id); Logger::log('like: unknown verb ' . $verb . ' for item ' . $item_id);
return false; return false;
} }
// Enable activity toggling instead of on/off // Enable activity toggling instead of on/off
$event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE; $event_verb_flag = $activity === ACTIVITY_ATTEND || $activity === ACTIVITY_ATTENDNO || $activity === ACTIVITY_ATTENDMAYBE;
logger('like: verb ' . $verb . ' item ' . $item_id); Logger::log('like: verb ' . $verb . ' item ' . $item_id);
$item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]); $item = self::selectFirst(self::ITEM_FIELDLIST, ['`id` = ? OR `uri` = ?', $item_id, $item_id]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
logger('like: unknown item ' . $item_id); Logger::log('like: unknown item ' . $item_id);
return false; return false;
} }
@ -3017,14 +3018,14 @@ class Item extends BaseObject
} }
if (!Security::canWriteToUserWall($uid)) { if (!Security::canWriteToUserWall($uid)) {
logger('like: unable to write on wall ' . $uid); Logger::log('like: unable to write on wall ' . $uid);
return false; return false;
} }
// Retrieves the local post owner // Retrieves the local post owner
$owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]); $owner_self_contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'self' => true]);
if (!DBA::isResult($owner_self_contact)) { if (!DBA::isResult($owner_self_contact)) {
logger('like: unknown owner ' . $uid); Logger::log('like: unknown owner ' . $uid);
return false; return false;
} }
@ -3033,7 +3034,7 @@ class Item extends BaseObject
$author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]); $author_contact = DBA::selectFirst('contact', ['url'], ['id' => $author_id]);
if (!DBA::isResult($author_contact)) { if (!DBA::isResult($author_contact)) {
logger('like: unknown author ' . $author_id); Logger::log('like: unknown author ' . $author_id);
return false; return false;
} }
@ -3045,7 +3046,7 @@ class Item extends BaseObject
$item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true); $item_contact_id = Contact::getIdForURL($author_contact['url'], $uid, true);
$item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]); $item_contact = DBA::selectFirst('contact', [], ['id' => $item_contact_id]);
if (!DBA::isResult($item_contact)) { if (!DBA::isResult($item_contact)) {
logger('like: unknown item contact ' . $item_contact_id); Logger::log('like: unknown item contact ' . $item_contact_id);
return false; return false;
} }
} }
@ -3147,7 +3148,7 @@ class Item extends BaseObject
if (!$onlyshadow) { if (!$onlyshadow) {
$result = DBA::insert('thread', $item); $result = DBA::insert('thread', $item);
logger("Add thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG); Logger::log("Add thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
} }
} }
@ -3179,26 +3180,26 @@ class Item extends BaseObject
$result = DBA::update('thread', $fields, ['iid' => $itemid]); $result = DBA::update('thread', $fields, ['iid' => $itemid]);
logger("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, LOGGER_DEBUG); Logger::log("Update thread for item ".$itemid." - guid ".$item["guid"]." - ".(int)$result, Logger::DEBUG);
} }
private static function deleteThread($itemid, $itemuri = "") private static function deleteThread($itemid, $itemuri = "")
{ {
$item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]); $item = DBA::selectFirst('thread', ['uid'], ['iid' => $itemid]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
logger('No thread found for id '.$itemid, LOGGER_DEBUG); Logger::log('No thread found for id '.$itemid, Logger::DEBUG);
return; return;
} }
$result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]); $result = DBA::delete('thread', ['iid' => $itemid], ['cascade' => false]);
logger("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), LOGGER_DEBUG); Logger::log("deleteThread: Deleted thread for item ".$itemid." - ".print_r($result, true), Logger::DEBUG);
if ($itemuri != "") { if ($itemuri != "") {
$condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]]; $condition = ["`uri` = ? AND NOT `deleted` AND NOT (`uid` IN (?, 0))", $itemuri, $item["uid"]];
if (!self::exists($condition)) { if (!self::exists($condition)) {
DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]); DBA::delete('item', ['uri' => $itemuri, 'uid' => 0]);
logger("deleteThread: Deleted shadow for item ".$itemuri, LOGGER_DEBUG); Logger::log("deleteThread: Deleted shadow for item ".$itemuri, Logger::DEBUG);
} }
} }
} }

View file

@ -6,6 +6,7 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -87,7 +88,7 @@ class Mail
} }
if (!$convid) { if (!$convid) {
logger('send message: conversation not found.'); Logger::log('send message: conversation not found.');
return -4; return -4;
} }
@ -200,7 +201,7 @@ class Mail
} }
if (!$convid) { if (!$convid) {
logger('send message: conversation not found.'); Logger::log('send message: conversation not found.');
return -4; return -4;
} }

View file

@ -12,6 +12,7 @@ use Friendica\Core\Addon;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
@ -106,7 +107,7 @@ class Profile
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]); $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nickname, 'account_removed' => false]);
if (!DBA::isResult($user) && empty($profiledata)) { if (!DBA::isResult($user) && empty($profiledata)) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG); Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
notice(L10n::t('Requested account is not available.') . EOL); notice(L10n::t('Requested account is not available.') . EOL);
$a->error = 404; $a->error = 404;
return; return;
@ -124,7 +125,7 @@ class Profile
$pdata = self::getByNickname($nickname, $user['uid'], $profile); $pdata = self::getByNickname($nickname, $user['uid'], $profile);
if (empty($pdata) && empty($profiledata)) { if (empty($pdata) && empty($profiledata)) {
logger('profile error: ' . $a->query_string, LOGGER_DEBUG); Logger::log('profile error: ' . $a->query_string, Logger::DEBUG);
notice(L10n::t('Requested profile is not available.') . EOL); notice(L10n::t('Requested profile is not available.') . EOL);
$a->error = 404; $a->error = 404;
return; return;
@ -1020,27 +1021,27 @@ class Profile
// Try to find the public contact entry of the visitor. // Try to find the public contact entry of the visitor.
$cid = Contact::getIdForURL($my_url); $cid = Contact::getIdForURL($my_url);
if (!$cid) { if (!$cid) {
logger('No contact record found for ' . $my_url, LOGGER_DEBUG); Logger::log('No contact record found for ' . $my_url, Logger::DEBUG);
return; return;
} }
$contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]); $contact = DBA::selectFirst('contact',['id', 'url'], ['id' => $cid]);
if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) { if (DBA::isResult($contact) && remote_user() && remote_user() == $contact['id']) {
logger('The visitor ' . $my_url . ' is already authenticated', LOGGER_DEBUG); Logger::log('The visitor ' . $my_url . ' is already authenticated', Logger::DEBUG);
return; return;
} }
// Avoid endless loops // Avoid endless loops
$cachekey = 'zrlInit:' . $my_url; $cachekey = 'zrlInit:' . $my_url;
if (Cache::get($cachekey)) { if (Cache::get($cachekey)) {
logger('URL ' . $my_url . ' already tried to authenticate.', LOGGER_DEBUG); Logger::log('URL ' . $my_url . ' already tried to authenticate.', Logger::DEBUG);
return; return;
} else { } else {
Cache::set($cachekey, true, Cache::MINUTE); Cache::set($cachekey, true, Cache::MINUTE);
} }
logger('Not authenticated. Invoking reverse magic-auth for ' . $my_url, LOGGER_DEBUG); Logger::log('Not authenticated. Invoking reverse magic-auth for ' . $my_url, Logger::DEBUG);
Worker::add(PRIORITY_LOW, 'GProbe', $my_url); Worker::add(PRIORITY_LOW, 'GProbe', $my_url);
@ -1061,7 +1062,7 @@ class Profile
// We have to check if the remote server does understand /magic without invoking something // We have to check if the remote server does understand /magic without invoking something
$serverret = Network::curl($basepath . '/magic'); $serverret = Network::curl($basepath . '/magic');
if ($serverret->isSuccess()) { if ($serverret->isSuccess()) {
logger('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, LOGGER_DEBUG); Logger::log('Doing magic auth for visitor ' . $my_url . ' to ' . $magic_path, Logger::DEBUG);
System::externalRedirect($magic_path); System::externalRedirect($magic_path);
} }
} }
@ -1092,7 +1093,7 @@ class Profile
// Try to find the public contact entry of the visitor. // Try to find the public contact entry of the visitor.
$cid = Contact::getIdForURL($visitor_handle); $cid = Contact::getIdForURL($visitor_handle);
if(!$cid) { if(!$cid) {
logger('owt: unable to finger ' . $visitor_handle, LOGGER_DEBUG); Logger::log('owt: unable to finger ' . $visitor_handle, Logger::DEBUG);
return; return;
} }
@ -1121,7 +1122,7 @@ class Profile
info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name'])); info(L10n::t('OpenWebAuth: %1$s welcomes %2$s', $a->getHostName(), $visitor['name']));
logger('OpenWebAuth: auth success from ' . $visitor['addr'], LOGGER_DEBUG); Logger::log('OpenWebAuth: auth success from ' . $visitor['addr'], Logger::DEBUG);
} }
public static function zrl($s, $force = false) public static function zrl($s, $force = false)

View file

@ -4,6 +4,7 @@
*/ */
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -45,7 +46,7 @@ class PushSubscriber
$priority = $default_priority; $priority = $default_priority;
} }
logger('Publish feed to ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' with priority ' . $priority, LOGGER_DEBUG); Logger::log('Publish feed to ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' with priority ' . $priority, Logger::DEBUG);
Worker::add($priority, 'PubSubPublish', (int)$subscriber['id']); Worker::add($priority, 'PubSubPublish', (int)$subscriber['id']);
} }
@ -88,9 +89,9 @@ class PushSubscriber
'secret' => $hub_secret]; 'secret' => $hub_secret];
DBA::insert('push_subscriber', $fields); DBA::insert('push_subscriber', $fields);
logger("Successfully subscribed [$hub_callback] for $nick"); Logger::log("Successfully subscribed [$hub_callback] for $nick");
} else { } else {
logger("Successfully unsubscribed [$hub_callback] for $nick"); Logger::log("Successfully unsubscribed [$hub_callback] for $nick");
// we do nothing here, since the row was already deleted // we do nothing here, since the row was already deleted
} }
} }
@ -115,10 +116,10 @@ class PushSubscriber
if ($days > 60) { if ($days > 60) {
DBA::update('push_subscriber', ['push' => -1, 'next_try' => DBA::NULL_DATETIME], ['id' => $id]); DBA::update('push_subscriber', ['push' => -1, 'next_try' => DBA::NULL_DATETIME], ['id' => $id]);
logger('Delivery error: Subscription ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' is marked as ended.', LOGGER_DEBUG); Logger::log('Delivery error: Subscription ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' is marked as ended.', Logger::DEBUG);
} else { } else {
DBA::update('push_subscriber', ['push' => 0, 'next_try' => DBA::NULL_DATETIME], ['id' => $id]); DBA::update('push_subscriber', ['push' => 0, 'next_try' => DBA::NULL_DATETIME], ['id' => $id]);
logger('Delivery error: Giving up ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' for now.', LOGGER_DEBUG); Logger::log('Delivery error: Giving up ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' for now.', Logger::DEBUG);
} }
} else { } else {
// Calculate the delay until the next trial // Calculate the delay until the next trial
@ -128,7 +129,7 @@ class PushSubscriber
$retrial = $retrial + 1; $retrial = $retrial + 1;
DBA::update('push_subscriber', ['push' => $retrial, 'next_try' => $next], ['id' => $id]); DBA::update('push_subscriber', ['push' => $retrial, 'next_try' => $next], ['id' => $id]);
logger('Delivery error: Next try (' . $retrial . ') ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' at ' . $next, LOGGER_DEBUG); Logger::log('Delivery error: Next try (' . $retrial . ') ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' at ' . $next, Logger::DEBUG);
} }
} }
@ -148,6 +149,6 @@ class PushSubscriber
// set last_update to the 'created' date of the last item, and reset push=0 // set last_update to the 'created' date of the last item, and reset push=0
$fields = ['push' => 0, 'next_try' => DBA::NULL_DATETIME, 'last_update' => $last_update]; $fields = ['push' => 0, 'next_try' => DBA::NULL_DATETIME, 'last_update' => $last_update];
DBA::update('push_subscriber', $fields, ['id' => $id]); DBA::update('push_subscriber', $fields, ['id' => $id]);
logger('Subscriber ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' is marked as vital', LOGGER_DEBUG); Logger::log('Subscriber ' . $subscriber['callback_url'] . ' for ' . $subscriber['nickname'] . ' is marked as vital', Logger::DEBUG);
} }
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Model; namespace Friendica\Model;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
@ -17,7 +18,7 @@ class Queue
*/ */
public static function updateTime($id) public static function updateTime($id)
{ {
logger('queue: requeue item ' . $id); Logger::log('queue: requeue item ' . $id);
$queue = DBA::selectFirst('queue', ['retrial'], ['id' => $id]); $queue = DBA::selectFirst('queue', ['retrial'], ['id' => $id]);
if (!DBA::isResult($queue)) { if (!DBA::isResult($queue)) {
return; return;
@ -41,7 +42,7 @@ class Queue
*/ */
public static function removeItem($id) public static function removeItem($id)
{ {
logger('queue: remove queue item ' . $id); Logger::log('queue: remove queue item ' . $id);
DBA::delete('queue', ['id' => $id]); DBA::delete('queue', ['id' => $id]);
} }
@ -100,10 +101,10 @@ class Queue
if (DBA::isResult($r)) { if (DBA::isResult($r)) {
if ($batch && ($r[0]['total'] > $batch_queue)) { if ($batch && ($r[0]['total'] > $batch_queue)) {
logger('too many queued items for batch server ' . $cid . ' - discarding message'); Logger::log('too many queued items for batch server ' . $cid . ' - discarding message');
return; return;
} elseif ((! $batch) && ($r[0]['total'] > $max_queue)) { } elseif ((! $batch) && ($r[0]['total'] > $max_queue)) {
logger('too many queued items for contact ' . $cid . ' - discarding message'); Logger::log('too many queued items for contact ' . $cid . ' - discarding message');
return; return;
} }
} }
@ -117,6 +118,6 @@ class Queue
'content' => $msg, 'content' => $msg,
'batch' =>($batch) ? 1 : 0 'batch' =>($batch) ? 1 : 0
]); ]);
logger('Added item ' . $guid . ' for ' . $cid); Logger::log('Added item ' . $guid . ' for ' . $cid);
} }
} }

View file

@ -10,6 +10,7 @@ use Exception;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
@ -470,7 +471,7 @@ class User
$username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48)))); $username_max_length = max(1, min(64, intval(Config::get('system', 'username_max_length', 48))));
if ($username_min_length > $username_max_length) { if ($username_min_length > $username_max_length) {
logger(L10n::t('system.username_min_length (%s) and system.username_max_length (%s) are excluding each other, swapping values.', $username_min_length, $username_max_length), LOGGER_WARNING); Logger::log(L10n::t('system.username_min_length (%s) and system.username_max_length (%s) are excluding each other, swapping values.', $username_min_length, $username_max_length), Logger::WARNING);
$tmp = $username_min_length; $tmp = $username_min_length;
$username_min_length = $username_max_length; $username_min_length = $username_max_length;
$username_max_length = $tmp; $username_max_length = $tmp;
@ -785,7 +786,7 @@ class User
$a = get_app(); $a = get_app();
logger('Removing user: ' . $uid); Logger::log('Removing user: ' . $uid);
$user = DBA::selectFirst('user', [], ['uid' => $uid]); $user = DBA::selectFirst('user', [], ['uid' => $uid]);

View file

@ -36,7 +36,7 @@ class Inbox extends BaseModule
$tempfile = tempnam(get_temppath(), $filename); $tempfile = tempnam(get_temppath(), $filename);
file_put_contents($tempfile, json_encode(['argv' => $a->argv, 'header' => $_SERVER, 'body' => $postdata], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); file_put_contents($tempfile, json_encode(['argv' => $a->argv, 'header' => $_SERVER, 'body' => $postdata], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
logger('Incoming message stored under ' . $tempfile); Logger::log('Incoming message stored under ' . $tempfile);
*/ */
if (!empty($a->argv[1])) { if (!empty($a->argv[1])) {
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]); $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);

View file

@ -10,6 +10,7 @@ use Friendica\Core\Addon;
use Friendica\Core\Authentication; use Friendica\Core\Authentication;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\User; use Friendica\Model\User;
@ -146,7 +147,7 @@ class Login extends BaseModule
); );
} }
} catch (Exception $e) { } catch (Exception $e) {
logger('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']); Logger::log('authenticate: failed login attempt: ' . notags($username) . ' from IP ' . $_SERVER['REMOTE_ADDR']);
info('Login failed. Please check your credentials.' . EOL); info('Login failed. Please check your credentials.' . EOL);
$a->internalRedirect(); $a->internalRedirect();
} }
@ -195,7 +196,7 @@ class Login extends BaseModule
); );
if (DBA::isResult($user)) { if (DBA::isResult($user)) {
if ($data->hash != Authentication::getCookieHashForUser($user)) { if ($data->hash != Authentication::getCookieHashForUser($user)) {
logger("Hash for user " . $data->uid . " doesn't fit."); Logger::log("Hash for user " . $data->uid . " doesn't fit.");
Authentication::deleteSession(); Authentication::deleteSession();
$a->internalRedirect(); $a->internalRedirect();
} }
@ -231,7 +232,7 @@ class Login extends BaseModule
$check = Config::get('system', 'paranoia'); $check = Config::get('system', 'paranoia');
// extra paranoia - if the IP changed, log them out // extra paranoia - if the IP changed, log them out
if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) { if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
logger('Session address changed. Paranoid setting in effect, blocking session. ' . Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
$_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']); $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
Authentication::deleteSession(); Authentication::deleteSession();
$a->internalRedirect(); $a->internalRedirect();

View file

@ -5,9 +5,10 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Logger;
use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Core\System;
use Friendica\Util\HTTPSignature; use Friendica\Util\HTTPSignature;
use Friendica\Util\Network; use Friendica\Util\Network;
@ -22,9 +23,9 @@ class Magic extends BaseModule
{ {
$a = self::getApp(); $a = self::getApp();
$ret = ['success' => false, 'url' => '', 'message' => '']; $ret = ['success' => false, 'url' => '', 'message' => ''];
logger('magic mdule: invoked', LOGGER_DEBUG); Logger::log('magic mdule: invoked', Logger::DEBUG);
logger('args: ' . print_r($_REQUEST, true), LOGGER_DATA); Logger::log('args: ' . print_r($_REQUEST, true), Logger::DATA);
$addr = ((x($_REQUEST, 'addr')) ? $_REQUEST['addr'] : ''); $addr = ((x($_REQUEST, 'addr')) ? $_REQUEST['addr'] : '');
$dest = ((x($_REQUEST, 'dest')) ? $_REQUEST['dest'] : ''); $dest = ((x($_REQUEST, 'dest')) ? $_REQUEST['dest'] : '');
@ -41,7 +42,7 @@ class Magic extends BaseModule
} }
if (!$cid) { if (!$cid) {
logger('No contact record found: ' . print_r($_REQUEST, true), LOGGER_DEBUG); Logger::log('No contact record found: ' . print_r($_REQUEST, true), Logger::DEBUG);
// @TODO Finding a more elegant possibility to redirect to either internal or external URL // @TODO Finding a more elegant possibility to redirect to either internal or external URL
$a->redirect($dest); $a->redirect($dest);
} }
@ -55,7 +56,7 @@ class Magic extends BaseModule
return $ret; return $ret;
} }
logger('Contact is already authenticated', LOGGER_DEBUG); Logger::log('Contact is already authenticated', Logger::DEBUG);
System::externalRedirect($dest); System::externalRedirect($dest);
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Module; namespace Friendica\Module;
use Friendica\BaseModule; use Friendica\BaseModule;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -57,8 +58,8 @@ class Owa extends BaseModule
$verified = HTTPSignature::verifyMagic($contact['pubkey']); $verified = HTTPSignature::verifyMagic($contact['pubkey']);
if ($verified && $verified['header_signed'] && $verified['header_valid']) { if ($verified && $verified['header_signed'] && $verified['header_valid']) {
logger('OWA header: ' . print_r($verified, true), LOGGER_DATA); Logger::log('OWA header: ' . print_r($verified, true), Logger::DATA);
logger('OWA success: ' . $contact['addr'], LOGGER_DATA); Logger::log('OWA success: ' . $contact['addr'], Logger::DATA);
$ret['success'] = true; $ret['success'] = true;
$token = random_string(32); $token = random_string(32);
@ -75,10 +76,10 @@ class Owa extends BaseModule
openssl_public_encrypt($token, $result, $contact['pubkey']); openssl_public_encrypt($token, $result, $contact['pubkey']);
$ret['encrypted_token'] = base64url_encode($result); $ret['encrypted_token'] = base64url_encode($result);
} else { } else {
logger('OWA fail: ' . $contact['id'] . ' ' . $contact['addr'] . ' ' . $contact['url'], LOGGER_DEBUG); Logger::log('OWA fail: ' . $contact['id'] . ' ' . $contact['addr'] . ' ' . $contact['url'], Logger::DEBUG);
} }
} else { } else {
logger('Contact not found: ' . $handle, LOGGER_DEBUG); Logger::log('Contact not found: ' . $handle, Logger::DEBUG);
} }
} }
} }

View file

@ -2,7 +2,7 @@
namespace Friendica\Network; namespace Friendica\Network;
use Friendica\Core\Logger;
use Friendica\Network\HTTPException\InternalServerErrorException; use Friendica\Network\HTTPException\InternalServerErrorException;
/** /**
@ -104,7 +104,7 @@ class CurlResult
$this->errorNumber = $errorNumber; $this->errorNumber = $errorNumber;
$this->error = $error; $this->error = $error;
logger($url . ': ' . $this->returnCode . " " . $result, LOGGER_DATA); Logger::log($url . ': ' . $this->returnCode . " " . $result, Logger::DATA);
$this->parseBodyHeader($result); $this->parseBodyHeader($result);
$this->checkSuccess(); $this->checkSuccess();
@ -134,8 +134,8 @@ class CurlResult
$this->isSuccess = ($this->returnCode >= 200 && $this->returnCode <= 299) || $this->errorNumber == 0; $this->isSuccess = ($this->returnCode >= 200 && $this->returnCode <= 299) || $this->errorNumber == 0;
if (!$this->isSuccess) { if (!$this->isSuccess) {
logger('error: ' . $this->url . ': ' . $this->returnCode . ' - ' . $this->error, LOGGER_INFO); Logger::log('error: ' . $this->url . ': ' . $this->returnCode . ' - ' . $this->error, Logger::INFO);
logger('debug: ' . print_r($this->info, true), LOGGER_DATA); Logger::log('debug: ' . print_r($this->info, true), Logger::DATA);
} }
if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) { if (!$this->isSuccess && $this->errorNumber == CURLE_OPERATION_TIMEDOUT) {

View file

@ -5,6 +5,7 @@
namespace Friendica\Network; namespace Friendica\Network;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -34,12 +35,12 @@ class FKOAuth1 extends OAuthServer
*/ */
public function loginUser($uid) public function loginUser($uid)
{ {
logger("FKOAuth1::loginUser $uid"); Logger::log("FKOAuth1::loginUser $uid");
$a = get_app(); $a = get_app();
$record = DBA::selectFirst('user', [], ['uid' => $uid, 'blocked' => 0, 'account_expired' => 0, 'account_removed' => 0, 'verified' => 1]); $record = DBA::selectFirst('user', [], ['uid' => $uid, 'blocked' => 0, 'account_expired' => 0, 'account_removed' => 0, 'verified' => 1]);
if (!DBA::isResult($record)) { if (!DBA::isResult($record)) {
logger('FKOAuth1::loginUser failure: ' . print_r($_SERVER, true), LOGGER_DEBUG); Logger::log('FKOAuth1::loginUser failure: ' . print_r($_SERVER, true), Logger::DEBUG);
header('HTTP/1.0 401 Unauthorized'); header('HTTP/1.0 401 Unauthorized');
die('This api requires login'); die('This api requires login');
} }

View file

@ -10,6 +10,7 @@
namespace Friendica\Network; namespace Friendica\Network;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use OAuthConsumer; use OAuthConsumer;
use OAuthDataStore; use OAuthDataStore;
@ -39,7 +40,7 @@ class FKOAuthDataStore extends OAuthDataStore
*/ */
public function lookup_consumer($consumer_key) public function lookup_consumer($consumer_key)
{ {
logger(__function__ . ":" . $consumer_key); Logger::log(__function__ . ":" . $consumer_key);
$s = DBA::select('clients', ['client_id', 'pw', 'redirect_uri'], ['client_id' => $consumer_key]); $s = DBA::select('clients', ['client_id', 'pw', 'redirect_uri'], ['client_id' => $consumer_key]);
$r = DBA::toArray($s); $r = DBA::toArray($s);
@ -59,7 +60,7 @@ class FKOAuthDataStore extends OAuthDataStore
*/ */
public function lookup_token($consumer, $token_type, $token) public function lookup_token($consumer, $token_type, $token)
{ {
logger(__function__ . ":" . $consumer . ", " . $token_type . ", " . $token); Logger::log(__function__ . ":" . $consumer . ", " . $token_type . ", " . $token);
$s = DBA::select('tokens', ['id', 'secret', 'scope', 'expires', 'uid'], ['client_id' => $consumer->key, 'scope' => $token_type, 'id' => $token]); $s = DBA::select('tokens', ['id', 'secret', 'scope', 'expires', 'uid'], ['client_id' => $consumer->key, 'scope' => $token_type, 'id' => $token]);
$r = DBA::toArray($s); $r = DBA::toArray($s);
@ -99,7 +100,7 @@ class FKOAuthDataStore extends OAuthDataStore
*/ */
public function new_request_token($consumer, $callback = null) public function new_request_token($consumer, $callback = null)
{ {
logger(__function__ . ":" . $consumer . ", " . $callback); Logger::log(__function__ . ":" . $consumer . ", " . $callback);
$key = self::genToken(); $key = self::genToken();
$sec = self::genToken(); $sec = self::genToken();
@ -134,7 +135,7 @@ class FKOAuthDataStore extends OAuthDataStore
*/ */
public function new_access_token($token, $consumer, $verifier = null) public function new_access_token($token, $consumer, $verifier = null)
{ {
logger(__function__ . ":" . $token . ", " . $consumer . ", " . $verifier); Logger::log(__function__ . ":" . $token . ", " . $consumer . ", " . $verifier);
// return a new access token attached to this consumer // return a new access token attached to this consumer
// for the user associated with this token if the request token // for the user associated with this token if the request token
@ -145,7 +146,7 @@ class FKOAuthDataStore extends OAuthDataStore
// get user for this verifier // get user for this verifier
$uverifier = Config::get("oauth", $verifier); $uverifier = Config::get("oauth", $verifier);
logger(__function__ . ":" . $verifier . "," . $uverifier); Logger::log(__function__ . ":" . $verifier . "," . $uverifier);
if (is_null($verifier) || ($uverifier !== false)) { if (is_null($verifier) || ($uverifier !== false)) {
$key = self::genToken(); $key = self::genToken();

View file

@ -12,6 +12,7 @@ namespace Friendica\Network;
use DOMDocument; use DOMDocument;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -109,7 +110,7 @@ class Probe
$xrd_timeout = Config::get('system', 'xrd_timeout', 20); $xrd_timeout = Config::get('system', 'xrd_timeout', 20);
$redirects = 0; $redirects = 0;
logger("Probing for ".$host, LOGGER_DEBUG); Logger::log("Probing for ".$host, Logger::DEBUG);
$xrd = null; $xrd = null;
$curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']); $curlResult = Network::curl($ssl_url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
@ -122,7 +123,7 @@ class Probe
if (!is_object($xrd)) { if (!is_object($xrd)) {
$curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']); $curlResult = Network::curl($url, false, $redirects, ['timeout' => $xrd_timeout, 'accept_content' => 'application/xrd+xml']);
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
logger("Probing timeout for " . $url, LOGGER_DEBUG); Logger::log("Probing timeout for " . $url, Logger::DEBUG);
return false; return false;
} }
$xml = $curlResult->getBody(); $xml = $curlResult->getBody();
@ -130,13 +131,13 @@ class Probe
$host_url = 'http://'.$host; $host_url = 'http://'.$host;
} }
if (!is_object($xrd)) { if (!is_object($xrd)) {
logger("No xrd object found for ".$host, LOGGER_DEBUG); Logger::log("No xrd object found for ".$host, Logger::DEBUG);
return []; return [];
} }
$links = XML::elementToArray($xrd); $links = XML::elementToArray($xrd);
if (!isset($links["xrd"]["link"])) { if (!isset($links["xrd"]["link"])) {
logger("No xrd data found for ".$host, LOGGER_DEBUG); Logger::log("No xrd data found for ".$host, Logger::DEBUG);
return []; return [];
} }
@ -164,7 +165,7 @@ class Probe
self::$baseurl = "http://".$host; self::$baseurl = "http://".$host;
logger("Probing successful for ".$host, LOGGER_DEBUG); Logger::log("Probing successful for ".$host, Logger::DEBUG);
return $lrdd; return $lrdd;
} }
@ -194,7 +195,7 @@ class Probe
$profile_link = ''; $profile_link = '';
$links = self::lrdd($webbie); $links = self::lrdd($webbie);
logger('webfingerDfrn: '.$webbie.':'.print_r($links, true), LOGGER_DATA); Logger::log('webfingerDfrn: '.$webbie.':'.print_r($links, true), Logger::DATA);
if (count($links)) { if (count($links)) {
foreach ($links as $link) { foreach ($links as $link) {
if ($link['@attributes']['rel'] === NAMESPACE_DFRN) { if ($link['@attributes']['rel'] === NAMESPACE_DFRN) {
@ -253,7 +254,7 @@ class Probe
} }
if (!$lrdd) { if (!$lrdd) {
logger("No lrdd data found for ".$uri, LOGGER_DEBUG); Logger::log("No lrdd data found for ".$uri, Logger::DEBUG);
return []; return [];
} }
@ -285,7 +286,7 @@ class Probe
} }
if (!is_array($webfinger["links"])) { if (!is_array($webfinger["links"])) {
logger("No webfinger links found for ".$uri, LOGGER_DEBUG); Logger::log("No webfinger links found for ".$uri, Logger::DEBUG);
return false; return false;
} }
@ -595,7 +596,7 @@ class Probe
$lrdd = self::hostMeta($host); $lrdd = self::hostMeta($host);
} }
if (!$lrdd) { if (!$lrdd) {
logger('No XRD data was found for '.$uri, LOGGER_DEBUG); Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
return self::feed($uri); return self::feed($uri);
} }
$nick = array_pop($path_parts); $nick = array_pop($path_parts);
@ -630,12 +631,12 @@ class Probe
} }
if (!$lrdd) { if (!$lrdd) {
logger('No XRD data was found for '.$uri, LOGGER_DEBUG); Logger::log('No XRD data was found for '.$uri, Logger::DEBUG);
return self::mail($uri, $uid); return self::mail($uri, $uid);
} }
$addr = $uri; $addr = $uri;
} else { } else {
logger("Uri ".$uri." was not detectable", LOGGER_DEBUG); Logger::log("Uri ".$uri." was not detectable", Logger::DEBUG);
return false; return false;
} }
@ -680,7 +681,7 @@ class Probe
$result = false; $result = false;
logger("Probing ".$uri, LOGGER_DEBUG); Logger::log("Probing ".$uri, Logger::DEBUG);
if (in_array($network, ["", Protocol::DFRN])) { if (in_array($network, ["", Protocol::DFRN])) {
$result = self::dfrn($webfinger); $result = self::dfrn($webfinger);
@ -716,7 +717,7 @@ class Probe
$result["url"] = $uri; $result["url"] = $uri;
} }
logger($uri." is ".$result["network"], LOGGER_DEBUG); Logger::log($uri." is ".$result["network"], Logger::DEBUG);
if (empty($result["baseurl"])) { if (empty($result["baseurl"])) {
$pos = strpos($result["url"], $host); $pos = strpos($result["url"], $host);
@ -751,7 +752,7 @@ class Probe
$webfinger = json_decode($data, true); $webfinger = json_decode($data, true);
if (is_array($webfinger)) { if (is_array($webfinger)) {
if (!isset($webfinger["links"])) { if (!isset($webfinger["links"])) {
logger("No json webfinger links for ".$url, LOGGER_DEBUG); Logger::log("No json webfinger links for ".$url, Logger::DEBUG);
return false; return false;
} }
return $webfinger; return $webfinger;
@ -760,13 +761,13 @@ class Probe
// If it is not JSON, maybe it is XML // If it is not JSON, maybe it is XML
$xrd = XML::parseString($data, false); $xrd = XML::parseString($data, false);
if (!is_object($xrd)) { if (!is_object($xrd)) {
logger("No webfinger data retrievable for ".$url, LOGGER_DEBUG); Logger::log("No webfinger data retrievable for ".$url, Logger::DEBUG);
return false; return false;
} }
$xrd_arr = XML::elementToArray($xrd); $xrd_arr = XML::elementToArray($xrd);
if (!isset($xrd_arr["xrd"]["link"])) { if (!isset($xrd_arr["xrd"]["link"])) {
logger("No XML webfinger links for ".$url, LOGGER_DEBUG); Logger::log("No XML webfinger links for ".$url, Logger::DEBUG);
return false; return false;
} }
@ -815,13 +816,13 @@ class Probe
} }
$content = $curlResult->getBody(); $content = $curlResult->getBody();
if (!$content) { if (!$content) {
logger("Empty body for ".$noscrape_url, LOGGER_DEBUG); Logger::log("Empty body for ".$noscrape_url, Logger::DEBUG);
return false; return false;
} }
$json = json_decode($content, true); $json = json_decode($content, true);
if (!is_array($json)) { if (!is_array($json)) {
logger("No json data for ".$noscrape_url, LOGGER_DEBUG); Logger::log("No json data for ".$noscrape_url, Logger::DEBUG);
return false; return false;
} }
@ -927,7 +928,7 @@ class Probe
{ {
$data = []; $data = [];
logger("Check profile ".$profile_link, LOGGER_DEBUG); Logger::log("Check profile ".$profile_link, Logger::DEBUG);
// Fetch data via noscrape - this is faster // Fetch data via noscrape - this is faster
$noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link); $noscrape_url = str_replace(["/hcard/", "/profile/"], "/noscrape/", $profile_link);
@ -961,7 +962,7 @@ class Probe
$prof_data["fn"] = defaults($data, 'name' , null); $prof_data["fn"] = defaults($data, 'name' , null);
$prof_data["key"] = defaults($data, 'pubkey' , null); $prof_data["key"] = defaults($data, 'pubkey' , null);
logger("Result for profile ".$profile_link.": ".print_r($prof_data, true), LOGGER_DEBUG); Logger::log("Result for profile ".$profile_link.": ".print_r($prof_data, true), Logger::DEBUG);
return $prof_data; return $prof_data;
} }
@ -1632,7 +1633,7 @@ class Probe
} }
$msgs = Email::poll($mbox, $uri); $msgs = Email::poll($mbox, $uri);
logger('searching '.$uri.', '.count($msgs).' messages found.', LOGGER_DEBUG); Logger::log('searching '.$uri.', '.count($msgs).' messages found.', Logger::DEBUG);
if (!count($msgs)) { if (!count($msgs)) {
return false; return false;
@ -1714,7 +1715,7 @@ class Probe
$fixed = $scheme.$host.$port.$path.$query.$fragment; $fixed = $scheme.$host.$port.$path.$query.$fragment;
logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA); Logger::log('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, Logger::DATA);
return $fixed; return $fixed;
} }

View file

@ -9,6 +9,7 @@ use Friendica\App;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -482,7 +483,7 @@ class Image
break; break;
} }
// logger('exif: ' . print_r($exif,true)); // Logger::log('exif: ' . print_r($exif,true));
return $exif; return $exif;
} }
@ -726,7 +727,7 @@ class Image
*/ */
public static function guessType($filename, $fromcurl = false, $header = '') public static function guessType($filename, $fromcurl = false, $header = '')
{ {
logger('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), LOGGER_DEBUG); Logger::log('Image: guessType: '.$filename . ($fromcurl?' from curl headers':''), Logger::DEBUG);
$type = null; $type = null;
if ($fromcurl) { if ($fromcurl) {
$a = get_app(); $a = get_app();
@ -764,7 +765,7 @@ class Image
} }
} }
} }
logger('Image: guessType: type='.$type, LOGGER_DEBUG); Logger::log('Image: guessType: type='.$type, Logger::DEBUG);
return $type; return $type;
} }
@ -890,7 +891,7 @@ class Image
); );
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
logger("Can't detect user data for uid ".$uid, LOGGER_DEBUG); Logger::log("Can't detect user data for uid ".$uid, Logger::DEBUG);
return([]); return([]);
} }
@ -901,10 +902,10 @@ class Image
/// $community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false); /// $community_page = (($r[0]['page-flags'] == Contact::PAGE_COMMUNITY) ? true : false);
if ((strlen($imagedata) == 0) && ($url == "")) { if ((strlen($imagedata) == 0) && ($url == "")) {
logger("No image data and no url provided", LOGGER_DEBUG); Logger::log("No image data and no url provided", Logger::DEBUG);
return([]); return([]);
} elseif (strlen($imagedata) == 0) { } elseif (strlen($imagedata) == 0) {
logger("Uploading picture from ".$url, LOGGER_DEBUG); Logger::log("Uploading picture from ".$url, Logger::DEBUG);
$stamp1 = microtime(true); $stamp1 = microtime(true);
$imagedata = @file_get_contents($url); $imagedata = @file_get_contents($url);
@ -914,7 +915,7 @@ class Image
$maximagesize = Config::get('system', 'maximagesize'); $maximagesize = Config::get('system', 'maximagesize');
if (($maximagesize) && (strlen($imagedata) > $maximagesize)) { if (($maximagesize) && (strlen($imagedata) > $maximagesize)) {
logger("Image exceeds size limit of ".$maximagesize, LOGGER_DEBUG); Logger::log("Image exceeds size limit of ".$maximagesize, Logger::DEBUG);
return([]); return([]);
} }
@ -928,7 +929,7 @@ class Image
if (!isset($data["mime"])) { if (!isset($data["mime"])) {
unlink($tempfile); unlink($tempfile);
logger("File is no picture", LOGGER_DEBUG); Logger::log("File is no picture", Logger::DEBUG);
return([]); return([]);
} }
@ -936,7 +937,7 @@ class Image
if (!$Image->isValid()) { if (!$Image->isValid()) {
unlink($tempfile); unlink($tempfile);
logger("Picture is no valid picture", LOGGER_DEBUG); Logger::log("Picture is no valid picture", Logger::DEBUG);
return([]); return([]);
} }
@ -967,7 +968,7 @@ class Image
$r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm); $r = Photo::store($Image, $uid, $visitor, $hash, $tempfile, L10n::t('Wall Photos'), 0, 0, $defperm);
if (!$r) { if (!$r) {
logger("Picture couldn't be stored", LOGGER_DEBUG); Logger::log("Picture couldn't be stored", Logger::DEBUG);
return([]); return([]);
} }

View file

@ -10,6 +10,7 @@ use Friendica\Content\Feature;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -487,10 +488,10 @@ class Post extends BaseObject
{ {
$item_id = $item->getId(); $item_id = $item->getId();
if (!$item_id) { if (!$item_id) {
logger('[ERROR] Post::addChild : Item has no ID!!', LOGGER_DEBUG); Logger::log('[ERROR] Post::addChild : Item has no ID!!', Logger::DEBUG);
return false; return false;
} elseif ($this->getChild($item->getId())) { } elseif ($this->getChild($item->getId())) {
logger('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', LOGGER_DEBUG); Logger::log('[WARN] Post::addChild : Item already exists (' . $item->getId() . ').', Logger::DEBUG);
return false; return false;
} }
/* /*
@ -584,7 +585,7 @@ class Post extends BaseObject
return true; return true;
} }
} }
logger('[WARN] Item::removeChild : Item is not a child (' . $id . ').', LOGGER_DEBUG); Logger::log('[WARN] Item::removeChild : Item is not a child (' . $id . ').', Logger::DEBUG);
return false; return false;
} }
@ -650,7 +651,7 @@ class Post extends BaseObject
public function getDataValue($name) public function getDataValue($name)
{ {
if (!isset($this->data[$name])) { if (!isset($this->data[$name])) {
// logger('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', LOGGER_DEBUG); // Logger::log('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".', Logger::DEBUG);
return false; return false;
} }
@ -667,7 +668,7 @@ class Post extends BaseObject
private function setTemplate($name) private function setTemplate($name)
{ {
if (!x($this->available_templates, $name)) { if (!x($this->available_templates, $name)) {
logger('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', LOGGER_DEBUG); Logger::log('[ERROR] Item::setTemplate : Template not available ("' . $name . '").', Logger::DEBUG);
return false; return false;
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Object; namespace Friendica\Object;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Object\Post; use Friendica\Object\Post;
use Friendica\Util\Security; use Friendica\Util\Security;
@ -77,7 +78,7 @@ class Thread extends BaseObject
$this->writable = $writable; $this->writable = $writable;
break; break;
default: default:
logger('[ERROR] Conversation::setMode : Unhandled mode ('. $mode .').', LOGGER_DEBUG); Logger::log('[ERROR] Conversation::setMode : Unhandled mode ('. $mode .').', Logger::DEBUG);
return false; return false;
break; break;
} }
@ -137,12 +138,12 @@ class Thread extends BaseObject
$item_id = $item->getId(); $item_id = $item->getId();
if (!$item_id) { if (!$item_id) {
logger('[ERROR] Conversation::addThread : Item has no ID!!', LOGGER_DEBUG); Logger::log('[ERROR] Conversation::addThread : Item has no ID!!', Logger::DEBUG);
return false; return false;
} }
if ($this->getParent($item->getId())) { if ($this->getParent($item->getId())) {
logger('[WARN] Conversation::addThread : Thread already exists ('. $item->getId() .').', LOGGER_DEBUG); Logger::log('[WARN] Conversation::addThread : Thread already exists ('. $item->getId() .').', Logger::DEBUG);
return false; return false;
} }
@ -150,12 +151,12 @@ class Thread extends BaseObject
* Only add will be displayed * Only add will be displayed
*/ */
if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) { if ($item->getDataValue('network') === Protocol::MAIL && local_user() != $item->getDataValue('uid')) {
logger('[WARN] Conversation::addThread : Thread is a mail ('. $item->getId() .').', LOGGER_DEBUG); Logger::log('[WARN] Conversation::addThread : Thread is a mail ('. $item->getId() .').', Logger::DEBUG);
return false; return false;
} }
if ($item->getDataValue('verb') === ACTIVITY_LIKE || $item->getDataValue('verb') === ACTIVITY_DISLIKE) { if ($item->getDataValue('verb') === ACTIVITY_LIKE || $item->getDataValue('verb') === ACTIVITY_DISLIKE) {
logger('[WARN] Conversation::addThread : Thread is a (dis)like ('. $item->getId() .').', LOGGER_DEBUG); Logger::log('[WARN] Conversation::addThread : Thread is a (dis)like ('. $item->getId() .').', Logger::DEBUG);
return false; return false;
} }
@ -189,7 +190,7 @@ class Thread extends BaseObject
$item_data = $item->getTemplateData($conv_responses); $item_data = $item->getTemplateData($conv_responses);
if (!$item_data) { if (!$item_data) {
logger('[ERROR] Conversation::getTemplateData : Failed to get item template data ('. $item->getId() .').', LOGGER_DEBUG); Logger::log('[ERROR] Conversation::getTemplateData : Failed to get item template data ('. $item->getId() .').', Logger::DEBUG);
return false; return false;
} }
$result[] = $item_data; $result[] = $item_data;

View file

@ -5,6 +5,7 @@
namespace Friendica\Protocol\ActivityPub; namespace Friendica\Protocol\ActivityPub;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Model\Conversation; use Friendica\Model\Conversation;
use Friendica\Model\Contact; use Friendica\Model\Contact;
@ -140,7 +141,7 @@ class Processor
} }
if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) { if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.'); Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
self::fetchMissingActivity($activity['reply-to-id'], $activity); self::fetchMissingActivity($activity['reply-to-id'], $activity);
} }
@ -158,7 +159,7 @@ class Processor
{ {
$owner = Contact::getIdForURL($activity['actor']); $owner = Contact::getIdForURL($activity['actor']);
logger('Deleting item ' . $activity['object_id'] . ' from ' . $owner, LOGGER_DEBUG); Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]); Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
} }
@ -211,7 +212,7 @@ class Processor
} }
$event_id = Event::store($event); $event_id = Event::store($event);
logger('Event '.$event_id.' was stored', LOGGER_DEBUG); Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
} }
/** /**
@ -225,7 +226,7 @@ class Processor
/// @todo What to do with $activity['context']? /// @todo What to do with $activity['context']?
if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) { if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG); Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
return; return;
} }
@ -238,7 +239,7 @@ class Processor
$item['owner-link'] = $activity['actor']; $item['owner-link'] = $activity['actor'];
$item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true); $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
} else { } else {
logger('Ignoring actor because of thread completion.', LOGGER_DEBUG); Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
$item['owner-link'] = $item['author-link']; $item['owner-link'] = $item['author-link'];
$item['owner-id'] = $item['author-id']; $item['owner-id'] = $item['author-id'];
} }
@ -284,7 +285,7 @@ class Processor
} }
$item_id = Item::insert($item); $item_id = Item::insert($item);
logger('Storing for user ' . $item['uid'] . ': ' . $item_id); Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
} }
} }
@ -302,7 +303,7 @@ class Processor
$object = ActivityPub::fetchContent($url); $object = ActivityPub::fetchContent($url);
if (empty($object)) { if (empty($object)) {
logger('Activity ' . $url . ' was not fetchable, aborting.'); Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
return; return;
} }
@ -322,7 +323,7 @@ class Processor
$ldactivity['thread-completion'] = true; $ldactivity['thread-completion'] = true;
ActivityPub\Receiver::processActivity($ldactivity); ActivityPub\Receiver::processActivity($ldactivity);
logger('Activity ' . $url . ' had been fetched and processed.'); Logger::log('Activity ' . $url . ' had been fetched and processed.');
} }
/** /**
@ -360,7 +361,7 @@ class Processor
} }
DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]); DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']); Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
} }
/** /**
@ -374,7 +375,7 @@ class Processor
return; return;
} }
logger('Updating profile for ' . $activity['object_id'], LOGGER_DEBUG); Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
APContact::getByURL($activity['object_id'], true); APContact::getByURL($activity['object_id'], true);
} }
@ -386,12 +387,12 @@ class Processor
public static function deletePerson($activity) public static function deletePerson($activity)
{ {
if (empty($activity['object_id']) || empty($activity['actor'])) { if (empty($activity['object_id']) || empty($activity['actor'])) {
logger('Empty object id or actor.', LOGGER_DEBUG); Logger::log('Empty object id or actor.', Logger::DEBUG);
return; return;
} }
if ($activity['object_id'] != $activity['actor']) { if ($activity['object_id'] != $activity['actor']) {
logger('Object id does not match actor.', LOGGER_DEBUG); Logger::log('Object id does not match actor.', Logger::DEBUG);
return; return;
} }
@ -401,7 +402,7 @@ class Processor
} }
DBA::close($contacts); DBA::close($contacts);
logger('Deleted contact ' . $activity['object_id'], LOGGER_DEBUG); Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
} }
/** /**
@ -420,7 +421,7 @@ class Processor
$cid = Contact::getIdForURL($activity['actor'], $uid); $cid = Contact::getIdForURL($activity['actor'], $uid);
if (empty($cid)) { if (empty($cid)) {
logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG); Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
return; return;
} }
@ -435,7 +436,7 @@ class Processor
$condition = ['id' => $cid]; $condition = ['id' => $cid];
DBA::update('contact', $fields, $condition); DBA::update('contact', $fields, $condition);
logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG); Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
} }
/** /**
@ -454,7 +455,7 @@ class Processor
$cid = Contact::getIdForURL($activity['actor'], $uid); $cid = Contact::getIdForURL($activity['actor'], $uid);
if (empty($cid)) { if (empty($cid)) {
logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG); Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
return; return;
} }
@ -462,9 +463,9 @@ class Processor
if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) { if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
Contact::remove($cid); Contact::remove($cid);
logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG); Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
} else { } else {
logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG); Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
} }
} }
@ -507,7 +508,7 @@ class Processor
$cid = Contact::getIdForURL($activity['actor'], $uid); $cid = Contact::getIdForURL($activity['actor'], $uid);
if (empty($cid)) { if (empty($cid)) {
logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG); Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
return; return;
} }
@ -519,7 +520,7 @@ class Processor
} }
Contact::removeFollower($owner, $contact); Contact::removeFollower($owner, $contact);
logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG); Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
} }
/** /**
@ -534,7 +535,7 @@ class Processor
return; return;
} }
logger('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.'); Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB); Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
} }
} }

View file

@ -6,6 +6,7 @@ namespace Friendica\Protocol\ActivityPub;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Util\HTTPSignature; use Friendica\Util\HTTPSignature;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\APContact; use Friendica\Model\APContact;
@ -59,16 +60,16 @@ class Receiver
{ {
$http_signer = HTTPSignature::getSigner($body, $header); $http_signer = HTTPSignature::getSigner($body, $header);
if (empty($http_signer)) { if (empty($http_signer)) {
logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG); Logger::log('Invalid HTTP signature, message will be discarded.', Logger::DEBUG);
return; return;
} else { } else {
logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG); Logger::log('HTTP signature is signed by ' . $http_signer, Logger::DEBUG);
} }
$activity = json_decode($body, true); $activity = json_decode($body, true);
if (empty($activity)) { if (empty($activity)) {
logger('Invalid body.', LOGGER_DEBUG); Logger::log('Invalid body.', Logger::DEBUG);
return; return;
} }
@ -76,31 +77,31 @@ class Receiver
$actor = JsonLD::fetchElement($ldactivity, 'as:actor'); $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG); Logger::log('Message for user ' . $uid . ' is from actor ' . $actor, Logger::DEBUG);
if (LDSignature::isSigned($activity)) { if (LDSignature::isSigned($activity)) {
$ld_signer = LDSignature::getSigner($activity); $ld_signer = LDSignature::getSigner($activity);
if (empty($ld_signer)) { if (empty($ld_signer)) {
logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG); Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
} }
if (!empty($ld_signer && ($actor == $http_signer))) { if (!empty($ld_signer && ($actor == $http_signer))) {
logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG); Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
$trust_source = true; $trust_source = true;
} elseif (!empty($ld_signer)) { } elseif (!empty($ld_signer)) {
logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG); Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
$trust_source = true; $trust_source = true;
} elseif ($actor == $http_signer) { } elseif ($actor == $http_signer) {
logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG); Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
$trust_source = true; $trust_source = true;
} else { } else {
logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG); Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
$trust_source = false; $trust_source = false;
} }
} elseif ($actor == $http_signer) { } elseif ($actor == $http_signer) {
logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG); Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
$trust_source = true; $trust_source = true;
} else { } else {
logger('No JSON-LD signature, different actor.', LOGGER_DEBUG); Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
$trust_source = false; $trust_source = false;
} }
@ -159,7 +160,7 @@ class Receiver
{ {
$actor = JsonLD::fetchElement($activity, 'as:actor'); $actor = JsonLD::fetchElement($activity, 'as:actor');
if (empty($actor)) { if (empty($actor)) {
logger('Empty actor', LOGGER_DEBUG); Logger::log('Empty actor', Logger::DEBUG);
return []; return [];
} }
@ -175,11 +176,11 @@ class Receiver
$receivers = array_merge($receivers, $additional); $receivers = array_merge($receivers, $additional);
} }
logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG); Logger::log('Receivers: ' . json_encode($receivers), Logger::DEBUG);
$object_id = JsonLD::fetchElement($activity, 'as:object'); $object_id = JsonLD::fetchElement($activity, 'as:object');
if (empty($object_id)) { if (empty($object_id)) {
logger('No object found', LOGGER_DEBUG); Logger::log('No object found', Logger::DEBUG);
return []; return [];
} }
@ -192,7 +193,7 @@ class Receiver
} }
$object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source); $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source);
if (empty($object_data)) { if (empty($object_data)) {
logger("Object data couldn't be processed", LOGGER_DEBUG); Logger::log("Object data couldn't be processed", Logger::DEBUG);
return []; return [];
} }
// We had been able to retrieve the object data - so we can trust the source // We had been able to retrieve the object data - so we can trust the source
@ -229,7 +230,7 @@ class Receiver
$object_data['actor'] = $actor; $object_data['actor'] = $actor;
$object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers); $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG); Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
return $object_data; return $object_data;
} }
@ -272,17 +273,17 @@ class Receiver
{ {
$type = JsonLD::fetchElement($activity, '@type'); $type = JsonLD::fetchElement($activity, '@type');
if (!$type) { if (!$type) {
logger('Empty type', LOGGER_DEBUG); Logger::log('Empty type', Logger::DEBUG);
return; return;
} }
if (!JsonLD::fetchElement($activity, 'as:object')) { if (!JsonLD::fetchElement($activity, 'as:object')) {
logger('Empty object', LOGGER_DEBUG); Logger::log('Empty object', Logger::DEBUG);
return; return;
} }
if (!JsonLD::fetchElement($activity, 'as:actor')) { if (!JsonLD::fetchElement($activity, 'as:actor')) {
logger('Empty actor', LOGGER_DEBUG); Logger::log('Empty actor', Logger::DEBUG);
return; return;
} }
@ -290,12 +291,12 @@ class Receiver
// $trust_source is called by reference and is set to true if the content was retrieved successfully // $trust_source is called by reference and is set to true if the content was retrieved successfully
$object_data = self::prepareObjectData($activity, $uid, $trust_source); $object_data = self::prepareObjectData($activity, $uid, $trust_source);
if (empty($object_data)) { if (empty($object_data)) {
logger('No object data found', LOGGER_DEBUG); Logger::log('No object data found', Logger::DEBUG);
return; return;
} }
if (!$trust_source) { if (!$trust_source) {
logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG); Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
return; return;
} }
@ -384,7 +385,7 @@ class Receiver
break; break;
default: default:
logger('Unknown activity: ' . $type . ' ' . $object_data['object_type'], LOGGER_DEBUG); Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
break; break;
} }
} }
@ -414,9 +415,9 @@ class Receiver
$profile = APContact::getByURL($actor); $profile = APContact::getByURL($actor);
$followers = defaults($profile, 'followers', ''); $followers = defaults($profile, 'followers', '');
logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG); Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
} else { } else {
logger('Empty actor', LOGGER_DEBUG); Logger::log('Empty actor', Logger::DEBUG);
$followers = ''; $followers = '';
} }
@ -486,7 +487,7 @@ class Receiver
return; return;
} }
logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub'); Logger::log('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
$photo = defaults($profile, 'photo', null); $photo = defaults($profile, 'photo', null);
unset($profile['photo']); unset($profile['photo']);
@ -500,7 +501,7 @@ class Receiver
// Send a new follow request to be sure that the connection still exists // Send a new follow request to be sure that the connection still exists
if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) { if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid); ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG); Logger::log('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, Logger::DEBUG);
} }
} }
@ -570,27 +571,27 @@ class Receiver
$data = ActivityPub::fetchContent($object_id); $data = ActivityPub::fetchContent($object_id);
if (!empty($data)) { if (!empty($data)) {
$object = JsonLD::compact($data); $object = JsonLD::compact($data);
logger('Fetched content for ' . $object_id, LOGGER_DEBUG); Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
} else { } else {
logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG); Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
$item = Item::selectFirst([], ['uri' => $object_id]); $item = Item::selectFirst([], ['uri' => $object_id]);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG); Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
return false; return false;
} }
logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG); Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
$data = ActivityPub\Transmitter::createNote($item); $data = ActivityPub\Transmitter::createNote($item);
$object = JsonLD::compact($data); $object = JsonLD::compact($data);
} }
} else { } else {
logger('Using original object for url ' . $object_id, LOGGER_DEBUG); Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
} }
$type = JsonLD::fetchElement($object, '@type'); $type = JsonLD::fetchElement($object, '@type');
if (empty($type)) { if (empty($type)) {
logger('Empty type', LOGGER_DEBUG); Logger::log('Empty type', Logger::DEBUG);
return false; return false;
} }
@ -606,7 +607,7 @@ class Receiver
return self::fetchObject($object_id); return self::fetchObject($object_id);
} }
logger('Unhandled object type: ' . $type, LOGGER_DEBUG); Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
} }
/** /**

View file

@ -6,6 +6,7 @@ namespace Friendica\Protocol\ActivityPub;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Core\Logger;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Util\HTTPSignature; use Friendica\Util\HTTPSignature;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
@ -1015,7 +1016,7 @@ class Transmitter
$signed = LDSignature::sign($data, $owner); $signed = LDSignature::sign($data, $owner);
logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG); Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
return HTTPSignature::transmit($signed, $inbox, $uid); return HTTPSignature::transmit($signed, $inbox, $uid);
} }
@ -1044,7 +1045,7 @@ class Transmitter
$signed = LDSignature::sign($data, $owner); $signed = LDSignature::sign($data, $owner);
logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG); Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
return HTTPSignature::transmit($signed, $inbox, $uid); return HTTPSignature::transmit($signed, $inbox, $uid);
} }
@ -1073,7 +1074,7 @@ class Transmitter
$signed = LDSignature::sign($data, $owner); $signed = LDSignature::sign($data, $owner);
logger('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG); Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
return HTTPSignature::transmit($signed, $inbox, $uid); return HTTPSignature::transmit($signed, $inbox, $uid);
} }
@ -1098,7 +1099,7 @@ class Transmitter
'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()], 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
'to' => $profile['url']]; 'to' => $profile['url']];
logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG); Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
$signed = LDSignature::sign($data, $owner); $signed = LDSignature::sign($data, $owner);
HTTPSignature::transmit($signed, $profile['inbox'], $uid); HTTPSignature::transmit($signed, $profile['inbox'], $uid);
@ -1126,7 +1127,7 @@ class Transmitter
'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()], 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
'to' => $profile['url']]; 'to' => $profile['url']];
logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG); Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
$signed = LDSignature::sign($data, $owner); $signed = LDSignature::sign($data, $owner);
HTTPSignature::transmit($signed, $profile['inbox'], $uid); HTTPSignature::transmit($signed, $profile['inbox'], $uid);
@ -1154,7 +1155,7 @@ class Transmitter
'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()], 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
'to' => $profile['url']]; 'to' => $profile['url']];
logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG); Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
$signed = LDSignature::sign($data, $owner); $signed = LDSignature::sign($data, $owner);
HTTPSignature::transmit($signed, $profile['inbox'], $uid); HTTPSignature::transmit($signed, $profile['inbox'], $uid);
@ -1183,7 +1184,7 @@ class Transmitter
'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()], 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
'to' => $profile['url']]; 'to' => $profile['url']];
logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG); Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
$signed = LDSignature::sign($data, $owner); $signed = LDSignature::sign($data, $owner);
HTTPSignature::transmit($signed, $profile['inbox'], $uid); HTTPSignature::transmit($signed, $profile['inbox'], $uid);

View file

@ -17,6 +17,7 @@ use Friendica\Content\Text\HTML;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -175,7 +176,7 @@ class DFRN
); );
if (! DBA::isResult($r)) { if (! DBA::isResult($r)) {
logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING); Logger::log(sprintf('No contact found for nickname=%d', $owner_nick), Logger::WARNING);
killme(); killme();
} }
@ -211,7 +212,7 @@ class DFRN
); );
if (! DBA::isResult($r)) { if (! DBA::isResult($r)) {
logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING); Logger::log(sprintf('No contact found for uid=%d', $owner_id), Logger::WARNING);
killme(); killme();
} }
@ -1171,7 +1172,7 @@ class DFRN
if (!$dissolve && !$legacy_transport) { if (!$dissolve && !$legacy_transport) {
$curlResult = self::transmit($owner, $contact, $atom); $curlResult = self::transmit($owner, $contact, $atom);
if ($curlResult >= 200) { if ($curlResult >= 200) {
logger('Delivery via Diaspora transport layer was successful with status ' . $curlResult); Logger::log('Delivery via Diaspora transport layer was successful with status ' . $curlResult);
return $curlResult; return $curlResult;
} }
} }
@ -1188,7 +1189,7 @@ class DFRN
$rino = Config::get('system', 'rino_encrypt'); $rino = Config::get('system', 'rino_encrypt');
$rino = intval($rino); $rino = intval($rino);
logger("Local rino version: ". $rino, LOGGER_DEBUG); Logger::log("Local rino version: ". $rino, Logger::DEBUG);
$ssl_val = intval(Config::get('system', 'ssl_policy')); $ssl_val = intval(Config::get('system', 'ssl_policy'));
$ssl_policy = ''; $ssl_policy = '';
@ -1208,7 +1209,7 @@ class DFRN
$url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : ''); $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
logger('dfrn_deliver: ' . $url); Logger::log('dfrn_deliver: ' . $url);
$curlResult = Network::curl($url); $curlResult = Network::curl($url);
@ -1225,7 +1226,7 @@ class DFRN
return -3; // timed out return -3; // timed out
} }
logger('dfrn_deliver: ' . $xml, LOGGER_DATA); Logger::log('dfrn_deliver: ' . $xml, Logger::DATA);
if (empty($xml)) { if (empty($xml)) {
Contact::markForArchival($contact); Contact::markForArchival($contact);
@ -1233,8 +1234,8 @@ class DFRN
} }
if (strpos($xml, '<?xml') === false) { if (strpos($xml, '<?xml') === false) {
logger('dfrn_deliver: no valid XML returned'); Logger::log('dfrn_deliver: no valid XML returned');
logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA); Logger::log('dfrn_deliver: returned XML: ' . $xml, Logger::DATA);
Contact::markForArchival($contact); Contact::markForArchival($contact);
return 3; return 3;
} }
@ -1261,7 +1262,7 @@ class DFRN
$rino_remote_version = intval($res->rino); $rino_remote_version = intval($res->rino);
$page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0); $page = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG); Logger::log("Remote rino version: ".$rino_remote_version." for ".$contact["url"], Logger::DEBUG);
if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) { if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
$page = 2; $page = 2;
@ -1297,7 +1298,7 @@ class DFRN
} }
if ($final_dfrn_id != $orig_id) { if ($final_dfrn_id != $orig_id) {
logger('dfrn_deliver: wrong dfrn_id.'); Logger::log('dfrn_deliver: wrong dfrn_id.');
// did not decode properly - cannot trust this site // did not decode properly - cannot trust this site
Contact::markForArchival($contact); Contact::markForArchival($contact);
return 3; return 3;
@ -1325,7 +1326,7 @@ class DFRN
if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) { if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
logger('rino version: '. $rino_remote_version); Logger::log('rino version: '. $rino_remote_version);
switch ($rino_remote_version) { switch ($rino_remote_version) {
case 1: case 1:
@ -1334,7 +1335,7 @@ class DFRN
break; break;
default: default:
logger("rino: invalid requested version '$rino_remote_version'"); Logger::log("rino: invalid requested version '$rino_remote_version'");
Contact::markForArchival($contact); Contact::markForArchival($contact);
return -8; return -8;
} }
@ -1359,19 +1360,19 @@ class DFRN
} }
} }
logger('md5 rawkey ' . md5($postvars['key'])); Logger::log('md5 rawkey ' . md5($postvars['key']));
$postvars['key'] = bin2hex($postvars['key']); $postvars['key'] = bin2hex($postvars['key']);
} }
logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA); Logger::log('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), Logger::DATA);
$postResult = Network::post($contact['notify'], $postvars); $postResult = Network::post($contact['notify'], $postvars);
$xml = $postResult->getBody(); $xml = $postResult->getBody();
logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA); Logger::log('dfrn_deliver: ' . "RECEIVED: " . $xml, Logger::DATA);
$curl_stat = $postResult->getReturnCode(); $curl_stat = $postResult->getReturnCode();
if (empty($curl_stat) || empty($xml)) { if (empty($curl_stat) || empty($xml)) {
@ -1385,8 +1386,8 @@ class DFRN
} }
if (strpos($xml, '<?xml') === false) { if (strpos($xml, '<?xml') === false) {
logger('dfrn_deliver: phase 2: no valid XML returned'); Logger::log('dfrn_deliver: phase 2: no valid XML returned');
logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA); Logger::log('dfrn_deliver: phase 2: returned XML: ' . $xml, Logger::DATA);
Contact::markForArchival($contact); Contact::markForArchival($contact);
return 3; return 3;
} }
@ -1404,7 +1405,7 @@ class DFRN
} }
if (!empty($res->message)) { if (!empty($res->message)) {
logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG); Logger::log('Delivery returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
} }
if (($res->status >= 200) && ($res->status <= 299)) { if (($res->status >= 200) && ($res->status <= 299)) {
@ -1429,14 +1430,14 @@ class DFRN
if (!$public_batch) { if (!$public_batch) {
if (empty($contact['addr'])) { if (empty($contact['addr'])) {
logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.'); Logger::log('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
if (Contact::updateFromProbe($contact['id'])) { if (Contact::updateFromProbe($contact['id'])) {
$new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]); $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
$contact['addr'] = $new_contact['addr']; $contact['addr'] = $new_contact['addr'];
} }
if (empty($contact['addr'])) { if (empty($contact['addr'])) {
logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']); Logger::log('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
Contact::markForArchival($contact); Contact::markForArchival($contact);
return -21; return -21;
} }
@ -1444,7 +1445,7 @@ class DFRN
$fcontact = Diaspora::personByHandle($contact['addr']); $fcontact = Diaspora::personByHandle($contact['addr']);
if (empty($fcontact)) { if (empty($fcontact)) {
logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']); Logger::log('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
Contact::markForArchival($contact); Contact::markForArchival($contact);
return -22; return -22;
} }
@ -1473,7 +1474,7 @@ class DFRN
$curl_stat = $postResult->getReturnCode(); $curl_stat = $postResult->getReturnCode();
if (empty($curl_stat) || empty($xml)) { if (empty($curl_stat) || empty($xml)) {
logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url); Logger::log('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
Contact::markForArchival($contact); Contact::markForArchival($contact);
return -9; // timed out return -9; // timed out
} }
@ -1484,8 +1485,8 @@ class DFRN
} }
if (strpos($xml, '<?xml') === false) { if (strpos($xml, '<?xml') === false) {
logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url); Logger::log('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
logger('Returned XML: ' . $xml, LOGGER_DATA); Logger::log('Returned XML: ' . $xml, Logger::DATA);
Contact::markForArchival($contact); Contact::markForArchival($contact);
return 3; return 3;
} }
@ -1498,7 +1499,7 @@ class DFRN
} }
if (!empty($res->message)) { if (!empty($res->message)) {
logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG); Logger::log('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, Logger::DEBUG);
} }
if (($res->status >= 200) && ($res->status <= 299)) { if (($res->status >= 200) && ($res->status <= 299)) {
@ -1525,7 +1526,7 @@ class DFRN
return; return;
} }
logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']); Logger::log('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
$bdtext = L10n::t('%s\'s birthday', $contact['name']); $bdtext = L10n::t('%s\'s birthday', $contact['name']);
$bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]'); $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
@ -1575,7 +1576,7 @@ class DFRN
$author["network"] = $contact_old["network"]; $author["network"] = $contact_old["network"];
} else { } else {
if (!$onlyfetch) { if (!$onlyfetch) {
logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG); Logger::log("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, Logger::DEBUG);
} }
$author["contact-unknown"] = true; $author["contact-unknown"] = true;
@ -1624,11 +1625,11 @@ class DFRN
} }
if (empty($author['avatar'])) { if (empty($author['avatar'])) {
logger('Empty author: ' . $xml); Logger::log('Empty author: ' . $xml);
} }
if (DBA::isResult($contact_old) && !$onlyfetch) { if (DBA::isResult($contact_old) && !$onlyfetch) {
logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG); Logger::log("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", Logger::DEBUG);
$poco = ["url" => $contact_old["url"]]; $poco = ["url" => $contact_old["url"]];
@ -1689,7 +1690,7 @@ class DFRN
// If the "hide" element is present then the profile isn't searchable. // If the "hide" element is present then the profile isn't searchable.
$hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true"); $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG); Logger::log("Hidden status for contact " . $contact_old["url"] . ": " . $hide, Logger::DEBUG);
// If the contact isn't searchable then set the contact to "hidden". // If the contact isn't searchable then set the contact to "hidden".
// Problem: This can be manually overridden by the user. // Problem: This can be manually overridden by the user.
@ -1761,20 +1762,20 @@ class DFRN
$contact[$field] = DateTimeFormat::utc($contact[$field]); $contact[$field] = DateTimeFormat::utc($contact[$field]);
if (strtotime($contact[$field]) > strtotime($contact_old[$field])) { if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG); Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
$update = true; $update = true;
} }
} }
foreach ($fields as $field => $data) { foreach ($fields as $field => $data) {
if ($contact[$field] != $contact_old[$field]) { if ($contact[$field] != $contact_old[$field]) {
logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG); Logger::log("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", Logger::DEBUG);
$update = true; $update = true;
} }
} }
if ($update) { if ($update) {
logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG); Logger::log("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", Logger::DEBUG);
q( q(
"UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s', "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
@ -1881,7 +1882,7 @@ class DFRN
*/ */
private static function processMail($xpath, $mail, $importer) private static function processMail($xpath, $mail, $importer)
{ {
logger("Processing mails"); Logger::log("Processing mails");
/// @TODO Rewrite this to one statement /// @TODO Rewrite this to one statement
$msg = []; $msg = [];
@ -1921,7 +1922,7 @@ class DFRN
notification($notif_params); notification($notif_params);
logger("Mail is processed, notification was sent."); Logger::log("Mail is processed, notification was sent.");
} }
/** /**
@ -1937,7 +1938,7 @@ class DFRN
{ {
$a = get_app(); $a = get_app();
logger("Processing suggestions"); Logger::log("Processing suggestions");
/// @TODO Rewrite this to one statement /// @TODO Rewrite this to one statement
$suggest = []; $suggest = [];
@ -2053,7 +2054,7 @@ class DFRN
*/ */
private static function processRelocation($xpath, $relocation, $importer) private static function processRelocation($xpath, $relocation, $importer)
{ {
logger("Processing relocations"); Logger::log("Processing relocations");
/// @TODO Rewrite this to one statement /// @TODO Rewrite this to one statement
$relocate = []; $relocate = [];
@ -2088,7 +2089,7 @@ class DFRN
); );
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
logger("Query failed to execute, no result returned in " . __FUNCTION__); Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
return false; return false;
} }
@ -2115,7 +2116,7 @@ class DFRN
Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true); Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
logger('Contacts are updated.'); Logger::log('Contacts are updated.');
/// @TODO /// @TODO
/// merge with current record, current contents have priority /// merge with current record, current contents have priority
@ -2174,7 +2175,7 @@ class DFRN
if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) { if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
$sql_extra = ""; $sql_extra = "";
$community = true; $community = true;
logger("possible community action"); Logger::log("possible community action");
} else { } else {
$sql_extra = " AND `contact`.`self` AND `item`.`wall` "; $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
} }
@ -2211,7 +2212,7 @@ class DFRN
*/ */
if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) { if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
$is_a_remote_action = false; $is_a_remote_action = false;
logger("not a community action"); Logger::log("not a community action");
} }
if ($is_a_remote_action) { if ($is_a_remote_action) {
@ -2298,7 +2299,7 @@ class DFRN
*/ */
private static function processVerbs($entrytype, $importer, &$item, &$is_like) private static function processVerbs($entrytype, $importer, &$item, &$is_like)
{ {
logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG); Logger::log("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, Logger::DEBUG);
if (($entrytype == DFRN::TOP_LEVEL)) { if (($entrytype == DFRN::TOP_LEVEL)) {
// The filling of the the "contact" variable is done for legcy reasons // The filling of the the "contact" variable is done for legcy reasons
@ -2310,22 +2311,22 @@ class DFRN
// Big question: Do we need these functions? They were part of the "consume_feed" function. // Big question: Do we need these functions? They were part of the "consume_feed" function.
// This function once was responsible for DFRN and OStatus. // This function once was responsible for DFRN and OStatus.
if (activity_match($item["verb"], ACTIVITY_FOLLOW)) { if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
logger("New follower"); Logger::log("New follower");
Contact::addRelationship($importer, $contact, $item, $nickname); Contact::addRelationship($importer, $contact, $item, $nickname);
return false; return false;
} }
if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) { if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
logger("Lost follower"); Logger::log("Lost follower");
Contact::removeFollower($importer, $contact, $item); Contact::removeFollower($importer, $contact, $item);
return false; return false;
} }
if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) { if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
logger("New friend request"); Logger::log("New friend request");
Contact::addRelationship($importer, $contact, $item, $nickname, true); Contact::addRelationship($importer, $contact, $item, $nickname, true);
return false; return false;
} }
if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) { if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
logger("Lost sharer"); Logger::log("Lost sharer");
Contact::removeSharer($importer, $contact, $item); Contact::removeSharer($importer, $contact, $item);
return false; return false;
} }
@ -2369,7 +2370,7 @@ class DFRN
$item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]); $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
if (!DBA::isResult($item_tag)) { if (!DBA::isResult($item_tag)) {
logger("Query failed to execute, no result returned in " . __FUNCTION__); Logger::log("Query failed to execute, no result returned in " . __FUNCTION__);
return false; return false;
} }
@ -2445,7 +2446,7 @@ class DFRN
*/ */
private static function processEntry($header, $xpath, $entry, $importer, $xml) private static function processEntry($header, $xpath, $entry, $importer, $xml)
{ {
logger("Processing entries"); Logger::log("Processing entries");
$item = $header; $item = $header;
@ -2463,7 +2464,7 @@ class DFRN
); );
// Is there an existing item? // Is there an existing item?
if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) { if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG); Logger::log("Item ".$item["uri"]." (".$item['edited'].") already existed.", Logger::DEBUG);
return; return;
} }
@ -2671,10 +2672,10 @@ class DFRN
// Is it an event? // Is it an event?
if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) { if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG); Logger::log("Item ".$item["uri"]." seems to contain an event.", Logger::DEBUG);
$ev = Event::fromBBCode($item["body"]); $ev = Event::fromBBCode($item["body"]);
if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) { if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG); Logger::log("Event in item ".$item["uri"]." was found.", Logger::DEBUG);
$ev["cid"] = $importer["id"]; $ev["cid"] = $importer["id"];
$ev["uid"] = $importer["importer_uid"]; $ev["uid"] = $importer["importer_uid"];
$ev["uri"] = $item["uri"]; $ev["uri"] = $item["uri"];
@ -2690,20 +2691,20 @@ class DFRN
} }
$event_id = Event::store($ev); $event_id = Event::store($ev);
logger("Event ".$event_id." was stored", LOGGER_DEBUG); Logger::log("Event ".$event_id." was stored", Logger::DEBUG);
return; return;
} }
} }
} }
if (!self::processVerbs($entrytype, $importer, $item, $is_like)) { if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG); Logger::log("Exiting because 'processVerbs' told us so", Logger::DEBUG);
return; return;
} }
// This check is done here to be able to receive connection requests in "processVerbs" // This check is done here to be able to receive connection requests in "processVerbs"
if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) { if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG); Logger::log("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", Logger::DEBUG);
return; return;
} }
@ -2711,9 +2712,9 @@ class DFRN
// Update content if 'updated' changes // Update content if 'updated' changes
if (DBA::isResult($current)) { if (DBA::isResult($current)) {
if (self::updateContent($current, $item, $importer, $entrytype)) { if (self::updateContent($current, $item, $importer, $entrytype)) {
logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG); Logger::log("Item ".$item["uri"]." was updated.", Logger::DEBUG);
} else { } else {
logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG); Logger::log("Item " . $item["uri"] . " already existed.", Logger::DEBUG);
} }
return; return;
} }
@ -2723,7 +2724,7 @@ class DFRN
$parent = 0; $parent = 0;
if ($posted_id) { if ($posted_id) {
logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG); Logger::log("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, Logger::DEBUG);
if ($item['uid'] == 0) { if ($item['uid'] == 0) {
Item::distribute($posted_id); Item::distribute($posted_id);
@ -2733,7 +2734,7 @@ class DFRN
} }
} else { // $entrytype == DFRN::TOP_LEVEL } else { // $entrytype == DFRN::TOP_LEVEL
if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) { if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG); Logger::log("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", Logger::DEBUG);
return; return;
} }
if (!link_compare($item["owner-link"], $importer["url"])) { if (!link_compare($item["owner-link"], $importer["url"])) {
@ -2743,13 +2744,13 @@ class DFRN
* the tgroup delivery code called from Item::insert will correct it if it's a forum, * the tgroup delivery code called from Item::insert will correct it if it's a forum,
* but we're going to unconditionally correct it here so that the post will always be owned by our contact. * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
*/ */
logger('Correcting item owner.', LOGGER_DEBUG); Logger::log('Correcting item owner.', Logger::DEBUG);
$item["owner-link"] = $importer["url"]; $item["owner-link"] = $importer["url"];
$item["owner-id"] = Contact::getIdForURL($importer["url"], 0); $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
} }
if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) { if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG); Logger::log("Contact ".$importer["id"]." is only follower and tgroup check was negative.", Logger::DEBUG);
return; return;
} }
@ -2763,7 +2764,7 @@ class DFRN
$posted_id = $notify; $posted_id = $notify;
} }
logger("Item was stored with id ".$posted_id, LOGGER_DEBUG); Logger::log("Item was stored with id ".$posted_id, Logger::DEBUG);
if ($item['uid'] == 0) { if ($item['uid'] == 0) {
Item::distribute($posted_id); Item::distribute($posted_id);
@ -2786,7 +2787,7 @@ class DFRN
*/ */
private static function processDeletion($xpath, $deletion, $importer) private static function processDeletion($xpath, $deletion, $importer)
{ {
logger("Processing deletions"); Logger::log("Processing deletions");
$uri = null; $uri = null;
foreach ($deletion->attributes as $attributes) { foreach ($deletion->attributes as $attributes) {
@ -2802,18 +2803,18 @@ class DFRN
$condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]]; $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
$item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition); $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG); Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", Logger::DEBUG);
return; return;
} }
if (strstr($item['file'], '[')) { if (strstr($item['file'], '[')) {
logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG); Logger::log("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", Logger::DEBUG);
return; return;
} }
// When it is a starting post it has to belong to the person that wants to delete it // When it is a starting post it has to belong to the person that wants to delete it
if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) { if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG); Logger::log("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
return; return;
} }
@ -2821,7 +2822,7 @@ class DFRN
if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) { if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
$condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]]; $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
if (!Item::exists($condition)) { if (!Item::exists($condition)) {
logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG); Logger::log("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", Logger::DEBUG);
return; return;
} }
} }
@ -2830,7 +2831,7 @@ class DFRN
return; return;
} }
logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG); Logger::log('deleting item '.$item['id'].' uri='.$uri, Logger::DEBUG);
Item::delete(['id' => $item['id']]); Item::delete(['id' => $item['id']]);
} }
@ -2884,7 +2885,7 @@ class DFRN
self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml); self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
} }
logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG); Logger::log("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
// is it a public forum? Private forums aren't exposed with this method // is it a public forum? Private forums aren't exposed with this method
$forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()")); $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
@ -2950,7 +2951,7 @@ class DFRN
self::processEntry($header, $xpath, $entry, $importer, $xml); self::processEntry($header, $xpath, $entry, $importer, $xml);
} }
} }
logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG); Logger::log("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], Logger::DEBUG);
return 200; return 200;
} }
@ -3035,7 +3036,7 @@ class DFRN
$url = curPageURL(); $url = curPageURL();
logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG); Logger::log('auto_redir: ' . $r[0]['name'] . ' ' . $sec, Logger::DEBUG);
$dest = (($url) ? '&destination_url=' . $url : ''); $dest = (($url) ? '&destination_url=' . $url : '');
System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id System::externalRedirect($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
. '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest); . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
@ -3090,7 +3091,7 @@ class DFRN
foreach ($matches as $mtch) { foreach ($matches as $mtch) {
if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) { if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
$mention = true; $mention = true;
logger('mention found: ' . $mtch[2]); Logger::log('mention found: ' . $mtch[2]);
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -4,6 +4,7 @@
*/ */
namespace Friendica\Protocol; namespace Friendica\Protocol;
use Friendica\Core\Logger;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
@ -28,12 +29,12 @@ class Email
$errors = imap_errors(); $errors = imap_errors();
if (!empty($errors)) { if (!empty($errors)) {
logger('IMAP Errors occured: ' . json_encode($errors)); Logger::log('IMAP Errors occured: ' . json_encode($errors));
} }
$alerts = imap_alerts(); $alerts = imap_alerts();
if (!empty($alerts)) { if (!empty($alerts)) {
logger('IMAP Alerts occured: ' . json_encode($alerts)); Logger::log('IMAP Alerts occured: ' . json_encode($alerts));
} }
return $mbox; return $mbox;
@ -54,21 +55,21 @@ class Email
if (!$search1) { if (!$search1) {
$search1 = []; $search1 = [];
} else { } else {
logger("Found mails from ".$email_addr, LOGGER_DEBUG); Logger::log("Found mails from ".$email_addr, Logger::DEBUG);
} }
$search2 = @imap_search($mbox, 'TO "' . $email_addr . '"', SE_UID); $search2 = @imap_search($mbox, 'TO "' . $email_addr . '"', SE_UID);
if (!$search2) { if (!$search2) {
$search2 = []; $search2 = [];
} else { } else {
logger("Found mails to ".$email_addr, LOGGER_DEBUG); Logger::log("Found mails to ".$email_addr, Logger::DEBUG);
} }
$search3 = @imap_search($mbox, 'CC "' . $email_addr . '"', SE_UID); $search3 = @imap_search($mbox, 'CC "' . $email_addr . '"', SE_UID);
if (!$search3) { if (!$search3) {
$search3 = []; $search3 = [];
} else { } else {
logger("Found mails cc ".$email_addr, LOGGER_DEBUG); Logger::log("Found mails cc ".$email_addr, Logger::DEBUG);
} }
$res = array_unique(array_merge($search1, $search2, $search3)); $res = array_unique(array_merge($search1, $search2, $search3));
@ -351,7 +352,7 @@ class Email
//$message = '<html><body>' . $html . '</body></html>'; //$message = '<html><body>' . $html . '</body></html>';
//$message = html2plain($html); //$message = html2plain($html);
logger('notifier: email delivery to ' . $addr); Logger::log('notifier: email delivery to ' . $addr);
mail($addr, $subject, $body, $headers); mail($addr, $subject, $body, $headers);
} }

View file

@ -9,6 +9,7 @@ namespace Friendica\Protocol;
use DOMDocument; use DOMDocument;
use DOMXPath; use DOMXPath;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -40,12 +41,12 @@ class Feed {
$a = get_app(); $a = get_app();
if (!$simulate) { if (!$simulate) {
logger("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], LOGGER_DEBUG); Logger::log("Import Atom/RSS feed '".$contact["name"]."' (Contact ".$contact["id"].") for user ".$importer["uid"], Logger::DEBUG);
} else { } else {
logger("Test Atom/RSS feed", LOGGER_DEBUG); Logger::log("Test Atom/RSS feed", Logger::DEBUG);
} }
if (empty($xml)) { if (empty($xml)) {
logger('XML is empty.', LOGGER_DEBUG); Logger::log('XML is empty.', Logger::DEBUG);
return; return;
} }
@ -199,7 +200,7 @@ class Feed {
$header["contact-id"] = $contact["id"]; $header["contact-id"] = $contact["id"];
if (!is_object($entries)) { if (!is_object($entries)) {
logger("There are no entries in this feed.", LOGGER_DEBUG); Logger::log("There are no entries in this feed.", Logger::DEBUG);
return; return;
} }
@ -248,7 +249,7 @@ class Feed {
$importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN]; $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
$previous = Item::selectFirst(['id'], $condition); $previous = Item::selectFirst(['id'], $condition);
if (DBA::isResult($previous)) { if (DBA::isResult($previous)) {
logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], LOGGER_DEBUG); Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$previous["id"], Logger::DEBUG);
continue; continue;
} }
} }
@ -423,7 +424,7 @@ class Feed {
} }
if (!$simulate) { if (!$simulate) {
logger("Stored feed: ".print_r($item, true), LOGGER_DEBUG); Logger::log("Stored feed: ".print_r($item, true), Logger::DEBUG);
$notify = Item::isRemoteSelf($contact, $item); $notify = Item::isRemoteSelf($contact, $item);
@ -440,7 +441,7 @@ class Feed {
$id = Item::insert($item, false, $notify); $id = Item::insert($item, false, $notify);
logger("Feed for contact ".$contact["url"]." stored under id ".$id); Logger::log("Feed for contact ".$contact["url"]." stored under id ".$id);
} else { } else {
$items[] = $item; $items[] = $item;
} }

View file

@ -11,6 +11,7 @@ use Friendica\Content\Text\HTML;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\L10n; use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\Lock; use Friendica\Core\Lock;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\System; use Friendica\Core\System;
@ -195,7 +196,7 @@ class OStatus
DBA::update('contact', $contact, ['id' => $contact["id"]], $current); DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) { if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG); Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]); Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
} }
@ -322,7 +323,7 @@ class OStatus
self::$conv_list = []; self::$conv_list = [];
} }
logger('Import OStatus message for user ' . $importer['uid'], LOGGER_DEBUG); Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
if ($xml == "") { if ($xml == "") {
return false; return false;
@ -348,7 +349,7 @@ class OStatus
foreach ($hub_attributes as $hub_attribute) { foreach ($hub_attributes as $hub_attribute) {
if ($hub_attribute->name == "href") { if ($hub_attribute->name == "href") {
$hub = $hub_attribute->textContent; $hub = $hub_attribute->textContent;
logger("Found hub ".$hub, LOGGER_DEBUG); Logger::log("Found hub ".$hub, Logger::DEBUG);
} }
} }
} }
@ -433,27 +434,27 @@ class OStatus
if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) { if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
// Ignore "Unfavorite" message // Ignore "Unfavorite" message
logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG); Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
continue; continue;
} }
// Deletions come with the same uri, so we check for duplicates after processing deletions // Deletions come with the same uri, so we check for duplicates after processing deletions
if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) { if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG); Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
continue; continue;
} else { } else {
logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG); Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
} }
if ($item["verb"] == ACTIVITY_JOIN) { if ($item["verb"] == ACTIVITY_JOIN) {
// ignore "Join" messages // ignore "Join" messages
logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG); Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
continue; continue;
} }
if ($item["verb"] == "http://mastodon.social/schema/1.0/block") { if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
// ignore mastodon "block" messages // ignore mastodon "block" messages
logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG); Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
continue; continue;
} }
@ -470,7 +471,7 @@ class OStatus
if ($item["verb"] == ACTIVITY_FAVORITE) { if ($item["verb"] == ACTIVITY_FAVORITE) {
$orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue; $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
logger("Favorite ".$orig_uri." ".print_r($item, true)); Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
$item["verb"] = ACTIVITY_LIKE; $item["verb"] = ACTIVITY_LIKE;
$item["parent-uri"] = $orig_uri; $item["parent-uri"] = $orig_uri;
@ -480,7 +481,7 @@ class OStatus
// http://activitystrea.ms/schema/1.0/rsvp-yes // http://activitystrea.ms/schema/1.0/rsvp-yes
if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) { if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG); Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
} }
self::processPost($xpath, $entry, $item, $importer); self::processPost($xpath, $entry, $item, $importer);
@ -493,10 +494,10 @@ class OStatus
// If not, then it depends on this setting // If not, then it depends on this setting
$valid = !Config::get('system', 'ostatus_full_threads'); $valid = !Config::get('system', 'ostatus_full_threads');
if ($valid) { if ($valid) {
logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG); Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
} }
} else { } else {
logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG); Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
} }
if ($valid) { if ($valid) {
// Never post a thread when the only interaction by our contact was a like // Never post a thread when the only interaction by our contact was a like
@ -508,14 +509,14 @@ class OStatus
} }
} }
if ($valid) { if ($valid) {
logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG); Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
} }
} }
} else { } else {
// But we will only import complete threads // But we will only import complete threads
$valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]); $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
if ($valid) { if ($valid) {
logger("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", LOGGER_DEBUG); Logger::log("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", Logger::DEBUG);
} }
} }
@ -532,25 +533,25 @@ class OStatus
foreach (self::$itemlist as $item) { foreach (self::$itemlist as $item) {
$found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]); $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
if ($found) { if ($found) {
logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG); Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
} elseif ($item['contact-id'] < 0) { } elseif ($item['contact-id'] < 0) {
logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG); Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
} else { } else {
// We are having duplicated entries. Hopefully this solves it. // We are having duplicated entries. Hopefully this solves it.
if (Lock::acquire('ostatus_process_item_insert')) { if (Lock::acquire('ostatus_process_item_insert')) {
$ret = Item::insert($item); $ret = Item::insert($item);
Lock::release('ostatus_process_item_insert'); Lock::release('ostatus_process_item_insert');
logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret); Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
} else { } else {
$ret = Item::insert($item); $ret = Item::insert($item);
logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret); Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
} }
} }
} }
} }
self::$itemlist = []; self::$itemlist = [];
} }
logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG); Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
} }
return true; return true;
} }
@ -564,13 +565,13 @@ class OStatus
{ {
$condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']]; $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
if (!Item::exists($condition)) { if (!Item::exists($condition)) {
logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it."); Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
return; return;
} }
Item::delete($condition); Item::delete($condition);
logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']); Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
} }
/** /**
@ -706,7 +707,7 @@ class OStatus
self::fetchRelated($related, $item["parent-uri"], $importer); self::fetchRelated($related, $item["parent-uri"], $importer);
} }
} else { } else {
logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG); Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
} }
} else { } else {
$item["parent-uri"] = $item["uri"]; $item["parent-uri"] = $item["uri"];
@ -852,11 +853,11 @@ class OStatus
$condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED]; $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
if (DBA::exists('conversation', $condition)) { if (DBA::exists('conversation', $condition)) {
logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG); Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
DBA::delete('conversation', ['item-uri' => $conv_data['uri']]); DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
} }
logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG); Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
Conversation::insert($conv_data); Conversation::insert($conv_data);
} }
} }
@ -876,7 +877,7 @@ class OStatus
{ {
$condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON]; $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
if (DBA::exists('conversation', $condition)) { if (DBA::exists('conversation', $condition)) {
logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG); Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
return; return;
} }
@ -896,7 +897,7 @@ class OStatus
$item["protocol"] = Conversation::PARCEL_SALMON; $item["protocol"] = Conversation::PARCEL_SALMON;
$item["source"] = $xml; $item["source"] = $xml;
logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG); Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
} }
/** /**
@ -915,11 +916,11 @@ class OStatus
$stored = true; $stored = true;
$xml = $conversation['source']; $xml = $conversation['source'];
if (self::process($xml, $importer, $contact, $hub, $stored, false)) { if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG); Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
return; return;
} }
if ($conversation['protocol'] == Conversation::PARCEL_SALMON) { if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG); Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
DBA::delete('conversation', ['item-uri' => $related_uri]); DBA::delete('conversation', ['item-uri' => $related_uri]);
} }
} }
@ -934,7 +935,7 @@ class OStatus
$xml = ''; $xml = '';
if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) { if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
logger('Directly fetched XML for URI ' . $related_uri, LOGGER_DEBUG); Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
$xml = $curlResult->getBody(); $xml = $curlResult->getBody();
} }
@ -959,7 +960,7 @@ class OStatus
$curlResult = Network::curl($atom_file); $curlResult = Network::curl($atom_file);
if ($curlResult->isSuccess()) { if ($curlResult->isSuccess()) {
logger('Fetched XML for URI ' . $related_uri, LOGGER_DEBUG); Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
$xml = $curlResult->getBody(); $xml = $curlResult->getBody();
} }
} }
@ -971,7 +972,7 @@ class OStatus
$curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom'); $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
if ($curlResult->isSuccess()) { if ($curlResult->isSuccess()) {
logger('GNU Social workaround to fetch XML for URI ' . $related_uri, LOGGER_DEBUG); Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
$xml = $curlResult->getBody(); $xml = $curlResult->getBody();
} }
} }
@ -982,7 +983,7 @@ class OStatus
$curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom'); $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
if ($curlResult->isSuccess()) { if ($curlResult->isSuccess()) {
logger('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, LOGGER_DEBUG); Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
$xml = $curlResult->getBody(); $xml = $curlResult->getBody();
} }
} }
@ -993,7 +994,7 @@ class OStatus
$conversation = DBA::selectFirst('conversation', ['source'], $condition); $conversation = DBA::selectFirst('conversation', ['source'], $condition);
if (DBA::isResult($conversation)) { if (DBA::isResult($conversation)) {
$stored = true; $stored = true;
logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG); Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
$xml = $conversation['source']; $xml = $conversation['source'];
} }
} }
@ -1001,7 +1002,7 @@ class OStatus
if ($xml != '') { if ($xml != '') {
self::process($xml, $importer, $contact, $hub, $stored, false); self::process($xml, $importer, $contact, $hub, $stored, false);
} else { } else {
logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG); Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
} }
return; return;
} }
@ -1651,7 +1652,7 @@ class OStatus
private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel) private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
{ {
if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) { if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG); Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
} }
$title = self::entryHeader($doc, $entry, $owner, $item, $toplevel); $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
@ -1714,7 +1715,7 @@ class OStatus
private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel) private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
{ {
if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) { if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG); Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
} }
$title = self::entryHeader($doc, $entry, $owner, $item, $toplevel); $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
@ -1861,7 +1862,7 @@ class OStatus
private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel) private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
{ {
if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) { if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG); Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
} }
$title = self::entryHeader($doc, $entry, $owner, $item, $toplevel); $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
@ -2152,7 +2153,7 @@ class OStatus
if ((time() - strtotime($owner['last-item'])) < 15*60) { if ((time() - strtotime($owner['last-item'])) < 15*60) {
$result = Cache::get($cachekey); $result = Cache::get($cachekey);
if (!$nocache && !is_null($result)) { if (!$nocache && !is_null($result)) {
logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG); Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
$last_update = $result['last_update']; $last_update = $result['last_update'];
return $result['feed']; return $result['feed'];
} }
@ -2212,7 +2213,7 @@ class OStatus
$msg = ['feed' => $feeddata, 'last_update' => $last_update]; $msg = ['feed' => $feeddata, 'last_update' => $last_update];
Cache::set($cachekey, $msg, Cache::QUARTER_HOUR); Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG); Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
return $feeddata; return $feeddata;
} }

View file

@ -14,6 +14,7 @@ use DOMXPath;
use Exception; use Exception;
use Friendica\Content\Text\HTML; use Friendica\Content\Text\HTML;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\Protocol; use Friendica\Core\Protocol;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
@ -84,14 +85,14 @@ class PortableContact
$url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ; $url = $url . (($uid) ? '/@me/@all?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation' : '?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation') ;
logger('load: ' . $url, LOGGER_DEBUG); Logger::log('load: ' . $url, Logger::DEBUG);
$fetchresult = Network::fetchUrlFull($url); $fetchresult = Network::fetchUrlFull($url);
$s = $fetchresult->getBody(); $s = $fetchresult->getBody();
logger('load: returns ' . $s, LOGGER_DATA); Logger::log('load: returns ' . $s, Logger::DATA);
logger('load: return code: ' . $fetchresult->getReturnCode(), LOGGER_DEBUG); Logger::log('load: return code: ' . $fetchresult->getReturnCode(), Logger::DEBUG);
if (($fetchresult->getReturnCode() > 299) || (! $s)) { if (($fetchresult->getReturnCode() > 299) || (! $s)) {
return; return;
@ -99,7 +100,7 @@ class PortableContact
$j = json_decode($s, true); $j = json_decode($s, true);
logger('load: json: ' . print_r($j, true), LOGGER_DATA); Logger::log('load: json: ' . print_r($j, true), Logger::DATA);
if (!isset($j['entry'])) { if (!isset($j['entry'])) {
return; return;
@ -199,10 +200,10 @@ class PortableContact
GContact::link($gcid, $uid, $cid, $zcid); GContact::link($gcid, $uid, $cid, $zcid);
} catch (Exception $e) { } catch (Exception $e) {
logger($e->getMessage(), LOGGER_DEBUG); Logger::log($e->getMessage(), Logger::DEBUG);
} }
} }
logger("load: loaded $total entries", LOGGER_DEBUG); Logger::log("load: loaded $total entries", Logger::DEBUG);
$condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid]; $condition = ["`cid` = ? AND `uid` = ? AND `zcid` = ? AND `updated` < UTC_TIMESTAMP - INTERVAL 2 DAY", $cid, $uid, $zcid];
DBA::delete('glink', $condition); DBA::delete('glink', $condition);
@ -335,7 +336,7 @@ class PortableContact
} }
if (!in_array($gcontacts[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) { if (!in_array($gcontacts[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG); Logger::log("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", Logger::DEBUG);
return false; return false;
} }
@ -346,7 +347,7 @@ class PortableContact
DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]); DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
} }
logger("Profile ".$profile.": Server ".$server_url." wasn't reachable.", LOGGER_DEBUG); Logger::log("Profile ".$profile.": Server ".$server_url." wasn't reachable.", Logger::DEBUG);
return false; return false;
} }
$contact['server_url'] = $server_url; $contact['server_url'] = $server_url;
@ -426,7 +427,7 @@ class PortableContact
$fields = ['last_contact' => DateTimeFormat::utcNow()]; $fields = ['last_contact' => DateTimeFormat::utcNow()];
DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]); DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
logger("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", LOGGER_DEBUG); Logger::log("Profile ".$profile." was last updated at ".$noscrape["updated"]." (noscrape)", Logger::DEBUG);
return $noscrape["updated"]; return $noscrape["updated"];
} }
@ -437,7 +438,7 @@ class PortableContact
// If we only can poll the feed, then we only do this once a while // If we only can poll the feed, then we only do this once a while
if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) { if (!$force && !self::updateNeeded($gcontacts[0]["created"], $gcontacts[0]["updated"], $gcontacts[0]["last_failure"], $gcontacts[0]["last_contact"])) {
logger("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", LOGGER_DEBUG); Logger::log("Profile ".$profile." was last updated at ".$gcontacts[0]["updated"]." (cached)", Logger::DEBUG);
GContact::update($contact); GContact::update($contact);
return $gcontacts[0]["updated"]; return $gcontacts[0]["updated"];
@ -464,10 +465,10 @@ class PortableContact
self::lastUpdated($data["url"], $force); self::lastUpdated($data["url"], $force);
} catch (Exception $e) { } catch (Exception $e) {
logger($e->getMessage(), LOGGER_DEBUG); Logger::log($e->getMessage(), Logger::DEBUG);
} }
logger("Profile ".$profile." was deleted", LOGGER_DEBUG); Logger::log("Profile ".$profile." was deleted", Logger::DEBUG);
return false; return false;
} }
@ -475,7 +476,7 @@ class PortableContact
$fields = ['last_failure' => DateTimeFormat::utcNow()]; $fields = ['last_failure' => DateTimeFormat::utcNow()];
DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]); DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
logger("Profile ".$profile." wasn't reachable (profile)", LOGGER_DEBUG); Logger::log("Profile ".$profile." wasn't reachable (profile)", Logger::DEBUG);
return false; return false;
} }
@ -491,7 +492,7 @@ class PortableContact
$fields = ['last_failure' => DateTimeFormat::utcNow()]; $fields = ['last_failure' => DateTimeFormat::utcNow()];
DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]); DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
logger("Profile ".$profile." wasn't reachable (no feed)", LOGGER_DEBUG); Logger::log("Profile ".$profile." wasn't reachable (no feed)", Logger::DEBUG);
return false; return false;
} }
@ -539,7 +540,7 @@ class PortableContact
DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]); DBA::update('gcontact', $fields, ['nurl' => normalise_link($profile)]);
} }
logger("Profile ".$profile." was last updated at ".$last_updated, LOGGER_DEBUG); Logger::log("Profile ".$profile." was last updated at ".$last_updated, Logger::DEBUG);
return $last_updated; return $last_updated;
} }
@ -662,7 +663,7 @@ class PortableContact
foreach ($nodeinfo['links'] as $link) { foreach ($nodeinfo['links'] as $link) {
if (!is_array($link) || empty($link['rel'])) { if (!is_array($link) || empty($link['rel'])) {
logger('Invalid nodeinfo format for ' . $server_url, LOGGER_DEBUG); Logger::log('Invalid nodeinfo format for ' . $server_url, Logger::DEBUG);
continue; continue;
} }
if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') { if ($link['rel'] == 'http://nodeinfo.diaspora.software/ns/schema/1.0') {
@ -963,7 +964,7 @@ class PortableContact
} }
if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) { if (!$force && !self::updateNeeded($gserver["created"], "", $last_failure, $last_contact)) {
logger("Use cached data for server ".$server_url, LOGGER_DEBUG); Logger::log("Use cached data for server ".$server_url, Logger::DEBUG);
return ($last_contact >= $last_failure); return ($last_contact >= $last_failure);
} }
} else { } else {
@ -979,7 +980,7 @@ class PortableContact
$last_contact = DBA::NULL_DATETIME; $last_contact = DBA::NULL_DATETIME;
$last_failure = DBA::NULL_DATETIME; $last_failure = DBA::NULL_DATETIME;
} }
logger("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, LOGGER_DEBUG); Logger::log("Server ".$server_url." is outdated or unknown. Start discovery. Force: ".$force." Created: ".$gserver["created"]." Failure: ".$last_failure." Contact: ".$last_contact, Logger::DEBUG);
$failure = false; $failure = false;
$possible_failure = false; $possible_failure = false;
@ -1004,7 +1005,7 @@ class PortableContact
// But we want to make sure to only quit if we are mostly sure that this server url fits. // But we want to make sure to only quit if we are mostly sure that this server url fits.
if (DBA::isResult($gserver) && ($orig_server_url == $server_url) && if (DBA::isResult($gserver) && ($orig_server_url == $server_url) &&
($curlResult->isTimeout())) { ($curlResult->isTimeout())) {
logger("Connection to server ".$server_url." timed out.", LOGGER_DEBUG); Logger::log("Connection to server ".$server_url." timed out.", Logger::DEBUG);
DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]); DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
return false; return false;
} }
@ -1019,7 +1020,7 @@ class PortableContact
// Quit if there is a timeout // Quit if there is a timeout
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
logger("Connection to server " . $server_url . " timed out.", LOGGER_DEBUG); Logger::log("Connection to server " . $server_url . " timed out.", Logger::DEBUG);
DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]); DBA::update('gserver', ['last_failure' => DateTimeFormat::utcNow()], ['nurl' => normalise_link($server_url)]);
return false; return false;
} }
@ -1398,9 +1399,9 @@ class PortableContact
} }
if (($last_contact <= $last_failure) && !$failure) { if (($last_contact <= $last_failure) && !$failure) {
logger("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", LOGGER_DEBUG); Logger::log("Server ".$server_url." seems to be alive, but last contact wasn't set - could be a bug", Logger::DEBUG);
} elseif (($last_contact >= $last_failure) && $failure) { } elseif (($last_contact >= $last_failure) && $failure) {
logger("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", LOGGER_DEBUG); Logger::log("Server ".$server_url." seems to be dead, but last failure wasn't set - could be a bug", Logger::DEBUG);
} }
// Check again if the server exists // Check again if the server exists
@ -1429,7 +1430,7 @@ class PortableContact
self::discoverRelay($server_url); self::discoverRelay($server_url);
} }
logger("End discovery for server " . $server_url, LOGGER_DEBUG); Logger::log("End discovery for server " . $server_url, Logger::DEBUG);
return !$failure; return !$failure;
} }
@ -1441,7 +1442,7 @@ class PortableContact
*/ */
private static function discoverRelay($server_url) private static function discoverRelay($server_url)
{ {
logger("Discover relay data for server " . $server_url, LOGGER_DEBUG); Logger::log("Discover relay data for server " . $server_url, Logger::DEBUG);
$curlResult = Network::curl($server_url . "/.well-known/x-social-relay"); $curlResult = Network::curl($server_url . "/.well-known/x-social-relay");
@ -1557,7 +1558,7 @@ class PortableContact
$r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(normalise_link($server_url))); $r = q("SELECT `nurl` FROM `gserver` WHERE `nurl` = '%s'", DBA::escape(normalise_link($server_url)));
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
logger("Call server check for server ".$server_url, LOGGER_DEBUG); Logger::log("Call server check for server ".$server_url, Logger::DEBUG);
Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url); Worker::add(PRIORITY_LOW, "DiscoverPoCo", "server", $server_url);
} }
} }
@ -1642,7 +1643,7 @@ class PortableContact
// Fetch all users from the other server // Fetch all users from the other server
$url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation"; $url = $server["poco"] . "/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation";
logger("Fetch all users from the server " . $server["url"], LOGGER_DEBUG); Logger::log("Fetch all users from the server " . $server["url"], Logger::DEBUG);
$curlResult = Network::curl($url); $curlResult = Network::curl($url);
@ -1670,7 +1671,7 @@ class PortableContact
$curlResult = Network::curl($url); $curlResult = Network::curl($url);
if ($curlResult->isSuccess() && !empty($curlResult->getBody())) { if ($curlResult->isSuccess() && !empty($curlResult->getBody())) {
logger("Fetch all global contacts from the server " . $server["nurl"], LOGGER_DEBUG); Logger::log("Fetch all global contacts from the server " . $server["nurl"], Logger::DEBUG);
$data = json_decode($curlResult->getBody(), true); $data = json_decode($curlResult->getBody(), true);
if (!empty($data)) { if (!empty($data)) {
@ -1679,7 +1680,7 @@ class PortableContact
} }
if (!$success && (Config::get('system', 'poco_discovery') > 2)) { if (!$success && (Config::get('system', 'poco_discovery') > 2)) {
logger("Fetch contacts from users of the server " . $server["nurl"], LOGGER_DEBUG); Logger::log("Fetch contacts from users of the server " . $server["nurl"], Logger::DEBUG);
self::discoverServerUsers($data, $server); self::discoverServerUsers($data, $server);
} }
} }
@ -1732,7 +1733,7 @@ class PortableContact
continue; continue;
} }
logger('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], LOGGER_DEBUG); Logger::log('Update directory from server ' . $gserver['url'] . ' with ID ' . $gserver['id'], Logger::DEBUG);
Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']); Worker::add(PRIORITY_LOW, 'DiscoverPoCo', 'update_server_directory', (int) $gserver['id']);
if (!$complete && ( --$no_of_queries == 0)) { if (!$complete && ( --$no_of_queries == 0)) {
@ -1762,7 +1763,7 @@ class PortableContact
} }
if ($username != '') { if ($username != '') {
logger('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], LOGGER_DEBUG); Logger::log('Fetch contacts for the user ' . $username . ' from the server ' . $server['nurl'], Logger::DEBUG);
// Fetch all contacts from a given user from the other server // Fetch all contacts from a given user from the other server
$url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation'; $url = $server['poco'] . '/' . $username . '/?fields=displayName,urls,photos,updated,network,aboutMe,currentLocation,tags,gender,contactType,generation';
@ -1865,7 +1866,7 @@ class PortableContact
if ($generation > 0) { if ($generation > 0) {
$success = true; $success = true;
logger("Store profile ".$profile_url, LOGGER_DEBUG); Logger::log("Store profile ".$profile_url, Logger::DEBUG);
$gcontact = ["url" => $profile_url, $gcontact = ["url" => $profile_url,
"name" => $name, "name" => $name,
@ -1884,10 +1885,10 @@ class PortableContact
$gcontact = GContact::sanitize($gcontact); $gcontact = GContact::sanitize($gcontact);
GContact::update($gcontact); GContact::update($gcontact);
} catch (Exception $e) { } catch (Exception $e) {
logger($e->getMessage(), LOGGER_DEBUG); Logger::log($e->getMessage(), Logger::DEBUG);
} }
logger("Done for profile ".$profile_url, LOGGER_DEBUG); Logger::log("Done for profile ".$profile_url, Logger::DEBUG);
} }
} }
return $success; return $success;

View file

@ -4,6 +4,7 @@
*/ */
namespace Friendica\Protocol; namespace Friendica\Protocol;
use Friendica\Core\Logger;
use Friendica\Network\Probe; use Friendica\Network\Probe;
use Friendica\Util\Crypto; use Friendica\Util\Crypto;
use Friendica\Util\Network; use Friendica\Util\Network;
@ -25,7 +26,7 @@ class Salmon
{ {
$ret = []; $ret = [];
logger('Fetching salmon key for '.$uri); Logger::log('Fetching salmon key for '.$uri);
$arr = Probe::lrdd($uri); $arr = Probe::lrdd($uri);
@ -57,7 +58,7 @@ class Salmon
} }
logger('Key located: ' . print_r($ret, true)); Logger::log('Key located: ' . print_r($ret, true));
if (count($ret) == 1) { if (count($ret) == 1) {
// We only found one one key so we don't care if the hash matches. // We only found one one key so we don't care if the hash matches.
@ -94,12 +95,12 @@ class Salmon
} }
if (! $owner['sprvkey']) { if (! $owner['sprvkey']) {
logger(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.", Logger::log(sprintf("user '%s' (%d) does not have a salmon private key. Send failed.",
$owner['username'], $owner['uid'])); $owner['username'], $owner['uid']));
return; return;
} }
logger('slapper called for '.$url.'. Data: ' . $slap); Logger::log('slapper called for '.$url.'. Data: ' . $slap);
// create a magic envelope // create a magic envelope
@ -143,7 +144,7 @@ class Salmon
// check for success, e.g. 2xx // check for success, e.g. 2xx
if ($return_code > 299) { if ($return_code > 299) {
logger('GNU Social salmon failed. Falling back to compliant mode'); Logger::log('GNU Social salmon failed. Falling back to compliant mode');
// Now try the compliant mode that normally isn't used for GNU Social // Now try the compliant mode that normally isn't used for GNU Social
$xmldata = ["me:env" => ["me:data" => $data, $xmldata = ["me:env" => ["me:data" => $data,
@ -166,7 +167,7 @@ class Salmon
} }
if ($return_code > 299) { if ($return_code > 299) {
logger('compliant salmon failed. Falling back to old status.net'); Logger::log('compliant salmon failed. Falling back to old status.net');
// Last try. This will most likely fail as well. // Last try. This will most likely fail as well.
$xmldata = ["me:env" => ["me:data" => $data, $xmldata = ["me:env" => ["me:data" => $data,
@ -187,7 +188,7 @@ class Salmon
$return_code = $postResult->getReturnCode(); $return_code = $postResult->getReturnCode();
} }
logger('slapper for '.$url.' returned ' . $return_code); Logger::log('slapper for '.$url.' returned ' . $return_code);
if (! $return_code) { if (! $return_code) {
return -1; return -1;

View file

@ -6,6 +6,7 @@ namespace Friendica\Util;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use ASN_BASE; use ASN_BASE;
use ASNValue; use ASNValue;
@ -232,7 +233,7 @@ class Crypto
$result = openssl_pkey_new($openssl_options); $result = openssl_pkey_new($openssl_options);
if (empty($result)) { if (empty($result)) {
logger('new_keypair: failed'); Logger::log('new_keypair: failed');
return false; return false;
} }
@ -347,7 +348,7 @@ class Crypto
private static function encapsulateOther($data, $pubkey, $alg) private static function encapsulateOther($data, $pubkey, $alg)
{ {
if (!$pubkey) { if (!$pubkey) {
logger('no key. data: '.$data); Logger::log('no key. data: '.$data);
} }
$fn = 'encrypt' . strtoupper($alg); $fn = 'encrypt' . strtoupper($alg);
if (method_exists(__CLASS__, $fn)) { if (method_exists(__CLASS__, $fn)) {
@ -359,7 +360,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('RSA failed. ' . print_r($x[0], true)); Logger::log('RSA failed. ' . print_r($x[0], true));
} }
$result['alg'] = $alg; $result['alg'] = $alg;
@ -388,7 +389,7 @@ class Crypto
private static function encapsulateAes($data, $pubkey) private static function encapsulateAes($data, $pubkey)
{ {
if (!$pubkey) { if (!$pubkey) {
logger('aes_encapsulate: no key. data: ' . $data); Logger::log('aes_encapsulate: no key. data: ' . $data);
} }
$key = random_bytes(32); $key = random_bytes(32);
@ -399,7 +400,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('aes_encapsulate: RSA failed. ' . print_r($x[0], true)); Logger::log('aes_encapsulate: RSA failed. ' . print_r($x[0], true));
} }
$result['alg'] = 'aes256cbc'; $result['alg'] = 'aes256cbc';

View file

@ -6,6 +6,7 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Logger;
use DateTime; use DateTime;
use DateTimeZone; use DateTimeZone;
use Exception; use Exception;
@ -125,7 +126,7 @@ class DateTimeFormat
try { try {
$d = new DateTime($s, $from_obj); $d = new DateTime($s, $from_obj);
} catch (Exception $e) { } catch (Exception $e) {
logger('DateTimeFormat::convert: exception: ' . $e->getMessage()); Logger::log('DateTimeFormat::convert: exception: ' . $e->getMessage());
$d = new DateTime('now', $from_obj); $d = new DateTime('now', $from_obj);
} }

View file

@ -6,6 +6,7 @@ namespace Friendica\Util;
use Friendica\Core\Addon; use Friendica\Core\Addon;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Core\PConfig; use Friendica\Core\PConfig;
use Friendica\Protocol\Email; use Friendica\Protocol\Email;
@ -96,8 +97,8 @@ class Emailer
$hookdata['headers'], $hookdata['headers'],
$hookdata['parameters'] $hookdata['parameters']
); );
logger("header " . 'To: ' . $params['toEmail'] . "\n" . $messageHeader, LOGGER_DEBUG); Logger::log("header " . 'To: ' . $params['toEmail'] . "\n" . $messageHeader, Logger::DEBUG);
logger("return value " . (($res)?"true":"false"), LOGGER_DEBUG); Logger::log("return value " . (($res)?"true":"false"), Logger::DEBUG);
return $res; return $res;
} }
} }

View file

@ -7,6 +7,7 @@ namespace Friendica\Util;
use Friendica\BaseObject; use Friendica\BaseObject;
use Friendica\Core\Config; use Friendica\Core\Config;
use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Model\User; use Friendica\Model\User;
use Friendica\Model\APContact; use Friendica\Model\APContact;
@ -59,7 +60,7 @@ class HTTPSignature
$sig_block = self::parseSigheader($headers['authorization']); $sig_block = self::parseSigheader($headers['authorization']);
if (!$sig_block) { if (!$sig_block) {
logger('no signature provided.'); Logger::log('no signature provided.');
return $result; return $result;
} }
@ -89,7 +90,7 @@ class HTTPSignature
$key = $key($sig_block['keyId']); $key = $key($sig_block['keyId']);
} }
logger('Got keyID ' . $sig_block['keyId']); Logger::log('Got keyID ' . $sig_block['keyId']);
if (!$key) { if (!$key) {
return $result; return $result;
@ -97,7 +98,7 @@ class HTTPSignature
$x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm); $x = Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm);
logger('verified: ' . $x, LOGGER_DEBUG); Logger::log('verified: ' . $x, Logger::DEBUG);
if (!$x) { if (!$x) {
return $result; return $result;
@ -307,7 +308,7 @@ class HTTPSignature
$postResult = Network::post($target, $content, $headers); $postResult = Network::post($target, $content, $headers);
$return_code = $postResult->getReturnCode(); $return_code = $postResult->getReturnCode();
logger('Transmit to ' . $target . ' returned ' . $return_code); Logger::log('Transmit to ' . $target . ' returned ' . $return_code);
return ($return_code >= 200) && ($return_code <= 299); return ($return_code >= 200) && ($return_code <= 299);
} }
@ -432,12 +433,12 @@ class HTTPSignature
$profile = APContact::getByURL($url); $profile = APContact::getByURL($url);
if (!empty($profile)) { if (!empty($profile)) {
logger('Taking key from id ' . $id, LOGGER_DEBUG); Logger::log('Taking key from id ' . $id, Logger::DEBUG);
return ['url' => $url, 'pubkey' => $profile['pubkey']]; return ['url' => $url, 'pubkey' => $profile['pubkey']];
} elseif ($url != $actor) { } elseif ($url != $actor) {
$profile = APContact::getByURL($actor); $profile = APContact::getByURL($actor);
if (!empty($profile)) { if (!empty($profile)) {
logger('Taking key from actor ' . $actor, LOGGER_DEBUG); Logger::log('Taking key from actor ' . $actor, Logger::DEBUG);
return ['url' => $actor, 'pubkey' => $profile['pubkey']]; return ['url' => $actor, 'pubkey' => $profile['pubkey']];
} }
} }

View file

@ -5,6 +5,7 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Cache; use Friendica\Core\Cache;
use Friendica\Core\Logger;
use Exception; use Exception;
/** /**
@ -33,7 +34,7 @@ class JsonLD
} }
if ($recursion > 5) { if ($recursion > 5) {
logger('jsonld bomb detected at: ' . $url); Logger::log('jsonld bomb detected at: ' . $url);
exit(); exit();
} }
@ -65,7 +66,7 @@ class JsonLD
} }
catch (Exception $e) { catch (Exception $e) {
$normalized = false; $normalized = false;
logger('normalise error:' . print_r($e, true), LOGGER_DEBUG); Logger::log('normalise error:' . print_r($e, true), Logger::DEBUG);
} }
return $normalized; return $normalized;
@ -98,7 +99,7 @@ class JsonLD
} }
catch (Exception $e) { catch (Exception $e) {
$compacted = false; $compacted = false;
logger('compacting error:' . print_r($e, true), LOGGER_DEBUG); Logger::log('compacting error:' . print_r($e, true), Logger::DEBUG);
} }
return json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true); return json_decode(json_encode($compacted, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), true);

View file

@ -2,6 +2,7 @@
namespace Friendica\Util; namespace Friendica\Util;
use Friendica\Core\Logger;
use Friendica\Util\JsonLD; use Friendica\Util\JsonLD;
use Friendica\Util\DateTimeFormat; use Friendica\Util\DateTimeFormat;
use Friendica\Protocol\ActivityPub; use Friendica\Protocol\ActivityPub;
@ -40,7 +41,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('LD-verify: ' . intval($x)); Logger::log('LD-verify: ' . intval($x));
if (empty($x)) { if (empty($x)) {
return false; return false;

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