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

Fixes/more type hints 004
This commit is contained in:
Hypolite Petovan 2022-06-22 10:49:20 -04:00 committed by GitHub
commit b96daeeeef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 1727 additions and 1541 deletions

View File

@ -102,6 +102,7 @@ abstract class BaseModule implements ICanHandleRequests
* e.g. from protocol implementations.
*
* @param string[] $request The $_REQUEST content
* @return void
*/
protected function rawContent(array $request = [])
{
@ -117,6 +118,7 @@ abstract class BaseModule implements ICanHandleRequests
* XML feed or a JSON output.
*
* @param string[] $request The $_REQUEST content
* @return string
*/
protected function content(array $request = []): string
{
@ -130,6 +132,7 @@ abstract class BaseModule implements ICanHandleRequests
* Doesn't display any content
*
* @param string[] $request The $_REQUEST content
* @return void
*/
protected function delete(array $request = [])
{
@ -142,6 +145,7 @@ abstract class BaseModule implements ICanHandleRequests
* Doesn't display any content
*
* @param string[] $request The $_REQUEST content
* @return void
*/
protected function patch(array $request = [])
{
@ -154,7 +158,7 @@ abstract class BaseModule implements ICanHandleRequests
* Doesn't display any content
*
* @param string[] $request The $_REQUEST content
*
* @return void
*/
protected function post(array $request = [])
{
@ -168,6 +172,7 @@ abstract class BaseModule implements ICanHandleRequests
* Doesn't display any content
*
* @param string[] $request The $_REQUEST content
* @return void
*/
protected function put(array $request = [])
{
@ -279,12 +284,12 @@ abstract class BaseModule implements ICanHandleRequests
/**
* Fetch a request value and apply default values and check against minimal and maximal values
*
* @param array $input
* @param string $parameter
* @param mixed $default
* @param mixed $minimal_value
* @param mixed $maximum_value
* @return mixed
* @param array $input Input fields
* @param string $parameter Parameter
* @param mixed $default Default
* @param mixed $minimal_value Minimal value
* @param mixed $maximum_value Maximum value
* @return mixed null on error anything else on success (?)
*/
public function getRequestValue(array $input, string $parameter, $default = null, $minimal_value = null, $maximum_value = null)
{
@ -320,7 +325,7 @@ abstract class BaseModule implements ICanHandleRequests
return $value;
}
/*
/**
* Functions used to protect against Cross-Site Request Forgery
* The security token has to base on at least one value that an attacker can't know - here it's the session ID and the private key.
* In this implementation, a security token is reusable (if the user submits a form, goes back and resubmits the form, maybe with small changes;
@ -330,8 +335,11 @@ abstract class BaseModule implements ICanHandleRequests
* If the new page contains by any chance external elements, then the used security token is exposed by the referrer.
* 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).
*
* @param string $typename Type name
* @return string Security hash with timestamp
*/
public static function getFormSecurityToken(string $typename = '')
public static function getFormSecurityToken(string $typename = ''): string
{
$user = User::getById(DI::app()->getLoggedInUserId(), ['guid', 'prvkey']);
$timestamp = time();
@ -404,7 +412,7 @@ abstract class BaseModule implements ICanHandleRequests
}
}
protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab)
protected static function getContactFilterTabs(string $baseUrl, string $current, bool $displayCommonTab): array
{
$tabs = [
[

View File

@ -1247,16 +1247,28 @@ class BBCode
return $text;
}
private static function expandLinksCallback($match)
/**
* Callback: Expands links from given $match array
*
* @param arrat $match Array with link match
* @return string BBCode
*/
private static function expandLinksCallback(array $match): string
{
if (($match[3] == '') || ($match[2] == $match[3]) || stristr($match[2], $match[3])) {
return ($match[1] . "[url]" . $match[2] . "[/url]");
return ($match[1] . '[url]' . $match[2] . '[/url]');
} else {
return ($match[1] . $match[3] . " [url]" . $match[2] . "[/url]");
return ($match[1] . $match[3] . ' [url]' . $match[2] . '[/url]');
}
}
private static function cleanPictureLinksCallback($match)
/**
* Callback: Cleans picture links
*
* @param arrat $match Array with link match
* @return string BBCode
*/
private static function cleanPictureLinksCallback(array $match): string
{
// When the picture link is the own photo path then we can avoid fetching the link
$own_photo_url = preg_quote(Strings::normaliseLink(DI::baseUrl()->get()) . '/photos/');
@ -1325,7 +1337,13 @@ class BBCode
return $text;
}
public static function cleanPictureLinks($text)
/**
* Cleans picture links
*
* @param string $text HTML/BBCode string
* @return string Cleaned HTML/BBCode
*/
public static function cleanPictureLinks(string $text): string
{
DI::profiler()->startRecording('rendering');
$return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img=(.*)\](.*)\[\/img\]\[\/url\]&Usi", 'self::cleanPictureLinksCallback', $text);
@ -1334,7 +1352,13 @@ class BBCode
return $return;
}
public static function removeLinks(string $bbcode)
/**
* Removes links
*
* @param string $text HTML/BBCode string
* @return string Cleaned HTML/BBCode
*/
public static function removeLinks(string $bbcode): string
{
DI::profiler()->startRecording('rendering');
$bbcode = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", ' $1 ', $bbcode);
@ -1350,10 +1374,10 @@ class BBCode
/**
* Replace names in mentions with nicknames
*
* @param string $body
* @param string $body HTML/BBCode
* @return string Body with replaced mentions
*/
public static function setMentionsToNicknames(string $body):string
public static function setMentionsToNicknames(string $body): string
{
DI::profiler()->startRecording('rendering');
$regexp = "/([@!])\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
@ -1366,10 +1390,10 @@ class BBCode
* Callback function to replace a Friendica style mention in a mention with the nickname
*
* @param array $match Matching values for the callback
* @return string Replaced mention
* @return string Replaced mention or empty string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function mentionCallback($match)
private static function mentionCallback(array $match): string
{
if (empty($match[2])) {
return '';
@ -1407,7 +1431,7 @@ class BBCode
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function convertForUriId(int $uriid = null, string $text = null, int $simple_html = self::INTERNAL)
public static function convertForUriId(int $uriid = null, string $text = null, int $simple_html = self::INTERNAL): string
{
$try_oembed = ($simple_html == self::INTERNAL);
@ -1437,10 +1461,10 @@ class BBCode
* @param int $simple_html
* @param bool $for_plaintext
* @param int $uriid
* @return string
* @return string Converted code or empty string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function convert(string $text = null, $try_oembed = true, $simple_html = self::INTERNAL, $for_plaintext = false, $uriid = 0)
public static function convert(string $text = null, bool $try_oembed = true, int $simple_html = self::INTERNAL, bool $for_plaintext = false, int $uriid = 0): string
{
// Accounting for null default column values
if (is_null($text) || $text === '') {
@ -2142,7 +2166,7 @@ class BBCode
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function bbCodeMention2DiasporaCallback($match)
private static function bbCodeMention2DiasporaCallback(array $match): string
{
$contact = Contact::getByURL($match[3], false, ['addr']);
if (empty($contact['addr'])) {
@ -2164,7 +2188,7 @@ class BBCode
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function toMarkdown($text, $for_diaspora = true)
public static function toMarkdown(string $text, bool $for_diaspora = true): string
{
DI::profiler()->startRecording('rendering');
$original_text = $text;
@ -2249,7 +2273,7 @@ class BBCode
*
* @return array List of tag and person names
*/
public static function getTags($string)
public static function getTags(string $string): array
{
DI::profiler()->startRecording('rendering');
$ret = [];
@ -2309,10 +2333,10 @@ class BBCode
/**
* Expand tags to URLs, checks the tag is at the start of a line or preceded by a non-word character
*
* @param string $body
* @param string $body HTML/BBCode
* @return string body with expanded tags
*/
public static function expandTags(string $body)
public static function expandTags(string $body): string
{
return preg_replace_callback("/(?<=\W|^)([!#@])([^\^ \x0D\x0A,;:?'\"]*[^\^ \x0D\x0A,;:?!'\".])/",
function ($match) {
@ -2336,7 +2360,7 @@ class BBCode
/**
* Perform a custom function on a text after having escaped blocks enclosed in the provided tag list.
*
* @param string $text
* @param string $text HTML/BBCode
* @param array $tagList A list of tag names, e.g ['noparse', 'nobb', 'pre']
* @param callable $callback
* @return string
@ -2352,14 +2376,14 @@ class BBCode
/**
* Replaces mentions in the provided message body in BBCode links for the provided user and network if any
*
* @param $body
* @param $profile_uid
* @param $network
* @return string
* @param string $body HTML/BBCode
* @param int $profile_uid Profile user id
* @param string $network Network name
* @return string HTML/BBCode with inserted images
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function setMentions($body, $profile_uid = 0, $network = '')
public static function setMentions(string $body, $profile_uid = 0, $network = '')
{
DI::profiler()->startRecording('rendering');
$body = self::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network) {
@ -2406,7 +2430,7 @@ class BBCode
* @return string
* @TODO Rewrite to handle over whole record array
*/
public static function getShareOpeningTag(string $author, string $profile, string $avatar, string $link, string $posted, string $guid = null)
public static function getShareOpeningTag(string $author, string $profile, string $avatar, string $link, string $posted, string $guid = null): string
{
DI::profiler()->startRecording('rendering');
$header = "[share author='" . str_replace(["'", "[", "]"], ["&#x27;", "&#x5B;", "&#x5D;"], $author) .

View File

@ -73,11 +73,12 @@ class Tag
/**
* Store tag/mention elements
*
* @param integer $uriid
* @param integer $type
* @param string $name
* @param string $url
* @param integer $target
* @param integer $uriid URI id
* @param integer $type Tag type
* @param string $name Tag name
* @param string $url Contact URL (optional)
* @param integer $target Target (default: null)
* @return void
*/
public static function store(int $uriid, int $type, string $name, string $url = '', int $target = null)
{
@ -249,13 +250,14 @@ class Tag
/**
* Store tag/mention elements
*
* @param integer $uriid
* @param string $hash
* @param string $name
* @param string $url
* @param boolean $probing
* @param integer $uriid URI id
* @param string $hash Hash
* @param string $name Name
* @param string $url URL
* @param boolean $probing Whether probing is active
* @return void
*/
public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', $probing = true)
public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', bool $probing = true)
{
$type = self::getTypeForHash($hash);
if ($type == self::UNKNOWN) {
@ -293,8 +295,9 @@ class Tag
* @param string $body Body of the post
* @param string $tags Accepted tags
* @param boolean $probing Perform a probing for contacts, adding them if needed
* @return void
*/
public static function storeFromBody(int $uriid, string $body, string $tags = null, $probing = true)
public static function storeFromBody(int $uriid, string $body, string $tags = null, bool $probing = true)
{
Logger::info('Check for tags', ['uri-id' => $uriid, 'hash' => $tags, 'callstack' => System::callstack()]);
@ -330,6 +333,7 @@ class Tag
*
* @param integer $uriid URI-Id
* @param string $body Body of the post
* @return void
*/
public static function storeRawTagsFromBody(int $uriid, string $body)
{
@ -364,10 +368,11 @@ class Tag
/**
* Remove tag/mention
*
* @param integer $uriid
* @param integer $type
* @param string $name
* @param string $url
* @param integer $uriid URI id
* @param integer $type Type
* @param string $name Name
* @param string $url URL
* @return void
*/
public static function remove(int $uriid, int $type, string $name, string $url = '')
{

View File

@ -43,7 +43,10 @@ require_once 'boot.php';
abstract class BaseAdmin extends BaseModule
{
/**
* Checks admin access and throws exceptions if not logged-in administrator
*
* @param bool $interactive
* @return void
* @throws HTTPException\ForbiddenException
* @throws HTTPException\InternalServerErrorException
*/

View File

@ -34,7 +34,7 @@ abstract class HTTPException extends Exception
protected $httpdesc = '';
protected $explanation = '';
public function __construct($message = '', Exception $previous = null)
public function __construct(string $message = '', Exception $previous = null)
{
parent::__construct($message, $this->code, $previous);
}

File diff suppressed because it is too large Load Diff

View File

@ -47,12 +47,13 @@ class Image
/**
* Constructor
* @param string $data
* @param boolean $type optional, default null
*
* @param string $data Image data
* @param string $type optional, default null
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public function __construct($data, $type = null)
public function __construct(string $data, string $type = null)
{
$this->imagick = class_exists('Imagick');
$this->types = Images::supportedTypes();
@ -62,12 +63,12 @@ class Image
$this->type = $type;
if ($this->isImagick() && $this->loadData($data)) {
return true;
return;
} else {
// Failed to load with Imagick, fallback
$this->imagick = false;
}
return $this->loadData($data);
$this->loadData($data);
}
/**
@ -98,12 +99,14 @@ class Image
}
/**
* @param string $data data
* @return boolean
* Loads image data into handler class
*
* @param string $data Image data
* @return boolean Success
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private function loadData($data)
private function loadData(string $data): bool
{
if ($this->isImagick()) {
$this->image = new Imagick();
@ -132,7 +135,7 @@ class Image
* setup the compression here, so we'll do it only once
*/
switch ($this->getType()) {
case "image/png":
case 'image/png':
$quality = DI::config()->get('system', 'png_quality');
/*
* From http://www.imagemagick.org/script/command-line-options.php#quality:
@ -145,7 +148,9 @@ class Image
$quality = $quality * 10;
$this->image->setCompressionQuality($quality);
break;
case "image/jpeg":
case 'image/jpg':
case 'image/jpeg':
$quality = DI::config()->get('system', 'jpeg_quality');
$this->image->setCompressionQuality($quality);
}
@ -185,7 +190,7 @@ class Image
/**
* @return boolean
*/
public function isValid()
public function isValid(): bool
{
if ($this->isImagick()) {
return ($this->image !== false);
@ -269,10 +274,12 @@ class Image
}
/**
* Scales image down
*
* @param integer $max max dimension
* @return mixed
*/
public function scaleDown($max)
public function scaleDown(int $max)
{
if (!$this->isValid()) {
return false;
@ -327,10 +334,12 @@ class Image
}
/**
* Rotates image
*
* @param integer $degrees degrees to rotate image
* @return mixed
*/
public function rotate($degrees)
public function rotate(int $degrees)
{
if (!$this->isValid()) {
return false;
@ -351,11 +360,13 @@ class Image
}
/**
* Flips image
*
* @param boolean $horiz optional, default true
* @param boolean $vert optional, default false
* @return mixed
*/
public function flip($horiz = true, $vert = false)
public function flip(bool $horiz = true, bool $vert = false)
{
if (!$this->isValid()) {
return false;
@ -391,10 +402,12 @@ class Image
}
/**
* @param string $filename filename
* Fixes orientation and maybe returns EXIF data (?)
*
* @param string $filename Filename
* @return mixed
*/
public function orient($filename)
public function orient(string $filename)
{
if ($this->isImagick()) {
// based off comment on http://php.net/manual/en/imagick.getimageorientation.php
@ -470,10 +483,12 @@ class Image
}
/**
* @param integer $min minimum dimension
* Rescales image to minimum size
*
* @param integer $min Minimum dimension
* @return mixed
*/
public function scaleUp($min)
public function scaleUp(int $min)
{
if (!$this->isValid()) {
return false;
@ -513,10 +528,12 @@ class Image
}
/**
* @param integer $dim dimension
* Scales image to square
*
* @param integer $dim Dimension
* @return mixed
*/
public function scaleToSquare($dim)
public function scaleToSquare(int $dim)
{
if (!$this->isValid()) {
return false;
@ -528,11 +545,11 @@ class Image
/**
* Scale image to target dimensions
*
* @param int $dest_width
* @param int $dest_height
* @return boolean
* @param int $dest_width Destination width
* @param int $dest_height Destination height
* @return boolean Success
*/
private function scale($dest_width, $dest_height)
private function scale(int $dest_width, int $dest_height): bool
{
if (!$this->isValid()) {
return false;
@ -584,6 +601,8 @@ class Image
/**
* Convert a GIF to a PNG to make it static
*
* @return void
*/
public function toStatic()
{
@ -598,6 +617,8 @@ class Image
}
/**
* Crops image
*
* @param integer $max maximum
* @param integer $x x coordinate
* @param integer $y y coordinate
@ -605,7 +626,7 @@ class Image
* @param integer $h height
* @return mixed
*/
public function crop($max, $x, $y, $w, $h)
public function crop(int $max, int $x, int $y, int $w, int $h)
{
if (!$this->isValid()) {
return false;
@ -638,6 +659,9 @@ class Image
$this->image = $dest;
$this->width = imagesx($this->image);
$this->height = imagesy($this->image);
// All successful
return true;
}
/**
@ -650,11 +674,14 @@ class Image
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public function __toString() {
return $this->asString();
public function __toString(): string
{
return (string) $this->asString();
}
/**
* Returns image as string or false on failure
*
* @return mixed
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
@ -681,13 +708,16 @@ class Image
imageinterlace($this->image, true);
switch ($this->getType()) {
case "image/png":
case 'image/png':
$quality = DI::config()->get('system', 'png_quality');
imagepng($this->image, null, $quality);
break;
case "image/jpeg":
case 'image/jpeg':
case 'image/jpg':
$quality = DI::config()->get('system', 'jpeg_quality');
imagejpeg($this->image, null, $quality);
break;
}
$string = ob_get_contents();
ob_end_clean();

File diff suppressed because it is too large Load Diff

View File

@ -38,10 +38,10 @@ class Email
* @param string $mailbox The mailbox name
* @param string $username The username
* @param string $password The password
* @return Connection|resource
* @return Connection|resource|bool
* @throws \Exception
*/
public static function connect($mailbox, $username, $password)
public static function connect(string $mailbox, string $username, string $password)
{
if (!function_exists('imap_open')) {
return false;
@ -68,7 +68,7 @@ class Email
* @return array
* @throws \Exception
*/
public static function poll($mbox, $email_addr): array
public static function poll($mbox, string $email_addr): array
{
if (!$mbox || !$email_addr) {
return [];
@ -101,10 +101,12 @@ class Email
}
/**
* Returns mailbox name
*
* @param array $mailacct mail account
* @return string
*/
public static function constructMailboxName($mailacct)
public static function constructMailboxName(array $mailacct): string
{
$ret = '{' . $mailacct['server'] . ((intval($mailacct['port'])) ? ':' . $mailacct['port'] : '');
$ret .= (($mailacct['ssltype']) ? '/' . $mailacct['ssltype'] . '/novalidate-cert' : '');
@ -117,7 +119,7 @@ class Email
* @param integer $uid user id
* @return mixed
*/
public static function messageMeta($mbox, $uid)
public static function messageMeta($mbox, int $uid)
{
$ret = (($mbox && $uid) ? @imap_fetch_overview($mbox, $uid, FT_UID) : [[]]); // POSSIBLE CLEANUP --> array(array()) is probably redundant now
return (count($ret)) ? $ret : [];
@ -127,10 +129,11 @@ class Email
* @param Connection|resource $mbox mailbox
* @param integer $uid user id
* @param string $reply reply
* @param array $item Item
* @return array
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getMessage($mbox, $uid, $reply, $item): array
public static function getMessage($mbox, int $uid, string $reply, array $item): array
{
$ret = $item;
@ -218,7 +221,7 @@ class Email
* @param string $subtype sub type
* @return string
*/
private static function messageGetPart($mbox, $uid, $p, $partno, $subtype)
private static function messageGetPart($mbox, int $uid, $p, in $partno, string $subtype): string
{
// $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
global $htmlmsg,$plainmsg,$charset,$attachments;
@ -296,11 +299,13 @@ class Email
}
/**
* Returns encoded header
*
* @param string $in_str in string
* @param string $charset character set
* @return string
*/
public static function encodeHeader($in_str, $charset)
public static function encodeHeader(string $in_str, string $charset): string
{
$out_str = $in_str;
$need_to_convert = false;
@ -360,21 +365,20 @@ class Email
* @param string $subject subject
* @param string $headers headers
* @param array $item item
*
* @return void
* @return bool Status from mail()
*
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
* @todo This could be changed to use the Emailer class
*/
public static function send($addr, $subject, $headers, $item)
public static function send(string $addr, string $subject, string $headers, array$item)
{
//$headers .= 'MIME-Version: 1.0' . "\n";
//$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
//$headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
//$headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
$part = uniqid("", true);
$part = uniqid('', true);
$html = Item::prepareBody($item);
@ -398,52 +402,70 @@ class Email
//$message = '<html><body>' . $html . '</body></html>';
//$message = html2plain($html);
Logger::notice('notifier: email delivery to ' . $addr);
mail($addr, $subject, $body, $headers);
return mail($addr, $subject, $body, $headers);
}
/**
* @param string $iri string
* @return string
* Convert item URI to message id
*
* @param string $itemUri Item URI
* @return string Message id
*/
public static function iri2msgid($iri)
public static function iri2msgid(string $itemUri): string
{
if (!strpos($iri, "@")) {
$msgid = preg_replace("/urn:(\S+):(\S+)\.(\S+):(\d+):(\S+)/i", "urn!$1!$4!$5@$2.$3", $iri);
} else {
$msgid = $iri;
$msgid = $itemUri;
if (!strpos($itemUri, '@')) {
$msgid = preg_replace("/urn:(\S+):(\S+)\.(\S+):(\d+):(\S+)/i", "urn!$1!$4!$5@$2.$3", $itemUri);
}
return $msgid;
}
/**
* @param string $msgid msgid
* @return string
* Converts message id to item URI
*
* @param string $msgid Message id
* @return string Item URI
*/
public static function msgid2iri($msgid)
public static function msgid2iri(string $msgid): string
{
if (strpos($msgid, "@")) {
$iri = preg_replace("/urn!(\S+)!(\d+)!(\S+)@(\S+)\.(\S+)/i", "urn:$1:$4.$5:$2:$3", $msgid);
} else {
$iri = $msgid;
$itemUri = $msgid;
if (strpos($msgid, '@')) {
$itemUri = preg_replace("/urn!(\S+)!(\d+)!(\S+)@(\S+)\.(\S+)/i", "urn:$1:$4.$5:$2:$3", $msgid);
}
return $iri;
return $itemUri;
}
private static function saveReplace($pattern, $replace, $text)
/**
* Invokes preg_replace() but does return full text from parameter if it
* returned an empty message.
*
* @param string $pattern Pattern to match
* @param string $replace String to replace with
* @param string $text String to check
* @return string Replaced string
*/
private static function saveReplace(string $pattern, string $replace, string $text): string
{
$save = $text;
$return = preg_replace($pattern, $replace, $text);
$text = preg_replace($pattern, $replace, $text);
if ($text == '') {
$text = $save;
if ($return == '') {
$return = $text;
}
return $text;
return $return;
}
private static function unifyAttributionLine($message)
/**
* Unifies attribution line(s)
*
* @param string $message Unfiltered message
* @return string Message with unified attribution line(s)
*/
private static function unifyAttributionLine(string $message): string
{
$quotestr = ['quote', 'spoiler'];
foreach ($quotestr as $quote) {
@ -520,7 +542,13 @@ class Email
return $message;
}
private static function removeGPG($message)
/**
* Removes GPG part from message
*
* @param string $message Unfiltered message
* @return string Message with GPG part
*/
private static function removeGPG(string $message): string
{
$pattern = '/(.*)\s*-----BEGIN PGP SIGNED MESSAGE-----\s*[\r\n].*Hash:.*?[\r\n](.*)'.
'[\r\n]\s*-----BEGIN PGP SIGNATURE-----\s*[\r\n].*'.
@ -537,7 +565,13 @@ class Email
return $cleaned;
}
private static function removeSig($message)
/**
* Removes signature from message
*
* @param string $message Unfiltered message
* @return string Message with no signature
*/
private static function removeSig(string $message): string
{
$sigpos = strrpos($message, "\n-- \n");
$quotepos = strrpos($message, "[/quote]");
@ -569,7 +603,13 @@ class Email
return ['body' => $cleaned, 'sig' => $sig];
}
private static function removeLinebreak($message)
/**
* Removes lines breaks from message
*
* @param string $message Unfiltered message
* @return string Message with no line breaks
*/
private static function removeLinebreak(string $message): string
{
$arrbody = explode("\n", trim($message));
@ -622,7 +662,7 @@ class Email
return implode("\n", $lines);
}
private static function convertQuote($body, $reply)
private static function convertQuote(strng $body, string $reply): string
{
// Convert Quotes
$arrbody = explode("\n", trim($body));
@ -682,14 +722,14 @@ class Email
return $body;
}
private static function removeToFu($message)
private static function removeToFu(string $message): string
{
$message = trim($message);
do {
$oldmessage = $message;
$message = preg_replace('=\[/quote\][\s](.*?)\[quote\]=i', '$1', $message);
$message = str_replace("[/quote][quote]", "", $message);
$message = str_replace('[/quote][quote]', '', $message);
} while ($message != $oldmessage);
$quotes = [];
@ -724,8 +764,9 @@ class Email
$start = $pos + 7;
}
if (strtolower(substr($message, -8)) != '[/quote]')
if (strtolower(substr($message, -8)) != '[/quote]') {
return($message);
}
krsort($quotes);
@ -739,7 +780,7 @@ class Email
}
if ($quotestart != 0) {
$message = trim(substr($message, 0, $quotestart))."\n[spoiler]".substr($message, $quotestart+7, -8).'[/spoiler]';
$message = trim(substr($message, 0, $quotestart))."\n[spoiler]".substr($message, $quotestart+7, -8) . '[/spoiler]';
}
return $message;

View File

@ -22,6 +22,7 @@
namespace Friendica\Protocol;
use DOMDocument;
use DOMElement;
use DOMXPath;
use Friendica\Content\PageInfo;
use Friendica\Content\Text\BBCode;
@ -66,7 +67,7 @@ class Feed
if ($dryRun) {
Logger::info("Test Atom/RSS feed");
} else {
Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
Logger::info('Import Atom/RSS feed "' . $contact['name'] . '" (Contact ' . $contact['id'] . ') for user ' . $importer['uid']);
}
$xml = trim($xml);
@ -378,7 +379,7 @@ class Feed
if (DBA::isResult($previous)) {
// Use the creation date when the post had been stored. It can happen this date changes in the feed.
$creation_dates[] = $previous['created'];
Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
Logger::info('Item with URI ' . $item['uri'] . ' for user ' . $importer['uid'] . ' already existed under id ' . $previous['id']);
continue;
}
$creation_dates[] = DateTimeFormat::utc($item['created']);
@ -683,7 +684,7 @@ class Feed
/**
* Automatically adjust the poll frequency according to the post frequency
*
* @param array $contact
* @param array $contact Contact array
* @param array $creation_dates
* @return void
*/
@ -803,7 +804,7 @@ class Feed
* @param array $contact
* @return int Poll interval in minutes
*/
public static function getPollInterval(array $contact)
public static function getPollInterval(array $contact): int
{
if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
$ratings = [0, 3, 7, 8, 9, 10];
@ -852,39 +853,39 @@ class Feed
* @param array $tags
* @return string tag string
*/
private static function tagToString(array $tags)
private static function tagToString(array $tags): string
{
$tagstr = '';
foreach ($tags as $tag) {
if ($tagstr != "") {
$tagstr .= ", ";
if ($tagstr != '') {
$tagstr .= ', ';
}
$tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
$tagstr .= '#[url=' . DI::baseUrl() . '/search?tag=' . urlencode($tag) . ']' . $tag . '[/url]';
}
return $tagstr;
}
private static function titleIsBody($title, $body)
private static function titleIsBody(string $title, string $body): bool
{
$title = strip_tags($title);
$title = trim($title);
$title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
$title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
$title = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $title);
$body = strip_tags($body);
$body = trim($body);
$body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
$body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
$body = str_replace(["\n", "\r", "\t", " "], ['', '', '', ''], $body);
if (strlen($title) < strlen($body)) {
$body = substr($body, 0, strlen($title));
}
if (($title != $body) && (substr($title, -3) == "...")) {
$pos = strrpos($title, "...");
if (($title != $body) && (substr($title, -3) == '...')) {
$pos = strrpos($title, '...');
if ($pos > 0) {
$title = substr($title, 0, $pos);
$body = substr($body, 0, $pos);
@ -914,7 +915,7 @@ class Feed
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
public static function atom(string $owner_nick, string $last_update, int $max_items = 300, string $filter = 'activity', bool $nocache = false)
{
$stamp = microtime(true);
@ -923,7 +924,7 @@ class Feed
return;
}
$cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
$cachekey = 'feed:feed:' . $owner_nick . ':' . $filter . ':' . $last_update;
// Display events in the users's timezone
if (strlen($owner['timezone'])) {
@ -942,11 +943,11 @@ class Feed
}
$check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
$authorid = Contact::getIdForURL($owner["url"]);
$authorid = Contact::getIdForURL($owner['url']);
$condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
$owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
$owner['uid'], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
Item::PRIVATE, Protocol::ACTIVITYPUB,
Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
@ -957,7 +958,7 @@ class Feed
if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
$condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
$condition[] = $owner["id"];
$condition[] = $owner['id'];
$condition[] = $authorid;
}
@ -1002,16 +1003,16 @@ class Feed
* @param array $owner Contact data of the poster
* @param string $filter The related feed filter (activity, posts or comments)
*
* @return object header root element
* @return DOMElement Header root element
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function addHeader(DOMDocument $doc, array $owner, $filter)
private static function addHeader(DOMDocument $doc, array $owner, string $filter): DOMElement
{
$root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
$doc->appendChild($root);
$title = '';
$selfUri = '/feed/' . $owner["nick"] . '/';
$selfUri = '/feed/' . $owner['nick'] . '/';
switch ($filter) {
case 'activity':
$title = DI::l10n()->t('%s\'s timeline', $owner['name']);
@ -1026,24 +1027,24 @@ class Feed
break;
}
$attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
XML::addElement($doc, $root, "title", $title);
XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
XML::addElement($doc, $root, "logo", User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
$attributes = ['uri' => 'https://friendi.ca', 'version' => FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION];
XML::addElement($doc, $root, 'generator', FRIENDICA_PLATFORM, $attributes);
XML::addElement($doc, $root, 'id', DI::baseUrl() . '/profile/' . $owner['nick']);
XML::addElement($doc, $root, 'title', $title);
XML::addElement($doc, $root, 'subtitle', sprintf("Updates from %s on %s", $owner['name'], DI::config()->get('config', 'sitename')));
XML::addElement($doc, $root, 'logo', User::getAvatarUrl($owner, Proxy::SIZE_SMALL));
XML::addElement($doc, $root, 'updated', DateTimeFormat::utcNow(DateTimeFormat::ATOM));
$author = self::addAuthor($doc, $owner);
$root->appendChild($author);
$attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
XML::addElement($doc, $root, "link", "", $attributes);
$attributes = ['href' => $owner['url'], 'rel' => 'alternate', 'type' => 'text/html'];
XML::addElement($doc, $root, 'link', '', $attributes);
OStatus::hublinks($doc, $root, $owner["nick"]);
OStatus::addHubLink($doc, $root, $owner['nick']);
$attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
XML::addElement($doc, $root, "link", "", $attributes);
$attributes = ['href' => DI::baseUrl() . $selfUri, 'rel' => 'self', 'type' => 'application/atom+xml'];
XML::addElement($doc, $root, 'link', '', $attributes);
return $root;
}
@ -1053,16 +1054,15 @@ class Feed
*
* @param DOMDocument $doc XML document
* @param array $owner Contact data of the poster
*
* @return \DOMElement author element
* @return DOMElement author element
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function addAuthor(DOMDocument $doc, array $owner)
private static function addAuthor(DOMDocument $doc, array $owner): DOMElement
{
$author = $doc->createElement("author");
XML::addElement($doc, $author, "uri", $owner["url"]);
XML::addElement($doc, $author, "name", $owner["nick"]);
XML::addElement($doc, $author, "email", $owner["addr"]);
$author = $doc->createElement('author');
XML::addElement($doc, $author, 'uri', $owner['url']);
XML::addElement($doc, $author, 'name', $owner['nick']);
XML::addElement($doc, $author, 'email', $owner['addr']);
return $author;
}
@ -1074,15 +1074,14 @@ class Feed
* @param array $item Data of the item that is to be posted
* @param array $owner Contact data of the poster
* @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
*
* @return \DOMElement Entry element
* @return DOMElement Entry element
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function noteEntry(DOMDocument $doc, array $item, array $owner)
private static function noteEntry(DOMDocument $doc, array $item, array $owner): DOMElement
{
if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item['author-link']) != Strings::normaliseLink($owner['url']))) {
Logger::info('Feed entry author does not match feed owner', ['owner' => $owner['url'], 'author' => $item['author-link']]);
}
$entry = OStatus::entryHeader($doc, $owner, $item, false);
@ -1104,31 +1103,30 @@ class Feed
* @param string $title Title for the post
* @param string $verb The activity verb
* @param bool $complete Add the "status_net" element?
* @param bool $feed_mode Behave like a regular feed for users if true
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
private static function entryContent(DOMDocument $doc, DOMElement $entry, array $item, $title, string $verb = '', bool $complete = true)
{
if ($verb == "") {
if ($verb == '') {
$verb = OStatus::constructVerb($item);
}
XML::addElement($doc, $entry, "id", $item["uri"]);
XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
XML::addElement($doc, $entry, 'id', $item['uri']);
XML::addElement($doc, $entry, 'title', html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
$body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
$body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
XML::addElement($doc, $entry, 'content', $body, ['type' => 'html']);
XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
"href" => DI::baseUrl()."/display/".$item["guid"]]
XML::addElement($doc, $entry, 'link', '', ['rel' => 'alternate', 'type' => 'text/html',
'href' => DI::baseUrl() . '/display/' . $item['guid']]
);
XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
}
/**
@ -1197,28 +1195,28 @@ class Feed
* @param array $item
* @return string title
*/
private static function getTitle(array $item)
private static function getTitle(array $item): string
{
if ($item['title'] != '') {
return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
}
// Fetch information about the post
$siteinfo = BBCode::getAttachedData($item["body"]);
if (isset($siteinfo["title"])) {
return $siteinfo["title"];
$siteinfo = BBCode::getAttachedData($item['body']);
if (isset($siteinfo['title'])) {
return $siteinfo['title'];
}
// If no bookmark is found then take the first line
// Remove the share element before fetching the first line
$title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
$title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism", "\n$1\n", $item['body']));
$title = BBCode::toPlaintext($title)."\n";
$pos = strpos($title, "\n");
$trailer = "";
$trailer = '';
if (($pos == 0) || ($pos > 100)) {
$pos = 100;
$trailer = "...";
$trailer = '...';
}
return substr($title, 0, $pos) . $trailer;

File diff suppressed because it is too large Load Diff

View File

@ -55,7 +55,7 @@ class Relay
* @param string $url
* @return boolean "true" is the post is wanted by the system
*/
public static function isSolicitedPost(array $tags, string $body, int $authorid, string $url, string $network = '')
public static function isSolicitedPost(array $tags, string $body, int $authorid, string $url, string $network = ''): bool
{
$config = DI::config();
@ -139,6 +139,7 @@ class Relay
*
* @param array $gserver Global server record
* @param array $fields Optional network specific fields
* @return void
* @throws \Exception
*/
public static function updateContact(array $gserver, array $fields = [])
@ -198,6 +199,7 @@ class Relay
* The relay contact is a technical contact entry that exists once per server.
*
* @param array $contact of the relay contact
* @return void
*/
public static function markForArchival(array $contact)
{
@ -229,15 +231,14 @@ class Relay
* @param integer $item_id id of the item that is sent
* @param array $contacts Previously fetched contacts
* @param array $networks Networks of the relay servers
*
* @return array of relay servers
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getDirectRelayList(int $item_id)
public static function getDirectRelayList(int $item_id): array
{
$serverlist = [];
if (!DI::config()->get("system", "relay_directly", false)) {
if (!DI::config()->get('system', 'relay_directly', false)) {
return [];
}
@ -302,10 +303,10 @@ class Relay
* Return a list of relay servers
*
* @param array $fields Field list
* @return array
* @return array List of relay servers
* @throws Exception
*/
public static function getList($fields = []):array
public static function getList(array $fields = []): array
{
return DBA::selectToArray('apcontact', $fields,
["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)", 'Application', 0, Contact::FRIEND]);
@ -316,7 +317,7 @@ class Relay
*
* @param array $gserver Global server record
* @param array $fields Fieldlist
* @return array with the contact
* @return array|bool Array with the contact or false on error
* @throws \Exception
*/
private static function getContact(array $gserver, array $fields = ['batch', 'id', 'url', 'name', 'network', 'protocol', 'archive', 'blocked'])
@ -344,6 +345,8 @@ class Relay
/**
* Resubscribe to all relay servers
*
* @return void
*/
public static function reSubscribe()
{

View File

@ -40,10 +40,10 @@ class Salmon
/**
* @param string $uri Uniform Resource Identifier
* @param string $keyhash encoded key
* @return mixed
* @return string Key or empty string on any errors
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getKey(string $uri, string $keyhash)
public static function getKey(string $uri, string $keyhash): string
{
$ret = [];
@ -83,13 +83,13 @@ class Salmon
Logger::notice('Key located', ['ret' => $ret]);
if (count($ret) == 1) {
// We only found one one key so we don't care if the hash matches.
// If it's the wrong key we'll find out soon enough because
// message verification will fail. This also covers some older
// software which don't supply a keyhash. As long as they only
// have one key we'll be right.
return $ret[0];
/* We only found one one key so we don't care if the hash matches.
* If it's the wrong key we'll find out soon enough because
* message verification will fail. This also covers some older
* software which don't supply a keyhash. As long as they only
* have one key we'll be right.
*/
return (string) $ret[0];
} else {
foreach ($ret as $a) {
$hash = Strings::base64UrlEncode(hash('sha256', $a));

View File

@ -34,23 +34,23 @@ class Images
/**
* Maps Mime types to Imagick formats
*
* @return array
* @return array Format map
*/
public static function getFormatsMap()
{
$m = [
return [
'image/jpeg' => 'JPG',
'image/jpg' => 'JPG',
'image/png' => 'PNG',
'image/gif' => 'GIF'
'image/gif' => 'GIF',
];
return $m;
}
/**
* Return file extension for mime type
* @param string $mimetype
* @return string
* Return file extension for MIME type
*
* @param string $mimetype MIME type
* @return string File extension for MIME type
*/
public static function getExtensionByMimeType(string $mimetype): string
{
@ -63,9 +63,14 @@ class Images
$imagetype = IMAGETYPE_GIF;
break;
default:
case 'image/jpeg':
case 'image/jpg':
$imagetype = IMAGETYPE_JPEG;
break;
default: // Unknown type must be a blob then
return 'blob';
break;
}
return image_type_to_extension($imagetype);
@ -76,11 +81,13 @@ class Images
*
* @return array
*/
public static function supportedTypes()
public static function supportedTypes(): array
{
$types = [
'image/jpeg' => 'jpg'
'image/jpeg' => 'jpg',
'image/jpg' => 'jpg',
];
if (class_exists('Imagick')) {
// Imagick::queryFormats won't help us a lot there...
// At least, not yet, other parts of friendica uses this array
@ -102,21 +109,20 @@ class Images
*
* @param string $image_data Image data
* @param string $filename File name (for guessing the type via the extension)
* @param string $mime default mime type
*
* @return string
* @param string $default Default MIME type
* @return string MIME type
* @throws \Exception
*/
public static function getMimeTypeByData(string $image_data, string $filename = '', string $mime = '')
public static function getMimeTypeByData(string $image_data, string $filename = '', string $default = ''): string
{
if (substr($mime, 0, 6) == 'image/') {
Logger::info('Using default mime type', ['filename' => $filename, 'mime' => $mime]);
return $mime;
if (substr($default, 0, 6) == 'image/') {
Logger::info('Using default mime type', ['filename' => $filename, 'mime' => $default]);
return $default;
}
$image = @getimagesizefromstring($image_data);
if (!empty($image['mime'])) {
Logger::info('Mime type detected via data', ['filename' => $filename, 'default' => $mime, 'mime' => $image['mime']]);
Logger::info('Mime type detected via data', ['filename' => $filename, 'default' => $default, 'mime' => $image['mime']]);
return $image['mime'];
}
@ -128,21 +134,20 @@ class Images
*
* @param string $sourcefile Source file of the image
* @param string $filename File name (for guessing the type via the extension)
* @param string $mime default mime type
*
* @return string
* @param string $default default MIME type
* @return string MIME type
* @throws \Exception
*/
public static function getMimeTypeBySource(string $sourcefile, string $filename = '', string $mime = '')
public static function getMimeTypeBySource(string $sourcefile, string $filename = '', string $default = ''): string
{
if (substr($mime, 0, 6) == 'image/') {
Logger::info('Using default mime type', ['filename' => $filename, 'mime' => $mime]);
return $mime;
if (substr($default, 0, 6) == 'image/') {
Logger::info('Using default mime type', ['filename' => $filename, 'mime' => $default]);
return $default;
}
$image = @getimagesize($sourcefile);
if (!empty($image['mime'])) {
Logger::info('Mime type detected via file', ['filename' => $filename, 'default' => $mime, 'image' => $image]);
Logger::info('Mime type detected via file', ['filename' => $filename, 'default' => $default, 'image' => $image]);
return $image['mime'];
}
@ -150,14 +155,13 @@ class Images
}
/**
* Guess image mimetype from the filename
* Guess image MIME type from the filename's extension
*
* @param string $filename Image filename
*
* @return string
* @param string $filename Image filename
* @return string Guessed MIME type by extension
* @throws \Exception
*/
public static function guessTypeByExtension(string $filename)
public static function guessTypeByExtension(string $filename): string
{
$ext = pathinfo(parse_url($filename, PHP_URL_PATH), PATHINFO_EXTENSION);
$types = self::supportedTypes();
@ -173,11 +177,13 @@ class Images
}
/**
* @param string $url
* @return array
* Gets info array from given URL, cached data has priority
*
* @param string $url URL
* @return array Info
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getInfoFromURLCached($url)
public static function getInfoFromURLCached(string $url): array
{
$data = [];
@ -195,15 +201,17 @@ class Images
DI::cache()->set($cacheKey, $data);
}
return $data;
return $data ?? [];
}
/**
* @param string $url
* @return array
* Gets info from URL uncached
*
* @param string $url URL
* @return array Info array
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getInfoFromURL($url)
public static function getInfoFromURL(string $url): array
{
$data = [];
@ -239,16 +247,18 @@ class Images
$data['size'] = $filesize;
}
return $data;
return $data ?? [];
}
/**
* @param integer $width
* @param integer $height
* @param integer $max
* @return array
* Returns scaling information
*
* @param integer $width Width
* @param integer $height Height
* @param integer $max Max width/height
* @return array Scaling dimensions
*/
public static function getScalingDimensions($width, $height, $max)
public static function getScalingDimensions(int $width, int $height, int $max): array
{
if ((!$width) || (!$height)) {
return ['width' => 0, 'height' => 0];

View File

@ -168,7 +168,7 @@ class XML
foreach ($attributes as $key => $value) {
$attribute = $doc->createAttribute($key);
$attribute->value = self::escape($value);
$attribute->value = self::escape($value ?? '');
$element->appendChild($attribute);
}
return $element;
@ -177,7 +177,7 @@ class XML
/**
* Create an XML and append it to the parent object
*
* @param DOMDocument $doc XML root
* @param DOMDocument $doc XML root
* @param object $parent parent object
* @param string $element XML element name
* @param string $value XML value

View File

@ -475,12 +475,13 @@ class Delivery
* @param array $owner Owner record of the sender
* @param array $target_item Item record of the content
* @param array $thr_parent Item record of the direct parent in the thread
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
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;
}
@ -570,10 +571,16 @@ class Delivery
}
}
Email::send($addr, $subject, $headers, $target_item);
// Try to send email
$success = Email::send($addr, $subject, $headers, $target_item);
Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);
if ($success) {
// Success
Model\Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Model\Post\DeliveryData::MAIL);
Logger::info('Delivered via mail', ['guid' => $target_item['guid'], 'to' => $addr, 'subject' => $subject]);
} else {
// Failed
Logger::warning('Delivery of mail has FAILED', ['to' => $addr, 'subject' => $subject, 'guid' => $target_item['guid']]);
}
}
}

View File

@ -31,10 +31,9 @@ class Image
* Give all available options for the background image
*
* @param array $arr Array with the present user settings
*
* @return array Array with the immage options
*/
public static function get_options($arr)
public static function get_options(array $arr): array
{
$bg_image_options = [
'stretch' => ['frio_bg_image_option', DI::l10n()->t('Top Banner'), 'stretch', DI::l10n()->t('Resize image to the width of the screen and show background color below on long pages.'), ($arr['bg_image_option'] == 'stretch')],