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
if (!defined("SIGTERM")) {
define("SIGTERM", 15);
if (!defined('SIGTERM')) {
define('SIGTERM', 15);
}
/**
@ -117,6 +117,7 @@ function local_user()
if (!empty($_SESSION['authenticated']) && !empty($_SESSION['uid'])) {
return intval($_SESSION['uid']);
}
return false;
}
@ -169,7 +170,7 @@ function remote_user()
*
* @param string $s - Text of notice
*/
function notice($s)
function notice(string $s)
{
if (empty($_SESSION)) {
return;
@ -189,7 +190,7 @@ function notice($s)
*
* @param string $s - Text of notice
*/
function info($s)
function info(string $s)
{
if (empty($_SESSION)) {
return;

View File

@ -1761,7 +1761,6 @@ class Database
* Checks if $array is 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
*/
public function isResult($array): bool
@ -1842,6 +1841,7 @@ class Database
$upds = implode(', ', $upd);
$r = $this->e(sprintf("UPDATE %s SET %s;", DBA::quoteIdentifier($table), $upds));
if (!$this->isResult($r)) {
throw new \RuntimeException("Failed updating `$table`: " . $this->errorMessage());
}

View File

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

View File

@ -174,7 +174,7 @@ class Relation
* @param array $rel
* @return array contact list
*/
private static function getContacts(int $uid, array $rel)
private static function getContacts(int $uid, array $rel): array
{
$list = [];
$profile = Profile::getByUID($uid);
@ -182,8 +182,15 @@ class Relation
return $list;
}
$condition = ['rel' => $rel, 'uid' => $uid, 'self' => false, 'deleted' => false,
'hidden' => false, 'archive' => false, 'pending' => false];
$condition = [
'rel' => $rel,
'uid' => $uid,
'self' => false,
'deleted' => false,
'hidden' => false,
'archive' => false,
'pending' => false,
];
$condition = DBA::mergeConditions($condition, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
$contacts = DBA::select('contact', ['url'], $condition);
while ($contact = DBA::fetch($contacts)) {
@ -201,7 +208,7 @@ class Relation
* @param array $contact Contact array
* @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');
@ -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 $limit optional, default 80
* @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);
$totallimit = $start + $limit;
@ -272,20 +281,25 @@ class Relation
// 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.
$results = DBA::select('contact', [],
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
$results = DBA::select('contact', [], ["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` IN
(SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ?)
AND NOT `cid` IN (SELECT `id` FROM `contact` WHERE `uid` = ? AND `nurl` IN
(SELECT `nurl` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))))
AND NOT `hidden` AND `network` IN (?, ?, ?, ?)",
$cid, 0, $uid, Contact::FRIEND, Contact::SHARING,
Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus],
['order' => ['last-item' => true], 'limit' => $totallimit]
$cid,
0,
$uid, Contact::FRIEND, Contact::SHARING,
Protocol::ACTIVITYPUB, Protocol::DFRN, $diaspora, $ostatus,
], [
'order' => ['last-item' => true],
'limit' => $totallimit,
]
);
while ($contact = DBA::fetch($results)) {
$contacts[$contact['id']] = $contact;
}
DBA::close($results);
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
* @throws Exception
*/
public static function countFollows(int $cid, array $condition = [])
public static function countFollows(int $cid, array $condition = []): int
{
$condition = DBA::mergeConditions($condition,
['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
$cid]
);
$condition = DBA::mergeConditions($condition, [
'`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)',
$cid,
]);
return DI::dba()->count('contact', $condition);
}
@ -556,7 +570,7 @@ class Relation
* @param int $count
* @param int $offset
* @param bool $shuffle
* @return array
* @return array|bool Array on success, false on failure
* @throws Exception
*/
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
* @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,
['`id` IN (SELECT `relation-cid` FROM `contact-relation` WHERE `cid` = ? AND `follows`)
@ -601,7 +615,7 @@ class Relation
* @param int $count
* @param int $offset
* @param bool $shuffle
* @return array
* @return array|bool Array on success, false on failure
* @throws Exception
*/
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
* @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,
["`id` IN (SELECT `cid` FROM `contact-relation` WHERE `relation-cid` = ? AND `follows`)
@ -646,7 +660,7 @@ class Relation
* @param int $count
* @param int $offset
* @param bool $shuffle
* @return array
* @return array|bool Array on success, false on failure
* @throws Exception
*/
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
*
* @param array $fields
* @param array $condition
* @return void
* @throws PDOException
* @throws Exception
* @param array $fields
* @param array $condition
* @return void
* @throws PDOException
* @throws Exception
*/
public static function updateByContactUpdate(array $fields, array $condition)
{
@ -106,7 +106,7 @@ class User
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 $uid User ID
* @param boolean $blocked Is the contact blocked or unblocked?
* @return void
* @throws \Exception
*/
public static function setBlocked($cid, $uid, $blocked)
public static function setBlocked(int $cid, int $uid, bool $blocked)
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {
@ -170,7 +171,7 @@ class User
* @return boolean is the contact id blocked for the given user?
* @throws \Exception
*/
public static function isBlocked($cid, $uid)
public static function isBlocked(int $cid, int $uid): bool
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {
@ -208,9 +209,10 @@ class User
* @param int $cid Either public contact id or user's contact id
* @param int $uid User ID
* @param boolean $ignored Is the contact ignored or unignored?
* @return void
* @throws \Exception
*/
public static function setIgnored($cid, $uid, $ignored)
public static function setIgnored(int $cid, int $uid, bool $ignored)
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {
@ -229,11 +231,10 @@ class User
*
* @param int $cid Either public contact id or user's contact id
* @param int $uid User ID
*
* @return boolean is the contact id ignored for the given user?
* @throws \Exception
*/
public static function isIgnored($cid, $uid)
public static function isIgnored(int $cid, int $uid): bool
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {
@ -271,9 +272,10 @@ class User
* @param int $cid Either public contact id or user's contact id
* @param int $uid User ID
* @param boolean $collapsed are the contact's posts collapsed or uncollapsed?
* @return void
* @throws \Exception
*/
public static function setCollapsed($cid, $uid, $collapsed)
public static function setCollapsed(int $cid, int $uid, bool $collapsed)
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {
@ -288,16 +290,15 @@ class User
*
* @param int $cid Either public contact id or user's contact id
* @param int $uid User ID
*
* @return boolean is the contact id blocked for the given user?
* @throws HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function isCollapsed($cid, $uid)
public static function isCollapsed(int $cid, int $uid): bool
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {
return;
return false;
}
$collapsed = false;
@ -318,9 +319,10 @@ class User
* @param int $cid Either public contact id or user's contact id
* @param int $uid User ID
* @param boolean $blocked Is the user blocked or unblocked by the contact?
* @return void
* @throws \Exception
*/
public static function setIsBlocked($cid, $uid, $blocked)
public static function setIsBlocked(int $cid, int $uid, bool $blocked)
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {
@ -335,11 +337,10 @@ class User
*
* @param int $cid Either public contact id or user's contact id
* @param int $uid User ID
*
* @return boolean Is the user blocked or unblocked by the contact?
* @throws \Exception
*/
public static function isIsBlocked($cid, $uid)
public static function isIsBlocked(int $cid, int $uid): bool
{
$cdata = Contact::getPublicAndUserContactID($cid, $uid);
if (empty($cdata)) {

View File

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

View File

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

View File

@ -40,36 +40,44 @@ class Link
/**
* Check if the link is stored
*
* @param int $uri_id
* @param string $url
* @return bool
* @param int $uriId
* @param string $url URL
* @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;
}
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;
}
$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'])) {
$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 {
$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();
Logger::info('Inserted', ['id' => $id, 'uri-id' => $uri_id, 'url' => $url]);
Logger::info('Inserted', ['id' => $id, 'uri-id' => $uriId, 'url' => $url]);
}
if (empty($id)) {
@ -81,15 +89,19 @@ class Link
case Proxy::SIZE_MICRO:
$url .= Proxy::PIXEL_MICRO . '/';
break;
case Proxy::SIZE_THUMB:
$url .= Proxy::PIXEL_THUMB . '/';
break;
case Proxy::SIZE_SMALL:
$url .= Proxy::PIXEL_SMALL . '/';
break;
case Proxy::SIZE_MEDIUM:
$url .= Proxy::PIXEL_MEDIUM . '/';
break;
case Proxy::SIZE_LARGE:
$url .= Proxy::PIXEL_LARGE . '/';
break;
@ -97,43 +109,50 @@ class Link
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');
$curlResult = DI::httpClient()->head($url, [HttpClientOptions::TIMEOUT => $timeout, HttpClientOptions::ACCEPT_CONTENT => $accept]);
if ($curlResult->isSuccess()) {
if (empty($media['mimetype'])) {
return $curlResult->getHeader('Content-Type')[0] ?? '';
}
if ($curlResult->isSuccess() && empty($media['mimetype'])) {
return $curlResult->getHeader('Content-Type')[0] ?? '';
}
return '';
}
/**
* Add external links and replace them in the body
*
* @param integer $uriid
* @param string $body
* @param integer $uriId
* @param string $body Item body formatted with BBCodes
* @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)) {
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)) {
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)) {
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
*
* @param array $profile Profile array (Generated from the "profile" table)
*
* @return string Location string
*/
public static function formatLocation(array $profile): string

View File

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

View File

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

View File

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

View File

@ -73,14 +73,14 @@ class Tag
/**
* Store tag/mention elements
*
* @param integer $uriid URI id
* @param integer $uriId
* @param integer $type Tag type
* @param string $name Tag name
* @param string $url Contact URL (optional)
* @param integer $target Target (default: null)
* @return void
*/
public static function store(int $uriid, int $type, string $name, string $url = '', int $target = null)
public static function store(int $uriId, int $type, string $name, string $url = '', int $target = null)
{
if ($type == self::HASHTAG) {
// Trim Unicode non-word characters
@ -89,7 +89,7 @@ class Tag
$tags = explode(self::TAG_CHARACTER[self::HASHTAG], $name);
if (count($tags) > 1) {
foreach ($tags as $tag) {
self::store($uriid, $type, $tag, $url);
self::store($uriId, $type, $tag, $url);
}
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])) {
$condition = $fields;
@ -156,7 +156,7 @@ class Tag
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 int $type
* @return void
* @param int $type Type of tag
* @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];
@ -243,6 +243,9 @@ class Tag
return $tid;
}
// Also log type
$fields['type'] = $type;
Logger::error('No tag id created', $fields);
return 0;
}
@ -250,21 +253,21 @@ class Tag
/**
* Store tag/mention elements
*
* @param integer $uriid URI id
* @param string $hash Hash
* @param string $name Name
* @param string $url URL
* @param integer $uriId
* @param string $hash
* @param string $name
* @param string $url
* @param boolean $probing Whether probing is active
* @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);
if ($type == self::UNKNOWN) {
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
*/
public static function getFromBody(string $body, string $tags = null)
public static function getFromBody(string $body, string $tags = null): array
{
if (is_null($tags)) {
$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
*
* @param integer $uriid URI-Id
* @param integer $uriId URI-Id
* @param string $body Body of the post
* @param string $tags Accepted tags
* @param boolean $probing Perform a probing for contacts, adding them if needed
* @return void
*/
public static function storeFromBody(int $uriid, string $body, string $tags = null, 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)) {
$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) {
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)
if (!empty($share_body) && (strpos($tags, self::TAG_CHARACTER[self::HASHTAG]) !== false)) {
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.
* 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
* @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);
if (empty($result)) {
return;
}
Logger::info('Found tags', ['uri-id' => $uriid, 'result' => $result]);
Logger::info('Found tags', ['uri-id' => $uriId, 'result' => $result]);
foreach ($result as $tag) {
if (substr($tag, 0, 1) != self::TAG_CHARACTER[self::HASHTAG]) {
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
*
* @param integer $uriid
* @param integer $uriId
* @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
*
* @param integer $uriid URI id
* @param integer $uriId
* @param integer $type Type
* @param string $name Name
* @param string $url URL
* @return void
*/
public static function remove(int $uriid, int $type, string $name, string $url = '')
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) {
$condition['name'] = $name;
}
@ -386,35 +389,36 @@ class Tag
return;
}
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']]);
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']]);
}
/**
* Remove tag/mention
*
* @param integer $uriid
* @param integer $uriId
* @param string $hash
* @param string $name
* @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);
if ($type == self::UNKNOWN) {
return;
}
self::remove($uriid, $type, $name, $url);
self::remove($uriId, $type, $name, $url);
}
/**
* Get the type for the given 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]) {
return self::MENTION;
@ -432,22 +436,23 @@ class Tag
/**
* Create implicit mentions for a given post
*
* @param integer $uri_id
* @param integer $parent_uri_id
* @param integer $uriId
* @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
$parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parent_uri_id]);
self::store($uri_id, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
$parent = Post::selectFirst(['author-link', 'author-name'], ['uri-id' => $parentUriId]);
self::store($uriId, self::IMPLICIT_MENTION, $parent['author-name'], $parent['author-link']);
if (DI::config()->get('system', 'disable_implicit_mentions')) {
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)) {
self::store($uri_id, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
self::store($uriId, self::IMPLICIT_MENTION, $tag['name'], $tag['url']);
}
DBA::close($tags);
}
@ -455,30 +460,29 @@ class Tag
/**
* Retrieves the terms from the provided type(s) associated with the provided item ID.
*
* @param int $item_id
* @param int|array $type
* @return array
* @param int $uriId
* @param array $type Tag type(s)
* @return array|bool Array on success, false on error
* @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 a string with all tags and mentions
*
* @param integer $uri_id
* @param array $type
* @param integer $uriId
* @param array $type Tag type(s)
* @return string tags and mentions
* @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 = [];
$tags = self::getByURIId($uri_id, $type);
foreach ($tags as $tag) {
foreach (self::getByURIId($uriId, $type) as $tag) {
$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 \ImagickException
*/
public static function populateFromItem(&$item)
public static function populateFromItem(array &$item): array
{
$return = [
'tags' => [],
@ -503,7 +507,7 @@ class Tag
'implicit_mentions' => [],
];
$searchpath = DI::baseUrl() . "/search?tag=";
$searchpath = DI::baseUrl() . '/search?tag=';
$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]]);
@ -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['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
break;
case self::MENTION:
case self::EXCLUSIVE_MENTION:
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['tags'][] = '<bdi>' . $prefix . '<a href="' . $tag['url'] . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tag['name']) . '</a></bdi>';
break;
case self::IMPLICIT_MENTION:
$return['implicit_mentions'][] = $prefix . $tag['name'];
break;
default:
Logger:warning('Unknown tag type found', $tag);
}
}
DBA::close($taglist);
@ -551,11 +560,13 @@ class Tag
* @param integer $uid
* @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`))
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);
}
@ -563,18 +574,20 @@ class Tag
/**
* Search posts for given tag
*
* @param string $search
* @param integer $uid
* @param integer $start
* @param integer $limit
* @param string $search Tag to search for
* @param integer $uid User Id
* @param integer $start Starting record
* @param integer $limit Maximum count of records
* @param integer $last_uriid
* @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`))
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)) {
$condition = DBA::mergeConditions($condition, ["`uri-id` < ?", $last_uriid]);
@ -587,13 +600,13 @@ class Tag
$tags = DBA::select('tag-search-view', ['uri-id'], $condition, $params);
$uriids = [];
$uriIds = [];
while ($tag = DBA::fetch($tags)) {
$uriids[] = $tag['uri-id'];
$uriIds[] = $tag['uri-id'];
}
DBA::close($tags);
return $uriids;
return $uriIds;
}
/**
@ -604,7 +617,7 @@ class Tag
* @return array
* @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);
if (!empty($tags)) {
@ -617,9 +630,9 @@ class Tag
/**
* 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');
if (empty($blocked_txt)) {
@ -628,7 +641,7 @@ class Tag
$blocked = explode(',', $blocked_txt);
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
* @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')],
['order' => ['received' => true]]);
if (empty($post['uri-id'])) {
return [];
}
@ -655,7 +671,9 @@ class Tag
FROM `tag-search-view`
WHERE `private` = ? AND `uid` = ? AND `uri-id` > ? $block_sql
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)) {
$tags = DBA::toArray($tagsStmt);
@ -674,7 +692,7 @@ class Tag
* @return array
* @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);
if (!empty($tags)) {
@ -692,7 +710,7 @@ class Tag
* @return array
* @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.
// 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`
WHERE `private` = ? AND `wall` AND `origin` AND `uri-id` > ? $block_sql
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)) {
$tags = DBA::toArray($tagsStmt);
@ -722,11 +742,11 @@ class Tag
/**
* Check if the provided tag is of one of the provided term types.
*
* @param string $tag
* @param string $tag Tag name
* @param int ...$types
* @return bool
*/
public static function isType($tag, ...$types)
public static function isType(string $tag, ...$types): bool
{
$tag_chars = [];
foreach ($types as $type) {
@ -744,7 +764,7 @@ class Tag
* @param string $tag
* @return array User list
*/
private static function getUIDListByTag(string $tag)
private static function getUIDListByTag(string $tag): array
{
$uids = [];
$searches = DBA::select('search', ['uid'], ['term' => $tag]);
@ -759,13 +779,13 @@ class Tag
/**
* Fetch user who subscribed to the tags of the given item
*
* @param integer $uri_id
* @param integer $uriId
* @return array User list
*/
public static function getUIDListByURIId(int $uri_id)
public static function getUIDListByURIId(int $uriId): array
{
$uids = [];
$tags = self::getByURIId($uri_id, [self::HASHTAG]);
$tags = self::getByURIId($uriId, [self::HASHTAG]);
foreach ($tags as $tag) {
$uids = array_merge($uids, self::getUIDListByTag(self::TAG_CHARACTER[self::HASHTAG] . $tag['name']));

View File

@ -117,16 +117,18 @@ class User
switch ($accounttype) {
case 'person':
return User::ACCOUNT_TYPE_PERSON;
case 'organisation':
return User::ACCOUNT_TYPE_ORGANISATION;
case 'news':
return User::ACCOUNT_TYPE_NEWS;
case '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
*
* @param string $email
* @param array $fields
*
* @param string $email
* @param array $fields
* @return array|boolean User record if it exists, false otherwise
*
* @throws Exception
*/
public static function getByEmail($email, array $fields = [])
public static function getByEmail(string $email, array $fields = [])
{
return DBA::selectFirst('user', $fields, ['email' => $email]);
}
@ -512,7 +512,7 @@ class User
* @throws HTTPException\ForbiddenException
* @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
// 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);
$Image = new Image($img_str, $type);
if ($Image->isValid()) {
$Image->scaleToSquare(300);
$image = new Image($img_str, $type);
if ($image->isValid()) {
$image->scaleToSquare(300);
$resource_id = Photo::newResource();
// Not using Photo::PROFILE_PHOTOS here, so that it is discovered as translateble string
$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) {
$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) {
$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) {
$photo_failure = true;
@ -1342,7 +1342,6 @@ class User
* @param string $email The user's email address
* @param string $nick The user's nick name
* @param string $lang The user's language (default is english)
*
* @return bool True, if the user was created successfully
* @throws HTTPException\InternalServerErrorException
* @throws ErrorException
@ -1731,7 +1730,6 @@ class User
* @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 bool $descending Order direction (Default is ascending)
*
* @return array|bool The list of the users
* @throws Exception
*/
@ -1744,11 +1742,13 @@ class User
$condition['account_removed'] = false;
$condition['blocked'] = false;
break;
case 'blocked':
$condition['account_removed'] = false;
$condition['blocked'] = true;
$condition['verified'] = true;
break;
case 'removed':
$condition['account_removed'] = true;
break;

View File

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

View File

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

View File

@ -131,7 +131,7 @@ class NoScrape extends BaseModule
$profile_fields = ['about', 'locality', 'region', 'postal-code', 'country-name', 'xmpp', 'matrix'];
foreach ($profile_fields as $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' => [
'xmlns' => 'http://a9.com/-/spec/opensearch/1.1',
],
'ShortName' => "Friendica $hostname",
'Description' => "Search in Friendica $hostname",
'Contact' => 'https://github.com/friendica/friendica/issues',
'ShortName' => "Friendica $hostname",
'Description' => "Search in Friendica $hostname",
'Contact' => 'https://github.com/friendica/friendica/issues',
'InputEncoding' => 'UTF-8',
'OutputEncoding' => 'UTF-8',
'Developer' => 'Friendica Developer Team',
],
], $xml);

View File

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

View File

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

View File

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

View File

@ -32,6 +32,7 @@ use Friendica\Core\L10n;
use Friendica\Core\System;
use Friendica\Database\Database;
use Friendica\Database\DBA;
use Friendica\Factory\Api\Mastodon\Notification as NotificationFactory;
use Friendica\Model;
use Friendica\Navigation\Notifications\Collection;
use Friendica\Navigation\Notifications\Entity;
@ -660,7 +661,7 @@ class Notify extends BaseRepository
public function NotifyOnDesktop(Entity\Notification $Notification, string $type = null): bool
{
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])) {

View File

@ -685,13 +685,13 @@ class Probe
$result = [];
if (in_array($network, ["", Protocol::DFRN])) {
if (in_array($network, ['', Protocol::DFRN])) {
$result = self::dfrn($webfinger);
}
if ((!$result && ($network == "")) || ($network == Protocol::DIASPORA)) {
if ((!$result && ($network == '')) || ($network == Protocol::DIASPORA)) {
$result = self::diaspora($webfinger);
}
if ((!$result && ($network == "")) || ($network == Protocol::OSTATUS)) {
if ((!$result && ($network == '')) || ($network == Protocol::OSTATUS)) {
$result = self::ostatus($webfinger);
}
if (in_array($network, ['', Protocol::ZOT])) {
@ -788,7 +788,7 @@ class Probe
return $data;
}
public static function pollZot($url, $data)
public static function pollZot(string $url, array $data): array
{
$curlResult = DI::httpClient()->get($url, HttpClientAccept::JSON);
if ($curlResult->isTimeout()) {
@ -1238,8 +1238,8 @@ class Probe
return [];
}
if (!isset($data["baseurl"])) {
$data["baseurl"] = "";
if (!isset($data['baseurl'])) {
$data['baseurl'] = '';
}
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
// Reason: Hubzilla doesn't use the value "uid" in the hcard like Diaspora does.
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' uid ')]", $vcard); // */
if (($search->length > 0) && empty($data["guid"])) {
$data["guid"] = $search->item(0)->nodeValue;
if (($search->length > 0) && empty($data['guid'])) {
$data['guid'] = $search->item(0)->nodeValue;
}
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' nickname ')]", $vcard); // */
if ($search->length > 0) {
$data["nick"] = $search->item(0)->nodeValue;
$data['nick'] = $search->item(0)->nodeValue;
}
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' fn ')]", $vcard); // */
if ($search->length > 0) {
$data["name"] = $search->item(0)->nodeValue;
$data['name'] = $search->item(0)->nodeValue;
}
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' searchable ')]", $vcard); // */
if ($search->length > 0) {
$data["searchable"] = $search->item(0)->nodeValue;
$data['searchable'] = $search->item(0)->nodeValue;
}
$search = $xpath->query("//*[contains(concat(' ', @class, ' '), ' key ')]", $vcard); // */
@ -1766,11 +1766,10 @@ class Probe
*
* @param string $url Profile link
* @param boolean $probe Do a probe if the page contains a feed link
*
* @return array feed data
* @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);
if ($curlResult->isTimeout()) {
@ -1977,7 +1976,7 @@ class Probe
* @param array $data Probing result
* @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'])) {
return '';

View File

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

View File

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

View File

@ -2244,7 +2244,7 @@ class Transmitter
* Prepends mentions (@) to $body variable
*
* @param string $body HTML code
* @param int $uriid URI id
* @param int $uriId
* @param string $authorLink Author link
* @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
*
* @param string $body The body
* @param integer $uriid URI id
* @param integer $uriId
* @return string The cleaned body
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/

View File

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

View File

@ -82,7 +82,7 @@ class Network
* @param string $addr The email address
* @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')) {
return true;
@ -113,7 +113,7 @@ class Network
* @param string $url URL which get tested
* @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);
@ -158,7 +158,7 @@ class Network
*
* @return boolean
*/
public static function isUrlBlocked(string $url)
public static function isUrlBlocked(string $url): bool
{
$host = @parse_url($url, PHP_URL_HOST);
if (!$host) {
@ -187,7 +187,7 @@ class Network
*
* @return boolean
*/
public static function isRedirectBlocked(string $url)
public static function isRedirectBlocked(string $url): bool
{
$host = @parse_url($url, PHP_URL_HOST);
if (!$host) {
@ -218,7 +218,7 @@ class Network
* or if allowed list is not configured
* @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));
if (!$domain) {
@ -242,7 +242,7 @@ class Network
* @param array $domain_list
* @return boolean
*/
public static function isDomainAllowed(string $domain, array $domain_list)
public static function isDomainAllowed(string $domain, array $domain_list): bool
{
$found = false;
@ -257,7 +257,7 @@ class Network
return $found;
}
public static function lookupAvatarByEmail(string $email)
public static function lookupAvatarByEmail(string $email): string
{
$avatar['size'] = 300;
$avatar['email'] = $email;
@ -280,11 +280,12 @@ class Network
* @param string $url Any user-submitted URL that may contain tracking params
* @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);
if (!empty($urldata["query"])) {
$query = $urldata["query"];
if (!empty($urldata['query'])) {
$query = $urldata['query'];
parse_str($query, $querydata);
if (is_array($querydata)) {
@ -292,30 +293,32 @@ class Network
if (in_array(
$param,
[
"utm_source", "utm_medium", "utm_term", "utm_content", "utm_campaign",
"wt_mc", "pk_campaign", "pk_kwd", "mc_cid", "mc_eid",
"fb_action_ids", "fb_action_types", "fb_ref",
"awesm", "wtrid",
"woo_campaign", "woo_source", "woo_medium", "woo_content", "woo_term"]
'utm_source', 'utm_medium', 'utm_term', 'utm_content', 'utm_campaign',
// As seen from Purism
'mtm_source', 'mtm_medium', 'mtm_term', 'mtm_content', 'mtm_campaign',
'wt_mc', 'pk_campaign', 'pk_kwd', 'mc_cid', 'mc_eid',
'fb_action_ids', 'fb_action_types', 'fb_ref',
'awesm', 'wtrid',
'woo_campaign', 'woo_source', 'woo_medium', 'woo_content', 'woo_term']
)
) {
$pair = $param . "=" . urlencode($value);
$url = str_replace($pair, "", $url);
$pair = $param . '=' . urlencode($value);
$url = str_replace($pair, '', $url);
// Second try: if the url isn't encoded completely
$pair = $param . "=" . str_replace(" ", "+", $value);
$url = str_replace($pair, "", $url);
$pair = $param . '=' . str_replace(' ', '+', $value);
$url = str_replace($pair, '', $url);
// Third try: Maybey the url isn't encoded at all
$pair = $param . "=" . $value;
$url = str_replace($pair, "", $url);
$pair = $param . '=' . $value;
$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);
}
}
@ -336,8 +339,10 @@ class Network
return $url;
}
$base = ['scheme' => parse_url($basepath, PHP_URL_SCHEME),
'host' => parse_url($basepath, PHP_URL_HOST)];
$base = [
'scheme' => parse_url($basepath, PHP_URL_SCHEME),
'host' => parse_url($basepath, PHP_URL_HOST),
];
$parts = array_merge($base, parse_url('/' . ltrim($url, '/')));
return self::unparseURL($parts);
@ -348,12 +353,12 @@ class Network
*
* @param string $url1
* @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 == "")) {
return "";
if (($url1 == '') || ($url2 == '')) {
return '';
}
$url1 = Strings::normaliseLink($url1);
@ -362,67 +367,67 @@ class Network
$parts1 = parse_url($url1);
$parts2 = parse_url($url2);
if (!isset($parts1["host"]) || !isset($parts2["host"])) {
return "";
if (!isset($parts1['host']) || !isset($parts2['host'])) {
return '';
}
if (empty($parts1["scheme"])) {
$parts1["scheme"] = '';
if (empty($parts1['scheme'])) {
$parts1['scheme'] = '';
}
if (empty($parts2["scheme"])) {
$parts2["scheme"] = '';
if (empty($parts2['scheme'])) {
$parts2['scheme'] = '';
}
if ($parts1["scheme"] != $parts2["scheme"]) {
return "";
if ($parts1['scheme'] != $parts2['scheme']) {
return '';
}
if (empty($parts1["host"])) {
$parts1["host"] = '';
if (empty($parts1['host'])) {
$parts1['host'] = '';
}
if (empty($parts2["host"])) {
$parts2["host"] = '';
if (empty($parts2['host'])) {
$parts2['host'] = '';
}
if ($parts1["host"] != $parts2["host"]) {
return "";
if ($parts1['host'] != $parts2['host']) {
return '';
}
if (empty($parts1["port"])) {
$parts1["port"] = '';
if (empty($parts1['port'])) {
$parts1['port'] = '';
}
if (empty($parts2["port"])) {
$parts2["port"] = '';
if (empty($parts2['port'])) {
$parts2['port'] = '';
}
if ($parts1["port"] != $parts2["port"]) {
return "";
if ($parts1['port'] != $parts2['port']) {
return '';
}
$match = $parts1["scheme"]."://".$parts1["host"];
$match = $parts1['scheme'] . '://' . $parts1['host'];
if ($parts1["port"]) {
$match .= ":".$parts1["port"];
if ($parts1['port']) {
$match .= ':' . $parts1['port'];
}
if (empty($parts1["path"])) {
$parts1["path"] = '';
if (empty($parts1['path'])) {
$parts1['path'] = '';
}
if (empty($parts2["path"])) {
$parts2["path"] = '';
if (empty($parts2['path'])) {
$parts2['path'] = '';
}
$pathparts1 = explode("/", $parts1["path"]);
$pathparts2 = explode("/", $parts2["path"]);
$pathparts1 = explode('/', $parts1['path']);
$pathparts2 = explode('/', $parts2['path']);
$i = 0;
$path = "";
$path = '';
do {
$path1 = $pathparts1[$i] ?? '';
$path2 = $pathparts2[$i] ?? '';
if ($path1 == $path2) {
$path .= $path1."/";
$path .= $path1 . '/';
}
} while (($path1 == $path2) && ($i++ <= count($pathparts1)));
@ -435,11 +440,10 @@ class Network
* Glue url parts together
*
* @param array $parsed URL parts
*
* @return string The glued URL.
* @return string|null The glued URL or null on error
* @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) {
return isset($parsed[$key]) ? $parsed[$key] : null;
@ -452,15 +456,15 @@ class Network
$scheme = $get('scheme');
$query = $get('query');
$fragment = $get('fragment');
$authority = ($userinfo !== null ? $userinfo."@" : '') .
$authority = ($userinfo !== null ? $userinfo . '@' : '') .
$get('host') .
($port ? ":$port" : '');
return (strlen($scheme) ? $scheme.":" : '') .
(strlen($authority) ? "//".$authority : '') .
return (strlen($scheme) ? $scheme . ':' : '') .
(strlen($authority) ? '//' . $authority : '') .
$get('path') .
(strlen($query) ? "?".$query : '') .
(strlen($fragment) ? "#".$fragment : '');
(strlen($query) ? '?' . $query : '') .
(strlen($fragment) ? '#' . $fragment : '');
}
/**
@ -490,11 +494,10 @@ class Network
/**
* Switch the scheme of an url between http and https
*
* @param string $url URL
*
* @return string switched URL
* @param string $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);
if (empty($scheme)) {
@ -517,7 +520,7 @@ class Network
* @param array $additionalParams Associative array of parameters
* @return string
*/
public static function appendQueryParam(string $path, array $additionalParams)
public static function appendQueryParam(string $path, array $additionalParams): string
{
$parsed = parse_url($path);
@ -541,6 +544,7 @@ class Network
*
* @param string $etag The page etag
* @param string $last_modified The page last modification UTC date
* @return void
* @throws \Exception
*/
public static function checkEtagModified(string $etag, string $last_modified)
@ -577,10 +581,10 @@ class Network
/**
* Check if the given URL is a local link
*
* @param string $url
* @return bool
* @param string $url
* @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);
}
@ -588,10 +592,10 @@ class Network
/**
* Check if the given URL is a valid HTTP/HTTPS URL
*
* @param string $url
* @return bool
* @param string $url
* @return bool
*/
public static function isValidHttpUrl(string $url)
public static function isValidHttpUrl(string $url): bool
{
$scheme = parse_url($url, PHP_URL_SCHEME);
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 $size One of the Proxy::SIZE_* constants
*
* @return string The proxyfied URL or relative path
* @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')) {
return $url;
@ -133,11 +132,10 @@ class Proxy
* proxy storage directory.
*
* @param string $html Un-proxified HTML code
*
* @return string Proxified HTML code
* @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);
@ -151,7 +149,7 @@ class Proxy
* @return boolean
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function isLocalImage($url)
public static function isLocalImage(string $url): bool
{
if (substr($url, 0, 1) == '/') {
return true;
@ -170,7 +168,7 @@ class Proxy
* @param string $url URL to parse
* @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 = html_entity_decode($query);
@ -187,7 +185,7 @@ class Proxy
* @return string Proxified HTML image tag
* @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
$queryvar = self::parseQuery($matches[2]);

View File

@ -38,7 +38,7 @@ class XML
* Creates an XML structure out of a given array
*
* @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 array $namespaces List of namespaces
* @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
*
* @param DOMDocument $doc XML root
* @param object $parent parent object
* @param string $element XML element name
* @param string $value XML value
* @param array $attributes array containing the attributes
* @param DOMDocument $doc XML root
* @param DOMElement $parent parent object
* @param string $element XML element name
* @param string $value XML value
* @param array $attributes Array containing the attributes
* @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);
$parent->appendChild($element);
}
/**
* Convert an XML document to a normalised, case-corrected array
* used by webfinger
* Convert an XML document to a normalised, case-corrected array used by webfinger
*
* @param object $xml_element The XML document
* @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 ($recursion_depth > 512) {
return(null);
return null;
}
$xml_element_copy = '';

View File

@ -31,7 +31,14 @@ use Friendica\Protocol\ActivityPub;
* Send updated profile data to Diaspora and ActivityPub
*/
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)) {
return;
}
@ -43,7 +50,13 @@ class ProfileUpdate {
foreach ($inboxes as $inbox => $receivers) {
Logger::info('Profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub');
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);

View File

@ -29,7 +29,13 @@ use Friendica\Protocol\OStatus;
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) {
return;
@ -38,7 +44,13 @@ class PubSubPublish
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]);
if (!DBA::isResult($subscriber)) {
@ -48,7 +60,7 @@ class PubSubPublish
/// @todo Check server status with GServer::check()
// 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'];
$params = OStatus::feed($subscriber['nickname'], $last_update);
@ -57,11 +69,11 @@ class PubSubPublish
return;
}
$hmac_sig = hash_hmac("sha1", $params, $subscriber['secret']);
$hmac_sig = hash_hmac('sha1', $params, $subscriber['secret']);
$headers = [
'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'],
$subscriber['topic']),
'X-Hub-Signature' => 'sha1=' . $hmac_sig];

View File

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

View File

@ -29,7 +29,13 @@ use Friendica\Model\Post;
* Removes orphaned data from deleted users
*/
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
$condition = ['account_removed' => true, 'uid' => $uid];

View File

@ -28,9 +28,11 @@ class UpdateContact
{
/**
* Update contact data via probe
*
* @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);

View File

@ -102,7 +102,7 @@ class UpdateContacts
* @param array $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]);
while ($contact = DBA::fetch($contacts)) {

View File

@ -30,8 +30,10 @@ class UpdateGServer
{
/**
* Update the given server
*
* @param string $server_url Server URL
* @param boolean $only_nodeinfo Only use nodeinfo for server detection
* @return void
*/
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
*
* @param string $gserver Server URL
* @return void
*/
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
* 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.
*
@ -40,8 +40,10 @@
* 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\Storage\Capability\ICanReadFromStorage;
use Friendica\Core\Storage\Type\Database as DatabaseStorage;
use Friendica\Core\Update;
use Friendica\Core\Worker;
use Friendica\Database\Database;
@ -988,9 +990,9 @@ function update_1434()
{
$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)) {
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
@ -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,
// we assume that the distributed cache driver should be the same as the current cache driver
if (
$distributed_cache_driver_source === \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC
&& $cache_driver_source > \Friendica\Core\Config\ValueObject\Cache::SOURCE_STATIC
) {
if ($distributed_cache_driver_source === Cache::SOURCE_STATIC && $cache_driver_source > Cache::SOURCE_STATIC) {
DI::config()->set('system', 'distributed_cache_driver', DI::config()->get('system', 'cache_driver'));
}