Merge pull request #11677 from Quix0r/rewrites/type-hints-doc-001

Rewrites/type hints doc 001
This commit is contained in:
Hypolite Petovan 2022-06-23 11:34:52 -04:00 committed by GitHub
commit d322e9288b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 583 additions and 476 deletions

View File

@ -87,8 +87,8 @@ define('PRIORITIES', [PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORIT
/* @}*/ /* @}*/
// Normally this constant is defined - but not if "pcntl" isn't installed // Normally this constant is defined - but not if "pcntl" isn't installed
if (!defined("SIGTERM")) { if (!defined('SIGTERM')) {
define("SIGTERM", 15); define('SIGTERM', 15);
} }
/** /**
@ -117,6 +117,7 @@ function local_user()
if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) { if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
return intval($_SESSION['uid']); return intval($_SESSION['uid']);
} }
return false; return false;
} }
@ -169,7 +170,7 @@ function remote_user()
* *
* @param string $s - Text of notice * @param string $s - Text of notice
*/ */
function notice($s) function notice(string $s)
{ {
if (empty($_SESSION)) { if (empty($_SESSION)) {
return; return;
@ -189,7 +190,7 @@ function notice($s)
* *
* @param string $s - Text of notice * @param string $s - Text of notice
*/ */
function info($s) function info(string $s)
{ {
if (empty($_SESSION)) { if (empty($_SESSION)) {
return; return;

View File

@ -1761,7 +1761,6 @@ class Database
* Checks if $array is a filled array with at least one entry. * Checks if $array is a filled array with at least one entry.
* *
* @param mixed $array A filled array with at least one entry * @param mixed $array A filled array with at least one entry
*
* @return boolean Whether $array is a filled array or an object with rows * @return boolean Whether $array is a filled array or an object with rows
*/ */
public function isResult($array): bool public function isResult($array): bool
@ -1842,6 +1841,7 @@ class Database
$upds = implode(', ', $upd); $upds = implode(', ', $upd);
$r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds)); $r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
if (!$this->isResult($r)) { if (!$this->isResult($r)) {
throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage()); throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());
} }

View File

@ -36,7 +36,7 @@ class Group
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function getById(int $gid) public static function getById(int $gid): array
{ {
$return = []; $return = [];

View File

@ -174,7 +174,7 @@ class Relation
* @param array $rel * @param array $rel
* @return array contact list * @return array contact list
*/ */
private static function getContacts(int $uid, array $rel) private static function getContacts(int $uid, array $rel): array
{ {
$list = []; $list = [];
$profile = Profile::getByUID($uid); $profile = Profile::getByUID($uid);
@ -182,8 +182,15 @@ class Relation
return $list; return $list;
} }
$condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false, $condition = [
'hidden' => false, 'archive' => false, 'pending' => false]; 'rel' => $rel,
'uid' => $uid,
'self' => false,
'deleted' => false,
'hidden' => false,
'archive' => false,
'pending' => false,
];
$condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]); $condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
$contacts = DBA::select('contact', ['url'], $condition); $contacts = DBA::select('contact', ['url'], $condition);
while ($contact = DBA::fetch($contacts)) { while ($contact = DBA::fetch($contacts)) {
@ -201,7 +208,7 @@ class Relation
* @param array $contact Contact array * @param array $contact Contact array
* @return boolean True if contact is discoverable * @return boolean True if contact is discoverable
*/ */
public static function isDiscoverable(string $url, array $contact = []) public static function isDiscoverable(string $url, array $contact = []): bool
{ {
$contact_discovery = DI::config()->get('system', 'contact_discovery'); $contact_discovery = DI::config()->get('system', 'contact_discovery');
@ -254,12 +261,14 @@ class Relation
} }
/** /**
* @param int $uid user * Returns an array of suggested contacts for given user id
*
* @param int $uid User id
* @param int $start optional, default 0 * @param int $start optional, default 0
* @param int $limit optional, default 80 * @param int $limit optional, default 80
* @return array * @return array
*/ */
static public function getSuggestions(int $uid, int $start = 0, int $limit = 80) static public function getSuggestions(int $uid, int $start = 0, int $limit = 80): array
{ {
$cid = Contact::getPublicIdByUserId($uid); $cid = Contact::getPublicIdByUserId($uid);
$totallimit = $start + $limit; $totallimit = $start + $limit;
@ -272,20 +281,25 @@ class Relation
// The query returns contacts where contacts interacted with whom the given user follows. // The query returns contacts where contacts interacted with whom the given user follows.
// Contacts who already are in the user's contact table are ignored. // Contacts who already are in the user's contact table are ignored.
$results = DBA::select('contact', [], $results = DBA::select('contact', [], ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
(SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?) (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
(SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?)))) (SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
AND NOT `hidden` AND `network` IN (?, ?, ?, ?)", AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
$cid, 0, $uid, Contact::FRIEND, Contact::SHARING, $cid,
Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus], 0,
['order' => ['last-item' => true], 'limit' => $totallimit] $uid, Contact::FRIEND, Contact::SHARING,
Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus,
], [
'order' => ['last-item' => true],
'limit' => $totallimit,
]
); );
while ($contact = DBA::fetch($results)) { while ($contact = DBA::fetch($results)) {
$contacts[$contact['id']] = $contact; $contacts[$contact['id']] = $contact;
} }
DBA::close($results); DBA::close($results);
Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]); Logger::info('Contacts of contacts who are followed by the given user', ['uid' => $uid, 'cid' => $cid, 'count' => count($contacts)]);
@ -365,12 +379,12 @@ class Relation
* @return int * @return int
* @throws Exception * @throws Exception
*/ */
public static function countFollows(int $cid, array $condition = []) public static function countFollows(int $cid, array $condition = []): int
{ {
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions($condition, [
['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)', '`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
$cid] $cid,
); ]);
return DI::dba()->count('contact', $condition); return DI::dba()->count('contact', $condition);
} }
@ -556,7 +570,7 @@ class Relation
* @param int $count * @param int $count
* @param int $offset * @param int $offset
* @param bool $shuffle * @param bool $shuffle
* @return array * @return array|bool Array on success, false on failure
* @throws Exception * @throws Exception
*/ */
public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false) public static function listCommon(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
@ -581,7 +595,7 @@ class Relation
* @return int * @return int
* @throws Exception * @throws Exception
*/ */
public static function countCommonFollows(int $sourceId, int $targetId, array $condition = []) public static function countCommonFollows(int $sourceId, int $targetId, array $condition = []): int
{ {
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions($condition,
['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`) ['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
@ -601,7 +615,7 @@ class Relation
* @param int $count * @param int $count
* @param int $offset * @param int $offset
* @param bool $shuffle * @param bool $shuffle
* @return array * @return array|bool Array on success, false on failure
* @throws Exception * @throws Exception
*/ */
public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false) public static function listCommonFollows(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)
@ -626,7 +640,7 @@ class Relation
* @return int * @return int
* @throws Exception * @throws Exception
*/ */
public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = []) public static function countCommonFollowers(int $sourceId, int $targetId, array $condition = []): int
{ {
$condition = DBA::mergeConditions($condition, $condition = DBA::mergeConditions($condition,
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`) ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
@ -646,7 +660,7 @@ class Relation
* @param int $count * @param int $count
* @param int $offset * @param int $offset
* @param bool $shuffle * @param bool $shuffle
* @return array * @return array|bool Array on success, false on failure
* @throws Exception * @throws Exception
*/ */
public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false) public static function listCommonFollowers(int $sourceId, int $targetId, array $condition = [], int $count = 30, int $offset = 0, bool $shuffle = false)

View File

@ -82,11 +82,11 @@ class User
/** /**
* Apply changes from contact update data to user-contact table * Apply changes from contact update data to user-contact table
* *
* @param array $fields * @param array $fields
* @param array $condition * @param array $condition
* @return void * @return void
* @throws PDOException * @throws PDOException
* @throws Exception * @throws Exception
*/ */
public static function updateByContactUpdate(array $fields, array $condition) public static function updateByContactUpdate(array $fields, array $condition)
{ {
@ -106,7 +106,7 @@ class User
DBA::close($contacts); DBA::close($contacts);
} }
DBA::commit(); DBA::commit();
} }
/** /**
@ -138,9 +138,10 @@ class User
* @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
* @param boolean $blocked Is the contact blocked or unblocked? * @param boolean $blocked Is the contact blocked or unblocked?
* @return void
* @throws \Exception * @throws \Exception
*/ */
public static function setBlocked($cid, $uid, $blocked) public static function setBlocked(int $cid, int $uid, bool $blocked)
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {
@ -170,7 +171,7 @@ class User
* @return boolean is the contact id blocked for the given user? * @return boolean is the contact id blocked for the given user?
* @throws \Exception * @throws \Exception
*/ */
public static function isBlocked($cid, $uid) public static function isBlocked(int $cid, int $uid): bool
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {
@ -208,9 +209,10 @@ class User
* @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
* @param boolean $ignored Is the contact ignored or unignored? * @param boolean $ignored Is the contact ignored or unignored?
* @return void
* @throws \Exception * @throws \Exception
*/ */
public static function setIgnored($cid, $uid, $ignored) public static function setIgnored(int $cid, int $uid, bool $ignored)
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {
@ -229,11 +231,10 @@ class User
* *
* @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 id ignored for the given user? * @return boolean is the contact id ignored for the given user?
* @throws \Exception * @throws \Exception
*/ */
public static function isIgnored($cid, $uid) public static function isIgnored(int $cid, int $uid): bool
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {
@ -271,9 +272,10 @@ class User
* @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
* @param boolean $collapsed are the contact's posts collapsed or uncollapsed? * @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
* @return void
* @throws \Exception * @throws \Exception
*/ */
public static function setCollapsed($cid, $uid, $collapsed) public static function setCollapsed(int $cid, int $uid, bool $collapsed)
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {
@ -288,16 +290,15 @@ class User
* *
* @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 id blocked for the given user? * @return boolean is the contact id blocked for the given user?
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isCollapsed($cid, $uid) public static function isCollapsed(int $cid, int $uid): bool
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {
return; return false;
} }
$collapsed = false; $collapsed = false;
@ -318,9 +319,10 @@ class User
* @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
* @param boolean $blocked Is the user blocked or unblocked by the contact? * @param boolean $blocked Is the user blocked or unblocked by the contact?
* @return void
* @throws \Exception * @throws \Exception
*/ */
public static function setIsBlocked($cid, $uid, $blocked) public static function setIsBlocked(int $cid, int $uid, bool $blocked)
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {
@ -335,11 +337,10 @@ class User
* *
* @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 user blocked or unblocked by the contact? * @return boolean Is the user blocked or unblocked by the contact?
* @throws \Exception * @throws \Exception
*/ */
public static function isIsBlocked($cid, $uid) public static function isIsBlocked(int $cid, int $uid): bool
{ {
$cdata = Contact::getPublicAndUserContactID($cid, $uid); $cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) { if (empty($cdata)) {

View File

@ -683,7 +683,6 @@ class GServer
* Fetch server data from '/statistics.json' on the given server * Fetch server data from '/statistics.json' on the given server
* *
* @param string $url URL of the given server * @param string $url URL of the given server
*
* @return array server data * @return array server data
*/ */
private static function fetchStatistics(string $url): array private static function fetchStatistics(string $url): array

View File

@ -45,7 +45,7 @@ class ParsedLogIterator implements \Iterator
private $filters = []; private $filters = [];
/** @var string search term */ /** @var string search term */
private $search = ""; private $search = '';
/** /**
@ -108,10 +108,11 @@ class ParsedLogIterator implements \Iterator
$match = true; $match = true;
foreach ($this->filters as $filter => $filtervalue) { foreach ($this->filters as $filter => $filtervalue) {
switch ($filter) { switch ($filter) {
case "level": case 'level':
$match = $match && ($parsedlogline->level == strtoupper($filtervalue)); $match = $match && ($parsedlogline->level == strtoupper($filtervalue));
break; break;
case "context":
case 'context':
$match = $match && ($parsedlogline->context == $filtervalue); $match = $match && ($parsedlogline->context == $filtervalue);
break; break;
} }
@ -128,7 +129,7 @@ class ParsedLogIterator implements \Iterator
*/ */
private function search(ParsedLogLine $parsedlogline): bool 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;
} }
return true; return true;
@ -138,7 +139,6 @@ class ParsedLogIterator implements \Iterator
* Read a line from reader and parse. * Read a line from reader and parse.
* Returns null if limit is reached or the reader is invalid. * Returns null if limit is reached or the reader is invalid.
* *
* @param ParsedLogLine $parsedlogline
* @return ?ParsedLogLine * @return ?ParsedLogLine
*/ */
private function read() private function read()
@ -191,7 +191,7 @@ class ParsedLogIterator implements \Iterator
* @see ReversedFileReader::key() * @see ReversedFileReader::key()
* @return int * @return int
*/ */
public function key() public function key(): int
{ {
return $this->reader->key(); return $this->reader->key();
} }
@ -213,8 +213,8 @@ class ParsedLogIterator implements \Iterator
* @see Iterator::valid() * @see Iterator::valid()
* @return bool * @return bool
*/ */
public function valid() public function valid(): bool
{ {
return ! is_null($this->value); return !is_null($this->value);
} }
} }

View File

@ -36,7 +36,6 @@ class OpenWebAuthToken
* @param int $uid The user ID. * @param int $uid The user ID.
* @param string $token * @param string $token
* @param string $meta * @param string $meta
*
* @return boolean * @return boolean
* @throws \Exception * @throws \Exception
*/ */
@ -80,6 +79,7 @@ class OpenWebAuthToken
* *
* @param string $type Verify type. * @param string $type Verify type.
* @param string $interval SQL compatible time interval * @param string $interval SQL compatible time interval
* @return void
* @throws \Exception * @throws \Exception
*/ */
public static function purge(string $type, string $interval) public static function purge(string $type, string $interval)

View File

@ -40,36 +40,44 @@ class Link
/** /**
* Check if the link is stored * Check if the link is stored
* *
* @param int $uri_id * @param int $uriId
* @param string $url * @param string $url URL
* @return bool * @return bool Whether record has been found
*/ */
public static function exists(int $uri_id, string $url) public static function exists(int $uriId, string $url): bool
{ {
return DBA::exists('post-link', ['uri-id' => $uri_id, 'url' => $url]); return DBA::exists('post-link', ['uri-id' => $uriId, 'url' => $url]);
} }
public static function getByLink(int $uri_id, string $url, $size = '') /**
* Returns URL by URI id and other URL
*
* @param int $uriId
* @param string $url
* @param string $size
* @return string Found link URL + id on success, $url on failture
*/
public static function getByLink(int $uriId, string $url, string $size = ''): string
{ {
if (empty($uri_id) || empty($url) || Proxy::isLocalImage($url)) { if (empty($uriId) || empty($url) || Proxy::isLocalImage($url)) {
return $url; return $url;
} }
if (!in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'])) { if (!in_array(parse_url($url, PHP_URL_SCHEME), ['http', 'https'])) {
Logger::info('Bad URL, quitting', ['uri-id' => $uri_id, 'url' => $url, 'callstack' => System::callstack(20)]); Logger::info('Bad URL, quitting', ['uri-id' => $uriId, 'url' => $url, 'callstack' => System::callstack(20)]);
return $url; return $url;
} }
$link = DBA::selectFirst('post-link', ['id'], ['uri-id' => $uri_id, 'url' => $url]); $link = DBA::selectFirst('post-link', ['id'], ['uri-id' => $uriId, 'url' => $url]);
if (!empty($link['id'])) { if (!empty($link['id'])) {
$id = $link['id']; $id = $link['id'];
Logger::info('Found', ['id' => $id, 'uri-id' => $uri_id, 'url' => $url]); Logger::info('Found', ['id' => $id, 'uri-id' => $uriId, 'url' => $url]);
} else { } else {
$mime = self::fetchMimeType($url); $mime = self::fetchMimeType($url);
DBA::insert('post-link', ['uri-id' => $uri_id, 'url' => $url, 'mimetype' => $mime], Database::INSERT_IGNORE); DBA::insert('post-link', ['uri-id' => $uriId, 'url' => $url, 'mimetype' => $mime], Database::INSERT_IGNORE);
$id = DBA::lastInsertId(); $id = DBA::lastInsertId();
Logger::info('Inserted', ['id' => $id, 'uri-id' => $uri_id, 'url' => $url]); Logger::info('Inserted', ['id' => $id, 'uri-id' => $uriId, 'url' => $url]);
} }
if (empty($id)) { if (empty($id)) {
@ -81,15 +89,19 @@ class Link
case Proxy::SIZE_MICRO: case Proxy::SIZE_MICRO:
$url .= Proxy::PIXEL_MICRO . '/'; $url .= Proxy::PIXEL_MICRO . '/';
break; break;
case Proxy::SIZE_THUMB: case Proxy::SIZE_THUMB:
$url .= Proxy::PIXEL_THUMB . '/'; $url .= Proxy::PIXEL_THUMB . '/';
break; break;
case Proxy::SIZE_SMALL: case Proxy::SIZE_SMALL:
$url .= Proxy::PIXEL_SMALL . '/'; $url .= Proxy::PIXEL_SMALL . '/';
break; break;
case Proxy::SIZE_MEDIUM: case Proxy::SIZE_MEDIUM:
$url .= Proxy::PIXEL_MEDIUM . '/'; $url .= Proxy::PIXEL_MEDIUM . '/';
break; break;
case Proxy::SIZE_LARGE: case Proxy::SIZE_LARGE:
$url .= Proxy::PIXEL_LARGE . '/'; $url .= Proxy::PIXEL_LARGE . '/';
break; break;
@ -97,43 +109,50 @@ class Link
return $url . $id; return $url . $id;
} }
private static function fetchMimeType(string $url, string $accept = HttpClientAccept::DEFAULT) /**
* Fetches MIME type by URL and Accept: header
*
* @param string $url URL to fetch
* @param string $accept Comma-separated list of expected response MIME type(s)
* @return string Discovered MIME type or empty string on failure
*/
private static function fetchMimeType(string $url, string $accept = HttpClientAccept::DEFAULT): string
{ {
$timeout = DI::config()->get('system', 'xrd_timeout'); $timeout = DI::config()->get('system', 'xrd_timeout');
$curlResult = DI::httpClient()->head($url, [HttpClientOptions::TIMEOUT => $timeout, HttpClientOptions::ACCEPT_CONTENT => $accept]); $curlResult = DI::httpClient()->head($url, [HttpClientOptions::TIMEOUT => $timeout, HttpClientOptions::ACCEPT_CONTENT => $accept]);
if ($curlResult->isSuccess()) {
if (empty($media['mimetype'])) { if ($curlResult->isSuccess() && empty($media['mimetype'])) {
return $curlResult->getHeader('Content-Type')[0] ?? ''; return $curlResult->getHeader('Content-Type')[0] ?? '';
}
} }
return ''; return '';
} }
/** /**
* Add external links and replace them in the body * Add external links and replace them in the body
* *
* @param integer $uriid * @param integer $uriId
* @param string $body * @param string $body Item body formatted with BBCodes
* @return string Body with replaced links * @return string Body with replaced links
*/ */
public static function insertFromBody(int $uriid, string $body) public static function insertFromBody(int $uriId, string $body): string
{ {
if (preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](http.*?)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) { if (preg_match_all("/\[img\=([0-9]*)x([0-9]*)\](http.*?)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
foreach ($pictures as $picture) { foreach ($pictures as $picture) {
$body = str_replace($picture[3], self::getByLink($uriid, $picture[3]), $body); $body = str_replace($picture[3], self::getByLink($uriId, $picture[3]), $body);
} }
} }
if (preg_match_all("/\[img=(http[^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) { if (preg_match_all("/\[img=(http[^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
foreach ($pictures as $picture) { foreach ($pictures as $picture) {
$body = str_replace($picture[1], self::getByLink($uriid, $picture[1]), $body); $body = str_replace($picture[1], self::getByLink($uriId, $picture[1]), $body);
} }
} }
if (preg_match_all("/\[img\](http[^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) { if (preg_match_all("/\[img\](http[^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
foreach ($pictures as $picture) { foreach ($pictures as $picture) {
$body = str_replace($picture[1], self::getByLink($uriid, $picture[1]), $body); $body = str_replace($picture[1], self::getByLink($uriId, $picture[1]), $body);
} }
} }

View File

@ -162,7 +162,6 @@ class Profile
* Returns a formatted location string from the given profile array * Returns a formatted location string from the given profile array
* *
* @param array $profile Profile array (Generated from the "profile" table) * @param array $profile Profile array (Generated from the "profile" table)
*
* @return string Location string * @return string Location string
*/ */
public static function formatLocation(array $profile): string public static function formatLocation(array $profile): string

View File

@ -34,13 +34,12 @@ class Register
/** /**
* Return the list of pending registrations * Return the list of pending registrations
* *
* @param int $start Start count (Default is 0) * @param int $start Start count (Default is 0)
* @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE) * @param int $count Count of the items per page (Default is @see Pager::ITEMS_PER_PAGE)
* * @return array|bool Array on succes, false on failure
* @return array
* @throws \Exception * @throws \Exception
*/ */
public static function getPending($start = 0, $count = Pager::ITEMS_PER_PAGE) public static function getPending(int $start = 0, int $count = Pager::ITEMS_PER_PAGE)
{ {
return DBA::selectToArray('pending-view', [], [], ['limit' => [$start, $count]]); return DBA::selectToArray('pending-view', [], [], ['limit' => [$start, $count]]);
} }
@ -50,8 +49,7 @@ class Register
* *
* @param int $uid The user id * @param int $uid The user id
* *
* @return array The pending user information * @return array|bool Array on succes, false on failure
*
* @throws \Exception * @throws \Exception
*/ */
public static function getPendingForUser(int $uid) public static function getPendingForUser(int $uid)
@ -65,7 +63,7 @@ class Register
* @return int * @return int
* @throws \Exception * @throws \Exception
*/ */
public static function getPendingCount() public static function getPendingCount(): int
{ {
return DBA::count('pending-view', ['self' => true]); return DBA::count('pending-view', ['self' => true]);
} }
@ -74,10 +72,10 @@ class Register
* Returns the register record associated with the provided hash * Returns the register record associated with the provided hash
* *
* @param string $hash * @param string $hash
* @return array * @return array|bool Array on succes, false on failure
* @throws \Exception * @throws \Exception
*/ */
public static function getByHash($hash) public static function getByHash(string $hash)
{ {
return DBA::selectFirst('register', [], ['hash' => $hash]); return DBA::selectFirst('register', [], ['hash' => $hash]);
} }
@ -89,7 +87,7 @@ class Register
* @return boolean * @return boolean
* @throws \Exception * @throws \Exception
*/ */
public static function existsByHash($hash) public static function existsByHash(string $hash): bool
{ {
return DBA::exists('register', ['hash' => $hash]); return DBA::exists('register', ['hash' => $hash]);
} }
@ -100,7 +98,7 @@ class Register
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public static function createForInvitation() public static function createForInvitation(): string
{ {
$code = Strings::getRandomName(8) . random_int(1000, 9999); $code = Strings::getRandomName(8) . random_int(1000, 9999);
@ -124,7 +122,7 @@ class Register
* @return boolean * @return boolean
* @throws \Exception * @throws \Exception
*/ */
public static function createForApproval($uid, $language, $note = '') public static function createForApproval(int $uid, string $language, string $note = ''): bool
{ {
$hash = Strings::getRandomHex(); $hash = Strings::getRandomHex();
@ -151,7 +149,7 @@ class Register
* @return boolean * @return boolean
* @throws \Exception * @throws \Exception
*/ */
public static function deleteByHash($hash) public static function deleteByHash(string $hash): bool
{ {
return DBA::delete('register', ['hash' => $hash]); return DBA::delete('register', ['hash' => $hash]);
} }

View File

@ -32,10 +32,9 @@ class Search
* Returns the list of user defined tags (e.g. #Friendica) * Returns the list of user defined tags (e.g. #Friendica)
* *
* @return array * @return array
*
* @throws \Exception * @throws \Exception
*/ */
public static function getUserTags() public static function getUserTags(): array
{ {
$termsStmt = DBA::p("SELECT DISTINCT(`term`) FROM `search`"); $termsStmt = DBA::p("SELECT DISTINCT(`term`) FROM `search`");

View File

@ -25,6 +25,7 @@ use Friendica\Core\Logger;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory;
use Friendica\Navigation\Notifications\Entity; use Friendica\Navigation\Notifications\Entity;
use Friendica\Object\Api\Mastodon\Notification; use Friendica\Object\Api\Mastodon\Notification;
use Minishlink\WebPush\VAPID; use Minishlink\WebPush\VAPID;
@ -37,8 +38,7 @@ class Subscription
* @param int $applicationid * @param int $applicationid
* @param int $uid * @param int $uid
* @param array $fields * @param array $fields
* * @return array|bool Array on success, false on failure
* @return bool Does it exist?
*/ */
public static function select(int $applicationid, int $uid, array $fields = []) public static function select(int $applicationid, int $uid, array $fields = [])
{ {
@ -53,7 +53,7 @@ class Subscription
* *
* @return bool Does it exist? * @return bool Does it exist?
*/ */
public static function exists(int $applicationid, int $uid) public static function exists(int $applicationid, int $uid): bool
{ {
return DBA::exists('subscription', ['application-id' => $applicationid, 'uid' => $uid]); return DBA::exists('subscription', ['application-id' => $applicationid, 'uid' => $uid]);
} }
@ -64,10 +64,9 @@ class Subscription
* @param int $applicationid * @param int $applicationid
* @param int $uid * @param int $uid
* @param array $fields subscription fields * @param array $fields subscription fields
*
* @return bool result of update * @return bool result of update
*/ */
public static function update(int $applicationid, int $uid, array $fields) public static function update(int $applicationid, int $uid, array $fields): bool
{ {
return DBA::update('subscription', $fields, ['application-id' => $applicationid, 'uid' => $uid]); return DBA::update('subscription', $fields, ['application-id' => $applicationid, 'uid' => $uid]);
} }
@ -76,10 +75,9 @@ class Subscription
* Insert or replace a subscription record * Insert or replace a subscription record
* *
* @param array $fields subscription fields * @param array $fields subscription fields
*
* @return bool result of replace * @return bool result of replace
*/ */
public static function replace(array $fields) public static function replace(array $fields): bool
{ {
return DBA::replace('subscription', $fields); return DBA::replace('subscription', $fields);
} }
@ -91,7 +89,7 @@ class Subscription
* @param int $uid * @param int $uid
* @return bool * @return bool
*/ */
public static function delete(int $applicationid, int $uid) public static function delete(int $applicationid, int $uid): bool
{ {
return DBA::delete('subscription', ['application-id' => $applicationid, 'uid' => $uid]); return DBA::delete('subscription', ['application-id' => $applicationid, 'uid' => $uid]);
} }
@ -136,25 +134,25 @@ class Subscription
/** /**
* Prepare push notification * Prepare push notification
* *
* @param int $nid * @param Notification $Notification
* @return void * @return void
*/ */
public static function pushByNotification(Entity\Notification $Notification) public static function pushByNotification(Entity\Notification $notification)
{ {
$type = \Friendica\Factory\Api\Mastodon\Notification::getType($Notification); $type = NotificationFactory::getType($notification);
if (DI::notify()->NotifyOnDesktop($Notification, $type)) { if (DI::notify()->NotifyOnDesktop($notification, $type)) {
DI::notify()->createFromNotification($Notification); DI::notify()->createFromNotification($notification);
} }
if (empty($type)) { if (empty($type)) {
return; return;
} }
$subscriptions = DBA::select('subscription', [], ['uid' => $Notification->uid, $type => true]); $subscriptions = DBA::select('subscription', [], ['uid' => $notification->uid, $type => true]);
while ($subscription = DBA::fetch($subscriptions)) { while ($subscription = DBA::fetch($subscriptions)) {
Logger::info('Push notification', ['id' => $subscription['id'], 'uid' => $subscription['uid'], 'type' => $type]); Logger::info('Push notification', ['id' => $subscription['id'], 'uid' => $subscription['uid'], 'type' => $type]);
Worker::add(PRIORITY_HIGH, 'PushSubscription', $subscription['id'], $Notification->id); Worker::add(PRIORITY_HIGH, 'PushSubscription', $subscription['id'], $notification->id);
} }
DBA::close($subscriptions); DBA::close($subscriptions);
} }

View File

@ -73,14 +73,14 @@ class Tag
/** /**
* Store tag/mention elements * Store tag/mention elements
* *
* @param integer $uriid URI id * @param integer $uriId
* @param integer $type Tag type * @param integer $type Tag type
* @param string $name Tag name * @param string $name Tag name
* @param string $url Contact URL (optional) * @param string $url Contact URL (optional)
* @param integer $target Target (default: null) * @param integer $target Target (default: null)
* @return void * @return void
*/ */
public static function store(int $uriid, int $type, string $name, string $url = '', int $target = null) public static function store(int $uriId, int $type, string $name, string $url = '', int $target = null)
{ {
if ($type == self::HASHTAG) { if ($type == self::HASHTAG) {
// Trim Unicode non-word characters // Trim Unicode non-word characters
@ -89,7 +89,7 @@ class Tag
$tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name); $tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
if (count($tags) > 1) { if (count($tags) > 1) {
foreach ($tags as $tag) { foreach ($tags as $tag) {
self::store($uriid, $type, $tag, $url); self::store($uriId, $type, $tag, $url);
} }
return; return;
} }
@ -143,7 +143,7 @@ class Tag
} }
} }
$fields = ['uri-id' => $uriid, 'type' => $type, 'tid' => $tagid, 'cid' => $cid]; $fields = ['uri-id' => $uriId, 'type' => $type, 'tid' => $tagid, 'cid' => $cid];
if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) { if (in_array($type, [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])) {
$condition = $fields; $condition = $fields;
@ -156,7 +156,7 @@ class Tag
DBA::insert('post-tag', $fields, Database::INSERT_IGNORE); DBA::insert('post-tag', $fields, Database::INSERT_IGNORE);
Logger::info('Stored tag/mention', ['uri-id' => $uriid, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]); Logger::info('Stored tag/mention', ['uri-id' => $uriId, 'tag-id' => $tagid, 'contact-id' => $cid, 'name' => $name, 'type' => $type, 'callstack' => System::callstack(8)]);
} }
/** /**
@ -214,14 +214,14 @@ class Tag
} }
/** /**
* Get a tag id for a given tag name and url * Get a tag id for a given tag name and URL
* *
* @param string $name * @param string $name Name of tag
* @param string $url * @param string $url
* @param int $type * @param int $type Type of tag
* @return void * @return int Tag id
*/ */
public static function getID(string $name, string $url = '', int $type = null) public static function getID(string $name, string $url = '', int $type = null): int
{ {
$fields = ['name' => substr($name, 0, 96), 'url' => $url]; $fields = ['name' => substr($name, 0, 96), 'url' => $url];
@ -243,6 +243,9 @@ class Tag
return $tid; return $tid;
} }
// Also log type
$fields['type'] = $type;
Logger::error('No tag id created', $fields); Logger::error('No tag id created', $fields);
return 0; return 0;
} }
@ -250,21 +253,21 @@ class Tag
/** /**
* Store tag/mention elements * Store tag/mention elements
* *
* @param integer $uriid URI id * @param integer $uriId
* @param string $hash Hash * @param string $hash
* @param string $name Name * @param string $name
* @param string $url URL * @param string $url
* @param boolean $probing Whether probing is active * @param boolean $probing Whether probing is active
* @return void * @return void
*/ */
public static function storeByHash(int $uriid, string $hash, string $name, string $url = '', bool $probing = true) public static function storeByHash(int $uriId, string $hash, string $name, string $url = '', bool $probing = true)
{ {
$type = self::getTypeForHash($hash); $type = self::getTypeForHash($hash);
if ($type == self::UNKNOWN) { if ($type == self::UNKNOWN) {
return; return;
} }
self::store($uriid, $type, $name, $url, $probing); self::store($uriId, $type, $name, $url, $probing);
} }
/** /**
@ -275,7 +278,7 @@ class Tag
* *
* @return array Tag list * @return array Tag list
*/ */
public static function getFromBody(string $body, string $tags = null) public static function getFromBody(string $body, string $tags = null): array
{ {
if (is_null($tags)) { if (is_null($tags)) {
$tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]; $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
@ -291,15 +294,15 @@ class Tag
/** /**
* Store tags and mentions from the body * Store tags and mentions from the body
* *
* @param integer $uriid URI-Id * @param integer $uriId URI-Id
* @param string $body Body of the post * @param string $body Body of the post
* @param string $tags Accepted tags * @param string $tags Accepted tags
* @param boolean $probing Perform a probing for contacts, adding them if needed * @param boolean $probing Perform a probing for contacts, adding them if needed
* @return void * @return void
*/ */
public static function storeFromBody(int $uriid, string $body, string $tags = null, bool $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()]); Logger::info('Check for tags', ['uri-id' => $uriId, 'hash' => $tags, 'callstack' => System::callstack()]);
if (is_null($tags)) { if (is_null($tags)) {
$tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION]; $tags = self::TAG_CHARACTER[self::HASHTAG] . self::TAG_CHARACTER[self::MENTION] . self::TAG_CHARACTER[self::EXCLUSIVE_MENTION];
@ -315,13 +318,13 @@ class Tag
} }
foreach (self::getFromBody($body, $tags) as $tag) { foreach (self::getFromBody($body, $tags) as $tag) {
self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing); self::storeByHash($uriId, $tag[1], $tag[3], $tag[2], $probing);
} }
// Search for hashtags in the shared body (but only if hashtags are wanted) // Search for hashtags in the shared body (but only if hashtags are wanted)
if (!empty($share_body) && (strpos($tags, self::TAG_CHARACTER[self::HASHTAG]) !== false)) { if (!empty($share_body) && (strpos($tags, self::TAG_CHARACTER[self::HASHTAG]) !== false)) {
foreach (self::getFromBody($share_body, self::TAG_CHARACTER[self::HASHTAG]) as $tag) { foreach (self::getFromBody($share_body, self::TAG_CHARACTER[self::HASHTAG]) as $tag) {
self::storeByHash($uriid, $tag[1], $tag[3], $tag[2], $probing); self::storeByHash($uriId, $tag[1], $tag[3], $tag[2], $probing);
} }
} }
} }
@ -331,52 +334,52 @@ class Tag
* This function is needed in the intermediate phase. * This function is needed in the intermediate phase.
* Later we can call item::setHashtags in advance to have all tags converted. * Later we can call item::setHashtags in advance to have all tags converted.
* *
* @param integer $uriid URI-Id * @param integer $uriId URI-Id
* @param string $body Body of the post * @param string $body Body of the post
* @return void * @return void
*/ */
public static function storeRawTagsFromBody(int $uriid, string $body) public static function storeRawTagsFromBody(int $uriId, string $body)
{ {
Logger::info('Check for tags', ['uri-id' => $uriid, 'callstack' => System::callstack()]); Logger::info('Check for tags', ['uri-id' => $uriId, 'callstack' => System::callstack()]);
$result = BBCode::getTags($body); $result = BBCode::getTags($body);
if (empty($result)) { if (empty($result)) {
return; return;
} }
Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]); Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]);
foreach ($result as $tag) { foreach ($result as $tag) {
if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) { if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
continue; continue;
} }
self::storeByHash($uriid, substr($tag, 0, 1), substr($tag, 1)); self::storeByHash($uriId, substr($tag, 0, 1), substr($tag, 1));
} }
} }
/** /**
* Checks for stored hashtags and mentions for the given post * Checks for stored hashtags and mentions for the given post
* *
* @param integer $uriid * @param integer $uriId
* @return bool * @return bool
*/ */
public static function existsForPost(int $uriid) public static function existsForPost(int $uriId): bool
{ {
return DBA::exists('post-tag', ['uri-id' => $uriid, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]); return DBA::exists('post-tag', ['uri-id' => $uriId, 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
} }
/** /**
* Remove tag/mention * Remove tag/mention
* *
* @param integer $uriid URI id * @param integer $uriId
* @param integer $type Type * @param integer $type Type
* @param string $name Name * @param string $name Name
* @param string $url URL * @param string $url URL
* @return void * @return void
*/ */
public static function remove(int $uriid, int $type, string $name, string $url = '') public static function remove(int $uriId, int $type, string $name, string $url = '')
{ {
$condition = ['uri-id' => $uriid, 'type' => $type, 'url' => $url]; $condition = ['uri-id' => $uriId, 'type' => $type, 'url' => $url];
if ($type == self::HASHTAG) { if ($type == self::HASHTAG) {
$condition['name'] = $name; $condition['name'] = $name;
} }
@ -386,35 +389,36 @@ class Tag
return; return;
} }
Logger::info('Removing tag/mention', ['uri-id' => $uriid, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]); Logger::info('Removing tag/mention', ['uri-id' => $uriId, 'tid' => $tag['tid'], 'name' => $name, 'url' => $url, 'callstack' => System::callstack(8)]);
DBA::delete('post-tag', ['uri-id' => $uriid, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]); DBA::delete('post-tag', ['uri-id' => $uriId, 'type' => $type, 'tid' => $tag['tid'], 'cid' => $tag['cid']]);
} }
/** /**
* Remove tag/mention * Remove tag/mention
* *
* @param integer $uriid * @param integer $uriId
* @param string $hash * @param string $hash
* @param string $name * @param string $name
* @param string $url * @param string $url
* @return void
*/ */
public static function removeByHash(int $uriid, string $hash, string $name, string $url = '') public static function removeByHash(int $uriId, string $hash, string $name, string $url = '')
{ {
$type = self::getTypeForHash($hash); $type = self::getTypeForHash($hash);
if ($type == self::UNKNOWN) { if ($type == self::UNKNOWN) {
return; return;
} }
self::remove($uriid, $type, $name, $url); self::remove($uriId, $type, $name, $url);
} }
/** /**
* Get the type for the given hash * Get the type for the given hash
* *
* @param string $hash * @param string $hash
* @return integer type * @return integer Tag type
*/ */
private static function getTypeForHash(string $hash) private static function getTypeForHash(string $hash): int
{ {
if ($hash == self::TAG_CHARACTER[self::MENTION]) { if ($hash == self::TAG_CHARACTER[self::MENTION]) {
return self::MENTION; return self::MENTION;
@ -432,22 +436,23 @@ class Tag
/** /**
* Create implicit mentions for a given post * Create implicit mentions for a given post
* *
* @param integer $uri_id * @param integer $uriId
* @param integer $parent_uri_id * @param integer $parentUriId
* @return void
*/ */
public static function createImplicitMentions(int $uri_id, int $parent_uri_id) public static function createImplicitMentions(int $uriId, int $parentUriId)
{ {
// Always mention the direct parent author // Always mention the direct parent author
$parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]); $parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parentUriId]);
self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']); self::store($uriId, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
if (DI::config()->get('system', 'disable_implicit_mentions')) { if (DI::config()->get('system', 'disable_implicit_mentions')) {
return; return;
} }
$tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parent_uri_id, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]); $tags = DBA::select('tag-view', ['name', 'url'], ['uri-id' => $parentUriId, 'type' => [self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
while ($tag = DBA::fetch($tags)) { while ($tag = DBA::fetch($tags)) {
self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']); self::store($uriId, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
} }
DBA::close($tags); DBA::close($tags);
} }
@ -455,30 +460,29 @@ class Tag
/** /**
* Retrieves the terms from the provided type(s) associated with the provided item ID. * Retrieves the terms from the provided type(s) associated with the provided item ID.
* *
* @param int $item_id * @param int $uriId
* @param int|array $type * @param array $type Tag type(s)
* @return array * @return array|bool Array on success, false on error
* @throws \Exception * @throws \Exception
*/ */
public static function getByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]) public static function getByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION])
{ {
$condition = ['uri-id' => $uri_id, 'type' => $type]; $condition = ['uri-id' => $uriId, 'type' => $type];
return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition); return DBA::selectToArray('tag-view', ['type', 'name', 'url', 'tag-type'], $condition);
} }
/** /**
* Return a string with all tags and mentions * Return a string with all tags and mentions
* *
* @param integer $uri_id * @param integer $uriId
* @param array $type * @param array $type Tag type(s)
* @return string tags and mentions * @return string tags and mentions
* @throws \Exception * @throws \Exception
*/ */
public static function getCSVByURIId(int $uri_id, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]) public static function getCSVByURIId(int $uriId, array $type = [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]): string
{ {
$tag_list = []; $tag_list = [];
$tags = self::getByURIId($uri_id, $type); foreach (self::getByURIId($uriId, $type) as $tag) {
foreach ($tags as $tag) {
$tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]'; $tag_list[] = self::TAG_CHARACTER[$tag['type']] . '[url=' . $tag['url'] . ']' . $tag['name'] . '[/url]';
} }
@ -494,7 +498,7 @@ class Tag
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function populateFromItem(&$item) public static function populateFromItem(array &$item): array
{ {
$return = [ $return = [
'tags' => [], 'tags' => [],
@ -503,7 +507,7 @@ class Tag
'implicit_mentions' => [], 'implicit_mentions' => [],
]; ];
$searchpath = DI::baseUrl() . "/search?tag="; $searchpath = DI::baseUrl() . '/search?tag=';
$taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'], $taglist = DBA::select('tag-view', ['type', 'name', 'url', 'cid'],
['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]); ['uri-id' => $item['uri-id'], 'type' => [self::HASHTAG, self::MENTION, self::EXCLUSIVE_MENTION, self::IMPLICIT_MENTION]]);
@ -524,6 +528,7 @@ class Tag
$return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>'; $return['hashtags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
$return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>'; $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
break; break;
case self::MENTION: case self::MENTION:
case self::EXCLUSIVE_MENTION: case self::EXCLUSIVE_MENTION:
if (!empty($tag['cid'])) { if (!empty($tag['cid'])) {
@ -534,9 +539,13 @@ class Tag
$return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>'; $return['mentions'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
$return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>'; $return['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
break; break;
case self::IMPLICIT_MENTION: case self::IMPLICIT_MENTION:
$return['implicit_mentions'][] = $prefix . $tag['name']; $return['implicit_mentions'][] = $prefix . $tag['name'];
break; break;
default:
Logger:warning('Unknown tag type found', $tag);
} }
} }
DBA::close($taglist); DBA::close($taglist);
@ -551,11 +560,13 @@ class Tag
* @param integer $uid * @param integer $uid
* @return integer number of posts * @return integer number of posts
*/ */
public static function countByTag(string $search, int $uid = 0) public static function countByTag(string $search, int $uid = 0): int
{ {
$condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`)) $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))", AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
$search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0]; $search, 0, $uid,
Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
];
return DBA::count('tag-search-view', $condition); return DBA::count('tag-search-view', $condition);
} }
@ -563,18 +574,20 @@ class Tag
/** /**
* Search posts for given tag * Search posts for given tag
* *
* @param string $search * @param string $search Tag to search for
* @param integer $uid * @param integer $uid User Id
* @param integer $start * @param integer $start Starting record
* @param integer $limit * @param integer $limit Maximum count of records
* @param integer $last_uriid * @param integer $last_uriid
* @return array with URI-ID * @return array with URI-ID
*/ */
public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0) public static function getURIIdListByTag(string $search, int $uid = 0, int $start = 0, int $limit = 100, int $last_uriid = 0): array
{ {
$condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`)) $condition = ["`name` = ? AND (`uid` = ? OR (`uid` = ? AND NOT `global`))
AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))", AND (`network` IN (?, ?, ?, ?) OR (`uid` = ? AND `uid` != ?))",
$search, 0, $uid, Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0]; $search, 0, $uid,
Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, $uid, 0,
];
if (!empty($last_uriid)) { if (!empty($last_uriid)) {
$condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]); $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
@ -587,13 +600,13 @@ class Tag
$tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params); $tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
$uriids = []; $uriIds = [];
while ($tag = DBA::fetch($tags)) { while ($tag = DBA::fetch($tags)) {
$uriids[] = $tag['uri-id']; $uriIds[] = $tag['uri-id'];
} }
DBA::close($tags); DBA::close($tags);
return $uriids; return $uriIds;
} }
/** /**
@ -604,7 +617,7 @@ class Tag
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function getGlobalTrendingHashtags(int $period, $limit = 10) public static function getGlobalTrendingHashtags(int $period, $limit = 10): array
{ {
$tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit); $tags = DI::cache()->get('global_trending_tags-' . $period . '-' . $limit);
if (!empty($tags)) { if (!empty($tags)) {
@ -617,9 +630,9 @@ class Tag
/** /**
* Fetch the blocked tags as SQL * Fetch the blocked tags as SQL
* *
* @return string * @return string SQL for blocked tag names or empty string
*/ */
private static function getBlockedSQL() private static function getBlockedSQL(): string
{ {
$blocked_txt = DI::config()->get('system', 'blocked_tags'); $blocked_txt = DI::config()->get('system', 'blocked_tags');
if (empty($blocked_txt)) { if (empty($blocked_txt)) {
@ -628,7 +641,7 @@ class Tag
$blocked = explode(',', $blocked_txt); $blocked = explode(',', $blocked_txt);
array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";}); array_walk($blocked, function(&$value) { $value = "'" . DBA::escape(trim($value)) . "'";});
return " AND NOT `name` IN (" . implode(',', $blocked) . ")"; return ' AND NOT `name` IN (' . implode(',', $blocked) . ')';
} }
/** /**
@ -639,12 +652,15 @@ class Tag
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function setGlobalTrendingHashtags(int $period, int $limit = 10) public static function setGlobalTrendingHashtags(int $period, int $limit = 10): array
{ {
// Get a uri-id that is at least X hours old. /*
// We use the uri-id in the query for the hash tags since this is much faster * Get a uri-id that is at least X hours old.
* We use the uri-id in the query for the hash tags since this is much faster
*/
$post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')], $post = Post::selectFirstThread(['uri-id'], ["`uid` = ? AND `received` < ?", 0, DateTimeFormat::utc('now - ' . $period . ' hour')],
['order' => ['received' => true]]); ['order' => ['received' => true]]);
if (empty($post['uri-id'])) { if (empty($post['uri-id'])) {
return []; return [];
} }
@ -655,7 +671,9 @@ class Tag
FROM `tag-search-view` FROM `tag-search-view`
WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?", GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
Item::PUBLIC, 0, $post['uri-id'], $limit); Item::PUBLIC, 0, $post['uri-id'],
$limit
);
if (DBA::isResult($tagsStmt)) { if (DBA::isResult($tagsStmt)) {
$tags = DBA::toArray($tagsStmt); $tags = DBA::toArray($tagsStmt);
@ -674,7 +692,7 @@ class Tag
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function getLocalTrendingHashtags(int $period, $limit = 10) public static function getLocalTrendingHashtags(int $period, $limit = 10): array
{ {
$tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit); $tags = DI::cache()->get('local_trending_tags-' . $period . '-' . $limit);
if (!empty($tags)) { if (!empty($tags)) {
@ -692,7 +710,7 @@ class Tag
* @return array * @return array
* @throws \Exception * @throws \Exception
*/ */
public static function setLocalTrendingHashtags(int $period, int $limit = 10) public static function setLocalTrendingHashtags(int $period, int $limit = 10): array
{ {
// Get a uri-id that is at least X hours old. // Get a uri-id that is at least X hours old.
// We use the uri-id in the query for the hash tags since this is much faster // We use the uri-id in the query for the hash tags since this is much faster
@ -708,7 +726,9 @@ class Tag
FROM `tag-search-view` FROM `tag-search-view`
WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?", GROUP BY `term` ORDER BY `authors` DESC, `score` DESC LIMIT ?",
Item::PUBLIC, $post['uri-id'], $limit); Item::PUBLIC, $post['uri-id'],
$limit
);
if (DBA::isResult($tagsStmt)) { if (DBA::isResult($tagsStmt)) {
$tags = DBA::toArray($tagsStmt); $tags = DBA::toArray($tagsStmt);
@ -722,11 +742,11 @@ class Tag
/** /**
* Check if the provided tag is of one of the provided term types. * Check if the provided tag is of one of the provided term types.
* *
* @param string $tag * @param string $tag Tag name
* @param int ...$types * @param int ...$types
* @return bool * @return bool
*/ */
public static function isType($tag, ...$types) public static function isType(string $tag, ...$types): bool
{ {
$tag_chars = []; $tag_chars = [];
foreach ($types as $type) { foreach ($types as $type) {
@ -744,7 +764,7 @@ class Tag
* @param string $tag * @param string $tag
* @return array User list * @return array User list
*/ */
private static function getUIDListByTag(string $tag) private static function getUIDListByTag(string $tag): array
{ {
$uids = []; $uids = [];
$searches = DBA::select('search', ['uid'], ['term' => $tag]); $searches = DBA::select('search', ['uid'], ['term' => $tag]);
@ -759,13 +779,13 @@ class Tag
/** /**
* Fetch user who subscribed to the tags of the given item * Fetch user who subscribed to the tags of the given item
* *
* @param integer $uri_id * @param integer $uriId
* @return array User list * @return array User list
*/ */
public static function getUIDListByURIId(int $uri_id) public static function getUIDListByURIId(int $uriId): array
{ {
$uids = []; $uids = [];
$tags = self::getByURIId($uri_id, [self::HASHTAG]); $tags = self::getByURIId($uriId, [self::HASHTAG]);
foreach ($tags as $tag) { foreach ($tags as $tag) {
$uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name'])); $uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));

View File

@ -117,16 +117,18 @@ class User
switch ($accounttype) { switch ($accounttype) {
case 'person': case 'person':
return User::ACCOUNT_TYPE_PERSON; return User::ACCOUNT_TYPE_PERSON;
case 'organisation': case 'organisation':
return User::ACCOUNT_TYPE_ORGANISATION; return User::ACCOUNT_TYPE_ORGANISATION;
case 'news': case 'news':
return User::ACCOUNT_TYPE_NEWS; return User::ACCOUNT_TYPE_NEWS;
case 'community': case 'community':
return User::ACCOUNT_TYPE_COMMUNITY; return User::ACCOUNT_TYPE_COMMUNITY;
default:
return null;
break;
} }
return null;
} }
/** /**
@ -362,14 +364,12 @@ class User
/** /**
* Get a user based on its email * Get a user based on its email
* *
* @param string $email * @param string $email
* @param array $fields * @param array $fields
*
* @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 getByEmail($email, array $fields = []) public static function getByEmail(string $email, array $fields = [])
{ {
return DBA::selectFirst('user', $fields, ['email' => $email]); return DBA::selectFirst('user', $fields, ['email' => $email]);
} }
@ -512,7 +512,7 @@ class User
* @throws HTTPException\ForbiddenException * @throws HTTPException\ForbiddenException
* @throws HTTPException\NotFoundException * @throws HTTPException\NotFoundException
*/ */
public static function getIdFromPasswordAuthentication($user_info, string $password, bool $third_party = false) public static function getIdFromPasswordAuthentication($user_info, string $password, bool $third_party = false): int
{ {
// 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
@ -1164,32 +1164,32 @@ class User
$type = Images::getMimeTypeByData($img_str, $photo, $type); $type = Images::getMimeTypeByData($img_str, $photo, $type);
$Image = new Image($img_str, $type); $image = new Image($img_str, $type);
if ($Image->isValid()) { if ($image->isValid()) {
$Image->scaleToSquare(300); $image->scaleToSquare(300);
$resource_id = Photo::newResource(); $resource_id = Photo::newResource();
// Not using Photo::PROFILE_PHOTOS here, so that it is discovered as translateble string // Not using Photo::PROFILE_PHOTOS here, so that it is discovered as translateble string
$profile_album = DI::l10n()->t('Profile Photos'); $profile_album = DI::l10n()->t('Profile Photos');
$r = Photo::store($Image, $uid, 0, $resource_id, $filename, $profile_album, 4); $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 4);
if ($r === false) { if ($r === false) {
$photo_failure = true; $photo_failure = true;
} }
$Image->scaleDown(80); $image->scaleDown(80);
$r = Photo::store($Image, $uid, 0, $resource_id, $filename, $profile_album, 5); $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 5);
if ($r === false) { if ($r === false) {
$photo_failure = true; $photo_failure = true;
} }
$Image->scaleDown(48); $image->scaleDown(48);
$r = Photo::store($Image, $uid, 0, $resource_id, $filename, $profile_album, 6); $r = Photo::store($image, $uid, 0, $resource_id, $filename, $profile_album, 6);
if ($r === false) { if ($r === false) {
$photo_failure = true; $photo_failure = true;
@ -1342,7 +1342,6 @@ class User
* @param string $email The user's email address * @param string $email The user's email address
* @param string $nick The user's nick name * @param string $nick The user's nick name
* @param string $lang The user's language (default is english) * @param string $lang The user's language (default is english)
*
* @return bool True, if the user was created successfully * @return bool True, if the user was created successfully
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
* @throws ErrorException * @throws ErrorException
@ -1731,7 +1730,6 @@ class User
* @param string $type The type of users, which should get (all, bocked, removed) * @param string $type The type of users, which should get (all, bocked, removed)
* @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|bool The list of the users * @return array|bool The list of the users
* @throws Exception * @throws Exception
*/ */
@ -1744,11 +1742,13 @@ class User
$condition['account_removed'] = false; $condition['account_removed'] = false;
$condition['blocked'] = false; $condition['blocked'] = false;
break; break;
case 'blocked': case 'blocked':
$condition['account_removed'] = false; $condition['account_removed'] = false;
$condition['blocked'] = true; $condition['blocked'] = true;
$condition['verified'] = true; $condition['verified'] = true;
break; break;
case 'removed': case 'removed':
$condition['account_removed'] = true; $condition['account_removed'] = true;
break; break;

View File

@ -34,7 +34,7 @@ class Verb
* @return integer verb id * @return integer verb id
* @throws \Exception * @throws \Exception
*/ */
public static function getID(string $verb) public static function getID(string $verb): int
{ {
if (empty($verb)) { if (empty($verb)) {
return 0; return 0;
@ -56,7 +56,7 @@ class Verb
* @param integer $id * @param integer $id
* @return string verb * @return string verb
*/ */
public static function getByID(int $id) public static function getByID(int $id): string
{ {
if (empty($id)) { if (empty($id)) {
return ''; return '';

View File

@ -363,7 +363,7 @@ class Install extends BaseModule
* @return string The text for the next steps * @return string The text for the next steps
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private function whatNext() private function whatNext(): string
{ {
$baseurl = $this->baseUrl->get(); $baseurl = $this->baseUrl->get();
return return
@ -383,6 +383,7 @@ class Install extends BaseModule
* @param string $cat The category of the setting * @param string $cat The category of the setting
* @param string $key The key of the setting * @param string $key The key of the setting
* @param null|string $default The default value * @param null|string $default The default value
* @return void
*/ */
private function checkSetting(Cache $configCache, array $post, string $cat, string $key, ?string $default = null) private function checkSetting(Cache $configCache, array $post, string $cat, string $key, ?string $default = null)
{ {

View File

@ -45,7 +45,7 @@ class Maintenance extends BaseModule
$exception = new HTTPException\ServiceUnavailableException($reason); $exception = new HTTPException\ServiceUnavailableException($reason);
header($_SERVER["SERVER_PROTOCOL"] . ' ' . $exception->getCode() . ' ' . DI::l10n()->t('System down for maintenance')); header($_SERVER['SERVER_PROTOCOL'] . ' ' . $exception->getCode() . ' ' . DI::l10n()->t('System down for maintenance'));
$tpl = Renderer::getMarkupTemplate('exception.tpl'); $tpl = Renderer::getMarkupTemplate('exception.tpl');

View File

@ -131,7 +131,7 @@ class NoScrape extends BaseModule
$profile_fields = ['about', 'locality', 'region', 'postal-code', 'country-name', 'xmpp', 'matrix']; $profile_fields = ['about', 'locality', 'region', 'postal-code', 'country-name', 'xmpp', 'matrix'];
foreach ($profile_fields as $field) { foreach ($profile_fields as $field) {
if (!empty($owner[$field])) { if (!empty($owner[$field])) {
$json_info["$field"] = $owner[$field]; $json_info[$field] = $owner[$field];
} }
} }

View File

@ -50,9 +50,12 @@ class OpenSearch extends BaseModule
'@attributes' => [ '@attributes' => [
'xmlns' => 'http://a9.com/-/spec/opensearch/1.1', 'xmlns' => 'http://a9.com/-/spec/opensearch/1.1',
], ],
'ShortName' => "Friendica $hostname", 'ShortName' => "Friendica $hostname",
'Description' => "Search in Friendica $hostname", 'Description' => "Search in Friendica $hostname",
'Contact' => 'https://github.com/friendica/friendica/issues', 'Contact' => 'https://github.com/friendica/friendica/issues',
'InputEncoding' => 'UTF-8',
'OutputEncoding' => 'UTF-8',
'Developer' => 'Friendica Developer Team',
], ],
], $xml); ], $xml);

View File

@ -174,7 +174,7 @@ class PermissionTooltip extends \Friendica\BaseModule
* @param int $uriId * @param int $uriId
* @return string * @return string
*/ */
private function fetchReceivers(int $uriId):string private function fetchReceivers(int $uriId): string
{ {
$own_url = ''; $own_url = '';
$uid = local_user(); $uid = local_user();

View File

@ -60,17 +60,17 @@ class Photo extends BaseModule
{ {
$totalstamp = microtime(true); $totalstamp = microtime(true);
if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) { if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT"); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) { if (!empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]); header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
} }
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT"); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
header("Cache-Control: max-age=31536000"); header('Cache-Control: max-age=31536000');
if (function_exists("header_remove")) { if (function_exists('header_remove')) {
header_remove("Last-Modified"); header_remove('Last-Modified');
header_remove("Expires"); header_remove('Expires');
header_remove("Cache-Control"); header_remove('Cache-Control');
} }
throw new NotModifiedException(); throw new NotModifiedException();
} }
@ -132,7 +132,7 @@ class Photo extends BaseModule
} else { } else {
$photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME); $photoid = pathinfo($this->parameters['name'], PATHINFO_FILENAME);
$scale = 0; $scale = 0;
if (substr($photoid, -2, 1) == "-") { if (substr($photoid, -2, 1) == '-') {
$scale = intval(substr($photoid, -1, 1)); $scale = intval(substr($photoid, -1, 1));
$photoid = substr($photoid, 0, -2); $photoid = substr($photoid, 0, -2);
} }
@ -148,7 +148,7 @@ class Photo extends BaseModule
throw new HTTPException\NotFoundException(); throw new HTTPException\NotFoundException();
} }
$cacheable = ($photo["allow_cid"] . $photo["allow_gid"] . $photo["deny_cid"] . $photo["deny_gid"] === "") && (isset($photo["cacheable"]) ? $photo["cacheable"] : true); $cacheable = ($photo['allow_cid'] . $photo['allow_gid'] . $photo['deny_cid'] . $photo['deny_gid'] === '') && (isset($photo['cacheable']) ? $photo['cacheable'] : true);
$stamp = microtime(true); $stamp = microtime(true);
@ -179,35 +179,35 @@ class Photo extends BaseModule
} }
// if customsize is set and image is not a gif, resize it // if customsize is set and image is not a gif, resize it
if ($photo['type'] !== "image/gif" && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) { if ($photo['type'] !== 'image/gif' && $customsize > 0 && $customsize <= Proxy::PIXEL_THUMB && $square_resize) {
$img = new Image($imgdata, $photo['type']); $img = new Image($imgdata, $photo['type']);
$img->scaleToSquare($customsize); $img->scaleToSquare($customsize);
$imgdata = $img->asString(); $imgdata = $img->asString();
} elseif ($photo['type'] !== "image/gif" && $customsize > 0) { } elseif ($photo['type'] !== 'image/gif' && $customsize > 0) {
$img = new Image($imgdata, $photo['type']); $img = new Image($imgdata, $photo['type']);
$img->scaleDown($customsize); $img->scaleDown($customsize);
$imgdata = $img->asString(); $imgdata = $img->asString();
} }
if (function_exists("header_remove")) { if (function_exists('header_remove')) {
header_remove("Pragma"); header_remove('Pragma');
header_remove("pragma"); header_remove('pragma');
} }
header("Content-type: " . $photo['type']); header('Content-type: ' . $photo['type']);
$stamp = microtime(true); $stamp = microtime(true);
if (!$cacheable) { if (!$cacheable) {
// it is a private photo that they have no permission to view. // it is a private photo that they have no permission to view.
// tell the browser not to cache it, in case they authenticate // tell the browser not to cache it, in case they authenticate
// and subsequently have permission to see it // and subsequently have permission to see it
header("Cache-Control: no-store, no-cache, must-revalidate"); header('Cache-Control: no-store, no-cache, must-revalidate');
} else { } else {
$md5 = $photo['hash'] ?: md5($imgdata); $md5 = $photo['hash'] ?: md5($imgdata);
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT"); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
header("Etag: \"{$md5}\""); header("Etag: \"{$md5}\"");
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT"); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
header("Cache-Control: max-age=31536000"); header('Cache-Control: max-age=31536000');
} }
$checksum = microtime(true) - $stamp; $checksum = microtime(true) - $stamp;

View File

@ -55,17 +55,17 @@ class Proxy extends BaseModule
throw new \Friendica\Network\HTTPException\NotFoundException(); throw new \Friendica\Network\HTTPException\NotFoundException();
} }
if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) { if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT"); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
if (!empty($_SERVER["HTTP_IF_NONE_MATCH"])) { if (!empty($_SERVER['HTTP_IF_NONE_MATCH'])) {
header("Etag: " . $_SERVER["HTTP_IF_NONE_MATCH"]); header('Etag: ' . $_SERVER['HTTP_IF_NONE_MATCH']);
} }
header("Expires: " . gmdate("D, d M Y H:i:s", time() + (31536000)) . " GMT"); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (31536000)) . ' GMT');
header("Cache-Control: max-age=31536000"); header('Cache-Control: max-age=31536000');
if (function_exists("header_remove")) { if (function_exists('header_remove')) {
header_remove("Last-Modified"); header_remove('Last-Modified');
header_remove("Expires"); header_remove('Expires');
header_remove("Cache-Control"); header_remove('Cache-Control');
} }
throw new NotModifiedException(); throw new NotModifiedException();
} }
@ -123,7 +123,7 @@ class Proxy extends BaseModule
* ] * ]
* @throws \Exception * @throws \Exception
*/ */
private function getRequestInfo() private function getRequestInfo(): array
{ {
$size = ProxyUtils::PIXEL_LARGE; $size = ProxyUtils::PIXEL_LARGE;
$sizetype = ''; $sizetype = '';
@ -187,6 +187,7 @@ class Proxy extends BaseModule
* Output the image with cache headers * Output the image with cache headers
* *
* @param Image $img * @param Image $img
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function responseImageHttpCache(Image $img) private static function responseImageHttpCache(Image $img)

View File

@ -32,6 +32,7 @@ use Friendica\Core\L10n;
use Friendica\Core\System; use Friendica\Core\System;
use Friendica\Database\Database; use Friendica\Database\Database;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory;
use Friendica\Model; use Friendica\Model;
use Friendica\Navigation\Notifications\Collection; use Friendica\Navigation\Notifications\Collection;
use Friendica\Navigation\Notifications\Entity; use Friendica\Navigation\Notifications\Entity;
@ -660,7 +661,7 @@ class Notify extends BaseRepository
public function NotifyOnDesktop(Entity\Notification $Notification, string $type = null): bool public function NotifyOnDesktop(Entity\Notification $Notification, string $type = null): bool
{ {
if (is_null($type)) { if (is_null($type)) {
$type = \Friendica\Factory\Api\Mastodon\Notification::getType($Notification); $type = NotificationFactory::getType($Notification);
} }
if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) { if (in_array($Notification->type, [Model\Post\UserNotification::TYPE_FOLLOW, Model\Post\UserNotification::TYPE_SHARED])) {

View File

@ -685,13 +685,13 @@ class Probe
$result = []; $result = [];
if (in_array($network, ["", Protocol::DFRN])) { if (in_array($network, ['', Protocol::DFRN])) {
$result = self::dfrn($webfinger); $result = self::dfrn($webfinger);
} }
if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) { if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
$result = self::diaspora($webfinger); $result = self::diaspora($webfinger);
} }
if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) { if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
$result = self::ostatus($webfinger); $result = self::ostatus($webfinger);
} }
if (in_array($network, ['', Protocol::ZOT])) { if (in_array($network, ['', Protocol::ZOT])) {
@ -788,7 +788,7 @@ class Probe
return $data; return $data;
} }
public static function pollZot($url, $data) public static function pollZot(string $url, array $data): array
{ {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON); $curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
@ -1238,8 +1238,8 @@ class Probe
return []; return [];
} }
if (!isset($data["baseurl"])) { if (!isset($data['baseurl'])) {
$data["baseurl"] = ""; $data['baseurl'] = '';
} }
if ($vcards->length > 0) { if ($vcards->length > 0) {
@ -1248,23 +1248,23 @@ class Probe
// We have to discard the guid from the hcard in favour of the guid from lrdd // We have to discard the guid from the hcard in favour of the guid from lrdd
// Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does. // Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */ $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
if (($search->length > 0) && empty($data["guid"])) { if (($search->length > 0) && empty($data['guid'])) {
$data["guid"] = $search->item(0)->nodeValue; $data['guid'] = $search->item(0)->nodeValue;
} }
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */ $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
if ($search->length > 0) { if ($search->length > 0) {
$data["nick"] = $search->item(0)->nodeValue; $data['nick'] = $search->item(0)->nodeValue;
} }
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */ $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
if ($search->length > 0) { if ($search->length > 0) {
$data["name"] = $search->item(0)->nodeValue; $data['name'] = $search->item(0)->nodeValue;
} }
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */ $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
if ($search->length > 0) { if ($search->length > 0) {
$data["searchable"] = $search->item(0)->nodeValue; $data['searchable'] = $search->item(0)->nodeValue;
} }
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */ $search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
@ -1766,11 +1766,10 @@ class Probe
* *
* @param string $url Profile link * @param string $url Profile link
* @param boolean $probe Do a probe if the page contains a feed link * @param boolean $probe Do a probe if the page contains a feed link
*
* @return array feed data * @return array feed data
* @throws HTTPException\InternalServerErrorException * @throws HTTPException\InternalServerErrorException
*/ */
private static function feed($url, $probe = true) private static function feed(string $url, bool $probe = true): array
{ {
$curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML); $curlResult = DI::httpClient()->get($url, HttpClientAccept::FEED_XML);
if ($curlResult->isTimeout()) { if ($curlResult->isTimeout()) {
@ -1977,7 +1976,7 @@ class Probe
* @param array $data Probing result * @param array $data Probing result
* @return string last activity or true if update was successful or the server was unreachable * @return string last activity or true if update was successful or the server was unreachable
*/ */
private static function updateFromNoScrape(array $data) private static function updateFromNoScrape(array $data): string
{ {
if (empty($data['baseurl'])) { if (empty($data['baseurl'])) {
return ''; return '';

View File

@ -42,6 +42,7 @@ use Friendica\Util\DateTimeFormat;
use Friendica\Util\Proxy; use Friendica\Util\Proxy;
use Friendica\Util\Strings; use Friendica\Util\Strings;
use Friendica\Util\Temporal; use Friendica\Util\Temporal;
use InvalidArgumentException;
/** /**
* An item * An item
@ -124,21 +125,27 @@ class Post
/** /**
* Fetch the privacy of the post * Fetch the privacy of the post
* *
* @param array $item * @param array $item Item record
* @return string * @return string Item privacy message
* @throws InvalidArgumentException If $item['private'] is unknown
*/ */
private function fetchPrivacy(array $item):string private function fetchPrivacy(array $item): string
{ {
switch ($item['private']) { switch ($item['private']) {
case Item::PRIVATE: case Item::PRIVATE:
$output = DI::l10n()->t('Private Message'); $output = DI::l10n()->t('Private Message');
break; break;
case Item::PUBLIC: case Item::PUBLIC:
$output = DI::l10n()->t('Public Message'); $output = DI::l10n()->t('Public Message');
break; break;
case Item::UNLISTED: case Item::UNLISTED:
$output = DI::l10n()->t('Unlisted Message'); $output = DI::l10n()->t('Unlisted Message');
break; break;
default:
throw new InvalidArgumentException('Item privacy ' . $item['privacy'] . ' is unsupported');
} }
return $output; return $output;
@ -151,25 +158,27 @@ class Post
* @param string $formSecurityToken A security Token to avoid CSF attacks * @param string $formSecurityToken A security Token to avoid CSF attacks
* @param integer $thread_level default = 1 * @param integer $thread_level default = 1
* *
* @return mixed The data requested on success * @return mixed The data requested on success, false on failure
* false on failure
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public function getTemplateData(array $conv_responses, string $formSecurityToken, $thread_level = 1) public function getTemplateData(array $conv_responses, string $formSecurityToken, int $thread_level = 1)
{ {
$item = $this->getData(); $item = $this->getData();
$edited = false; $edited = false;
// If the time between "created" and "edited" differs we add
// a notice that the post was edited. /*
// Note: In some networks reshared items seem to have (sometimes) a difference * If the time between "created" and "edited" differs we add
// between creation time and edit time of a second. Thats why we add the notice * a notice that the post was edited.
// only if the difference is more than 1 second. * Note: In some networks reshared items seem to have (sometimes) a difference
* between creation time and edit time of a second. Thats why we add the notice
* only if the difference is more than 1 second.
*/
if (strtotime($item['edited']) - strtotime($item['created']) > 1) { if (strtotime($item['edited']) - strtotime($item['created']) > 1) {
$edited = [ $edited = [
'label' => DI::l10n()->t('This entry was edited'), 'label' => DI::l10n()->t('This entry was edited'),
'date' => DateTimeFormat::local($item['edited'], 'r'), 'date' => DateTimeFormat::local($item['edited'], 'r'),
'relative' => Temporal::getRelativeDate($item['edited']) 'relative' => Temporal::getRelativeDate($item['edited']),
]; ];
} }
$sparkle = ''; $sparkle = '';
@ -184,8 +193,8 @@ class Post
$pin = false; $pin = false;
$star = false; $star = false;
$ignore = false; $ignore = false;
$ispinned = "unpinned"; $ispinned = 'unpinned';
$isstarred = "unstarred"; $isstarred = 'unstarred';
$indent = ''; $indent = '';
$shiny = ''; $shiny = '';
$osparkle = ''; $osparkle = '';
@ -209,10 +218,10 @@ class Post
if (local_user()) { if (local_user()) {
if (Strings::compareLink(Session::get('my_url'), $item['author-link'])) { if (Strings::compareLink(Session::get('my_url'), $item['author-link'])) {
if ($item["event-id"] != 0) { if ($item['event-id'] != 0) {
$edpost = ["events/event/" . $item['event-id'], DI::l10n()->t("Edit")]; $edpost = ['events/event/' . $item['event-id'], DI::l10n()->t('Edit')];
} else { } else {
$edpost = ["editpost/" . $item['id'], DI::l10n()->t("Edit")]; $edpost = ['editpost/' . $item['id'], DI::l10n()->t('Edit')];
} }
} }
$dropping = in_array($item['uid'], [0, local_user()]); $dropping = in_array($item['uid'], [0, local_user()]);
@ -289,6 +298,7 @@ class Post
$response_verbs[] = 'attendyes'; $response_verbs[] = 'attendyes';
$response_verbs[] = 'attendno'; $response_verbs[] = 'attendno';
$response_verbs[] = 'attendmaybe'; $response_verbs[] = 'attendmaybe';
if ($conv->isWritable()) { if ($conv->isWritable()) {
$isevent = true; $isevent = true;
$attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')]; $attend = [DI::l10n()->t('I will attend'), DI::l10n()->t('I will not attend'), DI::l10n()->t('I might attend')];
@ -324,20 +334,20 @@ class Post
'do' => DI::l10n()->t('Ignore thread'), 'do' => DI::l10n()->t('Ignore thread'),
'undo' => DI::l10n()->t('Unignore thread'), 'undo' => DI::l10n()->t('Unignore thread'),
'toggle' => DI::l10n()->t('Toggle ignore status'), 'toggle' => DI::l10n()->t('Toggle ignore status'),
'classdo' => $ignored ? "hidden" : "", 'classdo' => $ignored ? 'hidden' : '',
'classundo' => $ignored ? "" : "hidden", 'classundo' => $ignored ? '' : 'hidden',
'ignored' => DI::l10n()->t('Ignored'), 'ignored' => DI::l10n()->t('Ignored'),
]; ];
} }
$isstarred = (($item['starred']) ? "starred" : "unstarred"); $isstarred = (($item['starred']) ? 'starred' : 'unstarred');
$star = [ $star = [
'do' => DI::l10n()->t('Add star'), 'do' => DI::l10n()->t('Add star'),
'undo' => DI::l10n()->t('Remove star'), 'undo' => DI::l10n()->t('Remove star'),
'toggle' => DI::l10n()->t('Toggle star status'), 'toggle' => DI::l10n()->t('Toggle star status'),
'classdo' => $item['starred'] ? "hidden" : "", 'classdo' => $item['starred'] ? 'hidden' : '',
'classundo' => $item['starred'] ? "" : "hidden", 'classundo' => $item['starred'] ? '' : 'hidden',
'starred' => DI::l10n()->t('Starred'), 'starred' => DI::l10n()->t('Starred'),
]; ];
@ -357,7 +367,7 @@ class Post
$tagger = [ $tagger = [
'add' => DI::l10n()->t('Add tag'), 'add' => DI::l10n()->t('Add tag'),
'class' => "", 'class' => '',
]; ];
} }
} }
@ -402,17 +412,17 @@ class Post
} }
// Disable features that aren't available in several networks // Disable features that aren't available in several networks
if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) { if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
if ($buttons["dislike"]) { if ($buttons['dislike']) {
$buttons["dislike"] = false; $buttons['dislike'] = false;
} }
$isevent = false; $isevent = false;
$tagger = ''; $tagger = '';
} }
if ($buttons["like"] && in_array($item["network"], [Protocol::FEED, Protocol::MAIL])) { if ($buttons['like'] && in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
$buttons["like"] = false; $buttons['like'] = false;
} }
$tags = Tag::populateFromItem($item); $tags = Tag::populateFromItem($item);
@ -453,7 +463,7 @@ class Post
$tmp_item = [ $tmp_item = [
'template' => $this->getTemplate(), 'template' => $this->getTemplate(),
'type' => implode("", array_slice(explode("/", $item['verb']), -1)), 'type' => implode('', array_slice(explode('/', $item['verb']), -1)),
'comment_firstcollapsed' => false, 'comment_firstcollapsed' => false,
'comment_lastcollapsed' => false, 'comment_lastcollapsed' => false,
'suppress_tags' => DI::config()->get('system', 'suppress_tags'), 'suppress_tags' => DI::config()->get('system', 'suppress_tags'),
@ -528,7 +538,7 @@ class Post
'wait' => DI::l10n()->t('Please wait'), 'wait' => DI::l10n()->t('Please wait'),
'thread_level' => $thread_level, 'thread_level' => $thread_level,
'edited' => $edited, 'edited' => $edited,
'network' => $item["network"], 'network' => $item['network'],
'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']), 'network_name' => ContactSelector::networkToName($item['author-network'], $item['author-link'], $item['network'], $item['author-gsid']),
'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']), 'network_icon' => ContactSelector::networkToIcon($item['network'], $item['author-link'], $item['author-gsid']),
'received' => $item['received'], 'received' => $item['received'],
@ -595,7 +605,7 @@ class Post
/** /**
* @return integer * @return integer
*/ */
public function getId() public function getId(): int
{ {
return $this->getDataValue('id'); return $this->getDataValue('id');
} }
@ -603,7 +613,7 @@ class Post
/** /**
* @return boolean * @return boolean
*/ */
public function isThreaded() public function isThreaded(): bool
{ {
return $this->threaded; return $this->threaded;
} }
@ -649,10 +659,9 @@ class Post
* Get a child by its ID * Get a child by its ID
* *
* @param integer $id The child id * @param integer $id The child id
*
* @return mixed * @return mixed
*/ */
public function getChild($id) public function getChild(int $id)
{ {
foreach ($this->getChildren() as $child) { foreach ($this->getChildren() as $child) {
if ($child->getId() == $id) { if ($child->getId() == $id) {
@ -668,7 +677,7 @@ class Post
* *
* @return Post[] * @return Post[]
*/ */
public function getChildren() public function getChildren(): array
{ {
return $this->children; return $this->children;
} }
@ -677,7 +686,6 @@ class Post
* Set our parent * Set our parent
* *
* @param Post $item The item to set as parent * @param Post $item The item to set as parent
*
* @return void * @return void
*/ */
protected function setParent(Post $item) protected function setParent(Post $item)
@ -706,11 +714,10 @@ class Post
* Remove a child * Remove a child
* *
* @param Post $item The child to be removed * @param Post $item The child to be removed
*
* @return boolean Success or failure * @return boolean Success or failure
* @throws \Exception * @throws \Exception
*/ */
public function removeChild(Post $item) public function removeChild(Post $item): bool
{ {
$id = $item->getId(); $id = $item->getId();
foreach ($this->getChildren() as $key => $child) { foreach ($this->getChildren() as $key => $child) {
@ -722,6 +729,7 @@ class Post
return true; return true;
} }
} }
Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').'); Logger::info('[WARN] Item::removeChild : Item is not a child (' . $id . ').');
return false; return false;
} }
@ -739,8 +747,7 @@ class Post
/** /**
* Set conversation thread * Set conversation thread
* *
* @param Thread $thread * @param Thread|null $thread
*
* @return void * @return void
*/ */
public function setThread(Thread $thread = null) public function setThread(Thread $thread = null)
@ -756,7 +763,7 @@ class Post
/** /**
* Get conversation * Get conversation
* *
* @return Thread * @return Thread|null
*/ */
public function getThread() public function getThread()
{ {
@ -770,7 +777,7 @@ class Post
* *
* @return array * @return array
*/ */
public function getData() public function getData(): array
{ {
return $this->data; return $this->data;
} }
@ -779,11 +786,9 @@ class Post
* Get a data value * Get a data value
* *
* @param string $name key * @param string $name key
* * @return mixed value on success, false on failure
* @return mixed value on success
* false on failure
*/ */
public function getDataValue($name) public function getDataValue(string $name)
{ {
if (!isset($this->data[$name])) { if (!isset($this->data[$name])) {
// Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".'); // Logger::info('[ERROR] Item::getDataValue : Item has no value name "'. $name .'".');
@ -796,15 +801,15 @@ class Post
/** /**
* Set template * Set template
* *
* @param string $name template name * @param string $name Template name
* @return bool * @return bool If template was set
* @throws \Exception * @throws InvalidArgumentException
*/ */
private function setTemplate($name) private function setTemplate(string $name): bool
{ {
if (empty($this->available_templates[$name])) { if (empty($this->available_templates[$name])) {
Logger::info('[ERROR] Item::setTemplate : Template not available ("' . $name . '").'); // Throw exception
return false; throw new InvalidArgumentException('[ERROR] Item::setTemplate : Template not available ("' . $name . '").');
} }
$this->template = $this->available_templates[$name]; $this->template = $this->available_templates[$name];
@ -827,7 +832,7 @@ class Post
* *
* @return boolean * @return boolean
*/ */
private function isToplevel() private function isToplevel(): bool
{ {
return $this->toplevel; return $this->toplevel;
} }
@ -837,7 +842,7 @@ class Post
* *
* @return boolean * @return boolean
*/ */
private function isWritable() private function isWritable(): bool
{ {
$conv = $this->getThread(); $conv = $this->getThread();
@ -860,7 +865,7 @@ class Post
* *
* @return integer * @return integer
*/ */
private function countDescendants() private function countDescendants(): int
{ {
$children = $this->getChildren(); $children = $this->getChildren();
$total = count($children); $total = count($children);
@ -878,7 +883,7 @@ class Post
* *
* @return string * @return string
*/ */
private function getCommentBoxTemplate() private function getCommentBoxTemplate(): string
{ {
return $this->comment_box_template; return $this->comment_box_template;
} }
@ -889,7 +894,7 @@ class Post
* @return string * @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private function getDefaultText() private function getDefaultText(): string
{ {
$a = DI::app(); $a = DI::app();
@ -935,12 +940,11 @@ class Post
* Get the comment box * Get the comment box
* *
* @param string $indent Indent value * @param string $indent Indent value
* * @return mixed The comment box string (empty if no comment box), false on failure
* @return mixed The comment box string (empty if no comment box)
* false on failure
* @throws \Exception * @throws \Exception
* @todo return false is nowhere in this method?
*/ */
private function getCommentBox($indent) private function getCommentBox(string $indent)
{ {
$a = DI::app(); $a = DI::app();
@ -1033,21 +1037,24 @@ class Post
$owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name')); $owner_namematch = (($this->getDataValue('owner-name')) && $this->getDataValue('owner-name') == $this->getDataValue('author-name'));
if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) { if (!$owner_linkmatch && !$alias_linkmatch && !$owner_namematch) {
// The author url doesn't match the owner (typically the contact) /*
// and also doesn't match the contact alias. * The author url doesn't match the owner (typically the contact)
// The name match is a hack to catch several weird cases where URLs are * and also doesn't match the contact alias.
// all over the park. It can be tricked, but this prevents you from * The name match is a hack to catch several weird cases where URLs are
// seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn * all over the park. It can be tricked, but this prevents you from
// well that it's the same Bob Smith. * seeing "Bob Smith to Bob Smith via Wall-to-wall" and you know darn
// But it could be somebody else with the same name. It just isn't highly likely. * well that it's the same Bob Smith.
* But it could be somebody else with the same name. It just isn't highly likely.
*/
$this->owner_name = $this->getDataValue('owner-name'); $this->owner_name = $this->getDataValue('owner-name');
$this->wall_to_wall = true; $this->wall_to_wall = true;
$owner = ['uid' => 0, 'id' => $this->getDataValue('owner-id'), $owner = [
'uid' => 0,
'id' => $this->getDataValue('owner-id'),
'network' => $this->getDataValue('owner-network'), 'network' => $this->getDataValue('owner-network'),
'url' => $this->getDataValue('owner-link')]; 'url' => $this->getDataValue('owner-link'),
];
$this->owner_url = Contact::magicLinkByContact($owner); $this->owner_url = Contact::magicLinkByContact($owner);
} }
} }
@ -1064,7 +1071,7 @@ class Post
/** /**
* @return boolean * @return boolean
*/ */
private function isWallToWall() private function isWallToWall(): bool
{ {
return $this->wall_to_wall; return $this->wall_to_wall;
} }
@ -1072,7 +1079,7 @@ class Post
/** /**
* @return string * @return string
*/ */
private function getOwnerUrl() private function getOwnerUrl(): string
{ {
return $this->owner_url; return $this->owner_url;
} }
@ -1080,7 +1087,7 @@ class Post
/** /**
* @return string * @return string
*/ */
private function getOwnerName() private function getOwnerName(): string
{ {
return $this->owner_name; return $this->owner_name;
} }
@ -1088,7 +1095,7 @@ class Post
/** /**
* @return boolean * @return boolean
*/ */
private function isVisiting() private function isVisiting(): bool
{ {
return $this->visiting; return $this->visiting;
} }

View File

@ -83,7 +83,7 @@ class ActivityPub
* *
* @return bool is it AP? * @return bool is it AP?
*/ */
public static function isRequest() public static function isRequest(): bool
{ {
$isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') || $isrequest = stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') || stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') ||
@ -202,6 +202,7 @@ class ActivityPub
* *
* @param string $url * @param string $url
* @param integer $uid User ID * @param integer $uid User ID
* @return void
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function fetchOutbox(string $url, int $uid) public static function fetchOutbox(string $url, int $uid)
@ -268,7 +269,7 @@ class ActivityPub
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException * @throws \ImagickException
*/ */
public static function isSupportedByContactUrl(string $url, $update = null) public static function isSupportedByContactUrl(string $url, $update = null): bool
{ {
return !empty(APContact::getByURL($url, $update)); return !empty(APContact::getByURL($url, $update));
} }

View File

@ -2244,7 +2244,7 @@ class Transmitter
* Prepends mentions (@) to $body variable * Prepends mentions (@) to $body variable
* *
* @param string $body HTML code * @param string $body HTML code
* @param int $uriid URI id * @param int $uriId
* @param string $authorLink Author link * @param string $authorLink Author link
* @return string HTML code with prepended mentions * @return string HTML code with prepended mentions
*/ */

View File

@ -1211,7 +1211,7 @@ class OStatus
* Cleans the body of a post if it contains picture links * Cleans the body of a post if it contains picture links
* *
* @param string $body The body * @param string $body The body
* @param integer $uriid URI id * @param integer $uriId
* @return string The cleaned body * @return string The cleaned body
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */

View File

@ -179,7 +179,7 @@ class Images
/** /**
* Gets info array from given URL, cached data has priority * Gets info array from given URL, cached data has priority
* *
* @param string $url URL * @param string $url
* @return array Info * @return array Info
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
@ -207,7 +207,7 @@ class Images
/** /**
* Gets info from URL uncached * Gets info from URL uncached
* *
* @param string $url URL * @param string $url
* @return array Info array * @return array Info array
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */

View File

@ -82,7 +82,7 @@ class Network
* @param string $addr The email address * @param string $addr The email address
* @return boolean True if it's a valid email address, false if it's not * @return boolean True if it's a valid email address, false if it's not
*/ */
public static function isEmailDomainValid(string $addr) public static function isEmailDomainValid(string $addr): bool
{ {
if (DI::config()->get('system', 'disable_email_validation')) { if (DI::config()->get('system', 'disable_email_validation')) {
return true; return true;
@ -113,7 +113,7 @@ class Network
* @param string $url URL which get tested * @param string $url URL which get tested
* @return boolean True if url is allowed otherwise return false * @return boolean True if url is allowed otherwise return false
*/ */
public static function isUrlAllowed(string $url) public static function isUrlAllowed(string $url): bool
{ {
$h = @parse_url($url); $h = @parse_url($url);
@ -158,7 +158,7 @@ class Network
* *
* @return boolean * @return boolean
*/ */
public static function isUrlBlocked(string $url) public static function isUrlBlocked(string $url): bool
{ {
$host = @parse_url($url, PHP_URL_HOST); $host = @parse_url($url, PHP_URL_HOST);
if (!$host) { if (!$host) {
@ -187,7 +187,7 @@ class Network
* *
* @return boolean * @return boolean
*/ */
public static function isRedirectBlocked(string $url) public static function isRedirectBlocked(string $url): bool
{ {
$host = @parse_url($url, PHP_URL_HOST); $host = @parse_url($url, PHP_URL_HOST);
if (!$host) { if (!$host) {
@ -218,7 +218,7 @@ class Network
* or if allowed list is not configured * or if allowed list is not configured
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function isEmailDomainAllowed(string $email) public static function isEmailDomainAllowed(string $email): bool
{ {
$domain = strtolower(substr($email, strpos($email, '@') + 1)); $domain = strtolower(substr($email, strpos($email, '@') + 1));
if (!$domain) { if (!$domain) {
@ -242,7 +242,7 @@ class Network
* @param array $domain_list * @param array $domain_list
* @return boolean * @return boolean
*/ */
public static function isDomainAllowed(string $domain, array $domain_list) public static function isDomainAllowed(string $domain, array $domain_list): bool
{ {
$found = false; $found = false;
@ -257,7 +257,7 @@ class Network
return $found; return $found;
} }
public static function lookupAvatarByEmail(string $email) public static function lookupAvatarByEmail(string $email): string
{ {
$avatar['size'] = 300; $avatar['size'] = 300;
$avatar['email'] = $email; $avatar['email'] = $email;
@ -280,11 +280,12 @@ class Network
* @param string $url Any user-submitted URL that may contain tracking params * @param string $url Any user-submitted URL that may contain tracking params
* @return string The same URL stripped of tracking parameters * @return string The same URL stripped of tracking parameters
*/ */
public static function stripTrackingQueryParams(string $url) public static function stripTrackingQueryParams(string $url): string
{ {
$urldata = parse_url($url); $urldata = parse_url($url);
if (!empty($urldata["query"])) {
$query = $urldata["query"]; if (!empty($urldata['query'])) {
$query = $urldata['query'];
parse_str($query, $querydata); parse_str($query, $querydata);
if (is_array($querydata)) { if (is_array($querydata)) {
@ -292,30 +293,32 @@ class Network
if (in_array( if (in_array(
$param, $param,
[ [
"utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign", 'utm_source', 'utm_medium', 'utm_term', 'utm_content', 'utm_campaign',
"wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid", // As seen from Purism
"fb_action_ids", "fb_action_types", "fb_ref", 'mtm_source', 'mtm_medium', 'mtm_term', 'mtm_content', 'mtm_campaign',
"awesm", "wtrid", 'wt_mc', 'pk_campaign', 'pk_kwd', 'mc_cid', 'mc_eid',
"woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"] 'fb_action_ids', 'fb_action_types', 'fb_ref',
'awesm', 'wtrid',
'woo_campaign', 'woo_source', 'woo_medium', 'woo_content', 'woo_term']
) )
) { ) {
$pair = $param . "=" . urlencode($value); $pair = $param . '=' . urlencode($value);
$url = str_replace($pair, "", $url); $url = str_replace($pair, '', $url);
// Second try: if the url isn't encoded completely // Second try: if the url isn't encoded completely
$pair = $param . "=" . str_replace(" ", "+", $value); $pair = $param . '=' . str_replace(' ', '+', $value);
$url = str_replace($pair, "", $url); $url = str_replace($pair, '', $url);
// Third try: Maybey the url isn't encoded at all // Third try: Maybey the url isn't encoded at all
$pair = $param . "=" . $value; $pair = $param . '=' . $value;
$url = str_replace($pair, "", $url); $url = str_replace($pair, '', $url);
$url = str_replace(["?&", "&&"], ["?", ""], $url); $url = str_replace(['?&', '&&'], ['?', ''], $url);
} }
} }
} }
if (substr($url, -1, 1) == "?") { if (substr($url, -1, 1) == '?') {
$url = substr($url, 0, -1); $url = substr($url, 0, -1);
} }
} }
@ -336,8 +339,10 @@ class Network
return $url; return $url;
} }
$base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME), $base = [
'host' => parse_url($basepath, PHP_URL_HOST)]; 'scheme' => parse_url($basepath, PHP_URL_SCHEME),
'host' => parse_url($basepath, PHP_URL_HOST),
];
$parts = array_merge($base, parse_url('/' . ltrim($url, '/'))); $parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
return self::unparseURL($parts); return self::unparseURL($parts);
@ -348,12 +353,12 @@ class Network
* *
* @param string $url1 * @param string $url1
* @param string $url2 * @param string $url2
* @return string The matching part * @return string The matching part or empty string on error
*/ */
public static function getUrlMatch(string $url1, string $url2) public static function getUrlMatch(string $url1, string $url2): string
{ {
if (($url1 == "") || ($url2 == "")) { if (($url1 == '') || ($url2 == '')) {
return ""; return '';
} }
$url1 = Strings::normaliseLink($url1); $url1 = Strings::normaliseLink($url1);
@ -362,67 +367,67 @@ class Network
$parts1 = parse_url($url1); $parts1 = parse_url($url1);
$parts2 = parse_url($url2); $parts2 = parse_url($url2);
if (!isset($parts1["host"]) || !isset($parts2["host"])) { if (!isset($parts1['host']) || !isset($parts2['host'])) {
return ""; return '';
} }
if (empty($parts1["scheme"])) { if (empty($parts1['scheme'])) {
$parts1["scheme"] = ''; $parts1['scheme'] = '';
} }
if (empty($parts2["scheme"])) { if (empty($parts2['scheme'])) {
$parts2["scheme"] = ''; $parts2['scheme'] = '';
} }
if ($parts1["scheme"] != $parts2["scheme"]) { if ($parts1['scheme'] != $parts2['scheme']) {
return ""; return '';
} }
if (empty($parts1["host"])) { if (empty($parts1['host'])) {
$parts1["host"] = ''; $parts1['host'] = '';
} }
if (empty($parts2["host"])) { if (empty($parts2['host'])) {
$parts2["host"] = ''; $parts2['host'] = '';
} }
if ($parts1["host"] != $parts2["host"]) { if ($parts1['host'] != $parts2['host']) {
return ""; return '';
} }
if (empty($parts1["port"])) { if (empty($parts1['port'])) {
$parts1["port"] = ''; $parts1['port'] = '';
} }
if (empty($parts2["port"])) { if (empty($parts2['port'])) {
$parts2["port"] = ''; $parts2['port'] = '';
} }
if ($parts1["port"] != $parts2["port"]) { if ($parts1['port'] != $parts2['port']) {
return ""; return '';
} }
$match = $parts1["scheme"]."://".$parts1["host"]; $match = $parts1['scheme'] . '://' . $parts1['host'];
if ($parts1["port"]) { if ($parts1['port']) {
$match .= ":".$parts1["port"]; $match .= ':' . $parts1['port'];
} }
if (empty($parts1["path"])) { if (empty($parts1['path'])) {
$parts1["path"] = ''; $parts1['path'] = '';
} }
if (empty($parts2["path"])) { if (empty($parts2['path'])) {
$parts2["path"] = ''; $parts2['path'] = '';
} }
$pathparts1 = explode("/", $parts1["path"]); $pathparts1 = explode('/', $parts1['path']);
$pathparts2 = explode("/", $parts2["path"]); $pathparts2 = explode('/', $parts2['path']);
$i = 0; $i = 0;
$path = ""; $path = '';
do { do {
$path1 = $pathparts1[$i] ?? ''; $path1 = $pathparts1[$i] ?? '';
$path2 = $pathparts2[$i] ?? ''; $path2 = $pathparts2[$i] ?? '';
if ($path1 == $path2) { if ($path1 == $path2) {
$path .= $path1."/"; $path .= $path1 . '/';
} }
} while (($path1 == $path2) && ($i++ <= count($pathparts1))); } while (($path1 == $path2) && ($i++ <= count($pathparts1)));
@ -435,11 +440,10 @@ class Network
* Glue url parts together * Glue url parts together
* *
* @param array $parsed URL parts * @param array $parsed URL parts
* * @return string|null The glued URL or null on error
* @return string The glued URL.
* @deprecated since version 2021.12, use GuzzleHttp\Psr7\Uri::fromParts($parts) instead * @deprecated since version 2021.12, use GuzzleHttp\Psr7\Uri::fromParts($parts) instead
*/ */
public static function unparseURL(array $parsed) public static function unparseURL(array $parsed): string
{ {
$get = function ($key) use ($parsed) { $get = function ($key) use ($parsed) {
return isset($parsed[$key]) ? $parsed[$key] : null; return isset($parsed[$key]) ? $parsed[$key] : null;
@ -452,15 +456,15 @@ class Network
$scheme = $get('scheme'); $scheme = $get('scheme');
$query = $get('query'); $query = $get('query');
$fragment = $get('fragment'); $fragment = $get('fragment');
$authority = ($userinfo !== null ? $userinfo."@" : '') . $authority = ($userinfo !== null ? $userinfo . '@' : '') .
$get('host') . $get('host') .
($port ? ":$port" : ''); ($port ? ":$port" : '');
return (strlen($scheme) ? $scheme.":" : '') . return (strlen($scheme) ? $scheme . ':' : '') .
(strlen($authority) ? "//".$authority : '') . (strlen($authority) ? '//' . $authority : '') .
$get('path') . $get('path') .
(strlen($query) ? "?".$query : '') . (strlen($query) ? '?' . $query : '') .
(strlen($fragment) ? "#".$fragment : ''); (strlen($fragment) ? '#' . $fragment : '');
} }
/** /**
@ -490,11 +494,10 @@ class Network
/** /**
* Switch the scheme of an url between http and https * Switch the scheme of an url between http and https
* *
* @param string $url URL * @param string $url
* * @return string Switched URL
* @return string switched URL
*/ */
public static function switchScheme(string $url) public static function switchScheme(string $url): string
{ {
$scheme = parse_url($url, PHP_URL_SCHEME); $scheme = parse_url($url, PHP_URL_SCHEME);
if (empty($scheme)) { if (empty($scheme)) {
@ -517,7 +520,7 @@ class Network
* @param array $additionalParams Associative array of parameters * @param array $additionalParams Associative array of parameters
* @return string * @return string
*/ */
public static function appendQueryParam(string $path, array $additionalParams) public static function appendQueryParam(string $path, array $additionalParams): string
{ {
$parsed = parse_url($path); $parsed = parse_url($path);
@ -541,6 +544,7 @@ class Network
* *
* @param string $etag The page etag * @param string $etag The page etag
* @param string $last_modified The page last modification UTC date * @param string $last_modified The page last modification UTC date
* @return void
* @throws \Exception * @throws \Exception
*/ */
public static function checkEtagModified(string $etag, string $last_modified) public static function checkEtagModified(string $etag, string $last_modified)
@ -577,10 +581,10 @@ class Network
/** /**
* Check if the given URL is a local link * Check if the given URL is a local link
* *
* @param string $url * @param string $url
* @return bool * @return bool
*/ */
public static function isLocalLink(string $url) public static function isLocalLink(string $url): bool
{ {
return (strpos(Strings::normaliseLink($url), Strings::normaliseLink(DI::baseUrl())) !== false); return (strpos(Strings::normaliseLink($url), Strings::normaliseLink(DI::baseUrl())) !== false);
} }
@ -588,10 +592,10 @@ class Network
/** /**
* Check if the given URL is a valid HTTP/HTTPS URL * Check if the given URL is a valid HTTP/HTTPS URL
* *
* @param string $url * @param string $url
* @return bool * @return bool
*/ */
public static function isValidHttpUrl(string $url) public static function isValidHttpUrl(string $url): bool
{ {
$scheme = parse_url($url, PHP_URL_SCHEME); $scheme = parse_url($url, PHP_URL_SCHEME);
return !empty($scheme) && in_array($scheme, ['http', 'https']) && parse_url($url, PHP_URL_HOST); return !empty($scheme) && in_array($scheme, ['http', 'https']) && parse_url($url, PHP_URL_HOST);

View File

@ -76,11 +76,10 @@ class Proxy
* *
* @param string $url The URL to proxyfy * @param string $url The URL to proxyfy
* @param string $size One of the Proxy::SIZE_* constants * @param string $size One of the Proxy::SIZE_* constants
*
* @return string The proxyfied URL or relative path * @return string The proxyfied URL or relative path
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function proxifyUrl($url, $size = '') public static function proxifyUrl(string $url, string $size = ''): string
{ {
if (!DI::config()->get('system', 'proxify_content')) { if (!DI::config()->get('system', 'proxify_content')) {
return $url; return $url;
@ -133,11 +132,10 @@ class Proxy
* proxy storage directory. * proxy storage directory.
* *
* @param string $html Un-proxified HTML code * @param string $html Un-proxified HTML code
*
* @return string Proxified HTML code * @return string Proxified HTML code
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function proxifyHtml($html) public static function proxifyHtml(string $html): string
{ {
$html = str_replace(Strings::normaliseLink(DI::baseUrl()) . '/', DI::baseUrl() . '/', $html); $html = str_replace(Strings::normaliseLink(DI::baseUrl()) . '/', DI::baseUrl() . '/', $html);
@ -151,7 +149,7 @@ class Proxy
* @return boolean * @return boolean
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
public static function isLocalImage($url) public static function isLocalImage(string $url): bool
{ {
if (substr($url, 0, 1) == '/') { if (substr($url, 0, 1) == '/') {
return true; return true;
@ -170,7 +168,7 @@ class Proxy
* @param string $url URL to parse * @param string $url URL to parse
* @return array Associative array of query string parameters * @return array Associative array of query string parameters
*/ */
private static function parseQuery($url) private static function parseQuery(string $url): array
{ {
$query = parse_url($url, PHP_URL_QUERY); $query = parse_url($url, PHP_URL_QUERY);
$query = html_entity_decode($query); $query = html_entity_decode($query);
@ -187,7 +185,7 @@ class Proxy
* @return string Proxified HTML image tag * @return string Proxified HTML image tag
* @throws \Friendica\Network\HTTPException\InternalServerErrorException * @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/ */
private static function replaceUrl(array $matches) private static function replaceUrl(array $matches): string
{ {
// if the picture seems to be from another picture cache then take the original source // if the picture seems to be from another picture cache then take the original source
$queryvar = self::parseQuery($matches[2]); $queryvar = self::parseQuery($matches[2]);

View File

@ -38,7 +38,7 @@ class XML
* Creates an XML structure out of a given array * Creates an XML structure out of a given array
* *
* @param array $array The array of the XML structure that will be generated * @param array $array The array of the XML structure that will be generated
* @param object $xml The createdXML will be returned by reference * @param object $xml The created XML will be returned by reference
* @param bool $remove_header Should the XML header be removed or not? * @param bool $remove_header Should the XML header be removed or not?
* @param array $namespaces List of namespaces * @param array $namespaces List of namespaces
* @param bool $root interally used parameter. Mustn't be used from outside. * @param bool $root interally used parameter. Mustn't be used from outside.
@ -177,22 +177,21 @@ class XML
/** /**
* Create an XML and append it to the parent object * 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 DOMElement $parent parent object
* @param string $element XML element name * @param string $element XML element name
* @param string $value XML value * @param string $value XML value
* @param array $attributes array containing the attributes * @param array $attributes Array containing the attributes
* @return void * @return void
*/ */
public static function addElement(DOMDocument $doc, $parent, string $element, string $value = '', array $attributes = []) public static function addElement(DOMDocument $doc, DOMElement &$parent, string $element, string $value = '', array $attributes = [])
{ {
$element = self::createElement($doc, $element, $value, $attributes); $element = self::createElement($doc, $element, $value, $attributes);
$parent->appendChild($element); $parent->appendChild($element);
} }
/** /**
* Convert an XML document to a normalised, case-corrected array * Convert an XML document to a normalised, case-corrected array used by webfinger
* used by webfinger
* *
* @param object $xml_element The XML document * @param object $xml_element The XML document
* @param integer $recursion_depth recursion counter for internal use - default 0 * @param integer $recursion_depth recursion counter for internal use - default 0
@ -204,7 +203,7 @@ class XML
{ {
// If we're getting too deep, bail out // If we're getting too deep, bail out
if ($recursion_depth > 512) { if ($recursion_depth > 512) {
return(null); return null;
} }
$xml_element_copy = ''; $xml_element_copy = '';

View File

@ -31,7 +31,14 @@ use Friendica\Protocol\ActivityPub;
* Send updated profile data to Diaspora and ActivityPub * Send updated profile data to Diaspora and ActivityPub
*/ */
class ProfileUpdate { class ProfileUpdate {
public static function execute($uid = 0) { /**
* Sends updated profile data to Diaspora and ActivityPub
*
* @param int $uid User id (optional, default: 0)
* @return void
*/
public static function execute(int $uid = 0)
{
if (empty($uid)) { if (empty($uid)) {
return; return;
} }
@ -43,7 +50,13 @@ class ProfileUpdate {
foreach ($inboxes as $inbox => $receivers) { foreach ($inboxes as $inbox => $receivers) {
Logger::info('Profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub'); Logger::info('Profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub');
Worker::add(['priority' => $a->getQueueValue('priority'), 'created' => $a->getQueueValue('created'), 'dont_fork' => true], Worker::add(['priority' => $a->getQueueValue('priority'), 'created' => $a->getQueueValue('created'), 'dont_fork' => true],
'APDelivery', Delivery::PROFILEUPDATE, 0, $inbox, $uid, $receivers); 'APDelivery',
Delivery::PROFILEUPDATE,
0,
$inbox,
$uid,
$receivers
);
} }
Diaspora::sendProfile($uid); Diaspora::sendProfile($uid);

View File

@ -29,7 +29,13 @@ use Friendica\Protocol\OStatus;
class PubSubPublish class PubSubPublish
{ {
public static function execute($pubsubpublish_id = 0) /**
* Publishes subscriber id
*
* @param int $pubsubpublish_id Push subscriber id
* @return void
*/
public static function execute(int $pubsubpublish_id = 0)
{ {
if ($pubsubpublish_id == 0) { if ($pubsubpublish_id == 0) {
return; return;
@ -38,7 +44,13 @@ class PubSubPublish
self::publish($pubsubpublish_id); self::publish($pubsubpublish_id);
} }
private static function publish($id) /**
* Publishes push subscriber
*
* @param int $id Push subscriber id
* @return void
*/
private static function publish(int $id)
{ {
$subscriber = DBA::selectFirst('push_subscriber', [], ['id' => $id]); $subscriber = DBA::selectFirst('push_subscriber', [], ['id' => $id]);
if (!DBA::isResult($subscriber)) { if (!DBA::isResult($subscriber)) {
@ -48,7 +60,7 @@ class PubSubPublish
/// @todo Check server status with GServer::check() /// @todo Check server status with GServer::check()
// Before this can be done we need a way to safely detect the server url. // Before this can be done we need a way to safely detect the server url.
Logger::info("Generate feed of user " . $subscriber['nickname']. " to " . $subscriber['callback_url']. " - last updated " . $subscriber['last_update']); Logger::info('Generate feed of user ' . $subscriber['nickname'] . ' to ' . $subscriber['callback_url'] . ' - last updated ' . $subscriber['last_update']);
$last_update = $subscriber['last_update']; $last_update = $subscriber['last_update'];
$params = OStatus::feed($subscriber['nickname'], $last_update); $params = OStatus::feed($subscriber['nickname'], $last_update);
@ -57,11 +69,11 @@ class PubSubPublish
return; return;
} }
$hmac_sig = hash_hmac("sha1", $params, $subscriber['secret']); $hmac_sig = hash_hmac('sha1', $params, $subscriber['secret']);
$headers = [ $headers = [
'Content-type' => 'application/atom+xml', 'Content-type' => 'application/atom+xml',
'Link' => sprintf("<%s>;rel=hub,<%s>;rel=self", 'Link' => sprintf('<%s>;rel=hub,<%s>;rel=self',
DI::baseUrl() . '/pubsubhubbub/' . $subscriber['nickname'], DI::baseUrl() . '/pubsubhubbub/' . $subscriber['nickname'],
$subscriber['topic']), $subscriber['topic']),
'X-Hub-Signature' => 'sha1=' . $hmac_sig]; 'X-Hub-Signature' => 'sha1=' . $hmac_sig];

View File

@ -26,6 +26,7 @@ use Friendica\Content\Text\Plaintext;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Database\DBA; use Friendica\Database\DBA;
use Friendica\DI; use Friendica\DI;
use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory;
use Friendica\Model\Contact; use Friendica\Model\Contact;
use Friendica\Model\Post; use Friendica\Model\Post;
use Friendica\Model\Subscription as ModelSubscription; use Friendica\Model\Subscription as ModelSubscription;
@ -37,6 +38,13 @@ use Minishlink\WebPush\Subscription;
class PushSubscription class PushSubscription
{ {
/**
* Creates push subscription by subscription and notification ids
*
* @param int $sid Subscription id
* @param int $nid Notification id
* @return void
*/
public static function execute(int $sid, int $nid) public static function execute(int $sid, int $nid)
{ {
Logger::info('Start', ['subscription' => $sid, 'notification' => $nid]); Logger::info('Start', ['subscription' => $sid, 'notification' => $nid]);
@ -48,7 +56,7 @@ class PushSubscription
} }
try { try {
$Notification = DI::notification()->selectOneById($nid); $notification = DI::notification()->selectOneById($nid);
} catch (NotFoundException $e) { } catch (NotFoundException $e) {
Logger::info('Notification not found', ['notification' => $nid]); Logger::info('Notification not found', ['notification' => $nid]);
return; return;
@ -60,7 +68,7 @@ class PushSubscription
return; return;
} }
$user = User::getById($Notification->uid); $user = User::getById($notification->uid);
if (empty($user)) { if (empty($user)) {
Logger::info('User not found', ['application' => $subscription['uid']]); Logger::info('User not found', ['application' => $subscription['uid']]);
return; return;
@ -68,21 +76,21 @@ class PushSubscription
$l10n = DI::l10n()->withLang($user['language']); $l10n = DI::l10n()->withLang($user['language']);
if ($Notification->actorId) { if ($notification->actorId) {
$actor = Contact::getById($Notification->actorId); $actor = Contact::getById($notification->actorId);
} }
$body = ''; $body = '';
if ($Notification->targetUriId) { if ($notification->targetUriId) {
$post = Post::selectFirst([], ['uri-id' => $Notification->targetUriId, 'uid' => [0, $Notification->uid]]); $post = Post::selectFirst([], ['uri-id' => $notification->targetUriId, 'uid' => [0, $notification->uid]]);
if (!empty($post['body'])) { if (!empty($post['body'])) {
$body = BBCode::toPlaintext($post['body'], false); $body = BBCode::toPlaintext($post['body'], false);
$body = Plaintext::shorten($body, 160, $Notification->uid); $body = Plaintext::shorten($body, 160, $notification->uid);
} }
} }
$message = DI::notificationFactory()->getMessageFromNotification($Notification); $message = DI::notificationFactory()->getMessageFromNotification($notification);
$title = $message['plain'] ?: ''; $title = $message['plain'] ?: '';
$push = Subscription::create([ $push = Subscription::create([
@ -94,11 +102,12 @@ class PushSubscription
], ],
]); ]);
// @todo Only used for logging?
$payload = [ $payload = [
'access_token' => $application_token['access_token'], 'access_token' => $application_token['access_token'],
'preferred_locale' => $user['language'], 'preferred_locale' => $user['language'],
'notification_id' => $nid, 'notification_id' => $nid,
'notification_type' => \Friendica\Factory\Api\Mastodon\Notification::getType($Notification), 'notification_type' => NotificationFactory::getType($notification),
'icon' => $actor['thumb'] ?? '', 'icon' => $actor['thumb'] ?? '',
'title' => $title ?: $l10n->t('Notification from Friendica'), 'title' => $title ?: $l10n->t('Notification from Friendica'),
'body' => $body ?: $l10n->t('Empty Post'), 'body' => $body ?: $l10n->t('Empty Post'),

View File

@ -29,7 +29,13 @@ use Friendica\Model\Post;
* Removes orphaned data from deleted users * Removes orphaned data from deleted users
*/ */
class RemoveUser { class RemoveUser {
public static function execute($uid) /**
* Removes user by id
*
* @param int $uid User id
* @return void
*/
public static function execute(int $uid)
{ {
// Only delete if the user is archived // Only delete if the user is archived
$condition = ['account_removed' => true, 'uid' => $uid]; $condition = ['account_removed' => true, 'uid' => $uid];

View File

@ -28,9 +28,11 @@ class UpdateContact
{ {
/** /**
* Update contact data via probe * Update contact data via probe
*
* @param int $contact_id Contact ID * @param int $contact_id Contact ID
* @return void
*/ */
public static function execute($contact_id) public static function execute(int $contact_id)
{ {
$success = Contact::updateFromProbe($contact_id); $success = Contact::updateFromProbe($contact_id);

View File

@ -102,7 +102,7 @@ class UpdateContacts
* @param array $ids * @param array $ids
* @return array contact ids * @return array contact ids
*/ */
private static function getContactsToUpdate(array $condition, int $limit, array $ids = []) private static function getContactsToUpdate(array $condition, int $limit, array $ids = []): array
{ {
$contacts = DBA::select('contact', ['id'], $condition, ['limit' => $limit]); $contacts = DBA::select('contact', ['id'], $condition, ['limit' => $limit]);
while ($contact = DBA::fetch($contacts)) { while ($contact = DBA::fetch($contacts)) {

View File

@ -30,8 +30,10 @@ class UpdateGServer
{ {
/** /**
* Update the given server * Update the given server
*
* @param string $server_url Server URL * @param string $server_url Server URL
* @param boolean $only_nodeinfo Only use nodeinfo for server detection * @param boolean $only_nodeinfo Only use nodeinfo for server detection
* @return void
*/ */
public static function execute(string $server_url, bool $only_nodeinfo = false) public static function execute(string $server_url, bool $only_nodeinfo = false)
{ {

View File

@ -32,7 +32,9 @@ class UpdateServerPeers
{ {
/** /**
* Query the given server for their known peers * Query the given server for their known peers
*
* @param string $gserver Server URL * @param string $gserver Server URL
* @return void
*/ */
public static function execute(string $url) public static function execute(string $url)
{ {

View File

@ -17,7 +17,7 @@
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
* *
* Automatic post-databse structure change updates * Automatic post-database structure change updates
* *
* These functions are responsible for doing critical post update changes to the data (not the structure) in the database. * These functions are responsible for doing critical post update changes to the data (not the structure) in the database.
* *
@ -40,8 +40,10 @@
* If you need to run a script before the database update, name the function "pre_update_4712()" * If you need to run a script before the database update, name the function "pre_update_4712()"
*/ */
use Friendica\Core\Config\ValueObject\Cache;
use Friendica\Core\Logger; use Friendica\Core\Logger;
use Friendica\Core\Storage\Capability\ICanReadFromStorage; use Friendica\Core\Storage\Capability\ICanReadFromStorage;
use Friendica\Core\Storage\Type\Database as DatabaseStorage;
use Friendica\Core\Update; use Friendica\Core\Update;
use Friendica\Core\Worker; use Friendica\Core\Worker;
use Friendica\Database\Database; use Friendica\Database\Database;
@ -988,9 +990,9 @@ function update_1434()
{ {
$name = DI::config()->get('storage', 'name'); $name = DI::config()->get('storage', 'name');
// in case of an empty config, set "Database" as default storage backend // In case of an empty config, set "Database" as default storage backend
if (empty($name)) { if (empty($name)) {
DI::config()->set('storage', 'name', \Friendica\Core\Storage\Type\Database::getName()); DI::config()->set('storage', 'name', DatabaseStorage::getName());
} }
// In case of a Using deprecated storage class value, set the right name for it // In case of a Using deprecated storage class value, set the right name for it
@ -1079,10 +1081,7 @@ function update_1446()
// In case the distributed cache driver is the default value, but the current cache driver isn't default, // In case the distributed cache driver is the default value, but the current cache driver isn't default,
// we assume that the distributed cache driver should be the same as the current cache driver // we assume that the distributed cache driver should be the same as the current cache driver
if ( if ($distributed_cache_driver_source === Cache::SOURCE_STATIC && $cache_driver_source > Cache::SOURCE_STATIC) {
$distributed_cache_driver_source === \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC
&& $cache_driver_source > \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC
) {
DI::config()->set('system', 'distributed_cache_driver', DI::config()->get('system', 'cache_driver')); DI::config()->set('system', 'distributed_cache_driver', DI::config()->get('system', 'cache_driver'));
} }