1
0
Fork 0

Merge pull request #11653 from Quix0r/fixes/more-type-hints

More type-hints added
This commit is contained in:
Hypolite Petovan 2022-06-18 10:33:33 -04:00 committed by GitHub
commit e90ad0c1cd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
50 changed files with 1167 additions and 1067 deletions

View file

@ -145,7 +145,7 @@ class App
$this->nickname = $nickname; $this->nickname = $nickname;
} }
public function isLoggedIn() public function isLoggedIn(): bool
{ {
return local_user() && $this->user_id && ($this->user_id == local_user()); return local_user() && $this->user_id && ($this->user_id == local_user());
} }
@ -155,7 +155,7 @@ class App
* *
* @return bool true if user is an admin * @return bool true if user is an admin
*/ */
public function isSiteAdmin() public function isSiteAdmin(): bool
{ {
$admin_email = $this->config->get('config', 'admin_email'); $admin_email = $this->config->get('config', 'admin_email');
@ -166,18 +166,18 @@ class App
/** /**
* Fetch the user id * Fetch the user id
* @return int * @return int User id
*/ */
public function getLoggedInUserId() public function getLoggedInUserId(): int
{ {
return $this->user_id; return $this->user_id;
} }
/** /**
* Fetch the user nick name * Fetch the user nick name
* @return string * @return string User's nickname
*/ */
public function getLoggedInUserNickname() public function getLoggedInUserNickname(): string
{ {
return $this->nickname; return $this->nickname;
} }
@ -198,7 +198,7 @@ class App
* *
* @return int * @return int
*/ */
public function getProfileOwner():int public function getProfileOwner(): int
{ {
return $this->profile_owner; return $this->profile_owner;
} }
@ -219,7 +219,7 @@ class App
* *
* @return int * @return int
*/ */
public function getContactId():int public function getContactId(): int
{ {
return $this->contact_id; return $this->contact_id;
} }
@ -241,7 +241,7 @@ class App
* *
* @return int * @return int
*/ */
public function getTimeZone():string public function getTimeZone(): string
{ {
return $this->timezone; return $this->timezone;
} }
@ -260,9 +260,9 @@ class App
/** /**
* Fetch workerqueue information * Fetch workerqueue information
* *
* @return array * @return array Worker queue
*/ */
public function getQueue() public function getQueue(): array
{ {
return $this->queue ?? []; return $this->queue ?? [];
} }
@ -270,8 +270,8 @@ class App
/** /**
* Fetch a specific workerqueue field * Fetch a specific workerqueue field
* *
* @param string $index * @param string $index Work queue record to fetch
* @return mixed * @return mixed Work queue item or NULL if not found
*/ */
public function getQueueValue(string $index) public function getQueueValue(string $index)
{ {
@ -306,9 +306,9 @@ class App
/** /**
* The basepath of this app * The basepath of this app
* *
* @return string * @return string Base path from configuration
*/ */
public function getBasePath() public function getBasePath(): string
{ {
// Don't use the basepath of the config table for basepath (it should always be the config-file one) // Don't use the basepath of the config table for basepath (it should always be the config-file one)
return $this->config->getCache()->get('system', 'basepath'); return $this->config->getCache()->get('system', 'basepath');
@ -396,10 +396,10 @@ class App
/** /**
* Returns the current theme name. May be overriden by the mobile theme name. * Returns the current theme name. May be overriden by the mobile theme name.
* *
* @return string * @return string Current theme name or empty string in installation phase
* @throws Exception * @throws Exception
*/ */
public function getCurrentTheme() public function getCurrentTheme(): string
{ {
if ($this->mode->isInstall()) { if ($this->mode->isInstall()) {
return ''; return '';
@ -425,10 +425,10 @@ class App
/** /**
* Returns the current mobile theme name. * Returns the current mobile theme name.
* *
* @return string * @return string Mobile theme name or empty string if installer
* @throws Exception * @throws Exception
*/ */
public function getCurrentMobileTheme() public function getCurrentMobileTheme(): string
{ {
if ($this->mode->isInstall()) { if ($this->mode->isInstall()) {
return ''; return '';
@ -441,12 +441,22 @@ class App
return $this->currentMobileTheme; return $this->currentMobileTheme;
} }
public function setCurrentTheme($theme) /**
* Setter for current theme name
*
* @param string $theme Name of current theme
*/
public function setCurrentTheme(string $theme)
{ {
$this->currentTheme = $theme; $this->currentTheme = $theme;
} }
public function setCurrentMobileTheme($theme) /**
* Setter for current mobile theme name
*
* @param string $theme Name of current mobile theme
*/
public function setCurrentMobileTheme(string $theme)
{ {
$this->currentMobileTheme = $theme; $this->currentMobileTheme = $theme;
} }
@ -525,10 +535,10 @@ class App
/** /**
* Provide a sane default if nothing is chosen or the specified theme does not exist. * Provide a sane default if nothing is chosen or the specified theme does not exist.
* *
* @return string * @return string Current theme's stylsheet path
* @throws Exception * @throws Exception
*/ */
public function getCurrentThemeStylesheetPath() public function getCurrentThemeStylesheetPath(): string
{ {
return Core\Theme::getStylesheetPath($this->getCurrentTheme()); return Core\Theme::getStylesheetPath($this->getCurrentTheme());
} }
@ -730,7 +740,7 @@ class App
* *
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
public function redirect($toUrl) public function redirect(string $toUrl)
{ {
if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) { if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
Core\System::externalRedirect($toUrl); Core\System::externalRedirect($toUrl);

View file

@ -78,7 +78,7 @@ class Arguments
/** /**
* @return string The whole command of this call * @return string The whole command of this call
*/ */
public function getCommand() public function getCommand(): string
{ {
return $this->command; return $this->command;
} }
@ -94,7 +94,7 @@ class Arguments
/** /**
* @return array All arguments of this call * @return array All arguments of this call
*/ */
public function getArgv() public function getArgv(): array
{ {
return $this->argv; return $this->argv;
} }
@ -102,7 +102,7 @@ class Arguments
/** /**
* @return string The used HTTP method * @return string The used HTTP method
*/ */
public function getMethod() public function getMethod(): string
{ {
return $this->method; return $this->method;
} }
@ -110,7 +110,7 @@ class Arguments
/** /**
* @return int The count of arguments of this call * @return int The count of arguments of this call
*/ */
public function getArgc() public function getArgc(): int
{ {
return $this->argc; return $this->argc;
} }
@ -145,7 +145,7 @@ class Arguments
* *
* @return bool if the argument position exists * @return bool if the argument position exists
*/ */
public function has(int $position) public function has(int $position): bool
{ {
return array_key_exists($position, $this->argv); return array_key_exists($position, $this->argv);
} }
@ -158,7 +158,7 @@ class Arguments
* *
* @return Arguments The determined arguments * @return Arguments The determined arguments
*/ */
public function determine(array $server, array $get) public function determine(array $server, array $get): Arguments
{ {
// removing leading / - maybe a nginx problem // removing leading / - maybe a nginx problem
$server['QUERY_STRING'] = ltrim($server['QUERY_STRING'] ?? '', '/'); $server['QUERY_STRING'] = ltrim($server['QUERY_STRING'] ?? '', '/');

View file

@ -107,7 +107,7 @@ class BaseURL
* *
* @return string * @return string
*/ */
public function getHostname() public function getHostname(): string
{ {
return $this->hostname; return $this->hostname;
} }
@ -117,7 +117,7 @@ class BaseURL
* *
* @return string * @return string
*/ */
public function getScheme() public function getScheme(): string
{ {
return $this->scheme; return $this->scheme;
} }
@ -127,7 +127,7 @@ class BaseURL
* *
* @return int * @return int
*/ */
public function getSSLPolicy() public function getSSLPolicy(): int
{ {
return $this->sslPolicy; return $this->sslPolicy;
} }
@ -137,7 +137,7 @@ class BaseURL
* *
* @return string * @return string
*/ */
public function getUrlPath() public function getUrlPath(): string
{ {
return $this->urlPath; return $this->urlPath;
} }
@ -151,7 +151,7 @@ class BaseURL
* *
* @return string * @return string
*/ */
public function get($ssl = false) public function get(bool $ssl = false): string
{ {
if ($this->sslPolicy === self::SSL_POLICY_SELFSIGN && $ssl) { if ($this->sslPolicy === self::SSL_POLICY_SELFSIGN && $ssl) {
return Network::switchScheme($this->url); return Network::switchScheme($this->url);
@ -168,8 +168,9 @@ class BaseURL
* @param string? $urlPath * @param string? $urlPath
* *
* @return bool true, if successful * @return bool true, if successful
* @TODO Find proper types
*/ */
public function save($hostname = null, $sslPolicy = null, $urlPath = null) public function save($hostname = null, $sslPolicy = null, $urlPath = null): bool
{ {
$currHostname = $this->hostname; $currHostname = $this->hostname;
$currSSLPolicy = $this->sslPolicy; $currSSLPolicy = $this->sslPolicy;
@ -224,11 +225,11 @@ class BaseURL
/** /**
* Save the current url as base URL * Save the current url as base URL
* *
* @param $url * @param string $url
* *
* @return bool true, if the save was successful * @return bool true, if the save was successful
*/ */
public function saveByURL($url) public function saveByURL(string $url): bool
{ {
$parsed = @parse_url($url); $parsed = @parse_url($url);
@ -421,7 +422,7 @@ class BaseURL
* *
* @return string The cleaned url * @return string The cleaned url
*/ */
public function remove(string $origURL) public function remove(string $origURL): string
{ {
// Remove the hostname from the url if it is an internal link // Remove the hostname from the url if it is an internal link
$nurl = Strings::normaliseLink($origURL); $nurl = Strings::normaliseLink($origURL);
@ -445,7 +446,7 @@ class BaseURL
* *
* @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node * @throws HTTPException\InternalServerErrorException In Case the given URL is not relative to the Friendica node
*/ */
public function redirect($toUrl = '', $ssl = false) public function redirect(string $toUrl = '', bool $ssl = false)
{ {
if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) { if (!empty(parse_url($toUrl, PHP_URL_SCHEME))) {
throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo"); throw new HTTPException\InternalServerErrorException("'$toUrl is not a relative path, please use System::externalRedirectTo");
@ -458,8 +459,8 @@ class BaseURL
/** /**
* Returns the base url as string * Returns the base url as string
*/ */
public function __toString() public function __toString(): string
{ {
return $this->get(); return (string) $this->get();
} }
} }

View file

@ -130,7 +130,7 @@ class Mode
* *
* @throws \Exception * @throws \Exception
*/ */
public function determine(BasePath $basepath, Database $database, Cache $configCache) public function determine(BasePath $basepath, Database $database, Cache $configCache): Mode
{ {
$mode = 0; $mode = 0;
@ -178,7 +178,7 @@ class Mode
* *
* @return Mode returns the determined mode * @return Mode returns the determined mode
*/ */
public function determineRunMode(bool $isBackend, array $server, Arguments $args, MobileDetect $mobileDetect) public function determineRunMode(bool $isBackend, array $server, Arguments $args, MobileDetect $mobileDetect): Mode
{ {
foreach (self::BACKEND_CONTENT_TYPES as $type) { foreach (self::BACKEND_CONTENT_TYPES as $type) {
if (strpos(strtolower($server['HTTP_ACCEPT'] ?? ''), $type) !== false) { if (strpos(strtolower($server['HTTP_ACCEPT'] ?? ''), $type) !== false) {
@ -201,7 +201,7 @@ class Mode
* *
* @return bool returns true, if the mode is set * @return bool returns true, if the mode is set
*/ */
public function has($mode) public function has(int $mode): bool
{ {
return ($this->mode & $mode) > 0; return ($this->mode & $mode) > 0;
} }
@ -227,7 +227,7 @@ class Mode
* *
* @return int Execution Mode * @return int Execution Mode
*/ */
public function getExecutor() public function getExecutor(): int
{ {
return $this->executor; return $this->executor;
} }
@ -235,9 +235,9 @@ class Mode
/** /**
* Install mode is when the local config file is missing or the DB schema hasn't been installed yet. * Install mode is when the local config file is missing or the DB schema hasn't been installed yet.
* *
* @return bool * @return bool Whether installation mode is active (local/database configuration files present or not)
*/ */
public function isInstall() public function isInstall(): bool
{ {
return !$this->has(Mode::LOCALCONFIGPRESENT) || return !$this->has(Mode::LOCALCONFIGPRESENT) ||
!$this->has(MODE::DBCONFIGAVAILABLE); !$this->has(MODE::DBCONFIGAVAILABLE);
@ -248,7 +248,7 @@ class Mode
* *
* @return bool * @return bool
*/ */
public function isNormal() public function isNormal(): bool
{ {
return $this->has(Mode::LOCALCONFIGPRESENT) && return $this->has(Mode::LOCALCONFIGPRESENT) &&
$this->has(Mode::DBAVAILABLE) && $this->has(Mode::DBAVAILABLE) &&
@ -261,7 +261,7 @@ class Mode
* *
* @return bool Is it a backend call * @return bool Is it a backend call
*/ */
public function isBackend() public function isBackend(): bool
{ {
return $this->isBackend; return $this->isBackend;
} }
@ -271,7 +271,7 @@ class Mode
* *
* @return bool true if it was an AJAX request * @return bool true if it was an AJAX request
*/ */
public function isAjax() public function isAjax(): bool
{ {
return $this->isAjax; return $this->isAjax;
} }
@ -281,7 +281,7 @@ class Mode
* *
* @return bool true if it was an mobile request * @return bool true if it was an mobile request
*/ */
public function isMobile() public function isMobile(): bool
{ {
return $this->isMobile; return $this->isMobile;
} }
@ -291,7 +291,7 @@ class Mode
* *
* @return bool true if it was an tablet request * @return bool true if it was an tablet request
*/ */
public function isTablet() public function isTablet(): bool
{ {
return $this->isTablet; return $this->isTablet;
} }

View file

@ -195,7 +195,7 @@ class Page implements ArrayAccess
* @param string $media * @param string $media
* @see Page::initHead() * @see Page::initHead()
*/ */
public function registerStylesheet($path, string $media = 'screen') public function registerStylesheet(string $path, string $media = 'screen')
{ {
$path = Network::appendQueryParam($path, ['v' => FRIENDICA_VERSION]); $path = Network::appendQueryParam($path, ['v' => FRIENDICA_VERSION]);
@ -288,7 +288,7 @@ class Page implements ArrayAccess
* *
* Taken from http://webcheatsheet.com/php/get_current_page_url.php * Taken from http://webcheatsheet.com/php/get_current_page_url.php
*/ */
private function curPageURL() private function curPageURL(): string
{ {
$pageURL = 'http'; $pageURL = 'http';
if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) { if (!empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] == "on")) {

View file

@ -152,7 +152,7 @@ class Router
* *
* @throws HTTPException\InternalServerErrorException In case of invalid configs * @throws HTTPException\InternalServerErrorException In case of invalid configs
*/ */
public function loadRoutes(array $routes) public function loadRoutes(array $routes): Router
{ {
$routeCollector = ($this->routeCollector ?? new RouteCollector(new Std(), new GroupCountBased())); $routeCollector = ($this->routeCollector ?? new RouteCollector(new Std(), new GroupCountBased()));
@ -166,6 +166,13 @@ class Router
return $this; return $this;
} }
/**
* Adds multiple routes to a route collector
*
* @param RouteCollector $routeCollector Route collector instance
* @param array $routes Multiple routes to be added
* @throws HTTPException\InternalServerErrorException If route was wrong (somehow)
*/
private function addRoutes(RouteCollector $routeCollector, array $routes) private function addRoutes(RouteCollector $routeCollector, array $routes)
{ {
foreach ($routes as $route => $config) { foreach ($routes as $route => $config) {
@ -221,7 +228,7 @@ class Router
* *
* @return bool * @return bool
*/ */
private function isRoute(array $config) private function isRoute(array $config): bool
{ {
return return
// The config array should at least have one entry // The config array should at least have one entry
@ -253,7 +260,7 @@ class Router
* @throws HTTPException\MethodNotAllowedException If a rule matched but the method didn't * @throws HTTPException\MethodNotAllowedException If a rule matched but the method didn't
* @throws HTTPException\NotFoundException If no rule matched * @throws HTTPException\NotFoundException If no rule matched
*/ */
private function getModuleClass() private function getModuleClass(): string
{ {
$cmd = $this->args->getCommand(); $cmd = $this->args->getCommand();
$cmd = '/' . ltrim($cmd, '/'); $cmd = '/' . ltrim($cmd, '/');

View file

@ -70,9 +70,11 @@ class BaseCollection extends \ArrayIterator
} }
/** /**
* @return int * Getter for total count
*
* @return int Total count
*/ */
public function getTotalCount() public function getTotalCount(): int
{ {
return $this->totalCount; return $this->totalCount;
} }
@ -85,7 +87,7 @@ class BaseCollection extends \ArrayIterator
* @return array * @return array
* @see array_column() * @see array_column()
*/ */
public function column($column, $index_key = null) public function column(string $column, $index_key = null): array
{ {
return array_column($this->getArrayCopy(true), $column, $index_key); return array_column($this->getArrayCopy(true), $column, $index_key);
} }
@ -97,7 +99,7 @@ class BaseCollection extends \ArrayIterator
* @return BaseCollection * @return BaseCollection
* @see array_map() * @see array_map()
*/ */
public function map(callable $callback) public function map(callable $callback): BaseCollection
{ {
return new static(array_map($callback, $this->getArrayCopy()), $this->getTotalCount()); return new static(array_map($callback, $this->getArrayCopy()), $this->getTotalCount());
} }
@ -110,7 +112,7 @@ class BaseCollection extends \ArrayIterator
* @return BaseCollection * @return BaseCollection
* @see array_filter() * @see array_filter()
*/ */
public function filter(callable $callback = null, int $flag = 0) public function filter(callable $callback = null, int $flag = 0): BaseCollection
{ {
return new static(array_filter($this->getArrayCopy(), $callback, $flag)); return new static(array_filter($this->getArrayCopy(), $callback, $flag));
} }

View file

@ -55,14 +55,14 @@ abstract class BaseEntity extends BaseDataTransferObject
} }
/** /**
* @param $name * @param mixed $name
* @return bool * @return bool
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
public function __isset($name) public function __isset($name): bool
{ {
if (!property_exists($this, $name)) { if (!property_exists($this, $name)) {
throw new HTTPException\InternalServerErrorException('Unknown property ' . $name . ' in Entity ' . static::class); throw new HTTPException\InternalServerErrorException('Unknown property ' . $name . ' of type ' . gettype($name) . ' in Entity ' . static::class);
} }
return !empty($this->$name); return !empty($this->$name);

View file

@ -110,11 +110,11 @@ abstract class BaseModel extends BaseDataTransferObject
* - $model->field (outside of class) * - $model->field (outside of class)
* - $this->field (inside of class) * - $this->field (inside of class)
* *
* @param $name * @param string $name Name of data to fetch
* @return mixed * @return mixed
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
public function __get($name) public function __get(string $name)
{ {
$this->checkValid(); $this->checkValid();

View file

@ -331,7 +331,7 @@ abstract class BaseModule implements ICanHandleRequests
* Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are, * Actually, important actions should not be triggered by Links / GET-Requests at all, but sometimes they still are,
* so this mechanism brings in some damage control (the attacker would be able to forge a request to a form of this type, but not to forms of other types). * so this mechanism brings in some damage control (the attacker would be able to forge a request to a form of this type, but not to forms of other types).
*/ */
public static function getFormSecurityToken($typename = '') public static function getFormSecurityToken(string $typename = '')
{ {
$user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']); $user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
$timestamp = time(); $timestamp = time();
@ -340,7 +340,14 @@ abstract class BaseModule implements ICanHandleRequests
return $timestamp . '.' . $sec_hash; return $timestamp . '.' . $sec_hash;
} }
public static function checkFormSecurityToken($typename = '', $formname = 'form_security_token') /**
* Checks if form's security (CSRF) token is valid.
*
* @param string $typename ???
* @param string $formname Name of form/field (???)
* @return bool Whether it is valid
*/
public static function checkFormSecurityToken(string $typename = '', string $formname = 'form_security_token'): bool
{ {
$hash = null; $hash = null;
@ -372,12 +379,12 @@ abstract class BaseModule implements ICanHandleRequests
return ($sec_hash == $x[1]); return ($sec_hash == $x[1]);
} }
public static function getFormSecurityStandardErrorMessage() public static function getFormSecurityStandardErrorMessage(): string
{ {
return DI::l10n()->t("The form security token was not correct. This probably happened because the form has been opened for too long \x28>3 hours\x29 before submitting it.") . EOL; return DI::l10n()->t("The form security token was not correct. This probably happened because the form has been opened for too long \x28>3 hours\x29 before submitting it.") . EOL;
} }
public static function checkFormSecurityTokenRedirectOnError($err_redirect, $typename = '', $formname = 'form_security_token') public static function checkFormSecurityTokenRedirectOnError(string $err_redirect, string $typename = '', string $formname = 'form_security_token')
{ {
if (!self::checkFormSecurityToken($typename, $formname)) { if (!self::checkFormSecurityToken($typename, $formname)) {
Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename); Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);
@ -387,7 +394,7 @@ abstract class BaseModule implements ICanHandleRequests
} }
} }
public static function checkFormSecurityTokenForbiddenOnError($typename = '', $formname = 'form_security_token') public static function checkFormSecurityTokenForbiddenOnError(string $typename = '', string $formname = 'form_security_token')
{ {
if (!self::checkFormSecurityToken($typename, $formname)) { if (!self::checkFormSecurityToken($typename, $formname)) {
Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename); Logger::notice('checkFormSecurityToken failed: user ' . DI::app()->getLoggedInUserNickname() . ' - form element ' . $typename);

View file

@ -123,7 +123,7 @@ class Avatar
return $fields; return $fields;
} }
private static function getFilename(string $url) private static function getFilename(string $url): string
{ {
$guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST)); $guid = Item::guidFromUri($url, parse_url($url, PHP_URL_HOST));

View file

@ -49,7 +49,7 @@ class BoundariesPager extends Pager
* @param string $last_item_id The id† of the last item in the displayed item list * @param string $last_item_id The id† of the last item in the displayed item list
* @param integer $itemsPerPage An optional number of items per page to override the default value * @param integer $itemsPerPage An optional number of items per page to override the default value
*/ */
public function __construct(L10n $l10n, $queryString, $first_item_id = null, $last_item_id = null, $itemsPerPage = 50) public function __construct(L10n $l10n, string $queryString, string $first_item_id = null, string $last_item_id = null, int $itemsPerPage = 50)
{ {
parent::__construct($l10n, $queryString, $itemsPerPage); parent::__construct($l10n, $queryString, $itemsPerPage);
@ -102,7 +102,7 @@ class BoundariesPager extends Pager
* @return string HTML string of the pager * @return string HTML string of the pager
* @throws \Exception * @throws \Exception
*/ */
public function renderMinimal(int $itemCount) public function renderMinimal(int $itemCount): string
{ {
$displayedItemCount = max(0, intval($itemCount)); $displayedItemCount = max(0, intval($itemCount));

View file

@ -41,7 +41,7 @@ class ContactSelector
* @param boolean $disabled optional, default false * @param boolean $disabled optional, default false
* @return string * @return string
*/ */
public static function pollInterval($current, $disabled = false) public static function pollInterval(string $current, bool $disabled = false): string
{ {
$dis = (($disabled) ? ' disabled="disabled" ' : ''); $dis = (($disabled) ? ' disabled="disabled" ' : '');
$o = ''; $o = '';
@ -84,7 +84,7 @@ class ContactSelector
* @return string Server URL * @return string Server URL
* @throws \Exception * @throws \Exception
*/ */
private static function getServerURLForProfile($profile) private static function getServerURLForProfile(string $profile): string
{ {
if (!empty(self::$server_url[$profile])) { if (!empty(self::$server_url[$profile])) {
return self::$server_url[$profile]; return self::$server_url[$profile];
@ -111,13 +111,16 @@ class ContactSelector
} }
/** /**
* Determines network name
*
* @param string $network network of the contact * @param string $network network of the contact
* @param string $profile optional, default empty * @param string $profile optional, default empty
* @param string $protocol (Optional) Protocol that is used for the transmission * @param string $protocol (Optional) Protocol that is used for the transmission
* @param int $gsid Server id
* @return string * @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function networkToName($network, $profile = '', $protocol = '', $gsid = 0) public static function networkToName(string $network, string $profile = '', string $protocol = '', int $gsid = null): string
{ {
$nets = [ $nets = [
Protocol::DFRN => DI::l10n()->t('DFRN'), Protocol::DFRN => DI::l10n()->t('DFRN'),
@ -179,12 +182,15 @@ class ContactSelector
} }
/** /**
* Determines network's icon name
*
* @param string $network network * @param string $network network
* @param string $profile optional, default empty * @param string $profile optional, default empty
* @return string * @param int $gsid Server id
* @return string Name for network icon
* @throws \Exception * @throws \Exception
*/ */
public static function networkToIcon($network, $profile = "", $gsid = 0) public static function networkToIcon(string $network, string $profile = "", int $gsid = null): string
{ {
$nets = [ $nets = [
Protocol::DFRN => 'friendica', Protocol::DFRN => 'friendica',

View file

@ -189,7 +189,7 @@ class Conversation
* @return string formatted text * @return string formatted text
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public function formatActivity(array $links, $verb, $id) public function formatActivity(array $links, string $verb, int $id): string
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
$o = ''; $o = '';
@ -275,7 +275,7 @@ class Conversation
return $o; return $o;
} }
public function statusEditor(array $x = [], $notes_cid = 0, $popup = false) public function statusEditor(array $x = [], int $notes_cid = 0, bool $popup = false): string
{ {
$user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']); $user = User::getById($this->app->getLoggedInUserId(), ['uid', 'nickname', 'allow_location', 'default-location']);
if (empty($user['uid'])) { if (empty($user['uid'])) {
@ -414,8 +414,8 @@ class Conversation
* figures out how to determine page owner and other contextual items * figures out how to determine page owner and other contextual items
* that are based on unique features of the calling module. * that are based on unique features of the calling module.
* @param array $items * @param array $items
* @param $mode * @param string $mode
* @param $update * @param $update @TODO Which type?
* @param bool $preview * @param bool $preview
* @param string $order * @param string $order
* @param int $uid * @param int $uid
@ -423,7 +423,7 @@ class Conversation
* @throws ImagickException * @throws ImagickException
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public function create(array $items, $mode, $update, $preview = false, $order = 'commented', $uid = 0) public function create(array $items, string $mode, $update, bool $preview = false, string $order = 'commented', int $uid = 0): string
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
@ -784,7 +784,7 @@ class Conversation
return $o; return $o;
} }
private function getBlocklist() private function getBlocklist(): array
{ {
if (!local_user()) { if (!local_user()) {
return []; return [];
@ -816,7 +816,7 @@ class Conversation
* *
* @return array items with parents and comments * @return array items with parents and comments
*/ */
private function addRowInformation(array $row, array $activity, array $thr_parent) private function addRowInformation(array $row, array $activity, array $thr_parent): array
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
@ -911,7 +911,7 @@ class Conversation
* @return array items with parents and comments * @return array items with parents and comments
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode) private function addChildren(array $parents, bool $block_authors, string $order, int $uid, string $mode): array
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
if (count($parents) > 1) { if (count($parents) > 1) {
@ -1005,7 +1005,7 @@ class Conversation
* @param bool $recursive * @param bool $recursive
* @return array * @return array
*/ */
private function getItemChildren(array &$item_list, array $parent, $recursive = true) private function getItemChildren(array &$item_list, array $parent, bool $recursive = true): array
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
$children = []; $children = [];
@ -1040,7 +1040,7 @@ class Conversation
* @param array $items * @param array $items
* @return array * @return array
*/ */
private function sortItemChildren(array $items) private function sortItemChildren(array $items): array
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
$result = $items; $result = $items;
@ -1086,7 +1086,7 @@ class Conversation
* @param array $parent A tree-like array of items * @param array $parent A tree-like array of items
* @return array * @return array
*/ */
private function smartFlattenConversation(array $parent) private function smartFlattenConversation(array $parent): array
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
if (!isset($parent['children']) || count($parent['children']) == 0) { if (!isset($parent['children']) || count($parent['children']) == 0) {
@ -1142,7 +1142,7 @@ class Conversation
* @return array * @return array
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private function convSort(array $item_list, $order) private function convSort(array $item_list, string $order): array
{ {
$this->profiler->startRecording('rendering'); $this->profiler->startRecording('rendering');
$parents = []; $parents = [];
@ -1222,7 +1222,7 @@ class Conversation
* @param array $b * @param array $b
* @return int * @return int
*/ */
private function sortThrFeaturedReceived(array $a, array $b) private function sortThrFeaturedReceived(array $a, array $b): int
{ {
if ($b['featured'] && !$a['featured']) { if ($b['featured'] && !$a['featured']) {
return 1; return 1;
@ -1240,7 +1240,7 @@ class Conversation
* @param array $b * @param array $b
* @return int * @return int
*/ */
private function sortThrFeaturedCommented(array $a, array $b) private function sortThrFeaturedCommented(array $a, array $b): int
{ {
if ($b['featured'] && !$a['featured']) { if ($b['featured'] && !$a['featured']) {
return 1; return 1;
@ -1258,7 +1258,7 @@ class Conversation
* @param array $b * @param array $b
* @return int * @return int
*/ */
private function sortThrReceived(array $a, array $b) private function sortThrReceived(array $a, array $b): int
{ {
return strcmp($b['received'], $a['received']); return strcmp($b['received'], $a['received']);
} }
@ -1270,7 +1270,7 @@ class Conversation
* @param array $b * @param array $b
* @return int * @return int
*/ */
private function sortThrReceivedRev(array $a, array $b) private function sortThrReceivedRev(array $a, array $b): int
{ {
return strcmp($a['received'], $b['received']); return strcmp($a['received'], $b['received']);
} }
@ -1282,7 +1282,7 @@ class Conversation
* @param array $b * @param array $b
* @return int * @return int
*/ */
private function sortThrCommented(array $a, array $b) private function sortThrCommented(array $a, array $b): int
{ {
return strcmp($b['commented'], $a['commented']); return strcmp($b['commented'], $a['commented']);
} }
@ -1294,7 +1294,7 @@ class Conversation
* @param array $b * @param array $b
* @return int * @return int
*/ */
private function sortThrCreated(array $a, array $b) private function sortThrCreated(array $a, array $b): int
{ {
return strcmp($b['created'], $a['created']); return strcmp($b['created'], $a['created']);
} }

View file

@ -45,7 +45,7 @@ class Widget
* @return string * @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function follow($value = "") public static function follow(string $value = ''): string
{ {
return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/follow.tpl'), array( return Renderer::replaceMacros(Renderer::getMarkupTemplate('widget/follow.tpl'), array(
'$connect' => DI::l10n()->t('Add New Contact'), '$connect' => DI::l10n()->t('Add New Contact'),
@ -58,8 +58,10 @@ class Widget
/** /**
* Return Find People widget * Return Find People widget
*
* @return string HTML code respresenting "People Widget"
*/ */
public static function findPeople() public static function findPeople(): string
{ {
$global_dir = Search::getGlobalDirectory(); $global_dir = Search::getGlobalDirectory();
@ -97,7 +99,7 @@ class Widget
* *
* @return array Unsupported networks * @return array Unsupported networks
*/ */
public static function unavailableNetworks() public static function unavailableNetworks(): array
{ {
// Always hide content from these networks // Always hide content from these networks
$networks = [Protocol::PHANTOM, Protocol::FACEBOOK, Protocol::APPNET, Protocol::ZOT]; $networks = [Protocol::PHANTOM, Protocol::FACEBOOK, Protocol::APPNET, Protocol::ZOT];
@ -154,7 +156,7 @@ class Widget
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
private static function filter($type, $title, $desc, $all, $baseUrl, array $options, $selected = null) private static function filter(string $type, string $title, string $desc, string $all, string $baseUrl, array $options, string $selected = null): string
{ {
$queryString = parse_url($baseUrl, PHP_URL_QUERY); $queryString = parse_url($baseUrl, PHP_URL_QUERY);
$queryArray = []; $queryArray = [];
@ -191,7 +193,7 @@ class Widget
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public static function groups($baseurl, $selected = '') public static function groups(string $baseurl, string $selected = ''): string
{ {
if (!local_user()) { if (!local_user()) {
return ''; return '';

View file

@ -60,7 +60,7 @@ class Worker
* @return void * @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function processQueue($run_cron, Process $process) public static function processQueue(bool $run_cron, Process $process)
{ {
self::$up_start = microtime(true); self::$up_start = microtime(true);
@ -169,7 +169,7 @@ class Worker
* *
* @return boolean * @return boolean
*/ */
public static function isReady() public static function isReady(): bool
{ {
// 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()) {
@ -204,7 +204,7 @@ class Worker
* @return boolean Returns "true" if tasks are existing * @return boolean Returns "true" if tasks are existing
* @throws \Exception * @throws \Exception
*/ */
public static function entriesExists() public static function entriesExists(): bool
{ {
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
$exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]); $exists = DBA::exists('workerqueue', ["NOT `done` AND `pid` = 0 AND `next_try` < ?", DateTimeFormat::utcNow()]);
@ -218,7 +218,7 @@ class Worker
* @return integer Number of deferred entries in the worker queue * @return integer Number of deferred entries in the worker queue
* @throws \Exception * @throws \Exception
*/ */
private static function deferredEntries() private static function deferredEntries(): int
{ {
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
$count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]); $count = DBA::count('workerqueue', ["NOT `done` AND `pid` = 0 AND `retrial` > ?", 0]);
@ -233,7 +233,7 @@ class Worker
* @return integer Number of non executed entries in the worker queue * @return integer Number of non executed entries in the worker queue
* @throws \Exception * @throws \Exception
*/ */
private static function totalEntries() private static function totalEntries(): int
{ {
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
$count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]); $count = DBA::count('workerqueue', ['done' => false, 'pid' => 0]);
@ -248,7 +248,7 @@ class Worker
* @return integer Number of active worker processes * @return integer Number of active worker processes
* @throws \Exception * @throws \Exception
*/ */
private static function highestPriority() private static function highestPriority(): int
{ {
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
$condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()]; $condition = ["`pid` = 0 AND NOT `done` AND `next_try` < ?", DateTimeFormat::utcNow()];
@ -269,7 +269,7 @@ class Worker
* @return integer Is there a process running with that priority? * @return integer Is there a process running with that priority?
* @throws \Exception * @throws \Exception
*/ */
private static function processWithPriorityActive($priority) private static function processWithPriorityActive(int $priority): int
{ {
$condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority]; $condition = ["`priority` <= ? AND `pid` != 0 AND NOT `done`", $priority];
return DBA::exists('workerqueue', $condition); return DBA::exists('workerqueue', $condition);
@ -281,7 +281,7 @@ class Worker
* @param mixed $file * @param mixed $file
* @return bool * @return bool
*/ */
private static function validateInclude(&$file) private static function validateInclude(&$file): bool
{ {
$orig_file = $file; $orig_file = $file;
@ -321,7 +321,7 @@ class Worker
* @return boolean "true" if further processing should be stopped * @return boolean "true" if further processing should be stopped
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function execute($queue) public static function execute(array $queue): bool
{ {
$mypid = getmypid(); $mypid = getmypid();
@ -454,7 +454,7 @@ class Worker
* @return void * @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function execFunction($queue, $funcname, $argv, $method_call) private static function execFunction(array $queue, string $funcname, array $argv, bool $method_call)
{ {
$a = DI::app(); $a = DI::app();
@ -543,7 +543,7 @@ class Worker
* @return bool Are more than 3/4 of the maximum connections used? * @return bool Are more than 3/4 of the maximum connections used?
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function maxConnectionsReached() private static function maxConnectionsReached(): bool
{ {
// Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself. // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
$max = DI::config()->get("system", "max_connections"); $max = DI::config()->get("system", "max_connections");
@ -627,7 +627,7 @@ class Worker
* @return bool Are there too much workers running? * @return bool Are there too much workers running?
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function tooMuchWorkers() private static function tooMuchWorkers(): bool
{ {
$queues = DI::config()->get("system", "worker_queues", 10); $queues = DI::config()->get("system", "worker_queues", 10);
@ -751,7 +751,7 @@ class Worker
* @return integer Number of active worker processes * @return integer Number of active worker processes
* @throws \Exception * @throws \Exception
*/ */
private static function activeWorkers() private static function activeWorkers(): int
{ {
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
$count = DI::process()->countCommand('Worker.php'); $count = DI::process()->countCommand('Worker.php');
@ -766,7 +766,7 @@ class Worker
* @return array List of worker process ids * @return array List of worker process ids
* @throws \Exception * @throws \Exception
*/ */
private static function getWorkerPIDList() private static function getWorkerPIDList(): array
{ {
$ids = []; $ids = [];
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
@ -787,7 +787,7 @@ class Worker
/** /**
* Returns waiting jobs for the current process id * Returns waiting jobs for the current process id
* *
* @return array waiting workerqueue jobs * @return array|bool waiting workerqueue jobs or FALSE on failture
* @throws \Exception * @throws \Exception
*/ */
private static function getWaitingJobForPID() private static function getWaitingJobForPID()
@ -809,7 +809,7 @@ class Worker
* @return array array with next jobs * @return array array with next jobs
* @throws \Exception * @throws \Exception
*/ */
private static function nextProcess(int $limit) private static function nextProcess(int $limit): array
{ {
$priority = self::nextPriority(); $priority = self::nextPriority();
if (empty($priority)) { if (empty($priority)) {
@ -844,7 +844,7 @@ class Worker
/** /**
* Returns the priority of the next workerqueue job * Returns the priority of the next workerqueue job
* *
* @return string priority * @return string|bool priority or FALSE on failure
* @throws \Exception * @throws \Exception
*/ */
private static function nextPriority() private static function nextPriority()
@ -915,7 +915,7 @@ class Worker
/** /**
* Find and claim the next worker process for us * Find and claim the next worker process for us
* *
* @return boolean Have we found something? * @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function findWorkerProcesses() private static function findWorkerProcesses()
@ -993,7 +993,7 @@ class Worker
* @return array worker processes * @return array worker processes
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function workerProcess() public static function workerProcess(): array
{ {
// There can already be jobs for us in the queue. // There can already be jobs for us in the queue.
$waiting = self::getWaitingJobForPID(); $waiting = self::getWaitingJobForPID();
@ -1003,7 +1003,7 @@ class Worker
$stamp = (float)microtime(true); $stamp = (float)microtime(true);
if (!DI::lock()->acquire(self::LOCK_PROCESS)) { if (!DI::lock()->acquire(self::LOCK_PROCESS)) {
return false; return [];
} }
self::$lock_duration += (microtime(true) - $stamp); self::$lock_duration += (microtime(true) - $stamp);
@ -1011,7 +1011,9 @@ class Worker
DI::lock()->release(self::LOCK_PROCESS); DI::lock()->release(self::LOCK_PROCESS);
return self::getWaitingJobForPID(); // Prevents "Return value of Friendica\Core\Worker::workerProcess() must be of the type array, bool returned"
$process = self::getWaitingJobForPID();
return (is_array($process) ? $process : []);
} }
/** /**
@ -1097,7 +1099,7 @@ class Worker
* @return void * @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function spawnWorker($do_cron = false) public static function spawnWorker(bool $do_cron = false)
{ {
if (Worker\Daemon::isMode() && DI::config()->get('system', 'worker_fork')) { if (Worker\Daemon::isMode() && DI::config()->get('system', 'worker_fork')) {
self::forkProcess($do_cron); self::forkProcess($do_cron);
@ -1231,7 +1233,7 @@ class Worker
return $added; return $added;
} }
public static function countWorkersByCommand(string $command) public static function countWorkersByCommand(string $command): int
{ {
return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]); return DBA::count('workerqueue', ['done' => false, 'pid' => 0, 'command' => $command]);
} }
@ -1244,7 +1246,7 @@ class Worker
* @param integer $max_level maximum retrial level * @param integer $max_level maximum retrial level
* @return integer the next retrial level value * @return integer the next retrial level value
*/ */
private static function getNextRetrial($queue, $max_level) private static function getNextRetrial(array $queue, int $max_level): int
{ {
$created = strtotime($queue['created']); $created = strtotime($queue['created']);
$retrial_time = time() - $created; $retrial_time = time() - $created;
@ -1314,9 +1316,10 @@ class Worker
/** /**
* Check if the system is inside the defined maintenance window * Check if the system is inside the defined maintenance window
* *
* @param bool $check_last_execution Whether check last execution
* @return boolean * @return boolean
*/ */
public static function isInMaintenanceWindow(bool $check_last_execution = false) public static function isInMaintenanceWindow(bool $check_last_execution = false): bool
{ {
// Calculate the seconds of the start end end of the maintenance window // Calculate the seconds of the start end end of the maintenance window
$start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400; $start = strtotime(DI::config()->get('system', 'maintenance_start')) % 86400;

View file

@ -427,7 +427,7 @@ class DBA
* @return boolean was the update successfull? * @return boolean was the update successfull?
* @throws \Exception * @throws \Exception
*/ */
public static function update($table, $fields, $condition, $old_fields = [], $params = []) public static function update($table, array $fields, array $condition, $old_fields = [], array $params = [])
{ {
return DI::dba()->update($table, $fields, $condition, $old_fields, $params); return DI::dba()->update($table, $fields, $condition, $old_fields, $params);
} }
@ -443,7 +443,7 @@ class DBA
* @throws \Exception * @throws \Exception
* @see self::select * @see self::select
*/ */
public static function selectFirst($table, array $fields = [], array $condition = [], $params = []) public static function selectFirst($table, array $fields = [], array $condition = [], array $params = [])
{ {
return DI::dba()->selectFirst($table, $fields, $condition, $params); return DI::dba()->selectFirst($table, $fields, $condition, $params);
} }
@ -512,7 +512,7 @@ class DBA
* $count = DBA::count($table, $condition); * $count = DBA::count($table, $condition);
* @throws \Exception * @throws \Exception
*/ */
public static function count($table, array $condition = [], array $params = []) public static function count($table, array $condition = [], array $params = []): int
{ {
return DI::dba()->count($table, $condition, $params); return DI::dba()->count($table, $condition, $params);
} }
@ -771,7 +771,7 @@ class DBA
* *
* @return array Data array * @return array Data array
*/ */
public static function toArray($stmt, $do_close = true, int $count = 0) public static function toArray($stmt, $do_close = true, int $count = 0): array
{ {
return DI::dba()->toArray($stmt, $do_close, $count); return DI::dba()->toArray($stmt, $do_close, $count);
} }
@ -783,7 +783,7 @@ class DBA
* @param array $fields * @param array $fields
* @return array casted fields * @return array casted fields
*/ */
public static function castFields(string $table, array $fields) public static function castFields(string $table, array $fields): array
{ {
return DI::dba()->castFields($table, $fields); return DI::dba()->castFields($table, $fields);
} }
@ -793,7 +793,7 @@ class DBA
* *
* @return string Error number (0 if no error) * @return string Error number (0 if no error)
*/ */
public static function errorNo() public static function errorNo(): int
{ {
return DI::dba()->errorNo(); return DI::dba()->errorNo();
} }
@ -803,7 +803,7 @@ class DBA
* *
* @return string Error message ('' if no error) * @return string Error message ('' if no error)
*/ */
public static function errorMessage() public static function errorMessage(): string
{ {
return DI::dba()->errorMessage(); return DI::dba()->errorMessage();
} }
@ -814,7 +814,7 @@ class DBA
* @param object $stmt statement object * @param object $stmt statement object
* @return boolean was the close successful? * @return boolean was the close successful?
*/ */
public static function close($stmt) public static function close($stmt): bool
{ {
return DI::dba()->close($stmt); return DI::dba()->close($stmt);
} }
@ -827,7 +827,7 @@ class DBA
* 'amount' => Number of concurrent database processes * 'amount' => Number of concurrent database processes
* @throws \Exception * @throws \Exception
*/ */
public static function processlist() public static function processlist(): array
{ {
return DI::dba()->processlist(); return DI::dba()->processlist();
} }

View file

@ -541,7 +541,7 @@ class Database
if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) { if (!$retval = $this->connection->query($this->replaceParameters($sql, $args))) {
$errorInfo = $this->connection->errorInfo(); $errorInfo = $this->connection->errorInfo();
$this->error = $errorInfo[2]; $this->error = $errorInfo[2];
$this->errorno = $errorInfo[1]; $this->errorno = (int) $errorInfo[1];
$retval = false; $retval = false;
$is_error = true; $is_error = true;
break; break;
@ -554,7 +554,7 @@ class Database
if (!$stmt = $this->connection->prepare($sql)) { if (!$stmt = $this->connection->prepare($sql)) {
$errorInfo = $this->connection->errorInfo(); $errorInfo = $this->connection->errorInfo();
$this->error = $errorInfo[2]; $this->error = $errorInfo[2];
$this->errorno = $errorInfo[1]; $this->errorno = (int) $errorInfo[1];
$retval = false; $retval = false;
$is_error = true; $is_error = true;
break; break;
@ -574,7 +574,7 @@ class Database
if (!$stmt->execute()) { if (!$stmt->execute()) {
$errorInfo = $stmt->errorInfo(); $errorInfo = $stmt->errorInfo();
$this->error = $errorInfo[2]; $this->error = $errorInfo[2];
$this->errorno = $errorInfo[1]; $this->errorno = (int) $errorInfo[1];
$retval = false; $retval = false;
$is_error = true; $is_error = true;
} else { } else {
@ -709,7 +709,7 @@ class Database
} }
$this->error = $error; $this->error = $error;
$this->errorno = $errorno; $this->errorno = (int) $errorno;
} }
$this->profiler->stopRecording(); $this->profiler->stopRecording();
@ -1541,7 +1541,7 @@ class Database
* *
* @return array Data array * @return array Data array
*/ */
public function toArray($stmt, $do_close = true, int $count = 0) public function toArray($stmt, bool $do_close = true, int $count = 0): array
{ {
if (is_bool($stmt)) { if (is_bool($stmt)) {
return []; return [];
@ -1632,7 +1632,7 @@ class Database
* *
* @return string Error number (0 if no error) * @return string Error number (0 if no error)
*/ */
public function errorNo() public function errorNo(): int
{ {
return $this->errorno; return $this->errorno;
} }
@ -1654,7 +1654,7 @@ class Database
* *
* @return boolean was the close successful? * @return boolean was the close successful?
*/ */
public function close($stmt) public function close($stmt): bool
{ {
$this->profiler->startRecording('database'); $this->profiler->startRecording('database');
@ -1696,7 +1696,7 @@ class Database
* 'amount' => Number of concurrent database processes * 'amount' => Number of concurrent database processes
* @throws \Exception * @throws \Exception
*/ */
public function processlist() public function processlist(): array
{ {
$ret = $this->p("SHOW PROCESSLIST"); $ret = $this->p("SHOW PROCESSLIST");
$data = $this->toArray($ret); $data = $this->toArray($ret);

View file

@ -57,7 +57,7 @@ class Account extends BaseFactory
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws ImagickException|HTTPException\NotFoundException * @throws ImagickException|HTTPException\NotFoundException
*/ */
public function createFromContactId(int $contactId, $uid = 0): \Friendica\Object\Api\Mastodon\Account public function createFromContactId(int $contactId, int $uid = 0): \Friendica\Object\Api\Mastodon\Account
{ {
$contact = Contact::getById($contactId, ['uri-id']); $contact = Contact::getById($contactId, ['uri-id']);
if (empty($contact)) { if (empty($contact)) {
@ -74,7 +74,7 @@ class Account extends BaseFactory
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws ImagickException|HTTPException\NotFoundException * @throws ImagickException|HTTPException\NotFoundException
*/ */
public function createFromUriId(int $contactUriId, $uid = 0): \Friendica\Object\Api\Mastodon\Account public function createFromUriId(int $contactUriId, int $uid = 0): \Friendica\Object\Api\Mastodon\Account
{ {
$account = DBA::selectFirst('account-user-view', [], ['uri-id' => $contactUriId, 'uid' => [0, $uid]], ['order' => ['id' => true]]); $account = DBA::selectFirst('account-user-view', [], ['uri-id' => $contactUriId, 'uid' => [0, $uid]], ['order' => ['id' => true]]);
if (empty($account)) { if (empty($account)) {

View file

@ -70,6 +70,7 @@ class Status extends BaseFactory
/** /**
* @param int $uriId Uri-ID of the item * @param int $uriId Uri-ID of the item
* @param int $uid Item user * @param int $uid Item user
* @param bool $include_entities Whether to include entities
* *
* @return \Friendica\Object\Api\Twitter\Status * @return \Friendica\Object\Api\Twitter\Status
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
@ -90,12 +91,13 @@ class Status extends BaseFactory
/** /**
* @param int $uriId Uri-ID of the item * @param int $uriId Uri-ID of the item
* @param int $uid Item user * @param int $uid Item user
* @param bool $include_entities Whether to include entities
* *
* @return \Friendica\Object\Api\Twitter\Status * @return \Friendica\Object\Api\Twitter\Status
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws ImagickException|HTTPException\NotFoundException * @throws ImagickException|HTTPException\NotFoundException
*/ */
public function createFromUriId(int $uriId, $uid = 0, $include_entities = false): \Friendica\Object\Api\Twitter\Status public function createFromUriId(int $uriId, int $uid = 0, bool $include_entities = false): \Friendica\Object\Api\Twitter\Status
{ {
$fields = ['parent-uri-id', 'uri-id', 'uid', 'author-id', 'author-link', 'author-network', 'owner-id', 'causer-id', $fields = ['parent-uri-id', 'uri-id', 'uid', 'author-id', 'author-link', 'author-network', 'owner-id', 'causer-id',
'starred', 'app', 'title', 'body', 'raw-body', 'created', 'network','post-reason', 'language', 'gravity', 'starred', 'app', 'title', 'body', 'raw-body', 'created', 'network','post-reason', 'language', 'gravity',
@ -110,6 +112,7 @@ class Status extends BaseFactory
/** /**
* @param array $item item array * @param array $item item array
* @param int $uid Item user * @param int $uid Item user
* @param bool $include_entities Whether to include entities
* *
* @return \Friendica\Object\Api\Twitter\Status * @return \Friendica\Object\Api\Twitter\Status
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException

View file

@ -51,7 +51,7 @@ class User extends BaseFactory
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public function createFromContactId(int $contactId, $uid = 0, $skip_status = true, $include_user_entities = true) public function createFromContactId(int $contactId, int $uid = 0, bool $skip_status = true, bool $include_user_entities = true)
{ {
$cdata = Contact::getPublicAndUserContactID($contactId, $uid); $cdata = Contact::getPublicAndUserContactID($contactId, $uid);
if (!empty($cdata)) { if (!empty($cdata)) {
@ -78,7 +78,7 @@ class User extends BaseFactory
return new \Friendica\Object\Api\Twitter\User($publicContact, $apcontact, $userContact, $status, $include_user_entities); return new \Friendica\Object\Api\Twitter\User($publicContact, $apcontact, $userContact, $status, $include_user_entities);
} }
public function createFromUserId(int $uid, $skip_status = true, $include_user_entities = true) public function createFromUserId(int $uid, bool $skip_status = true, bool $include_user_entities = true)
{ {
return $this->createFromContactId(Contact::getPublicIdByUserId($uid), $uid, $skip_status, $include_user_entities); return $this->createFromContactId(Contact::getPublicIdByUserId($uid), $uid, $skip_status, $include_user_entities);
} }

View file

@ -57,7 +57,7 @@ class LegacyModule extends BaseModule
* @param string $file_path * @param string $file_path
* @throws \Exception * @throws \Exception
*/ */
private function setModuleFile($file_path) private function setModuleFile(string $file_path)
{ {
if (!is_readable($file_path)) { if (!is_readable($file_path)) {
throw new \Exception(DI::l10n()->t('Legacy module file not found: %s', $file_path)); throw new \Exception(DI::l10n()->t('Legacy module file not found: %s', $file_path));
@ -87,7 +87,7 @@ class LegacyModule extends BaseModule
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
private function runModuleFunction(string $function_suffix) private function runModuleFunction(string $function_suffix): string
{ {
$function_name = $this->moduleName . '_' . $function_suffix; $function_name = $this->moduleName . '_' . $function_suffix;

View file

@ -48,7 +48,7 @@ class APContact
* @param string $addr Address * @param string $addr Address
* @return array webfinger data * @return array webfinger data
*/ */
private static function fetchWebfingerData(string $addr) private static function fetchWebfingerData(string $addr): array
{ {
$addr_parts = explode('@', $addr); $addr_parts = explode('@', $addr);
if (count($addr_parts) != 2) { if (count($addr_parts) != 2) {
@ -117,14 +117,14 @@ class APContact
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function getByURL($url, $update = null) public static function getByURL(string $url, $update = null): array
{ {
if (empty($url) || Network::isUrlBlocked($url)) { if (empty($url) || Network::isUrlBlocked($url)) {
Logger::info('Domain is blocked', ['url' => $url]); Logger::info('Domain is blocked', ['url' => $url]);
return []; return [];
} }
$fetched_contact = false; $fetched_contact = [];
if (empty($update)) { if (empty($update)) {
if (is_null($update)) { if (is_null($update)) {
@ -220,14 +220,14 @@ class APContact
$apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type')); $apcontact['type'] = str_replace('as:', '', JsonLD::fetchElement($compacted, '@type'));
$apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id'); $apcontact['following'] = JsonLD::fetchElement($compacted, 'as:following', '@id');
$apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id'); $apcontact['followers'] = JsonLD::fetchElement($compacted, 'as:followers', '@id');
$apcontact['inbox'] = JsonLD::fetchElement($compacted, 'ldp:inbox', '@id'); $apcontact['inbox'] = (JsonLD::fetchElement($compacted, 'ldp:inbox', '@id') ?? '');
self::unarchiveInbox($apcontact['inbox'], false); self::unarchiveInbox($apcontact['inbox'], false);
$apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id'); $apcontact['outbox'] = JsonLD::fetchElement($compacted, 'as:outbox', '@id');
$apcontact['sharedinbox'] = ''; $apcontact['sharedinbox'] = '';
if (!empty($compacted['as:endpoints'])) { if (!empty($compacted['as:endpoints'])) {
$apcontact['sharedinbox'] = JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id'); $apcontact['sharedinbox'] = (JsonLD::fetchElement($compacted['as:endpoints'], 'as:sharedInbox', '@id') ?? '');
self::unarchiveInbox($apcontact['sharedinbox'], true); self::unarchiveInbox($apcontact['sharedinbox'], true);
} }
@ -527,7 +527,7 @@ class APContact
* @param string $url inbox url * @param string $url inbox url
* @param boolean $shared Shared Inbox * @param boolean $shared Shared Inbox
*/ */
private static function unarchiveInbox($url, $shared) private static function unarchiveInbox(string $url, bool $shared)
{ {
if (empty($url)) { if (empty($url)) {
return; return;

View file

@ -59,7 +59,7 @@ class Attach
* @param array $conditions Array of fields for conditions * @param array $conditions Array of fields for conditions
* @param array $params Array of several parameters * @param array $params Array of several parameters
* *
* @return array * @return array|bool
* *
* @throws \Exception * @throws \Exception
* @see \Friendica\Database\DBA::selectToArray * @see \Friendica\Database\DBA::selectToArray
@ -102,7 +102,7 @@ class Attach
* @return boolean * @return boolean
* @throws \Exception * @throws \Exception
*/ */
public static function exists(array $conditions) public static function exists(array $conditions): bool
{ {
return DBA::exists('attach', $conditions); return DBA::exists('attach', $conditions);
} }
@ -117,7 +117,7 @@ class Attach
* @throws \Exception * @throws \Exception
* @see \Friendica\Database\DBA::select * @see \Friendica\Database\DBA::select
*/ */
public static function getById($id) public static function getById(int $id)
{ {
return self::selectFirst([], ['id' => $id]); return self::selectFirst([], ['id' => $id]);
} }
@ -132,7 +132,7 @@ class Attach
* @throws \Exception * @throws \Exception
* @see \Friendica\Database\DBA::select * @see \Friendica\Database\DBA::select
*/ */
public static function getByIdWithPermission($id) public static function getByIdWithPermission(int $id)
{ {
$r = self::selectFirst(['uid'], ['id' => $id]); $r = self::selectFirst(['uid'], ['id' => $id]);
if ($r === false) { if ($r === false) {
@ -156,10 +156,10 @@ class Attach
* *
* @param array $item Attachment data. Needs at least 'id', 'backend-class', 'backend-ref' * @param array $item Attachment data. Needs at least 'id', 'backend-class', 'backend-ref'
* *
* @return string file data * @return string|null file data or null on failure
* @throws \Exception * @throws \Exception
*/ */
public static function getData($item) public static function getData(array $item)
{ {
if (!empty($item['data'])) { if (!empty($item['data'])) {
return $item['data']; return $item['data'];
@ -195,10 +195,10 @@ class Attach
* @param string $deny_cid Permissions, denied contacts.optional, default = '' * @param string $deny_cid Permissions, denied contacts.optional, default = ''
* @param string $deny_gid Permissions, denied greoup.optional, default = '' * @param string $deny_gid Permissions, denied greoup.optional, default = ''
* *
* @return boolean/integer Row id on success, False on errors * @return boolean|integer Row id on success, False on errors
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function store($data, $uid, $filename, $filetype = '' , $filesize = null, $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') public static function store(string $data, int $uid, string $filename, string $filetype = '' , int $filesize = null, string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '')
{ {
if ($filetype === '') { if ($filetype === '') {
$filetype = Mimetype::getContentType($filename); $filetype = Mimetype::getContentType($filename);
@ -241,17 +241,17 @@ class Attach
/** /**
* Store new file metadata in db and binary in default backend from existing file * Store new file metadata in db and binary in default backend from existing file
* *
* @param $src * @param string $src Source file name
* @param $uid * @param int $uid User id
* @param string $filename * @param string $filename Optional file name
* @param string $allow_cid * @param string $allow_cid
* @param string $allow_gid * @param string $allow_gid
* @param string $deny_cid * @param string $deny_cid
* @param string $deny_gid * @param string $deny_gid
* @return boolean True on success * @return boolean|int Insert id or false on failure
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function storeFile($src, $uid, $filename = '', $allow_cid = '', $allow_gid = '', $deny_cid = '', $deny_gid = '') public static function storeFile(string $src, int $uid, string $filename = '', string $allow_cid = '', string $allow_gid = '', string $deny_cid = '', string $deny_gid = '')
{ {
if ($filename === '') { if ($filename === '') {
$filename = basename($src); $filename = basename($src);
@ -276,7 +276,7 @@ class Attach
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @see \Friendica\Database\DBA::update * @see \Friendica\Database\DBA::update
*/ */
public static function update($fields, $conditions, Image $img = null, array $old_fields = []) public static function update(array $fields, array $conditions, Image $img = null, array $old_fields = []): bool
{ {
if (!is_null($img)) { if (!is_null($img)) {
// get items to update // get items to update
@ -311,7 +311,7 @@ class Attach
* @throws \Exception * @throws \Exception
* @see \Friendica\Database\DBA::delete * @see \Friendica\Database\DBA::delete
*/ */
public static function delete(array $conditions, array $options = []) public static function delete(array $conditions, array $options = []): bool
{ {
// get items to delete data info // get items to delete data info
$items = self::selectToArray(['backend-class','backend-ref'], $conditions); $items = self::selectToArray(['backend-class','backend-ref'], $conditions);

View file

@ -119,7 +119,7 @@ class Contact
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function selectToArray(array $fields = [], array $condition = [], array $params = []) public static function selectToArray(array $fields = [], array $condition = [], array $params = []): array
{ {
return DBA::selectToArray('contact', $fields, $condition, $params); return DBA::selectToArray('contact', $fields, $condition, $params);
} }
@ -128,7 +128,7 @@ class Contact
* @param array $fields Array of selected fields, empty for all * @param array $fields Array of selected fields, empty for all
* @param array $condition Array of fields for condition * @param array $condition Array of fields for condition
* @param array $params Array of several parameters * @param array $params Array of several parameters
* @return array * @return array|bool
* @throws \Exception * @throws \Exception
*/ */
public static function selectFirst(array $fields = [], array $condition = [], array $params = []) public static function selectFirst(array $fields = [], array $condition = [], array $params = [])
@ -148,7 +148,7 @@ class Contact
* @return int id of the created contact * @return int id of the created contact
* @throws \Exception * @throws \Exception
*/ */
public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT) public static function insert(array $fields, int $duplicate_mode = Database::INSERT_DEFAULT): int
{ {
if (!empty($fields['baseurl']) && empty($fields['gsid'])) { if (!empty($fields['baseurl']) && empty($fields['gsid'])) {
$fields['gsid'] = GServer::getID($fields['baseurl'], true); $fields['gsid'] = GServer::getID($fields['baseurl'], true);
@ -187,6 +187,7 @@ class Contact
* *
* @return boolean was the update successfull? * @return boolean was the update successfull?
* @throws \Exception * @throws \Exception
* @todo Let's get rid of boolean type of $old_fields
*/ */
public static function update(array $fields, array $condition, $old_fields = []) public static function update(array $fields, array $condition, $old_fields = [])
{ {
@ -204,7 +205,7 @@ class Contact
* @return array|boolean Contact record if it exists, false otherwise * @return array|boolean Contact record if it exists, false otherwise
* @throws \Exception * @throws \Exception
*/ */
public static function getById($id, $fields = []) public static function getById(int $id, array $fields = [])
{ {
return DBA::selectFirst('contact', $fields, ['id' => $id]); return DBA::selectFirst('contact', $fields, ['id' => $id]);
} }
@ -217,7 +218,7 @@ class Contact
* @return array|boolean Contact record if it exists, false otherwise * @return array|boolean Contact record if it exists, false otherwise
* @throws \Exception * @throws \Exception
*/ */
public static function getByUriId($uri_id, $fields = []) public static function getByUriId(int $uri_id, array $fields = [])
{ {
return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]); return DBA::selectFirst('contact', $fields, ['uri-id' => $uri_id], ['order' => ['uid']]);
} }
@ -231,7 +232,7 @@ class Contact
* @param integer $uid User ID of the contact * @param integer $uid User ID of the contact
* @return array contact array * @return array contact array
*/ */
public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0) public static function getByURL(string $url, $update = null, array $fields = [], int $uid = 0): array
{ {
if ($update || is_null($update)) { if ($update || is_null($update)) {
$cid = self::getIdForURL($url, $uid, $update); $cid = self::getIdForURL($url, $uid, $update);
@ -302,7 +303,7 @@ class Contact
* @param array $fields Field list * @param array $fields Field list
* @return array contact array * @return array contact array
*/ */
public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []) public static function getByURLForUser(string $url, int $uid = 0, $update = false, array $fields = []): array
{ {
if ($uid != 0) { if ($uid != 0) {
$contact = self::getByURL($url, $update, $fields, $uid); $contact = self::getByURL($url, $update, $fields, $uid);
@ -333,7 +334,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isFollower($cid, $uid) public static function isFollower(int $cid, int $uid): bool
{ {
if (Contact\User::isBlocked($cid, $uid)) { if (Contact\User::isBlocked($cid, $uid)) {
return false; return false;
@ -358,7 +359,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isFollowerByURL($url, $uid) public static function isFollowerByURL(string $url, uid $uid): bool
{ {
$cid = self::getIdForURL($url, $uid); $cid = self::getIdForURL($url, $uid);
@ -370,16 +371,16 @@ class Contact
} }
/** /**
* Tests if the given user follow the given contact * Tests if the given user shares with the given contact
* *
* @param int $cid Either public contact id or user's contact id * @param int $cid Either public contact id or user's contact id
* @param int $uid User ID * @param int $uid User ID
* *
* @return boolean is the contact url being followed? * @return boolean is the contact sharing with given user?
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isSharing($cid, $uid) public static function isSharing(int $cid, int $uid): bool
{ {
if (Contact\User::isBlocked($cid, $uid)) { if (Contact\User::isBlocked($cid, $uid)) {
return false; return false;
@ -404,7 +405,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isSharingByURL($url, $uid) public static function isSharingByURL(string $url, int $uid): bool
{ {
$cid = self::getIdForURL($url, $uid); $cid = self::getIdForURL($url, $uid);
@ -425,7 +426,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function getBasepath($url, $dont_update = false) public static function getBasepath(string $url, bool $dont_update = false): string
{ {
$contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]); $contact = DBA::selectFirst('contact', ['id', 'baseurl'], ['uid' => 0, 'nurl' => Strings::normaliseLink($url)]);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
@ -459,7 +460,7 @@ class Contact
* *
* @return boolean Is it the same server? * @return boolean Is it the same server?
*/ */
public static function isLocal($url) public static function isLocal(string $url): bool
{ {
if (!parse_url($url, PHP_URL_SCHEME)) { if (!parse_url($url, PHP_URL_SCHEME)) {
$addr_parts = explode('@', $url); $addr_parts = explode('@', $url);
@ -476,7 +477,7 @@ class Contact
* *
* @return boolean Is it the same server? * @return boolean Is it the same server?
*/ */
public static function isLocalById(int $cid) public static function isLocalById(int $cid): bool
{ {
$contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]); $contact = DBA::selectFirst('contact', ['url', 'baseurl'], ['id' => $cid]);
if (!DBA::isResult($contact)) { if (!DBA::isResult($contact)) {
@ -500,7 +501,7 @@ class Contact
* @return integer|boolean Public contact id for given user id * @return integer|boolean Public contact id for given user id
* @throws \Exception * @throws \Exception
*/ */
public static function getPublicIdByUserId($uid) public static function getPublicIdByUserId(int $uid)
{ {
$self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]); $self = DBA::selectFirst('contact', ['url'], ['self' => true, 'uid' => $uid]);
if (!DBA::isResult($self)) { if (!DBA::isResult($self)) {
@ -519,7 +520,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function getPublicAndUserContactID($cid, $uid) public static function getPublicAndUserContactID(int $cid, int $uid): array
{ {
// We have to use the legacy function as long as the post update hasn't finished // We have to use the legacy function as long as the post update hasn't finished
if (DI::config()->get('system', 'post_update_version') < 1427) { if (DI::config()->get('system', 'post_update_version') < 1427) {
@ -560,7 +561,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function legacyGetPublicAndUserContactID($cid, $uid) private static function legacyGetPublicAndUserContactID(int $cid, int $uid): array
{ {
if (empty($uid) || empty($cid)) { if (empty($uid) || empty($cid)) {
return []; return [];
@ -1526,7 +1527,7 @@ class Contact
* @param int $type type of contact or account * @param int $type type of contact or account
* @return string * @return string
*/ */
public static function getAccountType(int $type) public static function getAccountType(int $type): string
{ {
switch ($type) { switch ($type) {
case self::TYPE_ORGANISATION: case self::TYPE_ORGANISATION:
@ -1552,11 +1553,11 @@ class Contact
/** /**
* Blocks a contact * Blocks a contact
* *
* @param int $cid * @param int $cid Contact id to block
* @return bool * @param string $reason Block reason
* @throws \Exception * @return bool Whether it was successful
*/ */
public static function block($cid, $reason = null) public static function block(int $cid, string $reason = null): bool
{ {
$return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]); $return = self::update(['blocked' => true, 'block_reason' => $reason], ['id' => $cid]);
@ -1566,11 +1567,10 @@ class Contact
/** /**
* Unblocks a contact * Unblocks a contact
* *
* @param int $cid * @param int $cid Contact id to unblock
* @return bool * @return bool Whether it was successfull
* @throws \Exception
*/ */
public static function unblock($cid) public static function unblock(int $cid): bool
{ {
$return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]); $return = self::update(['blocked' => false, 'block_reason' => null], ['id' => $cid]);
@ -1580,7 +1580,7 @@ class Contact
/** /**
* Ensure that cached avatar exist * Ensure that cached avatar exist
* *
* @param integer $cid * @param integer $cid Contact id
*/ */
public static function checkAvatarCache(int $cid) public static function checkAvatarCache(int $cid)
{ {
@ -1620,7 +1620,7 @@ class Contact
* @param bool $no_update Don't perfom an update if no cached avatar was found * @param bool $no_update Don't perfom an update if no cached avatar was found
* @return string photo path * @return string photo path
*/ */
private static function getAvatarPath(array $contact, string $size, $no_update = false) private static function getAvatarPath(array $contact, string $size, bool $no_update = false): string
{ {
$contact = self::checkAvatarCacheByArray($contact, $no_update); $contact = self::checkAvatarCacheByArray($contact, $no_update);
@ -1654,7 +1654,7 @@ class Contact
* @param bool $no_update Don't perfom an update if no cached avatar was found * @param bool $no_update Don't perfom an update if no cached avatar was found
* @return string photo path * @return string photo path
*/ */
public static function getPhoto(array $contact, bool $no_update = false) public static function getPhoto(array $contact, bool $no_update = false): string
{ {
return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update); return self::getAvatarPath($contact, Proxy::SIZE_SMALL, $no_update);
} }
@ -1666,7 +1666,7 @@ class Contact
* @param bool $no_update Don't perfom an update if no cached avatar was found * @param bool $no_update Don't perfom an update if no cached avatar was found
* @return string photo path * @return string photo path
*/ */
public static function getThumb(array $contact, bool $no_update = false) public static function getThumb(array $contact, bool $no_update = false): string
{ {
return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update); return self::getAvatarPath($contact, Proxy::SIZE_THUMB, $no_update);
} }
@ -1678,7 +1678,7 @@ class Contact
* @param bool $no_update Don't perfom an update if no cached avatar was found * @param bool $no_update Don't perfom an update if no cached avatar was found
* @return string photo path * @return string photo path
*/ */
public static function getMicro(array $contact, bool $no_update = false) public static function getMicro(array $contact, bool $no_update = false): string
{ {
return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update); return self::getAvatarPath($contact, Proxy::SIZE_MICRO, $no_update);
} }
@ -1690,7 +1690,7 @@ class Contact
* @param bool $no_update Don't perfom an update if no cached avatar was found * @param bool $no_update Don't perfom an update if no cached avatar was found
* @return array contact array with avatar cache fields * @return array contact array with avatar cache fields
*/ */
private static function checkAvatarCacheByArray(array $contact, bool $no_update = false) private static function checkAvatarCacheByArray(array $contact, bool $no_update = false): array
{ {
$update = false; $update = false;
$contact_fields = []; $contact_fields = [];
@ -1796,7 +1796,7 @@ class Contact
* @param string $size Size of the avatar picture * @param string $size Size of the avatar picture
* @return string avatar URL * @return string avatar URL
*/ */
public static function getDefaultAvatar(array $contact, string $size) public static function getDefaultAvatar(array $contact, string $size): string
{ {
switch ($size) { switch ($size) {
case Proxy::SIZE_MICRO: case Proxy::SIZE_MICRO:
@ -2614,7 +2614,7 @@ class Contact
* @throws HTTPException\NotFoundException * @throws HTTPException\NotFoundException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function createFromProbeForUser(int $uid, $url, $network = '') public static function createFromProbeForUser(int $uid, string $url, string $network = ''): array
{ {
$result = ['cid' => -1, 'success' => false, 'message' => '']; $result = ['cid' => -1, 'success' => false, 'message' => ''];
@ -2803,7 +2803,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function addRelationship(array $importer, array $contact, array $datarray, $sharing = false, $note = '') public static function addRelationship(array $importer, array $contact, array $datarray, bool $sharing = false, string $note = '')
{ {
// Should always be set // Should always be set
if (empty($datarray['author-id'])) { if (empty($datarray['author-id'])) {
@ -3030,7 +3030,7 @@ class Contact
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function pruneUnavailable(array $contact_ids) public static function pruneUnavailable(array $contact_ids): array
{ {
if (empty($contact_ids)) { if (empty($contact_ids)) {
return []; return [];
@ -3058,7 +3058,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function magicLink($contact_url, $url = '') public static function magicLink(string $contact_url, string $url = ''): string
{ {
if (!Session::isAuthenticated()) { if (!Session::isAuthenticated()) {
return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url; return $url ?: $contact_url; // Equivalent to: ($url != '') ? $url : $contact_url;
@ -3085,7 +3085,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function magicLinkById($cid, $url = '') public static function magicLinkById(int $cid, string $url = ''): string
{ {
$contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]); $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], ['id' => $cid]);
@ -3102,7 +3102,7 @@ class Contact
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function magicLinkByContact($contact, $url = '') public static function magicLinkByContact(array $contact, string $url = ''): string
{ {
$destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url']; $destination = $url ?: $contact['url']; // Equivalent to ($url != '') ? $url : $contact['url'];
@ -3143,7 +3143,7 @@ class Contact
* *
* @return boolean "true" if it is a forum * @return boolean "true" if it is a forum
*/ */
public static function isForum($contactid) public static function isForum(int $contactid): bool
{ {
$fields = ['contact-type']; $fields = ['contact-type'];
$condition = ['id' => $contactid]; $condition = ['id' => $contactid];
@ -3162,7 +3162,7 @@ class Contact
* @param array $contact * @param array $contact
* @return bool * @return bool
*/ */
public static function canReceivePrivateMessages(array $contact) public static function canReceivePrivateMessages(array $contact): bool
{ {
$protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM; $protocol = $contact['network'] ?? $contact['protocol'] ?? Protocol::PHANTOM;
$self = $contact['self'] ?? false; $self = $contact['self'] ?? false;
@ -3180,7 +3180,7 @@ class Contact
* @return array with search results * @return array with search results
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function searchByName(string $search, string $mode = '', int $uid = 0) public static function searchByName(string $search, string $mode = '', int $uid = 0): array
{ {
if (empty($search)) { if (empty($search)) {
return []; return [];
@ -3223,7 +3223,7 @@ class Contact
* @param array $urls * @param array $urls
* @return array result "count", "added" and "updated" * @return array result "count", "added" and "updated"
*/ */
public static function addByUrls(array $urls) public static function addByUrls(array $urls): array
{ {
$added = 0; $added = 0;
$updated = 0; $updated = 0;
@ -3256,7 +3256,7 @@ class Contact
* @return array The profile array * @return array The profile array
* @throws Exception * @throws Exception
*/ */
public static function getRandomContact() public static function getRandomContact(): array
{ {
$contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [ $contact = DBA::selectFirst('contact', ['id', 'network', 'url', 'uid'], [
"`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?", "`uid` = ? AND `network` = ? AND NOT `failed` AND `last-item` > ?",

View file

@ -62,7 +62,7 @@ class Conversation
*/ */
const RELAY = 3; const RELAY = 3;
public static function getByItemUri($item_uri) public static function getByItemUri(string $item_uri)
{ {
return DBA::selectFirst('conversation', [], ['item-uri' => $item_uri]); return DBA::selectFirst('conversation', [], ['item-uri' => $item_uri]);
} }
@ -74,7 +74,7 @@ class Conversation
* @return array Item array with removed conversation data * @return array Item array with removed conversation data
* @throws \Exception * @throws \Exception
*/ */
public static function insert(array $arr) public static function insert(array $arr): array
{ {
if (in_array(($arr['network'] ?? '') ?: Protocol::PHANTOM, if (in_array(($arr['network'] ?? '') ?: Protocol::PHANTOM,
[Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::TWITTER]) && !empty($arr['uri'])) { [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::TWITTER]) && !empty($arr['uri'])) {

View file

@ -41,7 +41,7 @@ use Friendica\Util\XML;
class Event class Event
{ {
public static function getHTML(array $event, $simple = false, $uriid = 0) public static function getHTML(array $event, bool $simple = false, int $uriid = 0): string
{ {
if (empty($event)) { if (empty($event)) {
return ''; return '';
@ -127,7 +127,7 @@ class Event
* @param array $event Array which contains the event data. * @param array $event Array which contains the event data.
* @return string The event as a bbcode formatted string. * @return string The event as a bbcode formatted string.
*/ */
private static function getBBCode(array $event) private static function getBBCode(array $event): string
{ {
$o = ''; $o = '';
@ -157,11 +157,10 @@ class Event
/** /**
* Extract bbcode formatted event data from a string. * Extract bbcode formatted event data from a string.
* *
* @params: string $s The string which should be parsed for event data. * @param string $text The string which should be parsed for event data.
* @param $text
* @return array The array with the event information. * @return array The array with the event information.
*/ */
public static function fromBBCode($text) public static function fromBBCode(string $text): array
{ {
$ev = []; $ev = [];
@ -195,13 +194,13 @@ class Event
return $ev; return $ev;
} }
public static function sortByDate($event_list) public static function sortByDate(array $event_list): array
{ {
usort($event_list, ['self', 'compareDatesCallback']); usort($event_list, ['self', 'compareDatesCallback']);
return $event_list; return $event_list;
} }
private static function compareDatesCallback($event_a, $event_b) private static function compareDatesCallback(array $event_a, array $event_b)
{ {
$date_a = DateTimeFormat::local($event_a['start']); $date_a = DateTimeFormat::local($event_a['start']);
$date_b = DateTimeFormat::local($event_b['start']); $date_b = DateTimeFormat::local($event_b['start']);
@ -223,7 +222,7 @@ class Event
* @return void * @return void
* @throws \Exception * @throws \Exception
*/ */
public static function delete($event_id) public static function delete(int $event_id)
{ {
if ($event_id == 0) { if ($event_id == 0) {
return; return;
@ -242,7 +241,7 @@ class Event
* @return int The new event id. * @return int The new event id.
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function store($arr) public static function store(array $arr): int
{ {
$event = []; $event = [];
$event['id'] = intval($arr['id'] ?? 0); $event['id'] = intval($arr['id'] ?? 0);
@ -317,7 +316,7 @@ class Event
return $event['id']; return $event['id'];
} }
public static function getItemArrayForId(int $event_id, array $item = []):array public static function getItemArrayForId(int $event_id, array $item = []): array
{ {
if (empty($event_id)) { if (empty($event_id)) {
return $item; return $item;
@ -374,7 +373,7 @@ class Event
return $item; return $item;
} }
public static function getItemArrayForImportedId(int $event_id, array $item = []):array public static function getItemArrayForImportedId(int $event_id, array $item = []): array
{ {
if (empty($event_id)) { if (empty($event_id)) {
return $item; return $item;
@ -404,7 +403,7 @@ class Event
* @return array Array with translations strings. * @return array Array with translations strings.
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function getStrings() public static function getStrings(): array
{ {
// First day of the week (0 = Sunday). // First day of the week (0 = Sunday).
$firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0); $firstDay = DI::pConfig()->get(local_user(), 'system', 'first_day_of_week', 0);
@ -477,7 +476,7 @@ class Event
* *
* @todo We should replace this with a separate update function if there is some time left. * @todo We should replace this with a separate update function if there is some time left.
*/ */
private static function removeDuplicates(array $dates) private static function removeDuplicates(array $dates): array
{ {
$dates2 = []; $dates2 = [];
@ -500,7 +499,7 @@ class Event
* @return array Query result * @return array Query result
* @throws \Exception * @throws \Exception
*/ */
public static function getListById($owner_uid, $event_id, $sql_extra = '') public static function getListById(int $owner_uid, int $event_id, string $sql_extra = ''): array
{ {
$return = []; $return = [];
@ -536,7 +535,7 @@ class Event
* @return array Query results. * @return array Query results.
* @throws \Exception * @throws \Exception
*/ */
public static function getListByDate($owner_uid, $event_params, $sql_extra = '') public static function getListByDate(int $owner_uid, array $event_params, string $sql_extra = ''): array
{ {
$return = []; $return = [];
@ -570,7 +569,7 @@ class Event
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function prepareListForTemplate(array $event_result) public static function prepareListForTemplate(array $event_result): array
{ {
$event_list = []; $event_list = [];
@ -651,12 +650,12 @@ class Event
* @param array $events Query result for events. * @param array $events Query result for events.
* @param string $format The output format (ical/csv). * @param string $format The output format (ical/csv).
* *
* @param $timezone * @param string $timezone Timezone (missing parameter!)
* @return string Content according to selected export format. * @return string Content according to selected export format.
* *
* @todo Implement timezone support * @todo Implement timezone support
*/ */
private static function formatListForExport(array $events, $format) private static function formatListForExport(array $events, string $format): string
{ {
$o = ''; $o = '';
@ -757,7 +756,7 @@ class Event
* @return array Query results. * @return array Query results.
* @throws \Exception * @throws \Exception
*/ */
private static function getListByUserId($uid = 0) private static function getListByUserId(int $uid = 0): array
{ {
$return = []; $return = [];
@ -797,7 +796,7 @@ class Event
* @throws \Exception * @throws \Exception
* @todo Respect authenticated users with events_by_uid(). * @todo Respect authenticated users with events_by_uid().
*/ */
public static function exportListByUserId($uid, $format = 'ical') public static function exportListByUserId(int $uid, string $format = 'ical'): array
{ {
$process = false; $process = false;
@ -845,7 +844,8 @@ class Event
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function getItemHTML(array $item) { public static function getItemHTML(array $item): string
{
$same_date = false; $same_date = false;
$finish = false; $finish = false;
@ -933,10 +933,11 @@ class Event
* @return array The array with the location data. * @return array The array with the location data.
* 'name' => The name of the location,<br> * 'name' => The name of the location,<br>
* 'address' => The address of the location,<br> * 'address' => The address of the location,<br>
* 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br> * 'coordinates' => Latitude and longitude (e.g. '48.864716,2.349014').<br>
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function locationToArray($s = '') { private static function locationToArray(string $s = ''): array
{
if ($s == '') { if ($s == '') {
return []; return [];
} }
@ -981,7 +982,7 @@ class Event
* @return bool * @return bool
* @throws \Exception * @throws \Exception
*/ */
public static function createBirthday($contact, $birthday) public static function createBirthday(array $contact, string $birthday): bool
{ {
// Check for duplicates // Check for duplicates
$condition = [ $condition = [
@ -1011,8 +1012,7 @@ class Event
'type' => 'birthday', 'type' => 'birthday',
]; ];
self::store($values); // Check if self::store() was success
return (self::store($values) > 0);
return true;
} }
} }

View file

@ -40,7 +40,7 @@ class FContact
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function getByURL($handle, $update = null) public static function getByURL(string $handle, $update = null): array
{ {
$person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]); $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
if (!DBA::isResult($person)) { if (!DBA::isResult($person)) {
@ -90,7 +90,7 @@ class FContact
* @param array $arr The fcontact data * @param array $arr The fcontact data
* @throws \Exception * @throws \Exception
*/ */
public static function updateFromProbeArray($arr) public static function updateFromProbeArray(array $arr)
{ {
$uriid = ItemURI::insert(['uri' => $arr['url'], 'guid' => $arr['guid']]); $uriid = ItemURI::insert(['uri' => $arr['url'], 'guid' => $arr['guid']]);
@ -122,12 +122,12 @@ class FContact
* get a url (scheme://domain.tld/u/user) from a given Diaspora* * get a url (scheme://domain.tld/u/user) from a given Diaspora*
* fcontact guid * fcontact guid
* *
* @param mixed $fcontact_guid Hexadecimal string guid * @param string $fcontact_guid Hexadecimal string guid
* *
* @return string the contact url or null * @return string|null the contact url or null
* @throws \Exception * @throws \Exception
*/ */
public static function getUrlByGuid($fcontact_guid) public static function getUrlByGuid(string $fcontact_guid)
{ {
Logger::info('fcontact', ['guid' => $fcontact_guid]); Logger::info('fcontact', ['guid' => $fcontact_guid]);

View file

@ -2054,7 +2054,7 @@ class GServer
* @return int * @return int
* @throws Exception * @throws Exception
*/ */
public static function getProtocol(int $gsid) public static function getProtocol(int $gsid): int
{ {
if (empty($gsid)) { if (empty($gsid)) {
return null; return null;

View file

@ -60,7 +60,7 @@ class ParsedLogIterator implements \Iterator
* @param string $filename File to open * @param string $filename File to open
* @return $this * @return $this
*/ */
public function open(string $filename) public function open(string $filename): ParsedLogIterator
{ {
$this->reader->open($filename); $this->reader->open($filename);
return $this; return $this;
@ -70,7 +70,7 @@ class ParsedLogIterator implements \Iterator
* @param int $limit Max num of lines to read * @param int $limit Max num of lines to read
* @return $this * @return $this
*/ */
public function withLimit(int $limit) public function withLimit(int $limit): ParsedLogIterator
{ {
$this->limit = $limit; $this->limit = $limit;
return $this; return $this;
@ -80,7 +80,7 @@ class ParsedLogIterator implements \Iterator
* @param array $filters filters per column * @param array $filters filters per column
* @return $this * @return $this
*/ */
public function withFilters(array $filters) public function withFilters(array $filters): ParsedLogIterator
{ {
$this->filters = $filters; $this->filters = $filters;
return $this; return $this;
@ -90,7 +90,7 @@ class ParsedLogIterator implements \Iterator
* @param string $search string to search to filter lines * @param string $search string to search to filter lines
* @return $this * @return $this
*/ */
public function withSearch(string $search) public function withSearch(string $search): ParsedLogIterator
{ {
$this->search = $search; $this->search = $search;
return $this; return $this;
@ -100,10 +100,10 @@ class ParsedLogIterator implements \Iterator
* Check if parsed log line match filters. * Check if parsed log line match filters.
* Always match if no filters are set. * Always match if no filters are set.
* *
* @param ParsedLogLine $parsedlogline * @param ParsedLogLine $parsedlogline ParsedLogLine instance
* @return bool * @return bool Wether the parse log line matches
*/ */
private function filter($parsedlogline) private function filter(ParsedLogLine $parsedlogline): bool
{ {
$match = true; $match = true;
foreach ($this->filters as $filter => $filtervalue) { foreach ($this->filters as $filter => $filtervalue) {
@ -126,7 +126,7 @@ class ParsedLogIterator implements \Iterator
* @param ParsedLogLine $parsedlogline * @param ParsedLogLine $parsedlogline
* @return bool * @return bool
*/ */
private function search($parsedlogline) private function search(ParsedLogLine $parsedlogline): bool
{ {
if ($this->search != "") { if ($this->search != "") {
return strstr($parsedlogline->logline, $this->search) !== false; return strstr($parsedlogline->logline, $this->search) !== false;

View file

@ -110,7 +110,7 @@ class Photo
* @throws \Exception * @throws \Exception
* @see \Friendica\Database\DBA::select * @see \Friendica\Database\DBA::select
*/ */
public static function getPhotosForUser($uid, $resourceid, array $conditions = [], array $params = []) public static function getPhotosForUser(int $uid, string $resourceid, array $conditions = [], array $params = [])
{ {
$conditions["resource-id"] = $resourceid; $conditions["resource-id"] = $resourceid;
$conditions["uid"] = $uid; $conditions["uid"] = $uid;

View file

@ -237,7 +237,7 @@ class Profile
if (!local_user()) { if (!local_user()) {
$a->setCurrentTheme($profile['theme']); $a->setCurrentTheme($profile['theme']);
$a->setCurrentMobileTheme(DI::pConfig()->get($a->getProfileOwner(), 'system', 'mobile_theme')); $a->setCurrentMobileTheme(DI::pConfig()->get($a->getProfileOwner(), 'system', 'mobile_theme') ?? '');
} }
/* /*

View file

@ -134,7 +134,7 @@ class User
* *
* @return array system account * @return array system account
*/ */
public static function getSystemAccount() public static function getSystemAccount(): array
{ {
$system = Contact::selectFirst([], ['self' => true, 'uid' => 0]); $system = Contact::selectFirst([], ['self' => true, 'uid' => 0]);
if (!DBA::isResult($system)) { if (!DBA::isResult($system)) {
@ -244,7 +244,7 @@ class User
* *
* @return string actor account name * @return string actor account name
*/ */
public static function getActorName() public static function getActorName(): string
{ {
$system_actor_name = DI::config()->get('system', 'actor_name'); $system_actor_name = DI::config()->get('system', 'actor_name');
if (!empty($system_actor_name)) { if (!empty($system_actor_name)) {
@ -278,7 +278,7 @@ class User
* @return boolean * @return boolean
* @throws Exception * @throws Exception
*/ */
public static function exists($uid) public static function exists(int $uid): bool
{ {
return DBA::exists('user', ['uid' => $uid]); return DBA::exists('user', ['uid' => $uid]);
} }
@ -289,7 +289,7 @@ class User
* @return array|boolean User record if it exists, false otherwise * @return array|boolean User record if it exists, false otherwise
* @throws Exception * @throws Exception
*/ */
public static function getById($uid, array $fields = []) public static function getById(int $uid, array $fields = [])
{ {
return !empty($uid) ? DBA::selectFirst('user', $fields, ['uid' => $uid]) : []; return !empty($uid) ? DBA::selectFirst('user', $fields, ['uid' => $uid]) : [];
} }
@ -321,7 +321,7 @@ class User
* @return array|boolean User record if it exists, false otherwise * @return array|boolean User record if it exists, false otherwise
* @throws Exception * @throws Exception
*/ */
public static function getByNickname($nickname, array $fields = []) public static function getByNickname(string $nickname, array $fields = [])
{ {
return DBA::selectFirst('user', $fields, ['nickname' => $nickname]); return DBA::selectFirst('user', $fields, ['nickname' => $nickname]);
} }
@ -334,7 +334,7 @@ class User
* @return integer user id * @return integer user id
* @throws Exception * @throws Exception
*/ */
public static function getIdForURL(string $url) public static function getIdForURL(string $url): int
{ {
// Avoid database queries when the local node hostname isn't even part of the url. // Avoid database queries when the local node hostname isn't even part of the url.
if (!Contact::isLocal($url)) { if (!Contact::isLocal($url)) {
@ -380,7 +380,7 @@ class User
* @param array $fields * @param array $fields
* @return array user * @return array user
*/ */
public static function getFirstAdmin(array $fields = []) public static function getFirstAdmin(array $fields = []) : array
{ {
if (!empty(DI::config()->get('config', 'admin_nickname'))) { if (!empty(DI::config()->get('config', 'admin_nickname'))) {
return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields); return self::getByNickname(DI::config()->get('config', 'admin_nickname'), $fields);
@ -469,7 +469,7 @@ class User
* @return boolean|array * @return boolean|array
* @throws Exception * @throws Exception
*/ */
public static function getOwnerDataByNick($nick) public static function getOwnerDataByNick(string $nick)
{ {
$user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]); $user = DBA::selectFirst('user', ['uid'], ['nickname' => $nick]);
@ -488,7 +488,7 @@ class User
* @return int group id * @return int group id
* @throws Exception * @throws Exception
*/ */
public static function getDefaultGroup($uid) public static function getDefaultGroup(int $uid): int
{ {
$user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]); $user = DBA::selectFirst('user', ['def_gid'], ['uid' => $uid]);
if (DBA::isResult($user)) { if (DBA::isResult($user)) {
@ -512,7 +512,7 @@ class User
* @throws HTTPException\ForbiddenException * @throws HTTPException\ForbiddenException
* @throws HTTPException\NotFoundException * @throws HTTPException\NotFoundException
*/ */
public static function getIdFromPasswordAuthentication($user_info, $password, $third_party = false) public static function getIdFromPasswordAuthentication($user_info, string $password, bool $third_party = false)
{ {
// Addons registered with the "authenticate" hook may create the user on the // Addons registered with the "authenticate" hook may create the user on the
// fly. `getAuthenticationInfo` will fail if the user doesn't exist yet. If // fly. `getAuthenticationInfo` will fail if the user doesn't exist yet. If
@ -580,7 +580,7 @@ class User
* @return int User Id if authentication is successful * @return int User Id if authentication is successful
* @throws HTTPException\ForbiddenException * @throws HTTPException\ForbiddenException
*/ */
public static function getIdFromAuthenticateHooks($username, $password) public static function getIdFromAuthenticateHooks(string $username, string $password): int
{ {
$addon_auth = [ $addon_auth = [
'username' => $username, 'username' => $username,
@ -613,7 +613,7 @@ class User
* - User array with at least the uid and the hashed password * - User array with at least the uid and the hashed password
* *
* @param mixed $user_info * @param mixed $user_info
* @return array * @return array|null Null if not found/determined
* @throws HTTPException\NotFoundException * @throws HTTPException\NotFoundException
*/ */
public static function getAuthenticationInfo($user_info) public static function getAuthenticationInfo($user_info)
@ -671,7 +671,7 @@ class User
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public static function generateNewPassword() public static function generateNewPassword(): string
{ {
return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999); return ucfirst(Strings::getRandomName(8)) . random_int(1000, 9999);
} }
@ -683,7 +683,7 @@ class User
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public static function isPasswordExposed($password) public static function isPasswordExposed(string $password): bool
{ {
$cache = new CacheItemPool(); $cache = new CacheItemPool();
$cache->changeConfig([ $cache->changeConfig([
@ -712,7 +712,7 @@ class User
* @param string $password * @param string $password
* @return string * @return string
*/ */
private static function hashPasswordLegacy($password) private static function hashPasswordLegacy(string $password): string
{ {
return hash('whirlpool', $password); return hash('whirlpool', $password);
} }
@ -724,7 +724,7 @@ class User
* @return string * @return string
* @throws Exception * @throws Exception
*/ */
public static function hashPassword($password) public static function hashPassword(string $password): string
{ {
if (!trim($password)) { if (!trim($password)) {
throw new Exception(DI::l10n()->t('Password can\'t be empty')); throw new Exception(DI::l10n()->t('Password can\'t be empty'));
@ -741,7 +741,7 @@ class User
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
public static function updatePassword($uid, $password) public static function updatePassword(int $uid, string $password): bool
{ {
$password = trim($password); $password = trim($password);
@ -771,7 +771,7 @@ class User
* @return bool * @return bool
* @throws Exception * @throws Exception
*/ */
private static function updatePasswordHashed($uid, $pasword_hashed) private static function updatePasswordHashed(int $uid, string $pasword_hashed): bool
{ {
$fields = [ $fields = [
'password' => $pasword_hashed, 'password' => $pasword_hashed,
@ -792,7 +792,7 @@ class User
* @param string $nickname The nickname that should be checked * @param string $nickname The nickname that should be checked
* @return boolean True is the nickname is blocked on the node * @return boolean True is the nickname is blocked on the node
*/ */
public static function isNicknameBlocked($nickname) public static function isNicknameBlocked(string $nickname): bool
{ {
$forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', ''); $forbidden_nicknames = DI::config()->get('system', 'forbidden_nicknames', '');
if (!empty($forbidden_nicknames)) { if (!empty($forbidden_nicknames)) {
@ -829,7 +829,7 @@ class User
* @return string avatar link * @return string avatar link
* @throws Exception * @throws Exception
*/ */
public static function getAvatarUrl(array $user, string $size = ''):string public static function getAvatarUrl(array $user, string $size = ''): string
{ {
if (empty($user['nickname'])) { if (empty($user['nickname'])) {
DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]); DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]);
@ -871,7 +871,7 @@ class User
* @return string banner link * @return string banner link
* @throws Exception * @throws Exception
*/ */
public static function getBannerUrl(array $user):string public static function getBannerUrl(array $user): string
{ {
if (empty($user['nickname'])) { if (empty($user['nickname'])) {
DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]); DI::logger()->warning('Missing user nickname key', ['trace' => System::callstack(20)]);
@ -913,7 +913,7 @@ class User
* @throws ImagickException * @throws ImagickException
* @throws Exception * @throws Exception
*/ */
public static function create(array $data) public static function create(array $data): array
{ {
$return = ['user' => null, 'password' => '']; $return = ['user' => null, 'password' => ''];
@ -1255,7 +1255,7 @@ class User
* @throws Exception * @throws Exception
*/ */
public static function block(int $uid, bool $block = true) public static function block(int $uid, bool $block = true): bool
{ {
return DBA::update('user', ['blocked' => $block], ['uid' => $uid]); return DBA::update('user', ['blocked' => $block], ['uid' => $uid]);
} }
@ -1270,7 +1270,7 @@ class User
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws Exception * @throws Exception
*/ */
public static function allow(string $hash) public static function allow(string $hash): bool
{ {
$register = Register::getByHash($hash); $register = Register::getByHash($hash);
if (!DBA::isResult($register)) { if (!DBA::isResult($register)) {
@ -1316,7 +1316,7 @@ class User
* @return bool True, if the deny was successfull * @return bool True, if the deny was successfull
* @throws Exception * @throws Exception
*/ */
public static function deny(string $hash) public static function deny(string $hash): bool
{ {
$register = Register::getByHash($hash); $register = Register::getByHash($hash);
if (!DBA::isResult($register)) { if (!DBA::isResult($register)) {
@ -1348,7 +1348,7 @@ class User
* @throws ErrorException * @throws ErrorException
* @throws ImagickException * @throws ImagickException
*/ */
public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT) public static function createMinimal(string $name, string $email, string $nick, string $lang = L10n::DEFAULT): bool
{ {
if (empty($name) || if (empty($name) ||
empty($email) || empty($email) ||
@ -1418,7 +1418,7 @@ class User
* @return NULL|boolean from notification() and email() inherited * @return NULL|boolean from notification() and email() inherited
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
public static function sendRegisterPendingEmail($user, $sitename, $siteurl, $password) public static function sendRegisterPendingEmail(array $user, string $sitename, string $siteurl, string $password)
{ {
$body = Strings::deindent(DI::l10n()->t( $body = Strings::deindent(DI::l10n()->t(
' '
@ -1461,7 +1461,7 @@ class User
* @return NULL|boolean from notification() and email() inherited * @return NULL|boolean from notification() and email() inherited
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
public static function sendRegisterOpenEmail(L10n $l10n, $user, $sitename, $siteurl, $password) public static function sendRegisterOpenEmail(L10n $l10n, array $user, string $sitename, string $siteurl, string $password)
{ {
$preamble = Strings::deindent($l10n->t( $preamble = Strings::deindent($l10n->t(
' '
@ -1520,7 +1520,7 @@ class User
* @return bool * @return bool
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
public static function remove(int $uid) public static function remove(int $uid): bool
{ {
if (empty($uid)) { if (empty($uid)) {
return false; return false;
@ -1574,7 +1574,7 @@ class User
* ] * ]
* @throws Exception * @throws Exception
*/ */
public static function identities($uid) public static function identities(int $uid): array
{ {
if (empty($uid)) { if (empty($uid)) {
return []; return [];
@ -1646,7 +1646,7 @@ class User
* @param int $uid * @param int $uid
* @return bool * @return bool
*/ */
public static function hasIdentities(int $uid):bool public static function hasIdentities(int $uid): bool
{ {
if (empty($uid)) { if (empty($uid)) {
return false; return false;
@ -1679,7 +1679,7 @@ class User
* *
* @throws Exception * @throws Exception
*/ */
public static function getStatistics() public static function getStatistics(): array
{ {
$statistics = [ $statistics = [
'total_users' => 0, 'total_users' => 0,
@ -1732,10 +1732,10 @@ class User
* @param string $order Order of the user list (Default is 'contact.name') * @param string $order Order of the user list (Default is 'contact.name')
* @param bool $descending Order direction (Default is ascending) * @param bool $descending Order direction (Default is ascending)
* *
* @return array The list of the users * @return array|bool The list of the users
* @throws Exception * @throws Exception
*/ */
public static function getList($start = 0, $count = Pager::ITEMS_PER_PAGE, $type = 'all', $order = 'name', bool $descending = false) public static function getList(int $start = 0, int $count = Pager::ITEMS_PER_PAGE, string $type = 'all', string $order = 'name', bool $descending = false)
{ {
$param = ['limit' => [$start, $count], 'order' => [$order => $descending]]; $param = ['limit' => [$start, $count], 'order' => [$order => $descending]];
$condition = []; $condition = [];

View file

@ -59,12 +59,13 @@ class Notify extends BaseModule
} }
} }
private static function dispatchPublic($postdata) private static function dispatchPublic(array $postdata)
{ {
$msg = Diaspora::decodeRaw($postdata, '', true); $msg = Diaspora::decodeRaw($postdata, '', true);
if (!$msg) { if (!is_array($msg)) {
// We have to fail silently to be able to hand it over to the salmon parser // We have to fail silently to be able to hand it over to the salmon parser
return false; Logger::warning('Diaspora::decodeRaw() has failed for some reason.');
return;
} }
// Fetch the corresponding public contact // Fetch the corresponding public contact
@ -88,10 +89,10 @@ class Notify extends BaseModule
System::xmlExit($ret, 'Done'); System::xmlExit($ret, 'Done');
} }
private static function dispatchPrivate($user, $postdata) private static function dispatchPrivate(array $user, string $postdata)
{ {
$msg = Diaspora::decodeRaw($postdata, $user['prvkey'] ?? ''); $msg = Diaspora::decodeRaw($postdata, $user['prvkey'] ?? '');
if (!$msg) { if (!is_array($msg)) {
System::xmlExit(4, 'Unable to parse message'); System::xmlExit(4, 'Unable to parse message');
} }

View file

@ -34,6 +34,6 @@ class Poll extends BaseModule
protected function rawContent(array $request = []) protected function rawContent(array $request = [])
{ {
$last_update = $request['last_update'] ?? ''; $last_update = $request['last_update'] ?? '';
System::httpExit(OStatus::feed($this->parameters['nickname'], $last_update, 10), Response::TYPE_ATOM); System::httpExit(OStatus::feed($this->parameters['nickname'], $last_update, 10) ?? '', Response::TYPE_ATOM);
} }
} }

View file

@ -112,7 +112,7 @@ class Directory extends BaseModule
* *
* @throws \Exception * @throws \Exception
*/ */
public static function formatEntry(array $contact, $photo_size = 'photo') public static function formatEntry(array $contact, string $photo_size = 'photo'): array
{ {
$itemurl = (($contact['addr'] != "") ? $contact['addr'] : $contact['url']); $itemurl = (($contact['addr'] != "") ? $contact['addr'] : $contact['url']);
@ -166,7 +166,7 @@ class Directory extends BaseModule
'img_hover' => $contact['name'], 'img_hover' => $contact['name'],
'name' => $contact['name'], 'name' => $contact['name'],
'details' => $details, 'details' => $details,
'account_type' => Model\Contact::getAccountType($contact['contact-type']), 'account_type' => Model\Contact::getAccountType($contact['contact-type'] ?? ''),
'profile' => $profile, 'profile' => $profile,
'location' => $location_e, 'location' => $location_e,
'tags' => $contact['pub_keywords'], 'tags' => $contact['pub_keywords'],

View file

@ -1445,7 +1445,7 @@ class Probe
* @return array|bool OStatus data or "false" on error or "true" on short mode * @return array|bool OStatus data or "false" on error or "true" on short mode
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
private static function ostatus($webfinger, $short = false) private static function ostatus(array $webfinger, bool $short = false)
{ {
$data = []; $data = [];

View file

@ -33,9 +33,9 @@ class ProfileFields extends BaseCollection
/** /**
* @param callable $callback * @param callable $callback
* @return ProfileFields * @return ProfileFields (as an extended form of BaseCollection)
*/ */
public function map(callable $callback): ProfileFields public function map(callable $callback): BaseCollection
{ {
return parent::map($callback); return parent::map($callback);
} }
@ -43,9 +43,9 @@ class ProfileFields extends BaseCollection
/** /**
* @param callable|null $callback * @param callable|null $callback
* @param int $flag * @param int $flag
* @return ProfileFields * @return ProfileFields as an extended version of BaseCollection
*/ */
public function filter(callable $callback = null, int $flag = 0): ProfileFields public function filter(callable $callback = null, int $flag = 0): BaseCollection
{ {
return parent::filter($callback, $flag); return parent::filter($callback, $flag);
} }

View file

@ -212,7 +212,7 @@ final class Activity
* *
* @return bool True, if the activity is hidden * @return bool True, if the activity is hidden
*/ */
public function isHidden(string $activity) public function isHidden(string $activity): bool
{ {
foreach (self::HIDDEN_ACTIVITIES as $hiddenActivity) { foreach (self::HIDDEN_ACTIVITIES as $hiddenActivity) {
if ($this->match($activity, $hiddenActivity)) { if ($this->match($activity, $hiddenActivity)) {
@ -231,7 +231,7 @@ final class Activity
* *
* @return boolean * @return boolean
*/ */
public function match(string $haystack, string $needle) public function match(string $haystack, string $needle): bool
{ {
return (($haystack === $needle) || return (($haystack === $needle) ||
((basename($needle) === $haystack) && ((basename($needle) === $haystack) &&

View file

@ -104,12 +104,12 @@ class ActivityPub
* @return array * @return array
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function fetchContent(string $url, int $uid = 0) public static function fetchContent(string $url, int $uid = 0): array
{ {
return HTTPSignature::fetch($url, $uid); return HTTPSignature::fetch($url, $uid);
} }
private static function getAccountType($apcontact) private static function getAccountType(array $apcontact): int
{ {
$accounttype = -1; $accounttype = -1;
@ -146,7 +146,7 @@ class ActivityPub
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function probeProfile($url, $update = true) public static function probeProfile(string $url, bool $update = true): array
{ {
$apcontact = APContact::getByURL($url, $update); $apcontact = APContact::getByURL($url, $update);
if (empty($apcontact)) { if (empty($apcontact)) {
@ -204,7 +204,7 @@ class ActivityPub
* @param integer $uid User ID * @param integer $uid User ID
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function fetchOutbox($url, $uid) public static function fetchOutbox(string $url, int $uid)
{ {
$data = self::fetchContent($url, $uid); $data = self::fetchContent($url, $uid);
if (empty($data)) { if (empty($data)) {
@ -235,7 +235,7 @@ class ActivityPub
* @param integer $uid Optional user id * @param integer $uid Optional user id
* @return array Endpoint items * @return array Endpoint items
*/ */
public static function fetchItems(string $url, int $uid = 0) public static function fetchItems(string $url, int $uid = 0): array
{ {
$data = self::fetchContent($url, $uid); $data = self::fetchContent($url, $uid);
if (empty($data)) { if (empty($data)) {
@ -268,7 +268,7 @@ class ActivityPub
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isSupportedByContactUrl($url, $update = null) public static function isSupportedByContactUrl(string $url, $update = null)
{ {
return !empty(APContact::getByURL($url, $update)); return !empty(APContact::getByURL($url, $update));
} }

View file

@ -94,7 +94,7 @@ class Processor
* *
* @return string with replaced emojis * @return string with replaced emojis
*/ */
private static function replaceEmojis(int $uri_id, string $body, array $emojis) private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
{ {
$body = strtr($body, $body = strtr($body,
array_combine( array_combine(
@ -690,7 +690,7 @@ class Processor
* @param string $url message URL * @param string $url message URL
* @return string with GUID * @return string with GUID
*/ */
private static function getGUIDByURL(string $url) private static function getGUIDByURL(string $url): string
{ {
$parsed = parse_url($url); $parsed = parse_url($url);
@ -711,7 +711,7 @@ class Processor
* @param array $item * @param array $item
* @return boolean Is the message wanted? * @return boolean Is the message wanted?
*/ */
private static function isSolicitedMessage(array $activity, array $item) private static function isSolicitedMessage(array $activity, array $item): bool
{ {
// The checks are split to improve the support when searching why a message was accepted. // The checks are split to improve the support when searching why a message was accepted.
if (count($activity['receiver']) != 1) { if (count($activity['receiver']) != 1) {
@ -972,7 +972,7 @@ class Processor
* @return int|bool New mail table row id or false on error * @return int|bool New mail table row id or false on error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function postMail($activity, $item) private static function postMail(array $activity, array $item)
{ {
if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) { if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]); Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
@ -1113,7 +1113,7 @@ class Processor
* @return string fetched message URL * @return string fetched message URL
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL) public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
{ {
if (!empty($child['receiver'])) { if (!empty($child['receiver'])) {
$uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']); $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
@ -1208,7 +1208,7 @@ class Processor
* @param string $id object ID * @param string $id object ID
* @return boolean true if message is accepted * @return boolean true if message is accepted
*/ */
private static function acceptIncomingMessage(array $activity, string $id) private static function acceptIncomingMessage(array $activity, string $id): bool
{ {
if (empty($activity['as:object'])) { if (empty($activity['as:object'])) {
Logger::info('No object field in activity - accepted', ['id' => $id]); Logger::info('No object field in activity - accepted', ['id' => $id]);
@ -1248,7 +1248,7 @@ class Processor
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function followUser($activity) public static function followUser(array $activity)
{ {
$uid = User::getIdForURL($activity['object_id']); $uid = User::getIdForURL($activity['object_id']);
if (empty($uid)) { if (empty($uid)) {
@ -1326,7 +1326,7 @@ class Processor
* @param array $activity * @param array $activity
* @throws \Exception * @throws \Exception
*/ */
public static function updatePerson($activity) public static function updatePerson(array $activity)
{ {
if (empty($activity['object_id'])) { if (empty($activity['object_id'])) {
return; return;
@ -1342,7 +1342,7 @@ class Processor
* @param array $activity * @param array $activity
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function deletePerson($activity) public static function deletePerson(array $activity)
{ {
if (empty($activity['object_id']) || empty($activity['actor'])) { if (empty($activity['object_id']) || empty($activity['actor'])) {
Logger::info('Empty object id or actor.'); Logger::info('Empty object id or actor.');
@ -1369,7 +1369,7 @@ class Processor
* @param array $activity * @param array $activity
* @throws \Exception * @throws \Exception
*/ */
public static function blockAccount($activity) public static function blockAccount(array $activity)
{ {
$cid = Contact::getIdForURL($activity['actor']); $cid = Contact::getIdForURL($activity['actor']);
if (empty($cid)) { if (empty($cid)) {
@ -1392,7 +1392,7 @@ class Processor
* @param array $activity * @param array $activity
* @throws \Exception * @throws \Exception
*/ */
public static function unblockAccount($activity) public static function unblockAccount(array $activity)
{ {
$cid = Contact::getIdForURL($activity['actor']); $cid = Contact::getIdForURL($activity['actor']);
if (empty($cid)) { if (empty($cid)) {
@ -1416,7 +1416,7 @@ class Processor
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function acceptFollowUser($activity) public static function acceptFollowUser(array $activity)
{ {
$uid = User::getIdForURL($activity['object_actor']); $uid = User::getIdForURL($activity['object_actor']);
if (empty($uid)) { if (empty($uid)) {
@ -1450,7 +1450,7 @@ class Processor
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function rejectFollowUser($activity) public static function rejectFollowUser(array $activity)
{ {
$uid = User::getIdForURL($activity['object_actor']); $uid = User::getIdForURL($activity['object_actor']);
if (empty($uid)) { if (empty($uid)) {
@ -1483,7 +1483,7 @@ class Processor
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function undoActivity($activity) public static function undoActivity(array $activity)
{ {
if (empty($activity['object_id'])) { if (empty($activity['object_id'])) {
return; return;
@ -1508,7 +1508,7 @@ class Processor
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function undoFollowUser($activity) public static function undoFollowUser(array $activity)
{ {
$uid = User::getIdForURL($activity['object_object']); $uid = User::getIdForURL($activity['object_object']);
if (empty($uid)) { if (empty($uid)) {
@ -1543,7 +1543,7 @@ class Processor
* @param integer $cid Contact ID * @param integer $cid Contact ID
* @throws \Exception * @throws \Exception
*/ */
private static function switchContact($cid) private static function switchContact(int $cid)
{ {
$contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]); $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) { if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
@ -1563,7 +1563,7 @@ class Processor
* @return array * @return array
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function getImplicitMentionList(array $parent) private static function getImplicitMentionList(array $parent): array
{ {
$parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]); $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
@ -1601,7 +1601,7 @@ class Processor
* @param array $parent * @param array $parent
* @return string * @return string
*/ */
private static function removeImplicitMentionsFromBody(string $body, array $parent) private static function removeImplicitMentionsFromBody(string $body, array $parent): string
{ {
if (DI::config()->get('system', 'disable_implicit_mentions')) { if (DI::config()->get('system', 'disable_implicit_mentions')) {
return $body; return $body;

View file

@ -84,8 +84,9 @@ class Receiver
* @param $header * @param $header
* @param integer $uid User ID * @param integer $uid User ID
* @throws \Exception * @throws \Exception
* @todo Find type for $body/$header
*/ */
public static function processInbox($body, $header, $uid) public static function processInbox($body, $header, int $uid)
{ {
$activity = json_decode($body, true); $activity = json_decode($body, true);
if (empty($activity)) { if (empty($activity)) {
@ -220,11 +221,11 @@ class Receiver
* @param string $object_id Object ID of the the provided object * @param string $object_id Object ID of the the provided object
* @param integer $uid User ID * @param integer $uid User ID
* *
* @return string with object type * @return string with object type or NULL
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function fetchObjectType($activity, $object_id, $uid = 0) private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
{ {
if (!empty($activity['as:object'])) { if (!empty($activity['as:object'])) {
$object_type = JsonLD::fetchElement($activity['as:object'], '@type'); $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
@ -268,7 +269,7 @@ class Receiver
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function prepareObjectData($activity, $uid, $push, &$trust_source) public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
{ {
$id = JsonLD::fetchElement($activity, '@id'); $id = JsonLD::fetchElement($activity, '@id');
if (!empty($id) && !$trust_source) { if (!empty($id) && !$trust_source) {
@ -458,7 +459,7 @@ class Receiver
* @param array $receivers Array with receivers * @param array $receivers Array with receivers
* @return integer user id; * @return integer user id;
*/ */
public static function getFirstUserFromReceivers($receivers) public static function getFirstUserFromReceivers(array $receivers): int
{ {
foreach ($receivers as $receiver) { foreach ($receivers as $receiver) {
if (!empty($receiver)) { if (!empty($receiver)) {
@ -479,7 +480,7 @@ class Receiver
* @param array $signer The signer of the post * @param array $signer The signer of the post
* @throws \Exception * @throws \Exception
*/ */
public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = []) public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
{ {
$type = JsonLD::fetchElement($activity, '@type'); $type = JsonLD::fetchElement($activity, '@type');
if (!$type) { if (!$type) {
@ -818,7 +819,7 @@ class Receiver
* *
* @return int user id * @return int user id
*/ */
public static function getBestUserForActivity(array $activity) public static function getBestUserForActivity(array $activity): int
{ {
$uid = 0; $uid = 0;
$actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? ''; $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
@ -844,7 +845,8 @@ class Receiver
return $uid; return $uid;
} }
public static function getReceiverURL($activity) // @TODO Missing documentation
public static function getReceiverURL(array $activity): array
{ {
$urls = []; $urls = [];
@ -876,9 +878,9 @@ class Receiver
* @return array with receivers (user id) * @return array with receivers (user id)
* @throws \Exception * @throws \Exception
*/ */
private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false) private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
{ {
$reply = $receivers = []; $reply = $receivers = $profile = [];
// When it is an answer, we inherite the receivers from the parent // When it is an answer, we inherite the receivers from the parent
$replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id'); $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
@ -1005,7 +1007,7 @@ class Receiver
* @return array with receivers (user id) * @return array with receivers (user id)
* @throws \Exception * @throws \Exception
*/ */
private static function getReceiverForActor($actor, $tags, $receivers, $target_type, $profile) private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
{ {
$basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER], $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false]; 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
@ -1047,13 +1049,12 @@ class Receiver
* Tests if the contact is a valid receiver for this actor * Tests if the contact is a valid receiver for this actor
* *
* @param array $contact * @param array $contact
* @param string $actor
* @param array $tags * @param array $tags
* *
* @return bool with receivers (user id) * @return bool with receivers (user id)
* @throws \Exception * @throws \Exception
*/ */
private static function isValidReceiverForActor($contact, $tags) private static function isValidReceiverForActor(array $contact, array $tags): bool
{ {
// Are we following the contact? Then this is a valid receiver // Are we following the contact? Then this is a valid receiver
if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) { if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
@ -1089,7 +1090,7 @@ class Receiver
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function switchContact($cid, $uid, $url) public static function switchContact(int $cid, int $uid, string $url)
{ {
if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) { if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]); Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
@ -1108,7 +1109,7 @@ class Receiver
} }
/** /**
* * @TODO Fix documentation and type-hints
* *
* @param $receivers * @param $receivers
* @param $actor * @param $actor
@ -1135,14 +1136,14 @@ class Receiver
} }
/** /**
* * @TODO Fix documentation and type-hints
* *
* @param $object_data * @param $object_data
* @param array $activity * @param array $activity
* *
* @return mixed * @return mixed
*/ */
private static function addActivityFields($object_data, $activity) private static function addActivityFields($object_data, array $activity)
{ {
if (!empty($activity['published']) && empty($object_data['published'])) { if (!empty($activity['published']) && empty($object_data['published'])) {
$object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value'); $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
@ -1262,7 +1263,7 @@ class Receiver
* @param array $languages * @param array $languages
* @return array Languages * @return array Languages
*/ */
public static function processLanguages(array $languages) public static function processLanguages(array $languages): array
{ {
if (empty($languages)) { if (empty($languages)) {
return []; return [];
@ -1285,7 +1286,7 @@ class Receiver
* *
* @return array with tags in a simplified format * @return array with tags in a simplified format
*/ */
public static function processTags(array $tags) public static function processTags(array $tags): array
{ {
$taglist = []; $taglist = [];
@ -1317,7 +1318,7 @@ class Receiver
* @param array $emojis * @param array $emojis
* @return array with emojis in a simplified format * @return array with emojis in a simplified format
*/ */
private static function processEmojis(array $emojis) private static function processEmojis(array $emojis): array
{ {
$emojilist = []; $emojilist = [];
@ -1343,7 +1344,7 @@ class Receiver
* *
* @return array Attachments in a simplified format * @return array Attachments in a simplified format
*/ */
private static function processAttachments(array $attachments) private static function processAttachments(array $attachments): array
{ {
$attachlist = []; $attachlist = [];
@ -1460,7 +1461,7 @@ class Receiver
* *
* @return array Questions in a simplified format * @return array Questions in a simplified format
*/ */
private static function processQuestion(array $object) private static function processQuestion(array $object): array
{ {
$question = []; $question = [];
@ -1518,10 +1519,10 @@ class Receiver
* @param array $object * @param array $object
* @param array $object_data * @param array $object_data
* *
* @return array * @return array Object data (?)
* @throws \Exception * @throws \Exception
*/ */
private static function getSource($object, $object_data) private static function getSource(array $object, array $object_data): array
{ {
$object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode'); $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
$object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value'); $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
@ -1650,10 +1651,10 @@ class Receiver
* *
* @param array $object * @param array $object
* *
* @return array * @return array|bool Object data or FALSE if $object does not contain @id element
* @throws \Exception * @throws \Exception
*/ */
private static function processObject($object) private static function processObject(array $object)
{ {
if (!JsonLD::fetchElement($object, '@id')) { if (!JsonLD::fetchElement($object, '@id')) {
return false; return false;
@ -1767,7 +1768,7 @@ class Receiver
$object_data['question'] = self::processQuestion($object); $object_data['question'] = self::processQuestion($object);
} }
$receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true); $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
$receivers = $reception_types = []; $receivers = $reception_types = [];
foreach ($receiverdata as $key => $data) { foreach ($receiverdata as $key => $data) {
$receivers[$key] = $data['uid']; $receivers[$key] = $data['uid'];

View file

@ -68,7 +68,7 @@ class Transmitter
* @param array $inboxes * @param array $inboxes
* @return array inboxes with added relay servers * @return array inboxes with added relay servers
*/ */
public static function addRelayServerInboxes(array $inboxes = []) public static function addRelayServerInboxes(array $inboxes = []): array
{ {
foreach (Relay::getList(['inbox']) as $contact) { foreach (Relay::getList(['inbox']) as $contact) {
$inboxes[$contact['inbox']] = $contact['inbox']; $inboxes[$contact['inbox']] = $contact['inbox'];
@ -83,7 +83,7 @@ class Transmitter
* @param array $inboxes * @param array $inboxes
* @return array inboxes with added relay servers * @return array inboxes with added relay servers
*/ */
public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []) public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
{ {
$item = Post::selectFirst(['uid'], ['id' => $item_id]); $item = Post::selectFirst(['uid'], ['id' => $item_id]);
if (empty($item)) { if (empty($item)) {

View file

@ -72,7 +72,7 @@ class DFRN
* @return array importer * @return array importer
* @throws \Exception * @throws \Exception
*/ */
public static function getImporter($cid, $uid = 0) public static function getImporter(int $cid, int $uid = 0): array
{ {
$condition = ['id' => $cid, 'blocked' => false, 'pending' => false]; $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
$contact = DBA::selectFirst('contact', [], $condition); $contact = DBA::selectFirst('contact', [], $condition);
@ -115,7 +115,7 @@ class DFRN
* @throws \ImagickException * @throws \ImagickException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
public static function entries($items, $owner) public static function entries(array $items, array $owner): string
{ {
$doc = new DOMDocument('1.0', 'utf-8'); $doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true; $doc->formatOutput = true;
@ -152,7 +152,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function itemFeed(int $uri_id, int $uid, bool $conversation = false) public static function itemFeed(int $uri_id, int $uid, bool $conversation = false): string
{ {
if ($conversation) { if ($conversation) {
$condition = ['parent-uri-id' => $uri_id]; $condition = ['parent-uri-id' => $uri_id];
@ -222,7 +222,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
public static function mail(array $mail, array $owner) public static function mail(array $mail, array $owner): string
{ {
$doc = new DOMDocument('1.0', 'utf-8'); $doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true; $doc->formatOutput = true;
@ -259,7 +259,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
public static function fsuggest($item, $owner) public static function fsuggest(array $item, array $owner): string
{ {
$doc = new DOMDocument('1.0', 'utf-8'); $doc = new DOMDocument('1.0', 'utf-8');
$doc->formatOutput = true; $doc->formatOutput = true;
@ -289,7 +289,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
public static function relocate($owner, $uid) public static function relocate(array $owner, int $uid): string
{ {
/* get site pubkey. this could be a new installation with no site keys*/ /* get site pubkey. this could be a new installation with no site keys*/
@ -346,9 +346,9 @@ class DFRN
* *
* @return object XML root object * @return object XML root object
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find proper type-hints * @todo Find proper type-hint for returned type
*/ */
private static function addHeader(DOMDocument $doc, $owner, $authorelement, $alternatelink = "", $public = false) private static function addHeader(DOMDocument $doc, array $owner, string $authorelement, string $alternatelink = '', bool $public = false)
{ {
if ($alternatelink == "") { if ($alternatelink == "") {
@ -428,8 +428,12 @@ class DFRN
* viewer's timezone also, but first we are going to convert it from the birthday * viewer's timezone also, but first we are going to convert it from the birthday
* person's timezone to GMT - so the viewer may find the birthday starting at * person's timezone to GMT - so the viewer may find the birthday starting at
* 6:00PM the day before, but that will correspond to midnight to the birthday person. * 6:00PM the day before, but that will correspond to midnight to the birthday person.
*
* @param int $uid User id
* @param string $tz Time zone string, like UTC
* @return string Formatted birthday string
*/ */
private static function determineNextBirthday($uid, $tz) private static function determineNextBirthday(int $uid, string $tz): string
{ {
$birthday = ''; $birthday = '';
@ -467,7 +471,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
private static function addAuthor(DOMDocument $doc, array $owner, $authorelement, $public) private static function addAuthor(DOMDocument $doc, array $owner, string $authorelement, bool $public)
{ {
// Should the profile be "unsearchable" in the net? Then add the "hide" element // Should the profile be "unsearchable" in the net? Then add the "hide" element
$hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]); $hide = DBA::exists('profile', ['uid' => $owner['uid'], 'net-publish' => false]);
@ -592,7 +596,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
private static function addEntryAuthor(DOMDocument $doc, $element, $contact_url, $item) private static function addEntryAuthor(DOMDocument $doc, string $element, string $contact_url, array $item)
{ {
$author = $doc->createElement($element); $author = $doc->createElement($element);
@ -637,7 +641,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
private static function createActivity(DOMDocument $doc, $element, $activity, $uriid) private static function createActivity(DOMDocument $doc, string $element, string $activity, int $uriid)
{ {
if ($activity) { if ($activity) {
$entry = $doc->createElement($element); $entry = $doc->createElement($element);
@ -703,7 +707,7 @@ class DFRN
* @return void XML attachment object * @return void XML attachment object
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
private static function getAttachment($doc, $root, $item) private static function getAttachment($doc, $root, array $item)
{ {
foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) { foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
$attributes = ['rel' => 'enclosure', $attributes = ['rel' => 'enclosure',
@ -737,7 +741,7 @@ class DFRN
* @throws \ImagickException * @throws \ImagickException
* @todo Find proper type-hints * @todo Find proper type-hints
*/ */
private static function entry(DOMDocument $doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false) private static function entry(DOMDocument $doc, string $type, array $item, array $owner, bool $comment = false, int $cid = 0, bool $single = false)
{ {
$mentioned = []; $mentioned = [];
@ -961,13 +965,12 @@ class DFRN
* @param array $owner Owner record * @param array $owner Owner record
* @param array $contact Contact record of the receiver * @param array $contact Contact record of the receiver
* @param string $atom Content that will be transmitted * @param string $atom Content that will be transmitted
*
* @param bool $public_batch * @param bool $public_batch
* @return int Deliver status. Negative values mean an error. * @return int Deliver status. Negative values mean an error.
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function transmit($owner, $contact, $atom, $public_batch = false) public static function transmit(array $owner, array $contact, string $atom, bool $public_batch = false)
{ {
if (!$public_batch) { if (!$public_batch) {
if (empty($contact['addr'])) { if (empty($contact['addr'])) {
@ -1060,7 +1063,7 @@ class DFRN
* @throws \ImagickException * @throws \ImagickException
* @todo Find good type-hints for all parameter * @todo Find good type-hints for all parameter
*/ */
private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, $importer, $element, $onlyfetch, $xml = "") private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, array $importer, string $element, bool $onlyfetch, string $xml = ''): array
{ {
$author = []; $author = [];
$author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context); $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
@ -1280,7 +1283,7 @@ class DFRN
* @return string XML string * @return string XML string
* @todo Find good type-hints for all parameter * @todo Find good type-hints for all parameter
*/ */
private static function transformActivity($xpath, $activity, $element) private static function transformActivity($xpath, $activity, string $element): string
{ {
if (!is_object($activity)) { if (!is_object($activity)) {
return ""; return "";
@ -1335,7 +1338,7 @@ class DFRN
* @throws \Exception * @throws \Exception
* @todo Find good type-hints for all parameter * @todo Find good type-hints for all parameter
*/ */
private static function processMail($xpath, $mail, $importer) private static function processMail($xpath, $mail, array $importer)
{ {
Logger::notice("Processing mails"); Logger::notice("Processing mails");
@ -1364,7 +1367,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo Find good type-hints for all parameter * @todo Find good type-hints for all parameter
*/ */
private static function processSuggestion($xpath, $suggestion, $importer) private static function processSuggestion($xpath, $suggestion, array $importer)
{ {
Logger::notice('Processing suggestions'); Logger::notice('Processing suggestions');
@ -1383,7 +1386,7 @@ class DFRN
* @param integer $from_cid * @param integer $from_cid
* @return bool Was the adding successful? * @return bool Was the adding successful?
*/ */
private static function addSuggestion(int $uid, int $cid, int $from_cid, string $note = '') private static function addSuggestion(int $uid, int $cid, int $from_cid, string $note = ''): bool
{ {
$owner = User::getOwnerDataById($uid); $owner = User::getOwnerDataById($uid);
$contact = Contact::getById($cid); $contact = Contact::getById($cid);
@ -1440,7 +1443,7 @@ class DFRN
* @throws \ImagickException * @throws \ImagickException
* @todo Find good type-hints for all parameter * @todo Find good type-hints for all parameter
*/ */
private static function processRelocation($xpath, $relocation, $importer) private static function processRelocation($xpath, $relocation, array $importer): bool
{ {
Logger::notice("Processing relocations"); Logger::notice("Processing relocations");
@ -1510,7 +1513,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo set proper type-hints (array?) * @todo set proper type-hints (array?)
*/ */
private static function updateContent($current, $item, $importer, $entrytype) private static function updateContent(array $current, array $item, array $importer, int $entrytype)
{ {
$changed = false; $changed = false;
@ -1542,7 +1545,7 @@ class DFRN
* @throws \Exception * @throws \Exception
* @todo set proper type-hints (array?) * @todo set proper type-hints (array?)
*/ */
private static function getEntryType($importer, $item) private static function getEntryType(array $importer, array $item): int
{ {
if ($item["thr-parent"] != $item["uri"]) { if ($item["thr-parent"] != $item["uri"]) {
$community = false; $community = false;
@ -1638,7 +1641,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @todo set proper type-hints (array?) * @todo set proper type-hints (array?)
*/ */
private static function processVerbs($entrytype, $importer, &$item, &$is_like) private static function processVerbs(int $entrytype, array $importer, array &$item, bool &$is_like)
{ {
Logger::info("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype); Logger::info("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype);
@ -1734,7 +1737,7 @@ class DFRN
* @return void * @return void
* @todo set proper type-hints * @todo set proper type-hints
*/ */
private static function parseLinks($links, &$item) private static function parseLinks($links, array &$item)
{ {
$rel = ""; $rel = "";
$href = ""; $href = "";
@ -1772,7 +1775,7 @@ class DFRN
* @param array $imporer * @param array $imporer
* @return boolean Is the message wanted? * @return boolean Is the message wanted?
*/ */
private static function isSolicitedMessage(array $item, array $importer) private static function isSolicitedMessage(array $item, array $importer): bool
{ {
if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)", if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) { Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
@ -1807,12 +1810,13 @@ class DFRN
* @param object $entry entry elements * @param object $entry entry elements
* @param array $importer Record of the importer user mixed with contact of the content * @param array $importer Record of the importer user mixed with contact of the content
* @param string $xml xml * @param string $xml xml
* @param int $protocol Protocol
* @return void * @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
* @todo Add type-hints * @todo Add type-hints
*/ */
private static function processEntry($header, $xpath, $entry, $importer, $xml, $protocol) private static function processEntry(array $header, $xpath, $entry, array $importer, string $xml, int $protocol)
{ {
Logger::notice("Processing entries"); Logger::notice("Processing entries");
@ -2070,6 +2074,9 @@ class DFRN
} }
} }
// Need to initialize variable, otherwise E_NOTICE will happen
$is_like = false;
if (!self::processVerbs($entrytype, $importer, $item, $is_like)) { if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
Logger::info("Exiting because 'processVerbs' told us so"); Logger::info("Exiting because 'processVerbs' told us so");
return; return;
@ -2163,7 +2170,7 @@ class DFRN
* @throws \Exception * @throws \Exception
* @todo set proper type-hints * @todo set proper type-hints
*/ */
private static function processDeletion($xpath, $deletion, $importer) private static function processDeletion($xpath, $deletion, array $importer)
{ {
Logger::notice("Processing deletions"); Logger::notice("Processing deletions");
$uri = null; $uri = null;
@ -2224,9 +2231,8 @@ class DFRN
* @return integer Import status * @return integer Import status
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
* @todo set proper type-hints
*/ */
public static function import($xml, $importer, $protocol, $direction) public static function import(string $xml, array $importer, int $protocol, int $direction): int
{ {
if ($xml == "") { if ($xml == "") {
return 400; return 400;
@ -2365,7 +2371,7 @@ class DFRN
* *
* @return string activity verb * @return string activity verb
*/ */
private static function constructVerb(array $item) private static function constructVerb(array $item): string
{ {
if ($item['verb']) { if ($item['verb']) {
return $item['verb']; return $item['verb'];
@ -2373,7 +2379,8 @@ class DFRN
return Activity::POST; return Activity::POST;
} }
private static function tgroupCheck($uid, $item) // @TODO Documentation missing
private static function tgroupCheck(int $uid, array $item): bool
{ {
$mention = false; $mention = false;
@ -2421,12 +2428,12 @@ class DFRN
* item is assumed to be up-to-date. If the timestamps are equal it * item is assumed to be up-to-date. If the timestamps are equal it
* assumes the update has been seen before and should be ignored. * assumes the update has been seen before and should be ignored.
* *
* @param $existing * @param array $existing
* @param $update * @param array $update
* @return bool * @return bool
* @throws \Exception * @throws \Exception
*/ */
private static function isEditedTimestampNewer($existing, $update) private static function isEditedTimestampNewer(array $existing, array $update): bool
{ {
if (empty($existing['edited'])) { if (empty($existing['edited'])) {
return true; return true;
@ -2449,7 +2456,7 @@ class DFRN
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isSupportedByContactUrl($url) public static function isSupportedByContactUrl(string $url): bool
{ {
$probe = Probe::uri($url, Protocol::DFRN); $probe = Probe::uri($url, Protocol::DFRN);
return $probe['network'] == Protocol::DFRN; return $probe['network'] == Protocol::DFRN;

View file

@ -74,9 +74,9 @@ class Diaspora
* @return array of relay servers * @return array of relay servers
* @throws \Exception * @throws \Exception
*/ */
public static function participantsForThread(array $item, array $contacts) public static function participantsForThread(array $item, array $contacts): array
{ {
if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) { if (!in_array($item['private'], [Item::PUBLIC, Item::UNLISTED]) || in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]); Logger::info('Item is private or a participation request. It will not be relayed', ['guid' => $item['guid'], 'private' => $item['private'], 'verb' => $item['verb']]);
return $contacts; return $contacts;
} }
@ -114,11 +114,11 @@ class Diaspora
* *
* @param string $envelope The magic envelope * @param string $envelope The magic envelope
* *
* @return string verified data * @return string|bool verified data or false on error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function verifyMagicEnvelope($envelope) private static function verifyMagicEnvelope(string $envelope)
{ {
$basedom = XML::parseString($envelope, true); $basedom = XML::parseString($envelope, true);
@ -145,14 +145,14 @@ class Diaspora
$sig = Strings::base64UrlDecode($children->sig); $sig = Strings::base64UrlDecode($children->sig);
$key_id = $children->sig->attributes()->key_id[0]; $key_id = $children->sig->attributes()->key_id[0];
if ($key_id != "") { if ($key_id != '') {
$handle = Strings::base64UrlDecode($key_id); $handle = Strings::base64UrlDecode($key_id);
} }
$b64url_data = Strings::base64UrlEncode($data); $b64url_data = Strings::base64UrlEncode($data);
$msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data); $msg = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
$signable_data = $msg.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg); $signable_data = $msg . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
if ($handle == '') { if ($handle == '') {
Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope); Logger::notice('No author could be decoded. Discarding. Message: ' . $envelope);
@ -183,7 +183,7 @@ class Diaspora
* *
* @return string encrypted data * @return string encrypted data
*/ */
private static function aesEncrypt($key, $iv, $data) private static function aesEncrypt(string $key, string $iv, string $data): string
{ {
return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0")); return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
} }
@ -197,19 +197,19 @@ class Diaspora
* *
* @return string decrypted data * @return string decrypted data
*/ */
private static function aesDecrypt($key, $iv, $encrypted) private static function aesDecrypt(string $key, string $iv, string $encrypted): string
{ {
return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0")); return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
} }
/** /**
* Decodes incoming Diaspora message in the new format * Decodes incoming Diaspora message in the new format. This method returns false on an error.
* *
* @param string $raw raw post message * @param string $raw raw post message
* @param string $privKey The private key of the importer * @param string $privKey The private key of the importer
* @param boolean $no_exit Don't do an http exit on error * @param boolean $no_exit Don't do an http exit on error
* *
* @return array * @return bool|array
* 'message' -> decoded Diaspora XML message * 'message' -> decoded Diaspora XML message
* 'author' -> author diaspora handle * 'author' -> author diaspora handle
* 'key' -> author public key (converted to pkcs#8) * 'key' -> author public key (converted to pkcs#8)
@ -260,13 +260,13 @@ class Diaspora
$base = $basedom->children(ActivityNamespace::SALMON_ME); $base = $basedom->children(ActivityNamespace::SALMON_ME);
// Not sure if this cleaning is needed // Not sure if this cleaning is needed
$data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data); $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
// Build the signed data // Build the signed data
$type = $base->data[0]->attributes()->type[0]; $type = $base->data[0]->attributes()->type[0];
$encoding = $base->encoding; $encoding = $base->encoding;
$alg = $base->alg; $alg = $base->alg;
$signed_data = $data.'.'.Strings::base64UrlEncode($type).'.'.Strings::base64UrlEncode($encoding).'.'.Strings::base64UrlEncode($alg); $signed_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
// This is the signature // This is the signature
$signature = Strings::base64UrlDecode($base->sig); $signature = Strings::base64UrlDecode($base->sig);
@ -303,9 +303,11 @@ class Diaspora
} }
} }
return ['message' => (string)Strings::base64UrlDecode($base->data), return [
'message' => (string)Strings::base64UrlDecode($base->data),
'author' => XML::unescape($author_addr), 'author' => XML::unescape($author_addr),
'key' => (string)$key]; 'key' => (string)$key
];
} }
/** /**
@ -394,7 +396,7 @@ class Diaspora
// unpack the data // unpack the data
// strip whitespace so our data element will return to one big base64 blob // strip whitespace so our data element will return to one big base64 blob
$data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data); $data = str_replace([" ", "\t", "\r", "\n"], ['', '', '', ''], $base->data);
// stash away some other stuff for later // stash away some other stuff for later
@ -445,9 +447,11 @@ class Diaspora
Logger::notice('Message verified.'); Logger::notice('Message verified.');
return ['message' => (string)$inner_decrypted, return [
'message' => (string)$inner_decrypted,
'author' => XML::unescape($author_link), 'author' => XML::unescape($author_link),
'key' => (string)$key]; 'key' => (string)$key
];
} }
@ -457,11 +461,11 @@ class Diaspora
* @param array $msg The post that will be dispatched * @param array $msg The post that will be dispatched
* @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH) * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
* *
* @return int The message id of the generated message, "true" or "false" if there was an error * @return int|bool The message id of the generated message, "true" or "false" if there was an error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function dispatchPublic($msg, int $direction) public static function dispatchPublic(array $msg, int $direction)
{ {
$enabled = intval(DI::config()->get("system", "diaspora_enabled")); $enabled = intval(DI::config()->get("system", "diaspora_enabled"));
if (!$enabled) { if (!$enabled) {
@ -474,7 +478,10 @@ class Diaspora
return false; return false;
} }
$importer = ["uid" => 0, "page-flags" => User::PAGE_FLAGS_FREELOVE]; $importer = [
'uid' => 0,
'page-flags' => User::PAGE_FLAGS_FREELOVE
];
$success = self::dispatch($importer, $msg, $fields, $direction); $success = self::dispatch($importer, $msg, $fields, $direction);
return $success; return $success;
@ -488,15 +495,15 @@ class Diaspora
* @param SimpleXMLElement $fields SimpleXML object that contains the message * @param SimpleXMLElement $fields SimpleXML object that contains the message
* @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH) * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
* *
* @return int The message id of the generated message, "true" or "false" if there was an error * @return int|bool The message id of the generated message, "true" or "false" if there was an error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function dispatch(array $importer, $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED) public static function dispatch(array $importer, array $msg, SimpleXMLElement $fields = null, int $direction = self::PUSHED)
{ {
// The sender is the handle of the contact that sent the message. // The sender is the handle of the contact that sent the message.
// This will often be different with relayed messages (for example "like" and "comment") // This will often be different with relayed messages (for example "like" and "comment")
$sender = $msg["author"]; $sender = $msg['author'];
// This is only needed for private postings since this is already done for public ones before // This is only needed for private postings since this is already done for public ones before
if (is_null($fields)) { if (is_null($fields)) {
@ -511,77 +518,77 @@ class Diaspora
$type = $fields->getName(); $type = $fields->getName();
Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer["uid"]]); Logger::info('Received message', ['type' => $type, 'sender' => $sender, 'user' => $importer['uid']]);
switch ($type) { switch ($type) {
case "account_migration": case 'account_migration':
if (!$private) { if (!$private) {
Logger::notice('Message with type ' . $type . ' is not private, quitting.'); Logger::notice('Message with type ' . $type . ' is not private, quitting.');
return false; return false;
} }
return self::receiveAccountMigration($importer, $fields); return self::receiveAccountMigration($importer, $fields);
case "account_deletion": case 'account_deletion':
return self::receiveAccountDeletion($fields); return self::receiveAccountDeletion($fields);
case "comment": case 'comment':
return self::receiveComment($importer, $sender, $fields, $msg["message"], $direction); return self::receiveComment($importer, $sender, $fields, $msg['message'], $direction);
case "contact": case 'contact':
if (!$private) { if (!$private) {
Logger::notice('Message with type ' . $type . ' is not private, quitting.'); Logger::notice('Message with type ' . $type . ' is not private, quitting.');
return false; return false;
} }
return self::receiveContactRequest($importer, $fields); return self::receiveContactRequest($importer, $fields);
case "conversation": case 'conversation':
if (!$private) { if (!$private) {
Logger::notice('Message with type ' . $type . ' is not private, quitting.'); Logger::notice('Message with type ' . $type . ' is not private, quitting.');
return false; return false;
} }
return self::receiveConversation($importer, $msg, $fields); return self::receiveConversation($importer, $msg, $fields);
case "like": case 'like':
return self::receiveLike($importer, $sender, $fields, $direction); return self::receiveLike($importer, $sender, $fields, $direction);
case "message": case 'message':
if (!$private) { if (!$private) {
Logger::notice('Message with type ' . $type . ' is not private, quitting.'); Logger::notice('Message with type ' . $type . ' is not private, quitting.');
return false; return false;
} }
return self::receiveMessage($importer, $fields); return self::receiveMessage($importer, $fields);
case "participation": case 'participation':
if (!$private) { if (!$private) {
Logger::notice('Message with type ' . $type . ' is not private, quitting.'); Logger::notice('Message with type ' . $type . ' is not private, quitting.');
return false; return false;
} }
return self::receiveParticipation($importer, $fields, $direction); return self::receiveParticipation($importer, $fields, $direction);
case "photo": // Not implemented case 'photo': // Not implemented
return self::receivePhoto($importer, $fields); return self::receivePhoto($importer, $fields);
case "poll_participation": // Not implemented case 'poll_participation': // Not implemented
return self::receivePollParticipation($importer, $fields); return self::receivePollParticipation($importer, $fields);
case "profile": case 'profile':
if (!$private) { if (!$private) {
Logger::notice('Message with type ' . $type . ' is not private, quitting.'); Logger::notice('Message with type ' . $type . ' is not private, quitting.');
return false; return false;
} }
return self::receiveProfile($importer, $fields); return self::receiveProfile($importer, $fields);
case "reshare": case 'reshare':
return self::receiveReshare($importer, $fields, $msg["message"], $direction); return self::receiveReshare($importer, $fields, $msg['message'], $direction);
case "retraction": case 'retraction':
return self::receiveRetraction($importer, $sender, $fields); return self::receiveRetraction($importer, $sender, $fields);
case "status_message": case 'status_message':
return self::receiveStatusMessage($importer, $fields, $msg["message"], $direction); return self::receiveStatusMessage($importer, $fields, $msg['message'], $direction);
default: default:
Logger::notice("Unknown message type ".$type); Logger::notice("Unknown message type " . $type);
return false; return false;
} }
} }
@ -598,9 +605,9 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function validPosting($msg) private static function validPosting(array $msg)
{ {
$data = XML::parseString($msg["message"]); $data = XML::parseString($msg['message']);
if (!is_object($data)) { if (!is_object($data)) {
Logger::info('No valid XML', ['message' => $msg['message']]); Logger::info('No valid XML', ['message' => $msg['message']]);
@ -608,7 +615,7 @@ class Diaspora
} }
// Is this the new or the old version? // Is this the new or the old version?
if ($data->getName() == "XML") { if ($data->getName() == 'XML') {
$oldXML = true; $oldXML = true;
foreach ($data->post->children() as $child) { foreach ($data->post->children() as $child) {
$element = $child; $element = $child;
@ -621,106 +628,106 @@ class Diaspora
$type = $element->getName(); $type = $element->getName();
$orig_type = $type; $orig_type = $type;
Logger::debug("Got message type ".$type.": ".$msg["message"]); Logger::debug("Got message type " . $type . ": " . $msg['message']);
// All retractions are handled identically from now on. // All retractions are handled identically from now on.
// In the new version there will only be "retraction". // In the new version there will only be "retraction".
if (in_array($type, ["signed_retraction", "relayable_retraction"])) if (in_array($type, ['signed_retraction', 'relayable_retraction']))
$type = "retraction"; $type = 'retraction';
if ($type == "request") { if ($type == 'request') {
$type = "contact"; $type = 'contact';
} }
$fields = new SimpleXMLElement("<".$type."/>"); $fields = new SimpleXMLElement('<' . $type . '/>');
$signed_data = ""; $signed_data = '';
$author_signature = null; $author_signature = null;
$parent_author_signature = null; $parent_author_signature = null;
foreach ($element->children() as $fieldname => $entry) { foreach ($element->children() as $fieldname => $entry) {
if ($oldXML) { if ($oldXML) {
// Translation for the old XML structure // Translation for the old XML structure
if ($fieldname == "diaspora_handle") { if ($fieldname == 'diaspora_handle') {
$fieldname = "author"; $fieldname = 'author';
} }
if ($fieldname == "participant_handles") { if ($fieldname == 'participant_handles') {
$fieldname = "participants"; $fieldname = 'participants';
} }
if (in_array($type, ["like", "participation"])) { if (in_array($type, ['like', 'participation'])) {
if ($fieldname == "target_type") { if ($fieldname == 'target_type') {
$fieldname = "parent_type"; $fieldname = 'parent_type';
} }
} }
if ($fieldname == "sender_handle") { if ($fieldname == 'sender_handle') {
$fieldname = "author"; $fieldname = 'author';
} }
if ($fieldname == "recipient_handle") { if ($fieldname == 'recipient_handle') {
$fieldname = "recipient"; $fieldname = 'recipient';
} }
if ($fieldname == "root_diaspora_id") { if ($fieldname == 'root_diaspora_id') {
$fieldname = "root_author"; $fieldname = 'root_author';
} }
if ($type == "status_message") { if ($type == 'status_message') {
if ($fieldname == "raw_message") { if ($fieldname == 'raw_message') {
$fieldname = "text"; $fieldname = 'text';
} }
} }
if ($type == "retraction") { if ($type == 'retraction') {
if ($fieldname == "post_guid") { if ($fieldname == 'post_guid') {
$fieldname = "target_guid"; $fieldname = 'target_guid';
} }
if ($fieldname == "type") { if ($fieldname == 'type') {
$fieldname = "target_type"; $fieldname = 'target_type';
} }
} }
} }
if (($fieldname == "author_signature") && ($entry != "")) { if (($fieldname == 'author_signature') && ($entry != '')) {
$author_signature = base64_decode($entry); $author_signature = base64_decode($entry);
} elseif (($fieldname == "parent_author_signature") && ($entry != "")) { } elseif (($fieldname == 'parent_author_signature') && ($entry != '')) {
$parent_author_signature = base64_decode($entry); $parent_author_signature = base64_decode($entry);
} elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) { } elseif (!in_array($fieldname, ['author_signature', 'parent_author_signature', 'target_author_signature'])) {
if ($signed_data != "") { if ($signed_data != '') {
$signed_data .= ";"; $signed_data .= ';';
} }
$signed_data .= $entry; $signed_data .= $entry;
} }
if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"]) if (!in_array($fieldname, ['parent_author_signature', 'target_author_signature'])
|| ($orig_type == "relayable_retraction") || ($orig_type == 'relayable_retraction')
) { ) {
XML::copy($entry, $fields, $fieldname); XML::copy($entry, $fields, $fieldname);
} }
} }
// This is something that shouldn't happen at all. // This is something that shouldn't happen at all.
if (in_array($type, ["status_message", "reshare", "profile"])) { if (in_array($type, ['status_message', 'reshare', 'profile'])) {
if ($msg["author"] != $fields->author) { if ($msg['author'] != $fields->author) {
Logger::notice("Message handle is not the same as envelope sender. Quitting this message."); Logger::notice("Message handle is not the same as envelope sender. Quitting this message.");
return false; return false;
} }
} }
// Only some message types have signatures. So we quit here for the other types. // Only some message types have signatures. So we quit here for the other types.
if (!in_array($type, ["comment", "like"])) { if (!in_array($type, ['comment', 'like'])) {
return $fields; return $fields;
} }
// No author_signature? This is a must, so we quit. // No author_signature? This is a must, so we quit.
if (!isset($author_signature)) { if (!isset($author_signature)) {
Logger::info("No author signature for type ".$type." - Message: ".$msg["message"]); Logger::info("No author signature for type " . $type . " - Message: " . $msg['message']);
return false; return false;
} }
if (isset($parent_author_signature)) { if (isset($parent_author_signature)) {
$key = self::key($msg["author"]); $key = self::key($msg['author']);
if (empty($key)) { if (empty($key)) {
Logger::info('No key found for parent', ['author' => $msg["author"]]); Logger::info('No key found for parent', ['author' => $msg['author']]);
return false; return false;
} }
if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) { if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, 'sha256')) {
Logger::info("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature); Logger::info("No valid parent author signature for parent author " . $msg['author'] . " in type " . $type . " - signed data: " . $signed_data . " - Message: " . $msg['message'] . " - Signature " . $parent_author_signature);
return false; return false;
} }
} }
@ -731,8 +738,8 @@ class Diaspora
return false; return false;
} }
if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) { if (!Crypto::rsaVerify($signed_data, $author_signature, $key, 'sha256')) {
Logger::info("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature); Logger::info("No valid author signature for author " . $fields->author . " in type " . $type . " - signed data: " . $signed_data . " - Message: " . $msg['message'] . " - Signature " . $author_signature);
return false; return false;
} else { } else {
return $fields; return $fields;
@ -748,18 +755,18 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function key($handle) private static function key(string $handle): string
{ {
$handle = strval($handle); $handle = strval($handle);
Logger::notice("Fetching diaspora key for: ".$handle); Logger::notice("Fetching diaspora key for: " . $handle);
$r = FContact::getByURL($handle); $fcontact = FContact::getByURL($handle);
if ($r) { if ($fcontact) {
return $r["pubkey"]; return $fcontact['pubkey'];
} }
return ""; return '';
} }
/** /**
@ -771,7 +778,7 @@ class Diaspora
* @return string the handle * @return string the handle
* @throws \Exception * @throws \Exception
*/ */
private static function handleFromContact($contact_id, $pcontact_id = 0) private static function handleFromContact(int $contact_id, int $pcontact_id = 0): string
{ {
$handle = ''; $handle = '';
@ -804,7 +811,7 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function contactByHandle($uid, $handle) private static function contactByHandle(int $uid, string $handle): array
{ {
return Contact::getByURL($handle, null, [], $uid); return Contact::getByURL($handle, null, [], $uid);
} }
@ -818,7 +825,7 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isSupportedByContactUrl($url, $update = null) public static function isSupportedByContactUrl(string $url, $update = null)
{ {
return !empty(FContact::getByURL($url, $update)); return !empty(FContact::getByURL($url, $update));
} }
@ -832,7 +839,7 @@ class Diaspora
* *
* @return bool is the contact allowed to post? * @return bool is the contact allowed to post?
*/ */
private static function postAllow(array $importer, array $contact, $is_comment = false) private static function postAllow(array $importer, array $contact, bool $is_comment = false): bool
{ {
/* /*
* Perhaps we were already sharing with this person. Now they're sharing with us. * Perhaps we were already sharing with this person. Now they're sharing with us.
@ -855,15 +862,15 @@ class Diaspora
if (Network::isUrlBlocked($contact['url'])) { if (Network::isUrlBlocked($contact['url'])) {
return false; return false;
// We don't seem to like that person // We don't seem to like that person
} elseif ($contact["blocked"]) { } elseif ($contact['blocked']) {
// Maybe blocked, don't accept. // Maybe blocked, don't accept.
return false; return false;
// We are following this person? // We are following this person?
} elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) { } elseif (($contact['rel'] == Contact::SHARING) || ($contact['rel'] == Contact::FRIEND)) {
// Yes, then it is fine. // Yes, then it is fine.
return true; return true;
// Is the message a global user or a comment? // Is the message a global user or a comment?
} elseif (($importer["uid"] == 0) || $is_comment) { } elseif (($importer['uid'] == 0) || $is_comment) {
// Messages for the global users and comments are always accepted // Messages for the global users and comments are always accepted
return true; return true;
} }
@ -878,16 +885,16 @@ class Diaspora
* @param string $handle The checked handle in the format user@domain.tld * @param string $handle The checked handle in the format user@domain.tld
* @param bool $is_comment Is the check for a comment? * @param bool $is_comment Is the check for a comment?
* *
* @return array The contact data * @return array|bool The contact data or false on error
* @throws \Exception * @throws \Exception
*/ */
private static function allowedContactByHandle(array $importer, $handle, $is_comment = false) private static function allowedContactByHandle(array $importer, string $handle, bool $is_comment = false)
{ {
$contact = self::contactByHandle($importer["uid"], $handle); $contact = self::contactByHandle($importer['uid'], $handle);
if (!$contact) { if (!$contact) {
Logger::notice("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found"); Logger::notice("A Contact for handle " . $handle . " and user " . $importer['uid'] . " was not found");
// If a contact isn't found, we accept it anyway if it is a comment // If a contact isn't found, we accept it anyway if it is a comment
if ($is_comment && ($importer["uid"] != 0)) { if ($is_comment && ($importer['uid'] != 0)) {
return self::contactByHandle(0, $handle); return self::contactByHandle(0, $handle);
} elseif ($is_comment) { } elseif ($is_comment) {
return $importer; return $importer;
@ -897,7 +904,7 @@ class Diaspora
} }
if (!self::postAllow($importer, $contact, $is_comment)) { if (!self::postAllow($importer, $contact, $is_comment)) {
Logger::notice("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]); Logger::notice("The handle: " . $handle . " is not allowed to post to user " . $importer['uid']);
return false; return false;
} }
return $contact; return $contact;
@ -912,12 +919,12 @@ class Diaspora
* @return int|bool message id if the message already was stored into the system - or false. * @return int|bool message id if the message already was stored into the system - or false.
* @throws \Exception * @throws \Exception
*/ */
private static function messageExists($uid, $guid) private static function messageExists(int $uid, string $guid)
{ {
$item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]); $item = Post::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
if (DBA::isResult($item)) { if (DBA::isResult($item)) {
Logger::notice("message ".$guid." already exists for user ".$uid); Logger::notice("message " . $guid . " already exists for user " . $uid);
return $item["id"]; return $item['id'];
} }
return false; return false;
@ -931,13 +938,12 @@ class Diaspora
*/ */
private static function fetchGuid(array $item) private static function fetchGuid(array $item)
{ {
$expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
preg_replace_callback( preg_replace_callback(
$expression, "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism",
function ($match) use ($item) { function ($match) use ($item) {
self::fetchGuidSub($match, $item); self::fetchGuidSub($match, $item);
}, },
$item["body"] $item['body']
); );
preg_replace_callback( preg_replace_callback(
@ -945,7 +951,7 @@ class Diaspora
function ($match) use ($item) { function ($match) use ($item) {
self::fetchGuidSub($match, $item); self::fetchGuidSub($match, $item);
}, },
$item["body"] $item['body']
); );
} }
@ -958,7 +964,7 @@ class Diaspora
* *
* @return string the replaced string * @return string the replaced string
*/ */
public static function replacePeopleGuid($body, $author_link) public static function replacePeopleGuid(string $body, string $author_link): string
{ {
$return = preg_replace_callback( $return = preg_replace_callback(
"&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi", "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
@ -970,11 +976,11 @@ class Diaspora
$handle = FContact::getUrlByGuid($match[1]); $handle = FContact::getUrlByGuid($match[1]);
if ($handle) { if ($handle) {
$return = '@[url='.$handle.']'.$match[2].'[/url]'; $return = '@[url=' . $handle . ']' . $match[2] . '[/url]';
} else { } else {
// No local match, restoring absolute remote URL from author scheme and host // No local match, restoring absolute remote URL from author scheme and host
$author_url = parse_url($author_link); $author_url = parse_url($author_link);
$return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]'; $return = '[url=' . $author_url['scheme'] . '://' . $author_url['host'] . '/people/' . $match[1] . ']' . $match[2] . '[/url]';
} }
return $return; return $return;
@ -994,10 +1000,10 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function fetchGuidSub($match, $item) private static function fetchGuidSub(array $match, array $item)
{ {
if (!self::storeByGuid($match[1], $item["author-link"], true)) { if (!self::storeByGuid($match[1], $item['author-link'], true)) {
self::storeByGuid($match[1], $item["owner-link"], true); self::storeByGuid($match[1], $item['owner-link'], true);
} }
} }
@ -1008,21 +1014,21 @@ class Diaspora
* @param string $server The server address * @param string $server The server address
* @param bool $force Forced fetch * @param bool $force Forced fetch
* *
* @return int the message id of the stored message or false * @return int|bool the message id of the stored message or false
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function storeByGuid($guid, $server, $force) private static function storeByGuid(string $guid, string $server, bool $force)
{ {
$serverparts = parse_url($server); $serverparts = parse_url($server);
if (empty($serverparts["host"]) || empty($serverparts["scheme"])) { if (empty($serverparts['host']) || empty($serverparts['scheme'])) {
return false; return false;
} }
$server = $serverparts["scheme"]."://".$serverparts["host"]; $server = $serverparts['scheme'] . '://' . $serverparts['host'];
Logger::info("Trying to fetch item ".$guid." from ".$server); Logger::info("Trying to fetch item " . $guid . " from " . $server);
$msg = self::message($guid, $server); $msg = self::message($guid, $server);
@ -1030,7 +1036,7 @@ class Diaspora
return false; return false;
} }
Logger::info("Successfully fetched item ".$guid." from ".$server); Logger::info("Successfully fetched item " . $guid . " from " . $server);
// Now call the dispatcher // Now call the dispatcher
return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED); return self::dispatchPublic($msg, $force ? self::FORCED_FETCH : self::FETCHED);
@ -1049,16 +1055,16 @@ class Diaspora
* 'key' => The public key of the author * 'key' => The public key of the author
* @throws \Exception * @throws \Exception
*/ */
public static function message($guid, $server, $level = 0) public static function message(string $guid, string $server, int $level = 0)
{ {
if ($level > 5) { if ($level > 5) {
return false; return false;
} }
// This will work for new Diaspora servers and Friendica servers from 3.5 // This will work for new Diaspora servers and Friendica servers from 3.5
$source_url = $server."/fetch/post/".urlencode($guid); $source_url = $server . '/fetch/post/' . urlencode($guid);
Logger::info("Fetch post from ".$source_url); Logger::info("Fetch post from " . $source_url);
$envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC); $envelope = DI::httpClient()->fetch($source_url, HttpClientAccept::MAGIC);
if ($envelope) { if ($envelope) {
@ -1098,7 +1104,7 @@ class Diaspora
// Fetch the author - for the old and the new Diaspora version // Fetch the author - for the old and the new Diaspora version
if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) { if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
$author = (string)$source_xml->post->status_message->diaspora_handle; $author = (string)$source_xml->post->status_message->diaspora_handle;
} elseif ($source_xml->author && ($source_xml->getName() == "status_message")) { } elseif ($source_xml->author && ($source_xml->getName() == 'status_message')) {
$author = (string)$source_xml->author; $author = (string)$source_xml->author;
} }
@ -1108,26 +1114,27 @@ class Diaspora
return false; return false;
} }
$msg = ["message" => $x, "author" => $author]; return [
'message' => $x,
$msg["key"] = self::key($msg["author"]); 'author' => $author,
'key' => self::key($author)
return $msg; ];
} }
/** /**
* Fetches an item with a given URL * Fetches an item with a given URL
* *
* @param string $url the message url * @param string $url the message url
* @param int $uid User id
* *
* @return int the message id of the stored message or false * @return int|bool the message id of the stored message or false
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function fetchByURL($url, $uid = 0) public static function fetchByURL(string $url, int $uid = 0)
{ {
// Check for Diaspora (and Friendica) typical paths // Check for Diaspora (and Friendica) typical paths
if (!preg_match("=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i", $url, $matches)) { if (!preg_match('=(https?://.+)/(?:posts|display|objects)/([a-zA-Z0-9-_@.:%]+[a-zA-Z0-9])=i', $url, $matches)) {
Logger::info('Invalid url', ['url' => $url]); Logger::info('Invalid url', ['url' => $url]);
return false; return false;
} }
@ -1162,10 +1169,10 @@ class Diaspora
* @param string $author The handle of the item * @param string $author The handle of the item
* @param array $contact The contact of the item owner * @param array $contact The contact of the item owner
* *
* @return array the item record * @return array|bool the item record or false on failure
* @throws \Exception * @throws \Exception
*/ */
private static function parentItem($uid, $guid, $author, array $contact) private static function parentItem(int $uid, string $guid, string $author, array $contact)
{ {
$fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin', $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
'author-name', 'author-link', 'author-avatar', 'gravity', 'author-name', 'author-link', 'author-avatar', 'gravity',
@ -1175,25 +1182,25 @@ class Diaspora
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
$person = FContact::getByURL($author); $person = FContact::getByURL($author);
$result = self::storeByGuid($guid, $person["url"], false); $result = self::storeByGuid($guid, $person['url'], false);
// We don't have an url for items that arrived at the public dispatcher // We don't have an url for items that arrived at the public dispatcher
if (!$result && !empty($contact["url"])) { if (!$result && !empty($contact['url'])) {
$result = self::storeByGuid($guid, $contact["url"], false); $result = self::storeByGuid($guid, $contact['url'], false);
} }
if ($result) { if ($result) {
Logger::info("Fetched missing item ".$guid." - result: ".$result); Logger::info("Fetched missing item " . $guid . " - result: " . $result);
$item = Post::selectFirst($fields, $condition); $item = Post::selectFirst($fields, $condition);
} }
} }
if (!DBA::isResult($item)) { if (!DBA::isResult($item)) {
Logger::notice("parent item not found: parent: ".$guid." - user: ".$uid); Logger::notice("parent item not found: parent: " . $guid . " - user: " . $uid);
return false; return false;
} else { } else {
Logger::notice("parent item found: parent: ".$guid." - user: ".$uid); Logger::notice("parent item found: parent: " . $guid . " - user: " . $uid);
return $item; return $item;
} }
} }
@ -1210,19 +1217,22 @@ class Diaspora
* 'network' => network type * 'network' => network type
* @throws \Exception * @throws \Exception
*/ */
private static function authorContactByUrl($def_contact, $person, $uid) private static function authorContactByUrl(array $def_contact, array $person, int $uid): array
{ {
$condition = ['nurl' => Strings::normaliseLink($person["url"]), 'uid' => $uid]; $condition = ['nurl' => Strings::normaliseLink($person['url']), 'uid' => $uid];
$contact = DBA::selectFirst('contact', ['id', 'network'], $condition); $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
if (DBA::isResult($contact)) { if (DBA::isResult($contact)) {
$cid = $contact["id"]; $cid = $contact['id'];
$network = $contact["network"]; $network = $contact['network'];
} else { } else {
$cid = $def_contact["id"]; $cid = $def_contact['id'];
$network = Protocol::DIASPORA; $network = Protocol::DIASPORA;
} }
return ["cid" => $cid, "network" => $network]; return [
'cid' => $cid,
'network' => $network
];
} }
/** /**
@ -1232,9 +1242,9 @@ class Diaspora
* *
* @return bool is it a hubzilla server? * @return bool is it a hubzilla server?
*/ */
private static function isHubzilla($url) private static function isHubzilla(string $url): bool
{ {
return(strstr($url, '/channel/')); return strstr($url, '/channel/');
} }
/** /**
@ -1248,7 +1258,7 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function plink(string $addr, string $guid, string $parent_guid = '') private static function plink(string $addr, string $guid, string $parent_guid = ''): string
{ {
$contact = Contact::getByURL($addr); $contact = Contact::getByURL($addr);
if (empty($contact)) { if (empty($contact)) {
@ -1306,30 +1316,30 @@ class Diaspora
* Receives account migration * Receives account migration
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool Success * @return bool Success
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function receiveAccountMigration(array $importer, $data) private static function receiveAccountMigration(array $importer, SimpleXMLElement $data): bool
{ {
$old_handle = XML::unescape($data->author); $old_handle = XML::unescape($data->author);
$new_handle = XML::unescape($data->profile->author); $new_handle = XML::unescape($data->profile->author);
$signature = XML::unescape($data->signature); $signature = XML::unescape($data->signature);
$contact = self::contactByHandle($importer["uid"], $old_handle); $contact = self::contactByHandle($importer['uid'], $old_handle);
if (!$contact) { if (!$contact) {
Logger::notice("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]); Logger::notice("cannot find contact for sender: " . $old_handle . " and user " . $importer['uid']);
return false; return false;
} }
Logger::notice("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]); Logger::notice("Got migration for " . $old_handle . ", to " . $new_handle . " with user " . $importer['uid']);
// Check signature // Check signature
$signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle; $signed_text = 'AccountMigration:' . $old_handle . ':' . $new_handle;
$key = self::key($old_handle); $key = self::key($old_handle);
if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) { if (!Crypto::rsaVerify($signed_text, $signature, $key, 'sha256')) {
Logger::notice('No valid signature for migration.'); Logger::notice('No valid signature for migration.');
return false; return false;
} }
@ -1340,15 +1350,21 @@ class Diaspora
// change the technical stuff in contact // change the technical stuff in contact
$data = Probe::uri($new_handle); $data = Probe::uri($new_handle);
if ($data['network'] == Protocol::PHANTOM) { if ($data['network'] == Protocol::PHANTOM) {
Logger::notice('Account for '.$new_handle." couldn't be probed."); Logger::notice("Account for " . $new_handle . " couldn't be probed.");
return false; return false;
} }
$fields = ['url' => $data['url'], 'nurl' => Strings::normaliseLink($data['url']), $fields = [
'name' => $data['name'], 'nick' => $data['nick'], 'url' => $data['url'],
'addr' => $data['addr'], 'batch' => $data['batch'], 'nurl' => Strings::normaliseLink($data['url']),
'notify' => $data['notify'], 'poll' => $data['poll'], 'name' => $data['name'],
'network' => $data['network']]; 'nick' => $data['nick'],
'addr' => $data['addr'],
'batch' => $data['batch'],
'notify' => $data['notify'],
'poll' => $data['poll'],
'network' => $data['network']
];
Contact::update($fields, ['addr' => $old_handle]); Contact::update($fields, ['addr' => $old_handle]);
@ -1360,18 +1376,18 @@ class Diaspora
/** /**
* Processes an account deletion * Processes an account deletion
* *
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool Success * @return bool Success
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function receiveAccountDeletion($data) private static function receiveAccountDeletion(SimpleXMLElement $data): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$contacts = DBA::select('contact', ['id'], ['addr' => $author]); $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
while ($contact = DBA::fetch($contacts)) { while ($contact = DBA::fetch($contacts)) {
Contact::remove($contact["id"]); Contact::remove($contact['id']);
} }
DBA::close($contacts); DBA::close($contacts);
@ -1387,15 +1403,15 @@ class Diaspora
* @param string $guid Message guid * @param string $guid Message guid
* @param boolean $onlyfound Only return uri when found in the database * @param boolean $onlyfound Only return uri when found in the database
* *
* @return string The constructed uri or the one from our database * @return string The constructed uri or the one from our database or empty string on if $onlyfound is true
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function getUriFromGuid($author, $guid, $onlyfound = false) private static function getUriFromGuid(string $author, string $guid, bool $onlyfound = false): string
{ {
$item = Post::selectFirst(['uri'], ['guid' => $guid]); $item = Post::selectFirst(['uri'], ['guid' => $guid]);
if (DBA::isResult($item)) { if (DBA::isResult($item)) {
return $item["uri"]; return $item['uri'];
} elseif (!$onlyfound) { } elseif (!$onlyfound) {
$person = FContact::getByURL($author); $person = FContact::getByURL($author);
@ -1406,7 +1422,7 @@ class Diaspora
return $host_url . '/objects/' . $guid; return $host_url . '/objects/' . $guid;
} }
return ""; return '';
} }
/** /**
@ -1448,7 +1464,7 @@ class Diaspora
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param string $sender The sender of the message * @param string $sender The sender of the message
* @param object $data The message object * @param SimpleXMLElement $data The message object
* @param string $xml The original XML of the message * @param string $xml The original XML of the message
* @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH) * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
* *
@ -1456,7 +1472,7 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function receiveComment(array $importer, $sender, $data, $xml, int $direction) private static function receiveComment(array $importer, string $sender, SimpleXMLElement $data, string $xml, int $direction): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -1471,9 +1487,9 @@ class Diaspora
if (isset($data->thread_parent_guid)) { if (isset($data->thread_parent_guid)) {
$thread_parent_guid = XML::unescape($data->thread_parent_guid); $thread_parent_guid = XML::unescape($data->thread_parent_guid);
$thr_parent = self::getUriFromGuid("", $thread_parent_guid, true); $thr_parent = self::getUriFromGuid('', $thread_parent_guid, true);
} else { } else {
$thr_parent = ""; $thr_parent = '';
} }
$contact = self::allowedContactByHandle($importer, $sender, true); $contact = self::allowedContactByHandle($importer, $sender, true);
@ -1485,12 +1501,12 @@ class Diaspora
GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA); GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
} }
$message_id = self::messageExists($importer["uid"], $guid); $message_id = self::messageExists($importer['uid'], $guid);
if ($message_id) { if ($message_id) {
return true; return true;
} }
$toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact); $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
if (!$toplevel_parent_item) { if (!$toplevel_parent_item) {
return false; return false;
} }
@ -1502,60 +1518,60 @@ class Diaspora
} }
// Fetch the contact id - if we know this contact // Fetch the contact id - if we know this contact
$author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]); $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
$datarray = []; $datarray = [];
$datarray["uid"] = $importer["uid"]; $datarray['uid'] = $importer['uid'];
$datarray["contact-id"] = $author_contact["cid"]; $datarray['contact-id'] = $author_contact['cid'];
$datarray["network"] = $author_contact["network"]; $datarray['network'] = $author_contact['network'];
$datarray["author-link"] = $person["url"]; $datarray['author-link'] = $person['url'];
$datarray["author-id"] = Contact::getIdForURL($person["url"], 0); $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
$datarray["owner-link"] = $contact["url"]; $datarray['owner-link'] = $contact['url'];
$datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0); $datarray['owner-id'] = Contact::getIdForURL($contact['url'], 0);
// Will be overwritten for sharing accounts in Item::insert // Will be overwritten for sharing accounts in Item::insert
if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) { if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
$datarray["post-reason"] = Item::PR_FETCHED; $datarray['post-reason'] = Item::PR_FETCHED;
} elseif ($datarray["uid"] == 0) { } elseif ($datarray['uid'] == 0) {
$datarray["post-reason"] = Item::PR_GLOBAL; $datarray['post-reason'] = Item::PR_GLOBAL;
} else { } else {
$datarray["post-reason"] = Item::PR_COMMENT; $datarray['post-reason'] = Item::PR_COMMENT;
} }
$datarray["guid"] = $guid; $datarray['guid'] = $guid;
$datarray["uri"] = self::getUriFromGuid($author, $guid); $datarray['uri'] = self::getUriFromGuid($author, $guid);
$datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]); $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
$datarray["verb"] = Activity::POST; $datarray['verb'] = Activity::POST;
$datarray["gravity"] = GRAVITY_COMMENT; $datarray['gravity'] = GRAVITY_COMMENT;
$datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri']; $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
$datarray["object-type"] = Activity\ObjectType::COMMENT; $datarray['object-type'] = Activity\ObjectType::COMMENT;
$datarray["post-type"] = Item::PT_NOTE; $datarray['post-type'] = Item::PT_NOTE;
$datarray["protocol"] = Conversation::PARCEL_DIASPORA; $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
$datarray["source"] = $xml; $datarray['source'] = $xml;
$datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH; $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
$datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at; $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
$datarray["plink"] = self::plink($author, $guid, $toplevel_parent_item['guid']); $datarray['plink'] = self::plink($author, $guid, $toplevel_parent_item['guid']);
$body = Markdown::toBBCode($text); $body = Markdown::toBBCode($text);
$datarray["body"] = self::replacePeopleGuid($body, $person["url"]); $datarray['body'] = self::replacePeopleGuid($body, $person['url']);
self::storeMentions($datarray['uri-id'], $text); self::storeMentions($datarray['uri-id'], $text);
Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]); Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
self::fetchGuid($datarray); self::fetchGuid($datarray);
// If we are the origin of the parent we store the original data. // If we are the origin of the parent we store the original data.
// We notify our followers during the item storage. // We notify our followers during the item storage.
if ($toplevel_parent_item["origin"]) { if ($toplevel_parent_item['origin']) {
$datarray['diaspora_signed_text'] = json_encode($data); $datarray['diaspora_signed_text'] = json_encode($data);
} }
@ -1571,7 +1587,7 @@ class Diaspora
} }
if ($message_id) { if ($message_id) {
Logger::info("Stored comment ".$datarray["guid"]." with message id ".$message_id); Logger::info("Stored comment " . $datarray['guid'] . " with message id " . $message_id);
if ($datarray['uid'] == 0) { if ($datarray['uid'] == 0) {
Item::distribute($message_id, json_encode($data)); Item::distribute($message_id, json_encode($data));
} }
@ -1585,15 +1601,16 @@ class Diaspora
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param array $contact The contact of the message * @param array $contact The contact of the message
* @param object $data The message object * @param SimpleXMLElement $data The message object
* @param array $msg Array of the processed message, author handle and key * @param array $msg Array of the processed message, author handle and key
* @param object $mesg The private message * @param object $mesg The private message
* @param array $conversation The conversation record to which this message belongs * @param array $conversation The conversation record to which this message belongs
* *
* @return bool "true" if it was successful * @return bool "true" if it was successful
* @throws \Exception * @throws \Exception
* @todo Find type-hint for $mesg and update documentation
*/ */
private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation) private static function receiveConversationMessage(array $importer, array $contact, SimpleXMLElement $data, array $msg, $mesg, array $conversation): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -1645,12 +1662,12 @@ class Diaspora
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param array $msg Array of the processed message, author handle and key * @param array $msg Array of the processed message, author handle and key
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool Success * @return bool Success
* @throws \Exception * @throws \Exception
*/ */
private static function receiveConversation(array $importer, $msg, $data) private static function receiveConversation(array $importer, array $msg, SimpleXMLElement $data)
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -1665,7 +1682,7 @@ class Diaspora
return false; return false;
} }
$contact = self::allowedContactByHandle($importer, $msg["author"], true); $contact = self::allowedContactByHandle($importer, $msg['author'], true);
if (!$contact) { if (!$contact) {
return false; return false;
} }
@ -1674,7 +1691,7 @@ class Diaspora
GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA); GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
} }
$conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]); $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
if (!DBA::isResult($conversation)) { if (!DBA::isResult($conversation)) {
$r = DBA::insert('conv', [ $r = DBA::insert('conv', [
'uid' => $importer['uid'], 'uid' => $importer['uid'],
@ -1685,7 +1702,7 @@ class Diaspora
'subject' => $subject, 'subject' => $subject,
'recips' => $participants]); 'recips' => $participants]);
if ($r) { if ($r) {
$conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]); $conversation = DBA::selectFirst('conv', [], ['uid' => $importer['uid'], 'guid' => $guid]);
} }
} }
if (!$conversation) { if (!$conversation) {
@ -1705,14 +1722,14 @@ class Diaspora
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param string $sender The sender of the message * @param string $sender The sender of the message
* @param object $data The message object * @param SimpleXMLElement $data The message object
* @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH) * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
* *
* @return int The message id of the generated like or "false" if there was an error * @return bool Success or failure
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function receiveLike(array $importer, $sender, $data, int $direction) private static function receiveLike(array $importer, string $sender, SimpleXMLElement $data, int $direction): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -1722,7 +1739,7 @@ class Diaspora
// likes on comments aren't supported by Diaspora - only on posts // likes on comments aren't supported by Diaspora - only on posts
// But maybe this will be supported in the future, so we will accept it. // But maybe this will be supported in the future, so we will accept it.
if (!in_array($parent_type, ["Post", "Comment"])) { if (!in_array($parent_type, ['Post', 'Comment'])) {
return false; return false;
} }
@ -1735,12 +1752,12 @@ class Diaspora
GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA); GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
} }
$message_id = self::messageExists($importer["uid"], $guid); $message_id = self::messageExists($importer['uid'], $guid);
if ($message_id) { if ($message_id) {
return true; return true;
} }
$toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact); $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
if (!$toplevel_parent_item) { if (!$toplevel_parent_item) {
return false; return false;
} }
@ -1752,11 +1769,11 @@ class Diaspora
} }
// Fetch the contact id - if we know this contact // Fetch the contact id - if we know this contact
$author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]); $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
// "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
// We would accept this anyhow. // We would accept this anyhow.
if ($positive == "true") { if ($positive == 'true') {
$verb = Activity::LIKE; $verb = Activity::LIKE;
} else { } else {
$verb = Activity::DISLIKE; $verb = Activity::DISLIKE;
@ -1764,36 +1781,36 @@ class Diaspora
$datarray = []; $datarray = [];
$datarray["protocol"] = Conversation::PARCEL_DIASPORA; $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
$datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH; $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
$datarray["uid"] = $importer["uid"]; $datarray['uid'] = $importer['uid'];
$datarray["contact-id"] = $author_contact["cid"]; $datarray['contact-id'] = $author_contact['cid'];
$datarray["network"] = $author_contact["network"]; $datarray['network'] = $author_contact['network'];
$datarray["owner-link"] = $datarray["author-link"] = $person["url"]; $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
$datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0); $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
$datarray["guid"] = $guid; $datarray['guid'] = $guid;
$datarray["uri"] = self::getUriFromGuid($author, $guid); $datarray['uri'] = self::getUriFromGuid($author, $guid);
$datarray["verb"] = $verb; $datarray['verb'] = $verb;
$datarray["gravity"] = GRAVITY_ACTIVITY; $datarray['gravity'] = GRAVITY_ACTIVITY;
$datarray['thr-parent'] = $toplevel_parent_item['uri']; $datarray['thr-parent'] = $toplevel_parent_item['uri'];
$datarray["object-type"] = Activity\ObjectType::NOTE; $datarray['object-type'] = Activity\ObjectType::NOTE;
$datarray["body"] = $verb; $datarray['body'] = $verb;
// Diaspora doesn't provide a date for likes // Diaspora doesn't provide a date for likes
$datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow(); $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
// like on comments have the comment as parent. So we need to fetch the toplevel parent // like on comments have the comment as parent. So we need to fetch the toplevel parent
if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) { if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
$toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]); $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
$origin = $toplevel["origin"]; $origin = $toplevel['origin'];
} else { } else {
$origin = $toplevel_parent_item["origin"]; $origin = $toplevel_parent_item['origin'];
} }
// If we are the origin of the parent we store the original data. // If we are the origin of the parent we store the original data.
@ -1814,7 +1831,7 @@ class Diaspora
} }
if ($message_id) { if ($message_id) {
Logger::info("Stored like ".$datarray["guid"]." with message id ".$message_id); Logger::info("Stored like " . $datarray['guid'] . " with message id " . $message_id);
if ($datarray['uid'] == 0) { if ($datarray['uid'] == 0) {
Item::distribute($message_id, json_encode($data)); Item::distribute($message_id, json_encode($data));
} }
@ -1827,12 +1844,12 @@ class Diaspora
* Processes private messages * Processes private messages
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool Success? * @return bool Success?
* @throws \Exception * @throws \Exception
*/ */
private static function receiveMessage(array $importer, $data) private static function receiveMessage(array $importer, SimpleXMLElement $data): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -1851,7 +1868,7 @@ class Diaspora
$conversation = null; $conversation = null;
$condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid]; $condition = ['uid' => $importer['uid'], 'guid' => $conversation_guid];
$conversation = DBA::selectFirst('conv', [], $condition); $conversation = DBA::selectFirst('conv', [], $condition);
if (!DBA::isResult($conversation)) { if (!DBA::isResult($conversation)) {
@ -1859,7 +1876,7 @@ class Diaspora
return false; return false;
} }
$message_uri = $author.":".$guid; $message_uri = $author . ':' . $guid;
$person = FContact::getByURL($author); $person = FContact::getByURL($author);
if (!$person) { if (!$person) {
@ -1892,14 +1909,14 @@ class Diaspora
* Processes participations - unsupported by now * Processes participations - unsupported by now
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param object $data The message object * @param SimpleXMLElement $data The message object
* @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH) * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
* *
* @return bool success * @return bool success
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function receiveParticipation(array $importer, $data, int $direction) private static function receiveParticipation(array $importer, SimpleXMLElement $data, int $direction): bool
{ {
$author = strtolower(XML::unescape($data->author)); $author = strtolower(XML::unescape($data->author));
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -1914,11 +1931,11 @@ class Diaspora
GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA); GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
} }
if (self::messageExists($importer["uid"], $guid)) { if (self::messageExists($importer['uid'], $guid)) {
return true; return true;
} }
$toplevel_parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact); $toplevel_parent_item = self::parentItem($importer['uid'], $parent_guid, $author, $contact);
if (!$toplevel_parent_item) { if (!$toplevel_parent_item) {
return false; return false;
} }
@ -1934,38 +1951,38 @@ class Diaspora
$person = FContact::getByURL($author); $person = FContact::getByURL($author);
if (!is_array($person)) { if (!is_array($person)) {
Logger::notice("Person not found: ".$author); Logger::notice("Person not found: " . $author);
return false; return false;
} }
$author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]); $author_contact = self::authorContactByUrl($contact, $person, $importer['uid']);
// Store participation // Store participation
$datarray = []; $datarray = [];
$datarray["protocol"] = Conversation::PARCEL_DIASPORA; $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
$datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH; $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
$datarray["uid"] = $importer["uid"]; $datarray['uid'] = $importer['uid'];
$datarray["contact-id"] = $author_contact["cid"]; $datarray['contact-id'] = $author_contact['cid'];
$datarray["network"] = $author_contact["network"]; $datarray['network'] = $author_contact['network'];
$datarray["owner-link"] = $datarray["author-link"] = $person["url"]; $datarray['owner-link'] = $datarray['author-link'] = $person['url'];
$datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0); $datarray['owner-id'] = $datarray['author-id'] = Contact::getIdForURL($person['url'], 0);
$datarray["guid"] = $guid; $datarray['guid'] = $guid;
$datarray["uri"] = self::getUriFromGuid($author, $guid); $datarray['uri'] = self::getUriFromGuid($author, $guid);
$datarray["verb"] = Activity::FOLLOW; $datarray['verb'] = Activity::FOLLOW;
$datarray["gravity"] = GRAVITY_ACTIVITY; $datarray['gravity'] = GRAVITY_ACTIVITY;
$datarray['thr-parent'] = $toplevel_parent_item['uri']; $datarray['thr-parent'] = $toplevel_parent_item['uri'];
$datarray["object-type"] = Activity\ObjectType::NOTE; $datarray['object-type'] = Activity\ObjectType::NOTE;
$datarray["body"] = Activity::FOLLOW; $datarray['body'] = Activity::FOLLOW;
// Diaspora doesn't provide a date for a participation // Diaspora doesn't provide a date for a participation
$datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow(); $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
if (Item::isTooOld($datarray)) { if (Item::isTooOld($datarray)) {
Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]); Logger::info('Participation is too old', ['created' => $datarray['created'], 'uid' => $datarray['uid'], 'guid' => $datarray['guid']]);
@ -1995,8 +2012,8 @@ class Diaspora
continue; continue;
} }
Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact["cid"]]); Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact["cid"])) { if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['id'], $author_contact['cid'])) {
Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1); Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
} }
} }
@ -2009,7 +2026,7 @@ class Diaspora
* Processes photos - unneeded * Processes photos - unneeded
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool always true * @return bool always true
*/ */
@ -2038,68 +2055,69 @@ class Diaspora
* Processes incoming profile updates * Processes incoming profile updates
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool Success * @return bool Success
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function receiveProfile(array $importer, $data) private static function receiveProfile(array $importer, SimpleXMLElement $data): bool
{ {
$author = strtolower(XML::unescape($data->author)); $author = strtolower(XML::unescape($data->author));
$contact = self::contactByHandle($importer["uid"], $author); $contact = self::contactByHandle($importer['uid'], $author);
if (!$contact) { if (!$contact) {
return false; return false;
} }
$name = XML::unescape($data->first_name).((strlen($data->last_name)) ? " ".XML::unescape($data->last_name) : ""); $name = XML::unescape($data->first_name).((strlen($data->last_name)) ? ' ' . XML::unescape($data->last_name) : '');
$image_url = XML::unescape($data->image_url); $image_url = XML::unescape($data->image_url);
$birthday = XML::unescape($data->birthday); $birthday = XML::unescape($data->birthday);
$about = Markdown::toBBCode(XML::unescape($data->bio)); $about = Markdown::toBBCode(XML::unescape($data->bio));
$location = Markdown::toBBCode(XML::unescape($data->location)); $location = Markdown::toBBCode(XML::unescape($data->location));
$searchable = (XML::unescape($data->searchable) == "true"); $searchable = (XML::unescape($data->searchable) == 'true');
$nsfw = (XML::unescape($data->nsfw) == "true"); $nsfw = (XML::unescape($data->nsfw) == 'true');
$tags = XML::unescape($data->tag_string); $tags = XML::unescape($data->tag_string);
$tags = explode("#", $tags); $tags = explode('#', $tags);
$keywords = []; $keywords = [];
foreach ($tags as $tag) { foreach ($tags as $tag) {
$tag = trim(strtolower($tag)); $tag = trim(strtolower($tag));
if ($tag != "") { if ($tag != '') {
$keywords[] = $tag; $keywords[] = $tag;
} }
} }
$keywords = implode(", ", $keywords); $keywords = implode(', ', $keywords);
$handle_parts = explode("@", $author); $handle_parts = explode('@', $author);
$nick = $handle_parts[0]; $nick = $handle_parts[0];
if ($name === "") { if ($name === '') {
$name = $handle_parts[0]; $name = $handle_parts[0];
} }
if (preg_match("|^https?://|", $image_url) === 0) { if (preg_match('|^https?://|', $image_url) === 0) {
$image_url = "http://".$handle_parts[1].$image_url; // @TODO No HTTPS here?
$image_url = 'http://' . $handle_parts[1] . $image_url;
} }
Contact::updateAvatar($contact["id"], $image_url); Contact::updateAvatar($contact['id'], $image_url);
// Generic birthday. We don't know the timezone. The year is irrelevant. // Generic birthday. We don't know the timezone. The year is irrelevant.
$birthday = str_replace("1000", "1901", $birthday); $birthday = str_replace('1000', '1901', $birthday);
if ($birthday != "") { if ($birthday != '') {
$birthday = DateTimeFormat::utc($birthday, "Y-m-d"); $birthday = DateTimeFormat::utc($birthday, 'Y-m-d');
} }
// this is to prevent multiple birthday notifications in a single year // this is to prevent multiple birthday notifications in a single year
// if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
if (substr($birthday, 5) === substr($contact["bd"], 5)) { if (substr($birthday, 5) === substr($contact['bd'], 5)) {
$birthday = $contact["bd"]; $birthday = $contact['bd'];
} }
$fields = ['name' => $name, 'location' => $location, $fields = ['name' => $name, 'location' => $location,
@ -2113,7 +2131,7 @@ class Diaspora
Contact::update($fields, ['id' => $contact['id']]); Contact::update($fields, ['id' => $contact['id']]);
Logger::info("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"]); Logger::info("Profile of contact " . $contact['id'] . " stored for user " . $importer['uid']);
return true; return true;
} }
@ -2128,10 +2146,10 @@ class Diaspora
*/ */
private static function receiveRequestMakeFriend(array $importer, array $contact) private static function receiveRequestMakeFriend(array $importer, array $contact)
{ {
if ($contact["rel"] == Contact::SHARING) { if ($contact['rel'] == Contact::SHARING) {
Contact::update( Contact::update(
['rel' => Contact::FRIEND, 'writable' => true], ['rel' => Contact::FRIEND, 'writable' => true],
['id' => $contact["id"], 'uid' => $importer["uid"]] ['id' => $contact['id'], 'uid' => $importer['uid']]
); );
} }
} }
@ -2140,12 +2158,12 @@ class Diaspora
* Processes incoming sharing notification * Processes incoming sharing notification
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool Success * @return bool Success
* @throws \Exception * @throws \Exception
*/ */
private static function receiveContactRequest(array $importer, $data) private static function receiveContactRequest(array $importer, SimpleXMLElement $data): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$recipient = XML::unescape($data->recipient); $recipient = XML::unescape($data->recipient);
@ -2157,64 +2175,64 @@ class Diaspora
// the current protocol version doesn't know these fields // the current protocol version doesn't know these fields
// That means that we will assume their existance // That means that we will assume their existance
if (isset($data->following)) { if (isset($data->following)) {
$following = (XML::unescape($data->following) == "true"); $following = (XML::unescape($data->following) == 'true');
} else { } else {
$following = true; $following = true;
} }
if (isset($data->sharing)) { if (isset($data->sharing)) {
$sharing = (XML::unescape($data->sharing) == "true"); $sharing = (XML::unescape($data->sharing) == 'true');
} else { } else {
$sharing = true; $sharing = true;
} }
$contact = self::contactByHandle($importer["uid"], $author); $contact = self::contactByHandle($importer['uid'], $author);
// perhaps we were already sharing with this person. Now they're sharing with us. // perhaps we were already sharing with this person. Now they're sharing with us.
// That makes us friends. // That makes us friends.
if ($contact) { if ($contact) {
if ($following) { if ($following) {
Logger::info("Author ".$author." (Contact ".$contact["id"].") wants to follow us."); Logger::info("Author " . $author . " (Contact " . $contact['id'] . ") wants to follow us.");
self::receiveRequestMakeFriend($importer, $contact); self::receiveRequestMakeFriend($importer, $contact);
// refetch the contact array // refetch the contact array
$contact = self::contactByHandle($importer["uid"], $author); $contact = self::contactByHandle($importer['uid'], $author);
// If we are now friends, we are sending a share message. // If we are now friends, we are sending a share message.
// Normally we needn't to do so, but the first message could have been vanished. // Normally we needn't to do so, but the first message could have been vanished.
if (in_array($contact["rel"], [Contact::FRIEND])) { if (in_array($contact['rel'], [Contact::FRIEND])) {
$user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]); $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
if (DBA::isResult($user)) { if (DBA::isResult($user)) {
Logger::info("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"]); Logger::info("Sending share message to author " . $author . " - Contact: " . $contact['id'] . " - User: " . $importer['uid']);
self::sendShare($user, $contact); self::sendShare($user, $contact);
} }
} }
return true; return true;
} else { } else {
Logger::info("Author ".$author." doesn't want to follow us anymore."); Logger::info("Author " . $author . " doesn't want to follow us anymore.");
Contact::removeFollower($contact); Contact::removeFollower($contact);
return true; return true;
} }
} }
if (!$following && $sharing && in_array($importer["page-flags"], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) { if (!$following && $sharing && in_array($importer['page-flags'], [User::PAGE_FLAGS_SOAPBOX, User::PAGE_FLAGS_NORMAL])) {
Logger::info("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored."); Logger::info("Author " . $author . " wants to share with us - but doesn't want to listen. Request is ignored.");
return false; return false;
} elseif (!$following && !$sharing) { } elseif (!$following && !$sharing) {
Logger::info("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored."); Logger::info("Author " . $author . " doesn't want anything - and we don't know the author. Request is ignored.");
return false; return false;
} elseif (!$following && $sharing) { } elseif (!$following && $sharing) {
Logger::info("Author ".$author." wants to share with us."); Logger::info("Author " . $author . " wants to share with us.");
} elseif ($following && $sharing) { } elseif ($following && $sharing) {
Logger::info("Author ".$author." wants to have a bidirectional conection."); Logger::info("Author " . $author . " wants to have a bidirectional conection.");
} elseif ($following && !$sharing) { } elseif ($following && !$sharing) {
Logger::info("Author ".$author." wants to listen to us."); Logger::info("Author " . $author . " wants to listen to us.");
} }
$ret = FContact::getByURL($author); $ret = FContact::getByURL($author);
if (!$ret || ($ret["network"] != Protocol::DIASPORA)) { if (!$ret || ($ret['network'] != Protocol::DIASPORA)) {
Logger::notice("Cannot resolve diaspora handle ".$author." for ".$recipient); Logger::notice("Cannot resolve diaspora handle " . $author . " for ".$recipient);
return false; return false;
} }
@ -2233,7 +2251,7 @@ class Diaspora
$contact_record = self::contactByHandle($importer['uid'], $author); $contact_record = self::contactByHandle($importer['uid'], $author);
if (!$contact_record) { if (!$contact_record) {
Logger::info('unable to locate newly created contact record.'); Logger::info('unable to locate newly created contact record.');
return; return false;
} }
$user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]); $user = DBA::selectFirst('user', [], ['uid' => $importer['uid']]);
@ -2253,11 +2271,11 @@ class Diaspora
* *
* @param string $guid message guid * @param string $guid message guid
* @param string $orig_author handle of the original post * @param string $orig_author handle of the original post
* @return array The fetched item * @return array|bool The fetched item or false on failure
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function originalItem($guid, $orig_author) public static function originalItem(string $guid, string $orig_author)
{ {
if (empty($guid)) { if (empty($guid)) {
Logger::notice('Empty guid. Quitting.'); Logger::notice('Empty guid. Quitting.');
@ -2271,17 +2289,17 @@ class Diaspora
$item = Post::selectFirst($fields, $condition); $item = Post::selectFirst($fields, $condition);
if (DBA::isResult($item)) { if (DBA::isResult($item)) {
Logger::notice("reshared message ".$guid." already exists on system."); Logger::notice("reshared message " . $guid . " already exists on system.");
// Maybe it is already a reshared item? // Maybe it is already a reshared item?
// Then refetch the content, if it is a reshare from a reshare. // Then refetch the content, if it is a reshare from a reshare.
// If it is a reshared post from another network then reformat to avoid display problems with two share elements // If it is a reshared post from another network then reformat to avoid display problems with two share elements
if (self::isReshare($item["body"], true)) { if (self::isReshare($item['body'], true)) {
$item = []; $item = [];
} elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) { } elseif (self::isReshare($item['body'], false) || strstr($item['body'], '[share')) {
$item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"])); $item['body'] = Markdown::toBBCode(BBCode::toMarkdown($item['body']));
$item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]); $item['body'] = self::replacePeopleGuid($item['body'], $item['author-link']);
return $item; return $item;
} else { } else {
@ -2295,13 +2313,13 @@ class Diaspora
return false; return false;
} }
$server = "https://".substr($orig_author, strpos($orig_author, "@") + 1); $server = 'https://' . substr($orig_author, strpos($orig_author, '@') + 1);
Logger::notice("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server); Logger::notice("1st try: reshared message " . $guid . " will be fetched via SSL from the server " . $server);
$stored = self::storeByGuid($guid, $server, true); $stored = self::storeByGuid($guid, $server, true);
if (!$stored) { if (!$stored) {
$server = "http://".substr($orig_author, strpos($orig_author, "@") + 1); $server = 'http://' . substr($orig_author, strpos($orig_author, '@') + 1);
Logger::notice("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server); Logger::notice("2nd try: reshared message " . $guid . " will be fetched without SSL from the server " . $server);
$stored = self::storeByGuid($guid, $server, true); $stored = self::storeByGuid($guid, $server, true);
} }
@ -2313,9 +2331,9 @@ class Diaspora
if (DBA::isResult($item)) { if (DBA::isResult($item)) {
// If it is a reshared post from another network then reformat to avoid display problems with two share elements // If it is a reshared post from another network then reformat to avoid display problems with two share elements
if (self::isReshare($item["body"], false)) { if (self::isReshare($item['body'], false)) {
$item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"])); $item['body'] = Markdown::toBBCode(BBCode::toMarkdown($item['body']));
$item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]); $item['body'] = self::replacePeopleGuid($item['body'], $item['author-link']);
} }
return $item; return $item;
@ -2333,7 +2351,7 @@ class Diaspora
* @param string $guid GUID string of reshare action * @param string $guid GUID string of reshare action
* @param string $author Author handle * @param string $author Author handle
*/ */
private static function addReshareActivity($item, $parent_message_id, $guid, $author) private static function addReshareActivity(array $item, int $parent_message_id, string $guid, string $author)
{ {
$parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]); $parent = Post::selectFirst(['uri', 'guid'], ['id' => $parent_message_id]);
@ -2384,15 +2402,15 @@ class Diaspora
* Processes a reshare message * Processes a reshare message
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param object $data The message object * @param SimpleXMLElement $data The message object
* @param string $xml The original XML of the message * @param string $xml The original XML of the message
* @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH) * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
* *
* @return int the message id * @return bool Success or failure
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function receiveReshare(array $importer, $data, $xml, int $direction) private static function receiveReshare(array $importer, SimpleXMLElement $data, string $xml, int $direction): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -2411,7 +2429,7 @@ class Diaspora
GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA); GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
} }
$message_id = self::messageExists($importer["uid"], $guid); $message_id = self::messageExists($importer['uid'], $guid);
if ($message_id) { if ($message_id) {
return true; return true;
} }
@ -2427,53 +2445,53 @@ class Diaspora
$datarray = []; $datarray = [];
$datarray["uid"] = $importer["uid"]; $datarray['uid'] = $importer['uid'];
$datarray["contact-id"] = $contact["id"]; $datarray['contact-id'] = $contact['id'];
$datarray["network"] = Protocol::DIASPORA; $datarray['network'] = Protocol::DIASPORA;
$datarray["author-link"] = $contact["url"]; $datarray['author-link'] = $contact['url'];
$datarray["author-id"] = Contact::getIdForURL($contact["url"], 0); $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
$datarray["owner-link"] = $datarray["author-link"]; $datarray['owner-link'] = $datarray['author-link'];
$datarray["owner-id"] = $datarray["author-id"]; $datarray['owner-id'] = $datarray['author-id'];
$datarray["guid"] = $guid; $datarray['guid'] = $guid;
$datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid); $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
$datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]); $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
$datarray["verb"] = Activity::POST; $datarray['verb'] = Activity::POST;
$datarray["gravity"] = GRAVITY_PARENT; $datarray['gravity'] = GRAVITY_PARENT;
$datarray["protocol"] = Conversation::PARCEL_DIASPORA; $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
$datarray["source"] = $xml; $datarray['source'] = $xml;
$datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH; $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
/// @todo Copy tag data from original post /// @todo Copy tag data from original post
$prefix = BBCode::getShareOpeningTag( $prefix = BBCode::getShareOpeningTag(
$original_item["author-name"], $original_item['author-name'],
$original_item["author-link"], $original_item['author-link'],
$original_item["author-avatar"], $original_item['author-avatar'],
$original_item["plink"], $original_item['plink'],
$original_item["created"], $original_item['created'],
$original_item["guid"] $original_item['guid']
); );
if (!empty($original_item['title'])) { if (!empty($original_item['title'])) {
$prefix .= '[h3]' . $original_item['title'] . "[/h3]\n"; $prefix .= '[h3]' . $original_item['title'] . "[/h3]\n";
} }
$datarray["body"] = $prefix.$original_item["body"]."[/share]"; $datarray['body'] = $prefix.$original_item['body'] . '[/share]';
Tag::storeFromBody($datarray['uri-id'], $datarray["body"]); Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
$datarray["app"] = $original_item["app"]; $datarray['app'] = $original_item['app'];
$datarray["plink"] = self::plink($author, $guid); $datarray['plink'] = self::plink($author, $guid);
$datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC); $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
$datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at; $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
$datarray["object-type"] = $original_item["object-type"]; $datarray['object-type'] = $original_item['object-type'];
self::fetchGuid($datarray); self::fetchGuid($datarray);
@ -2486,13 +2504,13 @@ class Diaspora
self::sendParticipation($contact, $datarray); self::sendParticipation($contact, $datarray);
$root_message_id = self::messageExists($importer["uid"], $root_guid); $root_message_id = self::messageExists($importer['uid'], $root_guid);
if ($root_message_id) { if ($root_message_id) {
self::addReshareActivity($datarray, $root_message_id, $guid, $author); self::addReshareActivity($datarray, $root_message_id, $guid, $author);
} }
if ($message_id) { if ($message_id) {
Logger::info("Stored reshare ".$datarray["guid"]." with message id ".$message_id); Logger::info("Stored reshare " . $datarray['guid'] . " with message id " . $message_id);
if ($datarray['uid'] == 0) { if ($datarray['uid'] == 0) {
Item::distribute($message_id); Item::distribute($message_id);
} }
@ -2507,12 +2525,12 @@ class Diaspora
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param array $contact The contact of the item owner * @param array $contact The contact of the item owner
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool success * @return bool success
* @throws \Exception * @throws \Exception
*/ */
private static function itemRetraction(array $importer, array $contact, $data) private static function itemRetraction(array $importer, array $contact, SimpleXMLElement $data): bool
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$target_guid = XML::unescape($data->target_guid); $target_guid = XML::unescape($data->target_guid);
@ -2520,12 +2538,12 @@ class Diaspora
$person = FContact::getByURL($author); $person = FContact::getByURL($author);
if (!is_array($person)) { if (!is_array($person)) {
Logger::notice("unable to find author detail for ".$author); Logger::notice("unable to find author detail for " . $author);
return false; return false;
} }
if (empty($contact["url"])) { if (empty($contact['url'])) {
$contact["url"] = $person["url"]; $contact['url'] = $person['url'];
} }
// Fetch items that are about to be deleted // Fetch items that are about to be deleted
@ -2540,7 +2558,7 @@ class Diaspora
$r = Post::select($fields, $condition); $r = Post::select($fields, $condition);
if (!DBA::isResult($r)) { if (!DBA::isResult($r)) {
Logger::notice("Target guid ".$target_guid." was not found on this system for user ".$importer['uid']."."); Logger::notice("Target guid " . $target_guid . " was not found on this system for user " . $importer['uid'] . ".");
return false; return false;
} }
@ -2554,14 +2572,14 @@ class Diaspora
$parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]); $parent = Post::selectFirst(['author-link'], ['id' => $item['parent']]);
// Only delete it if the parent author really fits // Only delete it if the parent author really fits
if (!Strings::compareLink($parent["author-link"], $contact["url"]) && !Strings::compareLink($item["author-link"], $contact["url"])) { if (!Strings::compareLink($parent['author-link'], $contact['url']) && !Strings::compareLink($item['author-link'], $contact['url'])) {
Logger::info("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"]); Logger::info("Thread author " . $parent['author-link'] . " and item author " . $item['author-link'] . " don't fit to expected contact " . $contact['url']);
continue; continue;
} }
Item::markForDeletion(['id' => $item['id']]); Item::markForDeletion(['id' => $item['id']]);
Logger::info("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item['parent']); Logger::info("Deleted target " . $target_guid . " (" . $item['id'] . ") from user " . $item['uid'] . " parent: " . $item['parent']);
} }
DBA::close($r); DBA::close($r);
@ -2573,18 +2591,18 @@ class Diaspora
* *
* @param array $importer Array of the importer user * @param array $importer Array of the importer user
* @param string $sender The sender of the message * @param string $sender The sender of the message
* @param object $data The message object * @param SimpleXMLElement $data The message object
* *
* @return bool Success * @return bool Success
* @throws \Exception * @throws \Exception
*/ */
private static function receiveRetraction(array $importer, $sender, $data) private static function receiveRetraction(array $importer, string $sender, SimpleXMLElement $data)
{ {
$target_type = XML::unescape($data->target_type); $target_type = XML::unescape($data->target_type);
$contact = self::contactByHandle($importer["uid"], $sender); $contact = self::contactByHandle($importer['uid'], $sender);
if (!$contact && (in_array($target_type, ["Contact", "Person"]))) { if (!$contact && (in_array($target_type, ['Contact', 'Person']))) {
Logger::notice("cannot find contact for sender: ".$sender." and user ".$importer["uid"]); Logger::notice("cannot find contact for sender: " . $sender . " and user " . $importer['uid']);
return false; return false;
} }
@ -2592,23 +2610,23 @@ class Diaspora
$contact = []; $contact = [];
} }
Logger::info("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"]); Logger::info("Got retraction for " . $target_type . ", sender " . $sender . " and user " . $importer['uid']);
switch ($target_type) { switch ($target_type) {
case "Comment": case 'Comment':
case "Like": case 'Like':
case "Post": case 'Post':
case "Reshare": case 'Reshare':
case "StatusMessage": case 'StatusMessage':
return self::itemRetraction($importer, $contact, $data); return self::itemRetraction($importer, $contact, $data);
case "PollParticipation": case 'PollParticipation':
case "Photo": case 'Photo':
// Currently unsupported // Currently unsupported
break; break;
default: default:
Logger::notice("Unknown target type ".$target_type); Logger::notice("Unknown target type " . $target_type);
return false; return false;
} }
return true; return true;
@ -2624,11 +2642,10 @@ class Diaspora
* *
* @return boolean Is the message wanted? * @return boolean Is the message wanted?
*/ */
private static function isSolicitedMessage(array $item, string $author, string $body, int $direction) private static function isSolicitedMessage(array $item, string $author, string $body, int $direction): bool
{ {
$contact = Contact::getByURL($author); $contact = Contact::getByURL($author);
if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)", if (DBA::exists('contact', ['`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)', $contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
$contact['nurl'], 0, Contact::FRIEND, Contact::SHARING])) {
Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]); Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $author]);
return true; return true;
} }
@ -2656,6 +2673,8 @@ class Diaspora
*/ */
private static function storePhotoAsMedia(int $uriid, $photo) private static function storePhotoAsMedia(int $uriid, $photo)
{ {
// @TODO Need to find object type, roland@f.haeder.net
Logger::debug('photo='.get_class($photo));
$data = []; $data = [];
$data['uri-id'] = $uriid; $data['uri-id'] = $uriid;
$data['type'] = Post\Media::IMAGE; $data['type'] = Post\Media::IMAGE;
@ -2675,11 +2694,11 @@ class Diaspora
* @param string $xml The original XML of the message * @param string $xml The original XML of the message
* @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH) * @param int $direction Indicates if the message had been fetched or pushed (self::PUSHED, self::FETCHED, self::FORCED_FETCH)
* *
* @return int The message id of the newly created item * @return int|bool The message id of the newly created item or false on error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml, int $direction) private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, string $xml, int $direction)
{ {
$author = XML::unescape($data->author); $author = XML::unescape($data->author);
$guid = XML::unescape($data->guid); $guid = XML::unescape($data->guid);
@ -2697,7 +2716,7 @@ class Diaspora
GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA); GServer::setProtocol($contact['gsid'], Post\DeliveryData::DIASPORA);
} }
$message_id = self::messageExists($importer["uid"], $guid); $message_id = self::messageExists($importer['uid'], $guid);
if ($message_id) { if ($message_id) {
return true; return true;
} }
@ -2713,8 +2732,8 @@ class Diaspora
$datarray = []; $datarray = [];
$datarray["guid"] = $guid; $datarray['guid'] = $guid;
$datarray["uri"] = $datarray["thr-parent"] = self::getUriFromGuid($author, $guid); $datarray['uri'] = $datarray['thr-parent'] = self::getUriFromGuid($author, $guid);
$datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]); $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
// Attach embedded pictures to the body // Attach embedded pictures to the body
@ -2723,14 +2742,14 @@ class Diaspora
self::storePhotoAsMedia($datarray['uri-id'], $photo); self::storePhotoAsMedia($datarray['uri-id'], $photo);
} }
$datarray["object-type"] = Activity\ObjectType::IMAGE; $datarray['object-type'] = Activity\ObjectType::IMAGE;
$datarray["post-type"] = Item::PT_IMAGE; $datarray['post-type'] = Item::PT_IMAGE;
} elseif ($data->poll) { } elseif ($data->poll) {
$datarray["object-type"] = Activity\ObjectType::NOTE; $datarray['object-type'] = Activity\ObjectType::NOTE;
$datarray["post-type"] = Item::PT_POLL; $datarray['post-type'] = Item::PT_POLL;
} else { } else {
$datarray["object-type"] = Activity\ObjectType::NOTE; $datarray['object-type'] = Activity\ObjectType::NOTE;
$datarray["post-type"] = Item::PT_NOTE; $datarray['post-type'] = Item::PT_NOTE;
} }
/// @todo enable support for polls /// @todo enable support for polls
@ -2742,54 +2761,54 @@ class Diaspora
/// @todo enable support for events /// @todo enable support for events
$datarray["uid"] = $importer["uid"]; $datarray['uid'] = $importer['uid'];
$datarray["contact-id"] = $contact["id"]; $datarray['contact-id'] = $contact['id'];
$datarray["network"] = Protocol::DIASPORA; $datarray['network'] = Protocol::DIASPORA;
$datarray["author-link"] = $contact["url"]; $datarray['author-link'] = $contact['url'];
$datarray["author-id"] = Contact::getIdForURL($contact["url"], 0); $datarray['author-id'] = Contact::getIdForURL($contact['url'], 0);
$datarray["owner-link"] = $datarray["author-link"]; $datarray['owner-link'] = $datarray['author-link'];
$datarray["owner-id"] = $datarray["author-id"]; $datarray['owner-id'] = $datarray['author-id'];
$datarray["verb"] = Activity::POST; $datarray['verb'] = Activity::POST;
$datarray["gravity"] = GRAVITY_PARENT; $datarray['gravity'] = GRAVITY_PARENT;
$datarray["protocol"] = Conversation::PARCEL_DIASPORA; $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
$datarray["source"] = $xml; $datarray['source'] = $xml;
$datarray["direction"] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH; $datarray['direction'] = in_array($direction, [self::FETCHED, self::FORCED_FETCH]) ? Conversation::PULL : Conversation::PUSH;
if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) { if (in_array($direction, [self::FETCHED, self::FORCED_FETCH])) {
$datarray["post-reason"] = Item::PR_FETCHED; $datarray['post-reason'] = Item::PR_FETCHED;
} elseif ($datarray["uid"] == 0) { } elseif ($datarray['uid'] == 0) {
$datarray["post-reason"] = Item::PR_GLOBAL; $datarray['post-reason'] = Item::PR_GLOBAL;
} }
$datarray["body"] = self::replacePeopleGuid($body, $contact["url"]); $datarray['body'] = self::replacePeopleGuid($body, $contact['url']);
$datarray["raw-body"] = self::replacePeopleGuid($raw_body, $contact["url"]); $datarray['raw-body'] = self::replacePeopleGuid($raw_body, $contact['url']);
self::storeMentions($datarray['uri-id'], $text); self::storeMentions($datarray['uri-id'], $text);
Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray["body"]); Tag::storeRawTagsFromBody($datarray['uri-id'], $datarray['body']);
if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) { if (!self::isSolicitedMessage($datarray, $author, $body, $direction)) {
DBA::delete('item-uri', ['uri' => $datarray['uri']]); DBA::delete('item-uri', ['uri' => $datarray['uri']]);
return false; return false;
} }
if ($provider_display_name != "") { if ($provider_display_name != '') {
$datarray["app"] = $provider_display_name; $datarray['app'] = $provider_display_name;
} }
$datarray["plink"] = self::plink($author, $guid); $datarray['plink'] = self::plink($author, $guid);
$datarray["private"] = (($public == "false") ? Item::PRIVATE : Item::PUBLIC); $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
$datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at; $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
if (isset($address["address"])) { if (isset($address['address'])) {
$datarray["location"] = $address["address"]; $datarray['location'] = $address['address'];
} }
if (isset($address["lat"]) && isset($address["lng"])) { if (isset($address['lat']) && isset($address['lng'])) {
$datarray["coord"] = $address["lat"]." ".$address["lng"]; $datarray['coord'] = $address['lat'] . " " . $address['lng'];
} }
self::fetchGuid($datarray); self::fetchGuid($datarray);
@ -2804,7 +2823,7 @@ class Diaspora
self::sendParticipation($contact, $datarray); self::sendParticipation($contact, $datarray);
if ($message_id) { if ($message_id) {
Logger::info("Stored item ".$datarray["guid"]." with message id ".$message_id); Logger::info("Stored item " . $datarray['guid'] . " with message id " . $message_id);
if ($datarray['uid'] == 0) { if ($datarray['uid'] == 0) {
Item::distribute($message_id); Item::distribute($message_id);
} }
@ -2826,21 +2845,21 @@ class Diaspora
* @return string the handle in the format user@domain.tld * @return string the handle in the format user@domain.tld
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function myHandle(array $contact) private static function myHandle(array $contact): string
{ {
if (!empty($contact["addr"])) { if (!empty($contact['addr'])) {
return $contact["addr"]; return $contact['addr'];
} }
// Normally we should have a filled "addr" field - but in the past this wasn't the case // Normally we should have a filled "addr" field - but in the past this wasn't the case
// So - just in case - we build the the address here. // So - just in case - we build the the address here.
if ($contact["nickname"] != "") { if ($contact['nickname'] != '') {
$nick = $contact["nickname"]; $nick = $contact['nickname'];
} else { } else {
$nick = $contact["nick"]; $nick = $contact['nick'];
} }
return $nick . "@" . substr(DI::baseUrl(), strpos(DI::baseUrl(), "://") + 3); return $nick . '@' . substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3);
} }
@ -2856,7 +2875,7 @@ class Diaspora
* @return string The encrypted data * @return string The encrypted data
* @throws \Exception * @throws \Exception
*/ */
public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey) public static function encodePrivateData(string $msg, array $user, array $contact, string $prvkey, string $pubkey): string
{ {
Logger::debug("Message: ".$msg); Logger::debug("Message: ".$msg);
@ -2873,16 +2892,18 @@ class Diaspora
$ciphertext = self::aesEncrypt($aes_key, $iv, $msg); $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
$json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]); $json = json_encode(['iv' => $b_iv, 'key' => $b_aes_key]);
$encrypted_key_bundle = ""; $encrypted_key_bundle = '';
if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) { if (!@openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey)) {
return false; return false;
} }
$json_object = json_encode( $json_object = json_encode(
["aes_key" => base64_encode($encrypted_key_bundle), [
"encrypted_magic_envelope" => base64_encode($ciphertext)] 'aes_key' => base64_encode($encrypted_key_bundle),
'encrypted_magic_envelope' => base64_encode($ciphertext)
]
); );
return $json_object; return $json_object;
@ -2897,33 +2918,37 @@ class Diaspora
* @return string The envelope * @return string The envelope
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function buildMagicEnvelope($msg, array $user) public static function buildMagicEnvelope(string $msg, array $user): string
{ {
$b64url_data = Strings::base64UrlEncode($msg); $b64url_data = Strings::base64UrlEncode($msg);
$data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data); $data = str_replace(["\n", "\r", " ", "\t"], ['', '', '', ''], $b64url_data);
$key_id = Strings::base64UrlEncode(self::myHandle($user)); $key_id = Strings::base64UrlEncode(self::myHandle($user));
$type = "application/xml"; $type = 'application/xml';
$encoding = "base64url"; $encoding = 'base64url';
$alg = "RSA-SHA256"; $alg = 'RSA-SHA256';
$signable_data = $data.".".Strings::base64UrlEncode($type).".".Strings::base64UrlEncode($encoding).".".Strings::base64UrlEncode($alg); $signable_data = $data . '.' . Strings::base64UrlEncode($type) . '.' . Strings::base64UrlEncode($encoding) . '.' . Strings::base64UrlEncode($alg);
// Fallback if the private key wasn't transmitted in the expected field // Fallback if the private key wasn't transmitted in the expected field
if ($user['uprvkey'] == "") { if ($user['uprvkey'] == '') {
$user['uprvkey'] = $user['prvkey']; $user['uprvkey'] = $user['prvkey'];
} }
$signature = Crypto::rsaSign($signable_data, $user["uprvkey"]); $signature = Crypto::rsaSign($signable_data, $user['uprvkey']);
$sig = Strings::base64UrlEncode($signature); $sig = Strings::base64UrlEncode($signature);
$xmldata = ["me:env" => ["me:data" => $data, $xmldata = [
"@attributes" => ["type" => $type], 'me:env' => [
"me:encoding" => $encoding, 'me:data' => $data,
"me:alg" => $alg, '@attributes' => ['type' => $type],
"me:sig" => $sig, 'me:encoding' => $encoding,
"@attributes2" => ["key_id" => $key_id]]]; 'me:alg' => $alg,
'me:sig' => $sig,
'@attributes2' => ['key_id' => $key_id]
]
];
$namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"]; $namespaces = ['me' => 'http://salmon-protocol.org/ns/magic-env'];
return XML::fromArray($xmldata, $xml, false, $namespaces); return XML::fromArray($xmldata, $xml, false, $namespaces);
} }
@ -2941,7 +2966,7 @@ class Diaspora
* @return string The message that will be transmitted to other servers * @return string The message that will be transmitted to other servers
* @throws \Exception * @throws \Exception
*/ */
public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false) public static function buildMessage(string $msg, array $user, array $contact, string $prvkey, string $pubkey, bool $public = false): string
{ {
// The message is put into an envelope with the sender's signature // The message is put into an envelope with the sender's signature
$envelope = self::buildMagicEnvelope($msg, $user); $envelope = self::buildMagicEnvelope($msg, $user);
@ -2962,15 +2987,15 @@ class Diaspora
* *
* @return string The signature * @return string The signature
*/ */
private static function signature($owner, $message) private static function signature(array $owner, array $message): string
{ {
$sigmsg = $message; $sigmsg = $message;
unset($sigmsg["author_signature"]); unset($sigmsg['author_signature']);
unset($sigmsg["parent_author_signature"]); unset($sigmsg['parent_author_signature']);
$signed_text = implode(";", $sigmsg); $signed_text = implode(';', $sigmsg);
return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256")); return base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
} }
/** /**
@ -2986,9 +3011,9 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function transmit(array $owner, array $contact, $envelope, $public_batch, $guid = "") private static function transmit(array $owner, array $contact, string $envelope, bool $public_batch, string $guid = ''): int
{ {
$enabled = intval(DI::config()->get("system", "diaspora_enabled")); $enabled = intval(DI::config()->get('system', 'diaspora_enabled'));
if (!$enabled) { if (!$enabled) {
return 200; return 200;
} }
@ -3000,32 +3025,32 @@ class Diaspora
if (!empty($contact['addr'])) { if (!empty($contact['addr'])) {
$fcontact = FContact::getByURL($contact['addr']); $fcontact = FContact::getByURL($contact['addr']);
if (!empty($fcontact)) { if (!empty($fcontact)) {
$dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]); $dest_url = ($public_batch ? $fcontact['batch'] : $fcontact['notify']);
} }
} }
if (empty($dest_url)) { if (empty($dest_url)) {
$dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]); $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
} }
if (!$dest_url) { if (!$dest_url) {
Logger::notice("no url for contact: ".$contact["id"]." batch mode =".$public_batch); Logger::notice("no url for contact: " . $contact['id'] . " batch mode =" . $public_batch);
return 0; return 0;
} }
Logger::notice("transmit: ".$logid."-".$guid." ".$dest_url); Logger::notice("transmit: " . $logid . "-" . $guid . " " . $dest_url);
if (!intval(DI::config()->get("system", "diaspora_test"))) { if (!intval(DI::config()->get('system', 'diaspora_test'))) {
$content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json"); $content_type = (($public_batch) ? 'application/magic-envelope+xml' : 'application/json');
$postResult = DI::httpClient()->post($dest_url . "/", $envelope, ['Content-Type' => $content_type]); $postResult = DI::httpClient()->post($dest_url . '/', $envelope, ['Content-Type' => $content_type]);
$return_code = $postResult->getReturnCode(); $return_code = $postResult->getReturnCode();
} else { } else {
Logger::notice("test_mode"); Logger::notice('test_mode');
return 200; return 200;
} }
Logger::notice("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code); Logger::notice("transmit: " . $logid . "-" . $guid . " to " . $dest_url . " returns: " . $return_code);
return $return_code ? $return_code : -1; return $return_code ? $return_code : -1;
} }
@ -3039,7 +3064,7 @@ class Diaspora
* *
* @return string The post XML * @return string The post XML
*/ */
public static function buildPostXml($type, $message) public static function buildPostXml(string $type, array $message): string
{ {
$data = [$type => $message]; $data = [$type => $message];
@ -3060,7 +3085,7 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "") private static function buildAndTransmit(array $owner, array $contact, string $type, array $message, bool $public_batch = false, string $guid = '')
{ {
$msg = self::buildPostXml($type, $message); $msg = self::buildPostXml($type, $message);
@ -3103,18 +3128,18 @@ class Diaspora
* @return int The result of the transmission * @return int The result of the transmission
* @throws \Exception * @throws \Exception
*/ */
private static function sendParticipation(array $contact, array $item) private static function sendParticipation(array $contact, array $item): int
{ {
// Don't send notifications for private postings // Don't send notifications for private postings
if ($item['private'] == Item::PRIVATE) { if ($item['private'] == Item::PRIVATE) {
return; return 0;
} }
$cachekey = "diaspora:sendParticipation:".$item['guid']; $cachekey = 'diaspora:sendParticipation:' . $item['guid'];
$result = DI::cache()->get($cachekey); $result = DI::cache()->get($cachekey);
if (!is_null($result)) { if (!is_null($result)) {
return; return -1;
} }
// Fetch some user id to have a valid handle to transmit the participation. // Fetch some user id to have a valid handle to transmit the participation.
@ -3132,17 +3157,19 @@ class Diaspora
$author = self::myHandle($owner); $author = self::myHandle($owner);
$message = ["author" => $author, $message = [
"guid" => System::createUUID(), 'author' => $author,
"parent_type" => "Post", 'guid' => System::createUUID(),
"parent_guid" => $item["guid"]]; 'parent_type' => 'Post',
'parent_guid' => $item['guid']
];
Logger::info("Send participation for ".$item["guid"]." by ".$author); Logger::info("Send participation for " . $item['guid'] . " by " . $author);
// It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
DI::cache()->set($cachekey, $item["guid"], Duration::QUARTER_HOUR); DI::cache()->set($cachekey, $item['guid'], Duration::QUARTER_HOUR);
return self::buildAndTransmit($owner, $contact, "participation", $message); return self::buildAndTransmit($owner, $contact, 'participation', $message);
} }
/** /**
@ -3156,21 +3183,23 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function sendAccountMigration(array $owner, array $contact, $uid) public static function sendAccountMigration(array $owner, array $contact, int $uid): int
{ {
$old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr'); $old_handle = DI::pConfig()->get($uid, 'system', 'previous_addr');
$profile = self::createProfileData($uid); $profile = self::createProfileData($uid);
$signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author']; $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
$signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256")); $signature = base64_encode(Crypto::rsaSign($signed_text, $owner['uprvkey'], 'sha256'));
$message = ["author" => $old_handle, $message = [
"profile" => $profile, 'author' => $old_handle,
"signature" => $signature]; 'profile' => $profile,
'signature' => $signature
];
Logger::info('Send account migration', ['msg' => $message]); Logger::info('Send account migration', ['msg' => $message]);
return self::buildAndTransmit($owner, $contact, "account_migration", $message); return self::buildAndTransmit($owner, $contact, 'account_migration', $message);
} }
/** /**
@ -3182,7 +3211,7 @@ class Diaspora
* @return int The result of the transmission * @return int The result of the transmission
* @throws \Exception * @throws \Exception
*/ */
public static function sendShare(array $owner, array $contact) public static function sendShare(array $owner, array $contact): int
{ {
/** /**
* @todo support the different possible combinations of "following" and "sharing" * @todo support the different possible combinations of "following" and "sharing"
@ -3207,14 +3236,16 @@ class Diaspora
} }
*/ */
$message = ["author" => self::myHandle($owner), $message = [
"recipient" => $contact["addr"], 'author' => self::myHandle($owner),
"following" => "true", 'recipient' => $contact['addr'],
"sharing" => "true"]; 'following' => 'true',
'sharing' => 'true'
];
Logger::info('Send share', ['msg' => $message]); Logger::info('Send share', ['msg' => $message]);
return self::buildAndTransmit($owner, $contact, "contact", $message); return self::buildAndTransmit($owner, $contact, 'contact', $message);
} }
/** /**
@ -3226,16 +3257,18 @@ class Diaspora
* @return int The result of the transmission * @return int The result of the transmission
* @throws \Exception * @throws \Exception
*/ */
public static function sendUnshare(array $owner, array $contact) public static function sendUnshare(array $owner, array $contact): int
{ {
$message = ["author" => self::myHandle($owner), $message = [
"recipient" => $contact["addr"], 'author' => self::myHandle($owner),
"following" => "false", 'recipient' => $contact['addr'],
"sharing" => "false"]; 'following' => 'false',
'sharing' => 'false'
];
Logger::info('Send unshare', ['msg' => $message]); Logger::info('Send unshare', ['msg' => $message]);
return self::buildAndTransmit($owner, $contact, "contact", $message); return self::buildAndTransmit($owner, $contact, 'contact', $message);
} }
/** /**
@ -3248,7 +3281,7 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isReshare($body, $complete = true) public static function isReshare(string $body, bool $complete = true)
{ {
$body = trim($body); $body = trim($body);
@ -3268,8 +3301,8 @@ class Diaspora
$item = Post::selectFirst(['contact-id'], $condition); $item = Post::selectFirst(['contact-id'], $condition);
if (DBA::isResult($item)) { if (DBA::isResult($item)) {
$ret = []; $ret = [];
$ret["root_handle"] = self::handleFromContact($item["contact-id"]); $ret['root_handle'] = self::handleFromContact($item['contact-id']);
$ret["root_guid"] = $reshared['guid']; $ret['root_guid'] = $reshared['guid'];
return $ret; return $ret;
} elseif ($complete) { } elseif ($complete) {
// We are resharing something that isn't a DFRN or Diaspora post. // We are resharing something that isn't a DFRN or Diaspora post.
@ -3304,7 +3337,7 @@ class Diaspora
* @return array with event data * @return array with event data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function buildEvent($event_id) private static function buildEvent(string $event_id): array
{ {
$event = DBA::selectFirst('event', [], ['id' => $event_id]); $event = DBA::selectFirst('event', [], ['id' => $event_id]);
if (!DBA::isResult($event)) { if (!DBA::isResult($event)) {
@ -3327,7 +3360,7 @@ class Diaspora
$mask = DateTimeFormat::ATOM; $mask = DateTimeFormat::ATOM;
/// @todo - establish "all day" events in Friendica /// @todo - establish "all day" events in Friendica
$eventdata["all_day"] = "false"; $eventdata['all_day'] = 'false';
$eventdata['timezone'] = 'UTC'; $eventdata['timezone'] = 'UTC';
@ -3348,13 +3381,13 @@ class Diaspora
$coord = Map::getCoordinates($event['location']); $coord = Map::getCoordinates($event['location']);
$location = []; $location = [];
$location["address"] = html_entity_decode(BBCode::toMarkdown($event['location'])); $location['address'] = html_entity_decode(BBCode::toMarkdown($event['location']));
if (!empty($coord['lat']) && !empty($coord['lon'])) { if (!empty($coord['lat']) && !empty($coord['lon'])) {
$location["lat"] = $coord['lat']; $location['lat'] = $coord['lat'];
$location["lng"] = $coord['lon']; $location['lng'] = $coord['lon'];
} else { } else {
$location["lat"] = 0; $location['lat'] = 0;
$location["lng"] = 0; $location['lng'] = 0;
} }
$eventdata['location'] = $location; $eventdata['location'] = $location;
} }
@ -3376,7 +3409,7 @@ class Diaspora
*/ */
public static function buildStatus(array $item, array $owner) public static function buildStatus(array $item, array $owner)
{ {
$cachekey = "diaspora:buildStatus:".$item['guid']; $cachekey = 'diaspora:buildStatus:' . $item['guid'];
$result = DI::cache()->get($cachekey); $result = DI::cache()->get($cachekey);
if (!is_null($result)) { if (!is_null($result)) {
@ -3385,27 +3418,29 @@ class Diaspora
$myaddr = self::myHandle($owner); $myaddr = self::myHandle($owner);
$public = ($item["private"] == Item::PRIVATE ? "false" : "true"); $public = ($item['private'] == Item::PRIVATE ? 'false' : 'true');
$created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM); $created = DateTimeFormat::utc($item['received'], DateTimeFormat::ATOM);
$edited = DateTimeFormat::utc($item["edited"] ?? $item["created"], DateTimeFormat::ATOM); $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
// Detect a share element and do a reshare // Detect a share element and do a reshare
if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item["body"]))) { if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item['body']))) {
$message = ["author" => $myaddr, $message = [
"guid" => $item["guid"], 'author' => $myaddr,
"created_at" => $created, 'guid' => $item['guid'],
"root_author" => $ret["root_handle"], 'created_at' => $created,
"root_guid" => $ret["root_guid"], 'root_author' => $ret['root_handle'],
"provider_display_name" => $item["app"], 'root_guid' => $ret['root_guid'],
"public" => $public]; 'provider_display_name' => $item['app'],
'public' => $public
];
$type = "reshare"; $type = 'reshare';
} else { } else {
$title = $item["title"]; $title = $item['title'];
$body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']); $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
// Fetch the title from an attached link - if there is one // Fetch the title from an attached link - if there is one
if (empty($item["title"]) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) { if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
$page_data = BBCode::getAttachmentData($item['body']); $page_data = BBCode::getAttachmentData($item['body']);
if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) { if (!empty($page_data['type']) && !empty($page_data['title']) && ($page_data['type'] == 'link')) {
$title = $page_data['title']; $title = $page_data['title'];
@ -3422,7 +3457,7 @@ class Diaspora
// Adding the title // Adding the title
if (strlen($title)) { if (strlen($title)) {
$body = "### ".html_entity_decode($title)."\n\n".$body; $body = '### ' . html_entity_decode($title) . "\n\n" . $body;
} }
$attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]); $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]);
@ -3435,27 +3470,29 @@ class Diaspora
$location = []; $location = [];
if ($item["location"] != "") if ($item['location'] != '')
$location["address"] = $item["location"]; $location['address'] = $item['location'];
if ($item["coord"] != "") { if ($item['coord'] != '') {
$coord = explode(" ", $item["coord"]); $coord = explode(' ', $item['coord']);
$location["lat"] = $coord[0]; $location['lat'] = $coord[0];
$location["lng"] = $coord[1]; $location['lng'] = $coord[1];
} }
$message = ["author" => $myaddr, $message = [
"guid" => $item["guid"], 'author' => $myaddr,
"created_at" => $created, 'guid' => $item['guid'],
"edited_at" => $edited, 'created_at' => $created,
"public" => $public, 'edited_at' => $edited,
"text" => $body, 'public' => $public,
"provider_display_name" => $item["app"], 'text' => $body,
"location" => $location]; 'provider_display_name' => $item['app'],
'location' => $location
];
// Diaspora rejects messages when they contain a location without "lat" or "lng" // Diaspora rejects messages when they contain a location without "lat" or "lng"
if (!isset($location["lat"]) || !isset($location["lng"])) { if (!isset($location['lat']) || !isset($location['lng'])) {
unset($message["location"]); unset($message['location']);
} }
if ($item['event-id'] > 0) { if ($item['event-id'] > 0) {
@ -3474,17 +3511,20 @@ class Diaspora
} }
} }
$type = "status_message"; $type = 'status_message';
} }
$msg = ["type" => $type, "message" => $message]; $msg = [
'type' => $type,
'message' => $message
];
DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR); DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
return $msg; return $msg;
} }
private static function prependParentAuthorMention($body, $profile_url) private static function prependParentAuthorMention(string $body, string $profile_url): string
{ {
$profile = Contact::getByURL($profile_url, false, ['addr', 'name']); $profile = Contact::getByURL($profile_url, false, ['addr', 'name']);
if (!empty($profile['addr']) if (!empty($profile['addr'])
@ -3509,11 +3549,11 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false) public static function sendStatus(array $item, array $owner, array $contact, bool $public_batch = false): int
{ {
$status = self::buildStatus($item, $owner); $status = self::buildStatus($item, $owner);
return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]); return self::buildAndTransmit($owner, $contact, $status['type'], $status['message'], $public_batch, $item['guid']);
} }
/** /**
@ -3522,30 +3562,32 @@ class Diaspora
* @param array $item The item that will be exported * @param array $item The item that will be exported
* @param array $owner the array of the item owner * @param array $owner the array of the item owner
* *
* @return array The data for a "like" * @return array|bool The data for a "like" or false on error
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function constructLike(array $item, array $owner) private static function constructLike(array $item, array $owner)
{ {
$parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item["thr-parent"]]); $parent = Post::selectFirst(['guid', 'uri', 'thr-parent'], ['uri' => $item['thr-parent']]);
if (!DBA::isResult($parent)) { if (!DBA::isResult($parent)) {
return false; return false;
} }
$target_type = ($parent["uri"] === $parent["thr-parent"] ? "Post" : "Comment"); $target_type = ($parent['uri'] === $parent['thr-parent'] ? 'Post' : 'Comment');
$positive = null; $positive = null;
if ($item['verb'] === Activity::LIKE) { if ($item['verb'] === Activity::LIKE) {
$positive = "true"; $positive = 'true';
} elseif ($item['verb'] === Activity::DISLIKE) { } elseif ($item['verb'] === Activity::DISLIKE) {
$positive = "false"; $positive = 'false';
} }
return(["author" => self::myHandle($owner), return [
"guid" => $item["guid"], 'author' => self::myHandle($owner),
"parent_guid" => $parent["guid"], 'guid' => $item['guid'],
"parent_type" => $target_type, 'parent_guid' => $parent['guid'],
"positive" => $positive, 'parent_type' => $target_type,
"author_signature" => ""]); 'positive' => $positive,
'author_signature' => ''
];
} }
/** /**
@ -3554,7 +3596,7 @@ class Diaspora
* @param array $item The item that will be exported * @param array $item The item that will be exported
* @param array $owner the array of the item owner * @param array $owner the array of the item owner
* *
* @return array The data for an "EventParticipation" * @return array|bool The data for an "EventParticipation" or false on error
* @throws \Exception * @throws \Exception
*/ */
private static function constructAttend(array $item, array $owner) private static function constructAttend(array $item, array $owner)
@ -3579,11 +3621,13 @@ class Diaspora
return false; return false;
} }
return(["author" => self::myHandle($owner), return [
"guid" => $item["guid"], 'author' => self::myHandle($owner),
"parent_guid" => $parent["guid"], 'guid' => $item['guid'],
"status" => $attend_answer, 'parent_guid' => $parent['guid'],
"author_signature" => ""]); 'status' => $attend_answer,
'author_signature' => ''
];
} }
/** /**
@ -3597,7 +3641,7 @@ class Diaspora
*/ */
private static function constructComment(array $item, array $owner) private static function constructComment(array $item, array $owner)
{ {
$cachekey = "diaspora:constructComment:".$item['guid']; $cachekey = 'diaspora:constructComment:' . $item['guid'];
$result = DI::cache()->get($cachekey); $result = DI::cache()->get($cachekey);
if (!is_null($result)) { if (!is_null($result)) {
@ -3631,17 +3675,17 @@ class Diaspora
} }
$text = html_entity_decode(BBCode::toMarkdown($body)); $text = html_entity_decode(BBCode::toMarkdown($body));
$created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM); $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
$edited = DateTimeFormat::utc($item["edited"], DateTimeFormat::ATOM); $edited = DateTimeFormat::utc($item['edited'], DateTimeFormat::ATOM);
$comment = [ $comment = [
"author" => self::myHandle($owner), 'author' => self::myHandle($owner),
"guid" => $item["guid"], 'guid' => $item['guid'],
"created_at" => $created, 'created_at' => $created,
"edited_at" => $edited, 'edited_at' => $edited,
"parent_guid" => $toplevel_item["guid"], 'parent_guid' => $toplevel_item['guid'],
"text" => $text, 'text' => $text,
"author_signature" => "" 'author_signature' => ''
]; ];
// Send the thread parent guid only if it is a threaded comment // Send the thread parent guid only if it is a threaded comment
@ -3651,7 +3695,7 @@ class Diaspora
DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR); DI::cache()->set($cachekey, $comment, Duration::QUARTER_HOUR);
return($comment); return $comment;
} }
/** /**
@ -3666,26 +3710,26 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false) public static function sendFollowup(array $item, array $owner, array $contact, bool $public_batch = false): int
{ {
if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) { if (in_array($item['verb'], [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE])) {
$message = self::constructAttend($item, $owner); $message = self::constructAttend($item, $owner);
$type = "event_participation"; $type = 'event_participation';
} elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
$message = self::constructLike($item, $owner); $message = self::constructLike($item, $owner);
$type = "like"; $type = 'like';
} elseif (!in_array($item["verb"], [Activity::FOLLOW, Activity::TAG])) { } elseif (!in_array($item['verb'], [Activity::FOLLOW, Activity::TAG])) {
$message = self::constructComment($item, $owner); $message = self::constructComment($item, $owner);
$type = "comment"; $type = 'comment';
} }
if (empty($message)) { if (empty($message)) {
return false; return -1;
} }
$message["author_signature"] = self::signature($owner, $message); $message['author_signature'] = self::signature($owner, $message);
return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]); return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
} }
/** /**
@ -3699,43 +3743,43 @@ class Diaspora
* @return int The result of the transmission * @return int The result of the transmission
* @throws \Exception * @throws \Exception
*/ */
public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false) public static function sendRelay(array $item, array $owner, array $contact, bool $public_batch = false): int
{ {
if ($item["deleted"]) { if ($item['deleted']) {
return self::sendRetraction($item, $owner, $contact, $public_batch, true); return self::sendRetraction($item, $owner, $contact, $public_batch, true);
} elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
$type = "like"; $type = 'like';
} else { } else {
$type = "comment"; $type = 'comment';
} }
Logger::info("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")"); Logger::info("Got relayable data " . $type . " for item " . $item['guid'] . " (" . $item['id'] . ")");
$msg = json_decode($item['signed_text'], true); $msg = json_decode($item['signed_text'], true);
$message = []; $message = [];
if (is_array($msg)) { if (is_array($msg)) {
foreach ($msg as $field => $data) { foreach ($msg as $field => $data) {
if (!$item["deleted"]) { if (!$item['deleted']) {
if ($field == "diaspora_handle") { if ($field == 'diaspora_handle') {
$field = "author"; $field = 'author';
} }
if ($field == "target_type") { if ($field == 'target_type') {
$field = "parent_type"; $field = 'parent_type';
} }
} }
$message[$field] = $data; $message[$field] = $data;
} }
} else { } else {
Logger::info("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$item['signed_text']); Logger::info("Signature text for item " . $item["guid"] . " (" . $item["id"] . ") couldn't be extracted: " . $item['signed_text']);
} }
$message["parent_author_signature"] = self::signature($owner, $message); $message['parent_author_signature'] = self::signature($owner, $message);
Logger::info('Relayed data', ['msg' => $message]); Logger::info('Relayed data', ['msg' => $message]);
return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]); return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item['guid']);
} }
/** /**
@ -3750,27 +3794,29 @@ class Diaspora
* @return int The result of the transmission * @return int The result of the transmission
* @throws \Exception * @throws \Exception
*/ */
public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false) public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
{ {
$itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]); $itemaddr = self::handleFromContact($item['contact-id'], $item['author-id']);
$msg_type = "retraction"; $msg_type = 'retraction';
if ($item['gravity'] == GRAVITY_PARENT) { if ($item['gravity'] == GRAVITY_PARENT) {
$target_type = "Post"; $target_type = 'Post';
} elseif (in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
$target_type = "Like"; $target_type = 'Like';
} else { } else {
$target_type = "Comment"; $target_type = 'Comment';
} }
$message = ["author" => $itemaddr, $message = [
"target_guid" => $item['guid'], 'author' => $itemaddr,
"target_type" => $target_type]; 'target_guid' => $item['guid'],
'target_type' => $target_type
];
Logger::info('Got message', ['msg' => $message]); Logger::info('Got message', ['msg' => $message]);
return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]); return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item['guid']);
} }
/** /**
@ -3784,44 +3830,44 @@ class Diaspora
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function sendMail(array $item, array $owner, array $contact) public static function sendMail(array $item, array $owner, array $contact): int
{ {
$myaddr = self::myHandle($owner); $myaddr = self::myHandle($owner);
$cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]); $cnv = DBA::selectFirst('conv', [], ['id' => $item['convid'], 'uid' => $item['uid']]);
if (!DBA::isResult($cnv)) { if (!DBA::isResult($cnv)) {
Logger::notice("conversation not found."); Logger::notice("conversation not found.");
return; return -1;
} }
$body = BBCode::toMarkdown($item["body"]); $body = BBCode::toMarkdown($item['body']);
$created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM); $created = DateTimeFormat::utc($item['created'], DateTimeFormat::ATOM);
$msg = [ $msg = [
"author" => $myaddr, 'author' => $myaddr,
"guid" => $item["guid"], 'guid' => $item['guid'],
"conversation_guid" => $cnv["guid"], 'conversation_guid' => $cnv['guid'],
"text" => $body, 'text' => $body,
"created_at" => $created, 'created_at' => $created,
]; ];
if ($item["reply"]) { if ($item['reply']) {
$message = $msg; $message = $msg;
$type = "message"; $type = 'message';
} else { } else {
$message = [ $message = [
"author" => $cnv["creator"], 'author' => $cnv['creator'],
"guid" => $cnv["guid"], 'guid' => $cnv['guid'],
"subject" => $cnv["subject"], 'subject' => $cnv['subject'],
"created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM), 'created_at' => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
"participants" => $cnv["recips"], 'participants' => $cnv['recips'],
"message" => $msg 'message' => $msg
]; ];
$type = "conversation"; $type = 'conversation';
} }
return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]); return self::buildAndTransmit($owner, $contact, $type, $message, false, $item['guid']);
} }
/** /**
@ -3831,7 +3877,8 @@ class Diaspora
* *
* @return array The array with "first" and "last" * @return array The array with "first" and "last"
*/ */
public static function splitName($name) { public static function splitName(string $name): array
{
$name = trim($name); $name = trim($name);
// Is the name longer than 64 characters? Then cut the rest of it. // Is the name longer than 64 characters? Then cut the rest of it.
@ -3888,14 +3935,14 @@ class Diaspora
* @return array The profile data * @return array The profile data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function createProfileData($uid) private static function createProfileData(int $uid): array
{ {
$profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]); $profile = DBA::selectFirst('owner-view', ['uid', 'addr', 'name', 'location', 'net-publish', 'dob', 'about', 'pub_keywords'], ['uid' => $uid]);
if (!DBA::isResult($profile)) { if (!DBA::isResult($profile)) {
return []; return [];
} }
$handle = $profile["addr"]; $handle = $profile['addr'];
$split_name = self::splitName($profile['name']); $split_name = self::splitName($profile['name']);
$first = $split_name['first']; $first = $split_name['first'];
@ -3940,18 +3987,20 @@ class Diaspora
$tags = trim($tags); $tags = trim($tags);
} }
return ["author" => $handle, return [
"first_name" => $first, 'author' => $handle,
"last_name" => $last, 'first_name' => $first,
"image_url" => $large, 'last_name' => $last,
"image_url_medium" => $medium, 'image_url' => $large,
"image_url_small" => $small, 'image_url_medium' => $medium,
"birthday" => $dob, 'image_url_small' => $small,
"bio" => $about, 'birthday' => $dob,
"location" => $location, 'bio' => $about,
"searchable" => $searchable, 'location' => $location,
"nsfw" => "false", 'searchable' => $searchable,
"tag_string" => $tags]; 'nsfw' => 'false',
'tag_string' => $tags
];
} }
/** /**
@ -3962,7 +4011,7 @@ class Diaspora
* @return void * @return void
* @throws \Exception * @throws \Exception
*/ */
public static function sendProfile($uid, $recips = false) public static function sendProfile(int $uid, bool $recips = false)
{ {
if (!$uid) { if (!$uid) {
return; return;
@ -3985,8 +4034,8 @@ class Diaspora
// @ToDo Split this into single worker jobs // @ToDo Split this into single worker jobs
foreach ($recips as $recip) { foreach ($recips as $recip) {
Logger::info("Send updated profile data for user ".$uid." to contact ".$recip["id"]); Logger::info("Send updated profile data for user " . $uid . " to contact " . $recip['id']);
self::buildAndTransmit($owner, $recip, "profile", $message); self::buildAndTransmit($owner, $recip, 'profile', $message);
} }
} }
@ -3996,10 +4045,10 @@ class Diaspora
* @param integer $uid The user of that comment * @param integer $uid The user of that comment
* @param array $item Item array * @param array $item Item array
* *
* @return array Signed content * @return array|bool Signed content or false on error
* @throws \Exception * @throws \Exception
*/ */
public static function createLikeSignature($uid, array $item) public static function createLikeSignature(int $uid, array $item)
{ {
$owner = User::getOwnerDataById($uid); $owner = User::getOwnerDataById($uid);
if (empty($owner)) { if (empty($owner)) {
@ -4007,7 +4056,7 @@ class Diaspora
return false; return false;
} }
if (!in_array($item["verb"], [Activity::LIKE, Activity::DISLIKE])) { if (!in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
return false; return false;
} }
@ -4016,7 +4065,7 @@ class Diaspora
return false; return false;
} }
$message["author_signature"] = self::signature($owner, $message); $message['author_signature'] = self::signature($owner, $message);
return $message; return $message;
} }
@ -4026,7 +4075,7 @@ class Diaspora
* *
* @param array $item Item array * @param array $item Item array
* *
* @return array Signed content * @return array|bool Signed content or false on error
* @throws \Exception * @throws \Exception
*/ */
public static function createCommentSignature(array $item) public static function createCommentSignature(array $item)
@ -4064,12 +4113,12 @@ class Diaspora
return false; return false;
} }
$message["author_signature"] = self::signature($owner, $message); $message['author_signature'] = self::signature($owner, $message);
return $message; return $message;
} }
public static function performReshare(int $UriId, int $uid) public static function performReshare(int $UriId, int $uid): int
{ {
$fields = ['uri-id', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink']; $fields = ['uri-id', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink'];
$item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]); $item = Post::selectFirst($fields, ['uri-id' => $UriId, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);

View file

@ -708,7 +708,6 @@ class HTTPSignature
} }
} }
// @TODO really a notice or more a warning?
Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]); Logger::notice('Key could not be fetched', ['url' => $url, 'actor' => $actor]);
return []; return [];
} }

View file

@ -165,7 +165,7 @@ class Strings
* @return string Formatted network name * @return string Formatted network name
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function formatNetworkName($network, $url = '') public static function formatNetworkName(string $network, string $url = ''): string
{ {
if ($network != '') { if ($network != '') {
if ($url != '') { if ($url != '') {
@ -176,6 +176,8 @@ class Strings
return $network_name; return $network_name;
} }
return '';
} }
/** /**
@ -187,7 +189,7 @@ class Strings
* *
* @return string Transformed string. * @return string Transformed string.
*/ */
public static function deindent($text, $chr = "[\t ]", $count = NULL) public static function deindent(string $text, string $chr = "[\t ]", int $count = null)
{ {
$lines = explode("\n", $text); $lines = explode("\n", $text);

View file

@ -269,7 +269,7 @@ class Delivery
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function deliverDFRN($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup, $server_protocol) private static function deliverDFRN(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup, int $server_protocol)
{ {
// Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora // Transmit Diaspora reshares via Diaspora if the Friendica contact support Diaspora
if (Diaspora::isReshare($target_item['body'] ?? '') && !empty(FContact::getByURL($contact['addr'], false))) { if (Diaspora::isReshare($target_item['body'] ?? '') && !empty(FContact::getByURL($contact['addr'], false))) {
@ -384,7 +384,7 @@ class Delivery
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function deliverDiaspora($cmd, $contact, $owner, $items, $target_item, $public_message, $top_level, $followup) private static function deliverDiaspora(string $cmd, array $contact, array $owner, array $items, array $target_item, bool $public_message, bool $top_level, bool $followup)
{ {
// We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora // We don't treat Forum posts as "wall-to-wall" to be able to post them via Diaspora
$walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY); $walltowall = $top_level && ($owner['id'] != $items[0]['contact-id']) & ($owner['account-type'] != Model\User::ACCOUNT_TYPE_COMMUNITY);
@ -478,7 +478,7 @@ class Delivery
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
private static function deliverMail($cmd, $contact, $owner, $target_item, $thr_parent) private static function deliverMail(string $cmd, array $contact, array $owner, array $target_item, array $thr_parent)
{ {
if (DI::config()->get('system','imap_disabled')) { if (DI::config()->get('system','imap_disabled')) {
return; return;

View file

@ -34,7 +34,7 @@ use Friendica\Network\HTTPClient\Client\HttpClientAccept;
*/ */
class Directory class Directory
{ {
public static function execute($url = '') public static function execute(string $url = '')
{ {
$dir = Search::getGlobalDirectory(); $dir = Search::getGlobalDirectory();

View file

@ -43,7 +43,7 @@ class AppDouble extends App
$this->isLoggedIn = $isLoggedIn; $this->isLoggedIn = $isLoggedIn;
} }
public function isLoggedIn() public function isLoggedIn(): bool
{ {
return $this->isLoggedIn; return $this->isLoggedIn;
} }