[TOOLS][CS-FIXER] Run new PHP CS Fixer config. Notably, adds strict_types

This commit is contained in:
Hugo Sales 2021-10-10 09:26:18 +01:00 committed by Diogo Peralta Cordeiro
parent 8ef2d3339f
commit 9109c61af5
No known key found for this signature in database
GPG Key ID: 18D2D35001FBFAB0
327 changed files with 2246 additions and 2616 deletions

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -46,8 +48,6 @@ class Avatar extends Component
}
/**
* @param mixed $tabs
*
* @throws \App\Util\Exception\ClientException
*/
public function onPopulateProfileSettingsTabs(Request $request, &$tabs): bool
@ -82,14 +82,20 @@ class Avatar extends Component
public static function getAvatar(?int $actor_id = null): Entity\Avatar
{
$actor_id = $actor_id ?: Common::userId();
return GSFile::error(NoAvatarException::class,
return GSFile::error(
NoAvatarException::class,
$actor_id,
Cache::get("avatar-{$actor_id}",
Cache::get(
"avatar-{$actor_id}",
function () use ($actor_id) {
return DB::dql('select a from Component\Avatar\Entity\Avatar a ' .
'where a.actor_id = :actor_id',
['actor_id' => $actor_id]);
}));
return DB::dql(
'select a from Component\Avatar\Entity\Avatar a '
. 'where a.actor_id = :actor_id',
['actor_id' => $actor_id],
);
},
),
);
}
/**
@ -112,14 +118,17 @@ class Avatar extends Component
*/
public static function getAvatarFileInfo(int $actor_id, string $size = 'full'): array
{
$res = Cache::get("avatar-file-info-{$actor_id}-{$size}",
$res = Cache::get(
"avatar-file-info-{$actor_id}-{$size}",
function () use ($actor_id) {
return DB::dql('select f.id, f.filename, a.title, f.mimetype ' .
'from App\Entity\Attachment f ' .
'join Component\Avatar\Entity\Avatar a with f.id = a.attachment_id ' .
'where a.actor_id = :actor_id',
['actor_id' => $actor_id]);
}
return DB::dql(
'select f.id, f.filename, a.title, f.mimetype '
. 'from App\Entity\Attachment f '
. 'join Component\Avatar\Entity\Avatar a with f.id = a.attachment_id '
. 'where a.actor_id = :actor_id',
['actor_id' => $actor_id],
);
},
);
if ($res === []) { // Avatar not found
$filepath = INSTALLDIR . '/public/assets/default-avatar.svg';

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -96,7 +98,7 @@ class Avatar extends Controller
// Cropped client side
$matches = [];
if (!empty(preg_match('/data:([^;]*)(;(base64))?,(.*)/', $data['hidden'], $matches))) {
list(, , , $encoding_user, $data_user) = $matches;
[, , , $encoding_user, $data_user] = $matches;
if ($encoding_user === 'base64') {
$data_user = base64_decode($data_user);
$tempfile = new TemporaryFile(['prefix' => 'gs-avatar']);

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -75,17 +77,11 @@ class Avatar extends Entity
return $this->attachment_id;
}
/**
* @return null|string
*/
public function getTitle(): ?string
{
return $this->title;
}
/**
* @param null|string $title
*/
public function setTitle(?string $title): void
{
$this->title = $title;
@ -121,14 +117,12 @@ class Avatar extends Entity
public function getUrl(string $size = 'full', int $type = Router::ABSOLUTE_PATH): string
{
$actor_id = $this->getActorId();
return Cache::get("avatar-url-{$actor_id}-{$size}-{$type}", function () use ($actor_id, $size, $type) {
return Router::url('avatar_actor', ['actor_id' => $actor_id, 'size' => $size], $type);
});
return Cache::get("avatar-url-{$actor_id}-{$size}-{$type}", fn () => Router::url('avatar_actor', ['actor_id' => $actor_id, 'size' => $size], $type));
}
public function getAttachment(): Attachment
{
$this->attachment = $this->attachment ?? DB::findOneBy('attachment', ['id' => $this->attachment_id]);
$this->attachment ??= DB::findOneBy('attachment', ['id' => $this->attachment_id]);
return $this->attachment;
}
@ -144,8 +138,6 @@ class Avatar extends Entity
/**
* Delete this avatar and kill corresponding attachment
*
* @return bool
*/
public function delete(): bool
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -46,10 +48,10 @@ class ForeignLink
private int $noticesync = 1;
private int $friendsync = 2;
private int $profilesync = 1;
private ?\DateTimeInterface $last_noticesync;
private ?\DateTimeInterface $last_friendsync;
private \DateTimeInterface $created;
private \DateTimeInterface $modified;
private ?DateTimeInterface $last_noticesync;
private ?DateTimeInterface $last_friendsync;
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function setUserId(int $user_id): self
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -42,8 +44,8 @@ class ForeignService
private int $id;
private string $name;
private ?string $description;
private \DateTimeInterface $created;
private \DateTimeInterface $modified;
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function setId(int $id): self
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -42,7 +44,7 @@ class ForeignSubscription
private int $service;
private int $subscriber;
private int $subscribed;
private \DateTimeInterface $created;
private DateTimeInterface $created;
public function setService(int $service): self
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -43,8 +45,8 @@ class ForeignUser
private int $service;
private string $uri;
private ?string $nickname;
private \DateTimeInterface $created;
private \DateTimeInterface $modified;
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function setId(int $id): self
{

View File

@ -1,4 +1,6 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -50,100 +52,64 @@ class FreenetworkActor extends Entity
private string $source;
private int $actor_id;
private bool $is_local;
private \DateTimeInterface $created;
private \DateTimeInterface $modified;
private DateTimeInterface $created;
private DateTimeInterface $modified;
/**
* @return string
*/
public function getActorUri(): string
{
return $this->actor_uri;
}
/**
* @param string $actor_uri
*/
public function setActorUri(string $actor_uri): void
{
$this->actor_uri = $actor_uri;
}
/**
* @return string
*/
public function getSource(): string
{
return $this->source;
}
/**
* @param string $source
*/
public function setSource(string $source): void
{
$this->source = $source;
}
/**
* @return int
*/
public function getActorId(): int
{
return $this->actor_id;
}
/**
* @param int $actor_id
*/
public function setActorId(int $actor_id): void
{
$this->actor_id = $actor_id;
}
/**
* @return bool
*/
public function isIsLocal(): bool
{
return $this->is_local;
}
/**
* @param bool $is_local
*/
public function setIsLocal(bool $is_local): void
{
$this->is_local = $is_local;
}
/**
* @return DateTimeInterface
*/
public function getCreated(): DateTimeInterface
{
return $this->created;
}
/**
* @param DateTimeInterface $created
*/
public function setCreated(DateTimeInterface $created): void
{
$this->created = $created;
}
/**
* @return DateTimeInterface
*/
public function getModified(): DateTimeInterface
{
return $this->modified;
}
/**
* @param DateTimeInterface $modified
*/
public function setModified(DateTimeInterface $modified): void
{
$this->modified = $modified;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -29,7 +31,7 @@ class Left extends Component
*
* @param array $styles stylesheets path
*
* @return bool hook value; true means continue processing, false means stop.
* @return bool hook value; true means continue processing, false means stop
*/
public function onEndShowStyles(array &$styles, string $route): bool
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -68,68 +70,68 @@ class Link extends Component
$geouri_pctencoded_regex = '(?:\%[0-9a-fA-F][0-9a-fA-F])';
$geouri_paramchar_regex = $geouri_unreserved_regex . $geouri_punreserved_regex; //FIXME: add $geouri_pctencoded_regex here so it works
return '#' .
'(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])' .
'(' .
'(?:' .
'(?:' . //Known protocols
'(?:' .
'(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)' .
'|' .
'(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_SINGLE_COLON)) . '):)' .
')' .
'(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?' . //user:pass@
'(?:' .
'(?:' .
'\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]' . //[dns]
')|(?:' .
'[\pN\pL\-\_\:\.]+(?<![\.\:])' . //dns
')' .
')' .
')' .
'|(?:' .
'(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_COORDINATES)) . '):' .
return '#'
. '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'
. '('
. '(?:'
. '(?:' //Known protocols
. '(?:'
. '(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)'
. '|'
. '(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_SINGLE_COLON)) . '):)'
. ')'
. '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?' //user:pass@
. '(?:'
. '(?:'
. '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]' //[dns]
. ')|(?:'
. '[\pN\pL\-\_\:\.]+(?<![\.\:])' //dns
. ')'
. ')'
. ')'
. '|(?:'
. '(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_COORDINATES)) . '):'
// There's an order that must be followed here too, if ;crs= is used, it must precede ;u=
// Also 'crsp' (;crs=$crsp) must match $geouri_labeltext_regex
// Also 'uval' (;u=$uval) must be a pnum: \-?[0-9]+
'(?:' .
'(?:[0-9]+(?:\.[0-9]+)?(?:\,[0-9]+(?:\.[0-9]+)?){1,2})' . // 1(.23)?(,4(.56)){1,2}
'(?:\;(?:[' . $geouri_labeltext_regex . ']+)(?:\=[' . $geouri_paramchar_regex . ']+)*)*' .
')' .
')' .
. '(?:'
. '(?:[0-9]+(?:\.[0-9]+)?(?:\,[0-9]+(?:\.[0-9]+)?){1,2})' // 1(.23)?(,4(.56)){1,2}
. '(?:\;(?:[' . $geouri_labeltext_regex . ']+)(?:\=[' . $geouri_paramchar_regex . ']+)*)*'
. ')'
. ')'
// URLs without domain name, like magnet:?xt=...
'|(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_NO_DOMAIN)) . '):(?=\?))' . // zero-length lookahead requires ? after :
(Common::config('linkify', 'ipv4') // Convert IPv4 addresses to hyperlinks
. '|(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_NO_DOMAIN)) . '):(?=\?))' // zero-length lookahead requires ? after :
. (Common::config('linkify', 'ipv4') // Convert IPv4 addresses to hyperlinks
? '|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
: '') .
(Common::config('linkify', 'ipv6') // Convert IPv6 addresses to hyperlinks
? '|(?:' . //IPv6
'\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?(?<!:)' .
')'
: '') .
(Common::config('linkify', 'bare_domains')
? '|(?:' . //DNS
'(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?' . //user:pass@
'[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.' .
: '')
. (Common::config('linkify', 'ipv6') // Convert IPv6 addresses to hyperlinks
? '|(?:' //IPv6
. '\[?(?:(?:(?:[0-9A-Fa-f]{1,4}:){7}(?:(?:[0-9A-Fa-f]{1,4})|:))|(?:(?:[0-9A-Fa-f]{1,4}:){6}(?::|(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})|(?::[0-9A-Fa-f]{1,4})))|(?:(?:[0-9A-Fa-f]{1,4}:){5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){4}(?::[0-9A-Fa-f]{1,4}){0,1}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){3}(?::[0-9A-Fa-f]{1,4}){0,2}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:){2}(?::[0-9A-Fa-f]{1,4}){0,3}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:[0-9A-Fa-f]{1,4}:)(?::[0-9A-Fa-f]{1,4}){0,4}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?::(?::[0-9A-Fa-f]{1,4}){0,5}(?:(?::(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|(?:(?::[0-9A-Fa-f]{1,4}){1,2})))|(?:(?:(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))\]?(?<!:)'
. ')'
: '')
. (Common::config('linkify', 'bare_domains')
? '|(?:' //DNS
. '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?' //user:pass@
. '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'
//tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion
'(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZONE|ZW|local|loc|onion)' .
')(?![\pN\pL\-\_])'
: '') . // if common_config('linkify', 'bare_domains') is false, don't add anything here
')' .
'(?:' .
'(?:\:\d+)?' . //:port
'(?:/[' . URL_REGEX_VALID_PATH_CHARS . ']*)?' . // path
'(?:\?[' . URL_REGEX_VALID_QSTRING_CHARS . ']*)?' . // ?query string
'(?:\#[' . URL_REGEX_VALID_FRAGMENT_CHARS . ']*)?' . // #fragment
')(?<![' . URL_REGEX_EXCLUDED_END_CHARS . '])' .
')' .
'#ixu';
. '(?:AC|AD|AE|AERO|AF|AG|AI|AL|AM|AN|AO|AQ|AR|ARPA|AS|ASIA|AT|AU|AW|AX|AZ|BA|BB|BD|BE|BF|BG|BH|BI|BIZ|BJ|BM|BN|BO|BR|BS|BT|BV|BW|BY|BZ|CA|CAT|CC|CD|CF|CG|CH|CI|CK|CL|CM|CN|CO|COM|COOP|CR|CU|CV|CX|CY|CZ|DE|DJ|DK|DM|DO|DZ|EC|EDU|EE|EG|ER|ES|ET|EU|FI|FJ|FK|FM|FO|FR|GA|GB|GD|GE|GF|GG|GH|GI|GL|GM|GN|GOV|GP|GQ|GR|GS|GT|GU|GW|GY|HK|HM|HN|HR|HT|HU|ID|IE|IL|IM|IN|INFO|INT|IO|IQ|IR|IS|IT|JE|JM|JO|JOBS|JP|KE|KG|KH|KI|KM|KN|KP|KR|KW|KY|KZ|LA|LB|LC|LI|LK|LR|LS|LT|LU|LV|LY|MA|MC|MD|ME|MG|MH|MIL|MK|ML|MM|MN|MO|MOBI|MP|MQ|MR|MS|MT|MU|MUSEUM|MV|MW|MX|MY|MZ|NA|NAME|NC|NE|NET|NF|NG|NI|NL|NO|NP|NR|NU|NZ|OM|ORG|PA|PE|PF|PG|PH|PK|PL|PM|PN|PR|PRO|PS|PT|PW|PY|QA|RE|RO|RS|RU|RW|SA|SB|SC|SD|SE|SG|SH|SI|SJ|SK|SL|SM|SN|SO|SR|ST|SU|SV|SY|SZ|TC|TD|TEL|TF|TG|TH|TJ|TK|TL|TM|TN|TO|TP|TR|TRAVEL|TT|TV|TW|TZ|UA|UG|UK|US|UY|UZ|VA|VC|VE|VG|VI|VN|VU|WF|WS|XN--0ZWM56D|测试|XN--11B5BS3A9AJ6G|परीक्षा|XN--80AKHBYKNJ4F|испытание|XN--9T4B11YI5A|테스트|XN--DEBA0AD|טעסט|XN--G6W251D|測試|XN--HGBK6AJ7F53BBA|آزمایشی|XN--HLCJ6AYA9ESC7A|பரிட்சை|XN--JXALPDLP|δοκιμή|XN--KGBECHTV|إختبار|XN--ZCKZAH|テスト|YE|YT|YU|ZA|ZM|ZONE|ZW|local|loc|onion)'
. ')(?![\pN\pL\-\_])'
: '') // if common_config('linkify', 'bare_domains') is false, don't add anything here
. ')'
. '(?:'
. '(?:\:\d+)?' //:port
. '(?:/[' . URL_REGEX_VALID_PATH_CHARS . ']*)?' // path
. '(?:\?[' . URL_REGEX_VALID_QSTRING_CHARS . ']*)?' // ?query string
. '(?:\#[' . URL_REGEX_VALID_FRAGMENT_CHARS . ']*)?' // #fragment
. ')(?<![' . URL_REGEX_EXCLUDED_END_CHARS . '])'
. ')'
. '#ixu';
}
const URL_SCHEME_COLON_DOUBLE_SLASH = 1;
const URL_SCHEME_SINGLE_COLON = 2;
const URL_SCHEME_NO_DOMAIN = 4;
const URL_SCHEME_COLON_COORDINATES = 8;
public const URL_SCHEME_COLON_DOUBLE_SLASH = 1;
public const URL_SCHEME_SINGLE_COLON = 2;
public const URL_SCHEME_NO_DOMAIN = 4;
public const URL_SCHEME_COLON_COORDINATES = 8;
public function URLSchemes($filter = null)
{
@ -162,13 +164,11 @@ class Link extends Component
'geo' => self::URL_SCHEME_COLON_COORDINATES,
];
return array_keys(array_filter($schemes, fn ($scheme) => is_null($filter) || ($scheme & $filter)));
return array_keys(array_filter($schemes, fn ($scheme) => \is_null($filter) || ($scheme & $filter)));
}
/**
* Find links in the given text and pass them to the given callback function.
*
* @param string $text
*/
public function replaceURLs(string $text): string
{
@ -180,16 +180,13 @@ class Link extends Component
* Intermediate callback for `replaceURLs()`, which helps resolve some
* ambiguous link forms before passing on to the final callback.
*
* @param array $matches
* @param callable(string $text): string $callback: return replacement text
*
* @return string
*/
private function callbackHelper(array $matches, callable $callback): string
{
$url = $matches[1];
$left = strpos($matches[0], $url);
$right = $left + strlen($url);
$left = mb_strpos($matches[0], $url);
$right = $left + mb_strlen($url);
$groupSymbolSets = [
[
@ -214,23 +211,23 @@ class Link extends Component
do {
$original_url = $url;
foreach ($groupSymbolSets as $groupSymbolSet) {
if (substr($url, -1) == $groupSymbolSet['right']) {
$group_left_count = substr_count($url, $groupSymbolSet['left']);
$group_right_count = substr_count($url, $groupSymbolSet['right']);
if (mb_substr($url, -1) == $groupSymbolSet['right']) {
$group_left_count = mb_substr_count($url, $groupSymbolSet['left']);
$group_right_count = mb_substr_count($url, $groupSymbolSet['right']);
if ($group_left_count < $group_right_count) {
--$right;
$url = substr($url, 0, -1);
$url = mb_substr($url, 0, -1);
}
}
}
if (in_array(substr($url, -1), $cannotEndWith)) {
if (\in_array(mb_substr($url, -1), $cannotEndWith)) {
--$right;
$url = substr($url, 0, -1);
$url = mb_substr($url, 0, -1);
}
} while ($original_url != $url);
$result = $callback($url);
return substr($matches[0], 0, $left) . $result . substr($matches[0], $right);
return mb_substr($matches[0], 0, $left) . $result . mb_substr($matches[0], $right);
}
/**
@ -242,7 +239,7 @@ class Link extends Component
// functions
$url = htmlspecialchars_decode($url);
if (strpos($url, '@') !== false && strpos($url, ':') === false && ($email = filter_var($url, FILTER_VALIDATE_EMAIL)) !== false) {
if (str_contains($url, '@') && !str_contains($url, ':') && ($email = filter_var($url, \FILTER_VALIDATE_EMAIL)) !== false) {
//url is an email address without the mailto: protocol
$url = "mailto:{$email}";
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -63,8 +65,10 @@ class Posting extends Component
$actor_id = $user->getId();
$to_tags = [];
$tags = Cache::get("actor-circle-{$actor_id}",
fn () => DB::dql('select c.tag from App\Entity\ActorCircle c where c.tagger = :tagger', ['tagger' => $actor_id]));
$tags = Cache::get(
"actor-circle-{$actor_id}",
fn () => DB::dql('select c.tag from App\Entity\ActorCircle c where c.tagger = :tagger', ['tagger' => $actor_id]),
);
foreach ($tags as $t) {
$t = $t['tag'];
$to_tags[$t] = $t;
@ -87,7 +91,7 @@ class Posting extends Component
['content', TextareaType::class, ['label' => _m('Content:'), 'data' => $initial_content, 'attr' => ['placeholder' => _m($placeholder)]]],
['attachments', FileType::class, ['label' => _m('Attachments:'), 'data' => null, 'multiple' => true, 'required' => false]],
];
if (count($available_content_types) > 1) {
if (\count($available_content_types) > 1) {
$form_params[] = ['content_type', ChoiceType::class,
[
'label' => _m('Text format:'), 'multiple' => false, 'expanded' => false,
@ -121,13 +125,6 @@ class Posting extends Component
* $actor_id, possibly as a reply to note $reply_to and with flag
* $is_local. Sanitizes $content and $attachments
*
* @param Actor $actor
* @param string $content
* @param string $content_type
* @param array $attachments
* @param null|Note $reply_to
* @param null|Note $repeat_of
*
* @throws ClientException
* @throws ServerException
*/
@ -149,8 +146,8 @@ class Posting extends Component
$filesize = $f->getSize();
$max_file_size = Common::config('attachments', 'file_quota');
if ($max_file_size < $filesize) {
throw new ClientException(_m('No file may be larger than {quota} bytes and the file you sent was {size} bytes. ' .
'Try to upload a smaller version.', ['quota' => $max_file_size, 'size' => $filesize]));
throw new ClientException(_m('No file may be larger than {quota} bytes and the file you sent was {size} bytes. '
. 'Try to upload a smaller version.', ['quota' => $max_file_size, 'size' => $filesize], ));
}
Event::handle('EnforceUserFileQuota', [$filesize, $actor->getId()]);
$processed_attachments[] = [GSFile::storeFileAsAttachment($f), $f->getClientOriginalName()];
@ -193,11 +190,6 @@ class Posting extends Component
* Get a unique representation of a file on disk
*
* This can be used in the future to deduplicate images by visual content
*
* @param string $filename
* @param null|string $out_hash
*
* @return bool
*/
public function onHashFile(string $filename, ?string &$out_hash): bool
{
@ -207,10 +199,6 @@ class Posting extends Component
/**
* Fill the list with allowed sizes for an attachment, to prevent potential DoS'ing by requesting thousands of different thumbnail sizes
*
* @param null|array $sizes
*
* @return bool
*/
public function onGetAllowedThumbnailSizes(?array &$sizes): bool
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
//
@ -29,7 +31,7 @@ class Right extends Component
*
* @param array $styles stylesheets path
*
* @return bool hook value; true means continue processing, false means stop.
* @return bool hook value; true means continue processing, false means stop
*/
public function onEndShowStyles(array &$styles, string $route): bool
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -40,15 +42,13 @@ class Search extends Controller
$actor_qb->select('actor')->from('App\Entity\Actor', 'actor');
Event::handle('SeachQueryAddJoins', [&$note_qb, &$actor_qb]);
$notes = $actors = [];
if (!is_null($note_criteria)) {
if (!\is_null($note_criteria)) {
$note_qb->addCriteria($note_criteria);
$notes = $note_qb->getQuery()->execute();
} else {
if (!is_null($actor_criteria)) {
} elseif (!\is_null($actor_criteria)) {
$actor_qb->addCriteria($actor_criteria);
$actors = $actor_qb->getQuery()->execute();
}
}
return [
'_template' => 'search/show.html.twig',

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -23,12 +25,12 @@ namespace Component\Search;
use App\Core\Event;
use App\Core\Form;
use function App\Core\I18n\_m;
use App\Core\Modules\Component;
use App\Util\Exception\RedirectException;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;
use function App\Core\I18n\_m;
class Search extends Component
{
@ -44,7 +46,7 @@ class Search extends Component
{
$form = Form::create([
['query', TextType::class, [
'attr' => ['placeholder' => _m('Search tags...')]
'attr' => ['placeholder' => _m('Search tags...')],
]],
[$form_name = 'submit_search', SubmitType::class,
[
@ -74,7 +76,7 @@ class Search extends Component
*
* @param array $styles stylesheets path
*
* @return bool hook value; true means continue processing, false means stop.
* @return bool hook value; true means continue processing, false means stop
*/
public function onEndShowStyles(array &$styles, string $route): bool
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -27,7 +29,6 @@ use Doctrine\Common\Collections\Criteria;
abstract class Parser
{
/**
* Merge $parts into $criteria_arr
*/
@ -74,22 +75,18 @@ abstract class Parser
foreach (['&', '|', ' '] as $delimiter) {
if ($input[$index] === $delimiter || $end = ($index === $lenght - 1)) {
$term = substr($input, $left, $end ? null : $right - $left);
$term = mb_substr($input, $left, $end ? null : $right - $left);
$note_res = $actor_res = null;
$ret = Event::handle('SearchCreateExpression', [$eb, $term, &$note_res, &$actor_res]);
if ((is_null($note_res) && is_null($actor_res)) || $ret == Event::next) {
if ((\is_null($note_res) && \is_null($actor_res)) || $ret == Event::next) {
throw new ServerException("No one claimed responsibility for a match term: {$term}");
} else {
if (!is_null($note_res)) {
} elseif (!\is_null($note_res)) {
$note_parts[] = $note_res;
} else {
if (!is_null($actor_res)) {
} elseif (!\is_null($actor_res)) {
$actor_parts[] = $actor_res;
} else {
throw new ServerException('Unexpected state in Search parser');
}
}
}
$right = $left = $index + 1;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Component\Tag\Controller;
use App\Core\Cache;
@ -19,7 +21,7 @@ class Tag extends Controller
query: 'select n from note n join note_tag nt with n.id = nt.note_id where nt.canonical = :canon order by nt.created DESC, nt.note_id DESC',
query_args: ['canon' => $canonical],
actor: $user,
page: $page
page: $page,
);
return [

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -43,13 +45,13 @@ use Doctrine\ORM\QueryBuilder;
*/
class Tag extends Component
{
const MAX_TAG_LENGTH = 64;
const TAG_REGEX = '/(^|\\s)(#[\\pL\\pN_\\-\\.]{1,64})/u'; // Brion Vibber 2011-02-23 v2:classes/Notice.php:367 function saveTags
const TAG_SLUG_REGEX = '[A-Za-z0-9]{1,64}';
public const MAX_TAG_LENGTH = 64;
public const TAG_REGEX = '/(^|\\s)(#[\\pL\\pN_\\-\\.]{1,64})/u'; // Brion Vibber 2011-02-23 v2:classes/Notice.php:367 function saveTags
public const TAG_SLUG_REGEX = '[A-Za-z0-9]{1,64}';
public function onAddRoute($r): bool
{
$r->connect('tag', '/tag/{tag<' . self::TAG_SLUG_REGEX . '>}' , [Controller\Tag::class, 'tag']);
$r->connect('tag', '/tag/{tag<' . self::TAG_SLUG_REGEX . '>}', [Controller\Tag::class, 'tag']);
return Event::next;
}
@ -60,7 +62,7 @@ class Tag extends Component
{
$matched_tags = [];
$processed_tags = false;
preg_match_all(self::TAG_REGEX, $content, $matched_tags, PREG_SET_ORDER);
preg_match_all(self::TAG_REGEX, $content, $matched_tags, \PREG_SET_ORDER);
foreach ($matched_tags as $match) {
$tag = $match[2];
$canonical_tag = self::canonicalTag($tag);
@ -87,16 +89,13 @@ class Tag extends Component
public static function canonicalTag(string $tag): string
{
return substr(Formatting::slugify($tag), 0, self::MAX_TAG_LENGTH);
return mb_substr(Formatting::slugify($tag), 0, self::MAX_TAG_LENGTH);
}
/**
* Populate $note_expr with an expression to match a tag, if the term looks like a tag
*
* $term /^(note|tag|people|actor)/ means we want to match only either a note or an actor
*
* @param mixed $note_expr
* @param mixed $actor_expr
*/
public function onSearchCreateExpression(ExpressionBuilder $eb, string $term, &$note_expr, &$actor_expr)
{

View File

@ -1,17 +1,19 @@
<?php
declare(strict_types = 1);
use App\Core\ModuleManager;
use Symfony\Component\Dotenv\Dotenv;
$loader = require dirname(__DIR__) . '/vendor/autoload.php';
$loader = require \dirname(__DIR__) . '/vendor/autoload.php';
// Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2)
if (\is_array($env = @include dirname(__DIR__) . '/.env.local.php') && (!isset($env['APP_ENV']) || ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? $env['APP_ENV']) === $env['APP_ENV'])) {
if (\is_array($env = @include \dirname(__DIR__) . '/.env.local.php') && (!isset($env['APP_ENV']) || ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? $env['APP_ENV']) === $env['APP_ENV'])) {
foreach ($env as $k => $v) {
$_ENV[$k] = $_ENV[$k] ?? (isset($_SERVER[$k]) && 0 !== strpos($k, 'HTTP_') ? $_SERVER[$k] : $v);
$_ENV[$k] = $_ENV[$k] ?? (isset($_SERVER[$k]) && !str_starts_with($k, 'HTTP_') ? $_SERVER[$k] : $v);
}
} elseif (!\class_exists(Dotenv::class)) {
} elseif (!class_exists(Dotenv::class)) {
throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
} else {
// load all the .env files
@ -20,37 +22,37 @@ if (\is_array($env = @include dirname(__DIR__) . '/.env.local.php') && (!isset($
$_SERVER += $_ENV;
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev';
$_SERVER['APP_DEBUG'] = $_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
$_SERVER['APP_DEBUG'] ??= $_ENV['APP_DEBUG'] ?? 'prod' !== $_SERVER['APP_ENV'];
$_SERVER['APP_DEBUG'] = $_ENV['APP_DEBUG'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], \FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
define('INSTALLDIR', dirname(__DIR__));
define('SRCDIR', INSTALLDIR . '/src');
define('PUBLICDIR', INSTALLDIR . '/public');
define('GNUSOCIAL_ENGINE_NAME', 'GNU social');
\define('INSTALLDIR', \dirname(__DIR__));
\define('SRCDIR', INSTALLDIR . '/src');
\define('PUBLICDIR', INSTALLDIR . '/public');
\define('GNUSOCIAL_ENGINE_NAME', 'GNU social');
// MERGE Change to https://gnu.io/social/
define('GNUSOCIAL_PROJECT_URL', 'https://gnusocial.rocks/');
define('GNUSOCIAL_ENGINE_URL', GNUSOCIAL_PROJECT_URL);
\define('GNUSOCIAL_PROJECT_URL', 'https://gnusocial.rocks/');
\define('GNUSOCIAL_ENGINE_URL', GNUSOCIAL_PROJECT_URL);
// MERGE Change to https://git.gnu.io/gnu/gnu-social
define('GNUSOCIAL_REPOSITORY_URL', 'https://code.undefinedhackers.net/GNUsocial/gnu-social');
\define('GNUSOCIAL_REPOSITORY_URL', 'https://code.undefinedhackers.net/GNUsocial/gnu-social');
// Current base version, major.minor.patch
define('GNUSOCIAL_BASE_VERSION', '3.0.0');
\define('GNUSOCIAL_BASE_VERSION', '3.0.0');
// 'dev', 'alpha[0-9]+', 'beta[0-9]+', 'rc[0-9]+', 'release'
define('GNUSOCIAL_LIFECYCLE', 'dev');
define('GNUSOCIAL_VERSION', GNUSOCIAL_BASE_VERSION . '-' . GNUSOCIAL_LIFECYCLE);
define('GNUSOCIAL_CODENAME', 'Big bang');
\define('GNUSOCIAL_LIFECYCLE', 'dev');
\define('GNUSOCIAL_VERSION', GNUSOCIAL_BASE_VERSION . '-' . GNUSOCIAL_LIFECYCLE);
\define('GNUSOCIAL_CODENAME', 'Big bang');
define('MODULE_CACHE_FILE', INSTALLDIR . '/var/cache/module_manager.php');
\define('MODULE_CACHE_FILE', INSTALLDIR . '/var/cache/module_manager.php');
/**
* StatusNet had this string as valid path characters: '\pN\pL\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\'\@'
* Some of those characters can be troublesome when auto-linking plain text. Such as "http://some.com/)"
* URL encoding should be used whenever a weird character is used, the following strings are not definitive.
*/
define('URL_REGEX_VALID_PATH_CHARS', '\pN\pL\,\!\.\:\-\_\+\/\@\=\;\%\~\*\(\)');
define('URL_REGEX_VALID_QSTRING_CHARS', URL_REGEX_VALID_PATH_CHARS . '\&');
define('URL_REGEX_VALID_FRAGMENT_CHARS', URL_REGEX_VALID_QSTRING_CHARS . '\?\#');
define('URL_REGEX_EXCLUDED_END_CHARS', '\?\.\,\!\#\:\''); // don't include these if they are directly after a URL
define('URL_REGEX_DOMAIN_NAME', '(?:(?!-)[A-Za-z0-9\-]{1,63}(?<!-)\.)+[A-Za-z]{2,10}');
\define('URL_REGEX_VALID_PATH_CHARS', '\pN\pL\,\!\.\:\-\_\+\/\@\=\;\%\~\*\(\)');
\define('URL_REGEX_VALID_QSTRING_CHARS', URL_REGEX_VALID_PATH_CHARS . '\&');
\define('URL_REGEX_VALID_FRAGMENT_CHARS', URL_REGEX_VALID_QSTRING_CHARS . '\?\#');
\define('URL_REGEX_EXCLUDED_END_CHARS', '\?\.\,\!\#\:\''); // don't include these if they are directly after a URL
\define('URL_REGEX_DOMAIN_NAME', '(?:(?!-)[A-Za-z0-9\-]{1,63}(?<!-)\.)+[A-Za-z]{2,10}');
// Work internally in UTC
date_default_timezone_set('UTC');

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
return [
Symfony\Bundle\FrameworkBundle\FrameworkBundle::class => ['all' => true],
Symfony\Bundle\TwigBundle\TwigBundle::class => ['all' => true],

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
require_once 'bootstrap.php';
use App\Kernel;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
require_once 'bootstrap.php';
use App\Kernel;

View File

@ -1,5 +1,7 @@
<?php
if (file_exists(dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php')) {
require dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php';
declare(strict_types = 1);
if (file_exists(\dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php')) {
require \dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
return function (RoutingConfigurator $routes) {

View File

@ -1,4 +1,6 @@
<?php
declare(strict_types = 1);
/**
* Validation class
*
@ -27,35 +29,38 @@
*
* @category Validate
* @package Validate
*
* @author Tomas V.V.Cox <cox@idecnet.com>
* @author Pierre-Alain Joye <pajoye@php.net>
* @author Amir Mohammad Saied <amir@php.net>
* @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*
* @version CVS: $Id$
* @link http://pear.php.net/package/Validate
*
* @see http://pear.php.net/package/Validate
*/
// {{{ Constants
/**
* Methods for common data validations
*/
define('VALIDATE_NUM', '0-9');
define('VALIDATE_SPACE', '\s');
define('VALIDATE_ALPHA_LOWER', 'a-z');
define('VALIDATE_ALPHA_UPPER', 'A-Z');
define('VALIDATE_ALPHA', VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER);
define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß');
define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖܾÂÊÎÔÛÃÑÕ¦ÅÆǼÐØÞ');
define('VALIDATE_EALPHA', VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER);
define('VALIDATE_PUNCTUATION', VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)');
define('VALIDATE_NAME', VALIDATE_EALPHA . VALIDATE_SPACE . "'" . '\-');
define('VALIDATE_STREET', VALIDATE_NUM . VALIDATE_NAME . "/\\ºª\.");
\define('VALIDATE_NUM', '0-9');
\define('VALIDATE_SPACE', '\s');
\define('VALIDATE_ALPHA_LOWER', 'a-z');
\define('VALIDATE_ALPHA_UPPER', 'A-Z');
\define('VALIDATE_ALPHA', VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER);
\define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß');
\define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖܾÂÊÎÔÛÃÑÕ¦ÅÆǼÐØÞ');
\define('VALIDATE_EALPHA', VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER);
\define('VALIDATE_PUNCTUATION', VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)');
\define('VALIDATE_NAME', VALIDATE_EALPHA . VALIDATE_SPACE . "'" . '\-');
\define('VALIDATE_STREET', VALIDATE_NUM . VALIDATE_NAME . '/\\ºª\\.');
define('VALIDATE_ITLD_EMAILS', 1);
define('VALIDATE_GTLD_EMAILS', 2);
define('VALIDATE_CCTLD_EMAILS', 4);
define('VALIDATE_ALL_EMAILS', 8);
\define('VALIDATE_ITLD_EMAILS', 1);
\define('VALIDATE_GTLD_EMAILS', 2);
\define('VALIDATE_CCTLD_EMAILS', 4);
\define('VALIDATE_ALL_EMAILS', 8);
// }}}
/**
@ -71,14 +76,17 @@ define('VALIDATE_ALL_EMAILS', 8);
*
* @category Validate
* @package Validate
*
* @author Tomas V.V.Cox <cox@idecnet.com>
* @author Pierre-Alain Joye <pajoye@php.net>
* @author Amir Mohammad Saied <amir@php.net>
* @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*
* @version Release: @package_version@
* @link http://pear.php.net/package/Validate
*
* @see http://pear.php.net/package/Validate
*/
class Validate
{
@ -91,7 +99,7 @@ class Validate
*
* @var array $itld (International top-level domains)
*/
protected static $itld = [
protected static array $itld = [
'arpa',
'root',
];
@ -104,7 +112,7 @@ class Validate
*
* @var array $gtld (Generic top-level domains)
*/
protected static $gtld = [
protected static array $gtld = [
'aero',
'biz',
'cat',
@ -137,7 +145,7 @@ class Validate
*
* @var array $cctld (Country Code Top-Level Domain)
*/
protected static $cctld = [
protected static array $cctld = [
'ac',
'ad', 'ae', 'af', 'ag',
'ai', 'al', 'am', 'an',
@ -210,10 +218,9 @@ class Validate
*
* @param string $uri tag URI to validate
*
* @return bool true if valid tag URI, false if not
*
* @access private
* @throws Exception
*
* @return bool true if valid tag URI, false if not
*/
private static function uriRFC4151(string $uri): bool
{
@ -221,15 +228,15 @@ class Validate
if (preg_match(
'/^tag:(?<name>.*),(?<date>\d{4}-?\d{0,2}-?\d{0,2}):(?<specific>.*)(.*:)*$/',
$uri,
$matches
$matches,
)) {
$date = $matches['date'];
$date6 = strtotime($date);
if ((strlen($date) == 4) && $date <= date('Y')) {
if ((mb_strlen($date) == 4) && $date <= date('Y')) {
$datevalid = true;
} elseif ((strlen($date) == 7) && ($date6 < strtotime("now"))) {
} elseif ((mb_strlen($date) == 7) && ($date6 < strtotime('now'))) {
$datevalid = true;
} elseif ((strlen($date) == 10) && ($date6 < strtotime("now"))) {
} elseif ((mb_strlen($date) == 10) && ($date6 < strtotime('now'))) {
$datevalid = true;
}
if (self::email($matches['name'])) {
@ -257,17 +264,17 @@ class Validate
*
* @return bool true if valid number, false if not
*/
public static function number($number, array $options = []): bool
public static function number(string $number, array $options = []): bool
{
$decimal = $dec_prec = $min = $max = null;
if (is_array($options)) {
if (\is_array($options)) {
extract($options);
}
$dec_prec = $dec_prec ? "{1,$dec_prec}" : '+';
$dec_regex = $decimal ? "[$decimal][0-9]$dec_prec" : '';
$dec_prec = $dec_prec ? "{1,{$dec_prec}}" : '+';
$dec_regex = $decimal ? "[{$decimal}][0-9]{$dec_prec}" : '';
if (!preg_match("|^[-+]?\s*[0-9]+($dec_regex)?\$|", $number)) {
if (!preg_match("|^[-+]?\\s*[0-9]+({$dec_regex})?\$|", $number)) {
return false;
}
@ -275,15 +282,12 @@ class Validate
$number = strtr($number, $decimal, '.');
}
$number = (float)str_replace(' ', '', $number);
$number = (float) str_replace(' ', '', $number);
if ($min !== null && $min > $number) {
return false;
}
if ($max !== null && $max < $number) {
return false;
}
return true;
return !($max !== null && $max < $number);
}
/**
@ -302,18 +306,17 @@ class Validate
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
'3', '4', '5', '6', '7', '8', '9', '+', ','
'3', '4', '5', '6', '7', '8', '9', '+', ',',
];
$state = 0;
if (!empty($string)) {
$i = 0;
while ($i <= strlen($string)) {
$char = substr($string, $i, 1);
while ($i <= mb_strlen($string)) {
$char = mb_substr($string, $i, 1);
if ($state == 0) {
if ((ord($char) >= 0x7F) || (ord($char) <= 0x1F)) {
if ((\ord($char) >= 0x7F) || (\ord($char) <= 0x1F)) {
if ($char) {
$return .= '&';
}
@ -323,13 +326,13 @@ class Validate
} else {
$return .= $char;
}
} elseif (($i == strlen($string) ||
!((ord($char) >= 0x7F)) || (ord($char) <= 0x1F))) {
} elseif (($i == mb_strlen($string)
|| !((\ord($char) >= 0x7F)) || (\ord($char) <= 0x1F))) {
if ($state != 1) {
if (ord($char) > 64) {
if (\ord($char) > 64) {
$return .= '';
} else {
$return .= $utf7[ord($char)];
$return .= $utf7[\ord($char)];
}
}
$return .= '-';
@ -337,23 +340,23 @@ class Validate
} else {
switch ($state) {
case 1:
$return .= $utf7[ord($char) >> 2];
$residue = (ord($char) & 0x03) << 4;
$return .= $utf7[\ord($char) >> 2];
$residue = (\ord($char) & 0x03) << 4;
$state = 2;
break;
case 2:
$return .= $utf7[$residue | (ord($char) >> 4)];
$residue = (ord($char) & 0x0F) << 2;
$return .= $utf7[$residue | (\ord($char) >> 4)];
$residue = (\ord($char) & 0x0F) << 2;
$state = 3;
break;
case 3:
$return .= $utf7[$residue | (ord($char) >> 6)];
$return .= $utf7[ord($char) & 0x3F];
$return .= $utf7[$residue | (\ord($char) >> 6)];
$return .= $utf7[\ord($char) & 0x3F];
$state = 1;
break;
}
}
$i++;
++$i;
}
return $return;
}
@ -416,9 +419,9 @@ class Validate
// / group ; named list
$address = '/^\s*(?:' . $mailbox . '|' . $group . ')$/';
$uncomment =
'/((?:(?:\\\\"|[^("])*(?:' . $quoted_string .
')?)*)((?<!\\\\)\((?:(?2)|.)*?(?<!\\\\)\))/';
$uncomment
= '/((?:(?:\\\\"|[^("])*(?:' . $quoted_string
. ')?)*)((?<!\\\\)\((?:(?2)|.)*?(?<!\\\\)\))/';
}
// strip comments
$email = preg_replace($uncomment, '$1 ', $email);
@ -431,27 +434,27 @@ class Validate
* This function is used to make a much more proficient validation
* against all types of official domain names.
*
* @param string $email The email address to check.
* @param string $email the email address to check
* @param array $options The options for validation
*
* @return bool True if validating succeeds
*/
protected static function fullTLDValidation(
string $email,
array $options
array $options,
): bool {
$validate = [];
if (!empty($options["VALIDATE_ITLD_EMAILS"])) {
array_push($validate, 'itld');
if (!empty($options['VALIDATE_ITLD_EMAILS'])) {
$validate[] = 'itld';
}
if (!empty($options["VALIDATE_GTLD_EMAILS"])) {
array_push($validate, 'gtld');
if (!empty($options['VALIDATE_GTLD_EMAILS'])) {
$validate[] = 'gtld';
}
if (!empty($options["VALIDATE_CCTLD_EMAILS"])) {
array_push($validate, 'cctld');
if (!empty($options['VALIDATE_CCTLD_EMAILS'])) {
$validate[] = 'cctld';
}
if (count($validate) === 0) {
if (\count($validate) === 0) {
array_push($validate, 'itld', 'gtld', 'cctld');
}
@ -460,7 +463,7 @@ class Validate
foreach ($validate as $valid) {
$tmpVar = (string) $valid;
$toValidate[$valid] = self::$$tmpVar;
$toValidate[$valid] = self::${$tmpVar};
}
$e = self::executeFullEmailValidation($email, $toValidate);
@ -474,19 +477,19 @@ class Validate
* This function will execute the full email vs tld
* validation using an array of tlds passed to it.
*
* @param string $email The email to validate.
* @param string $email the email to validate
* @param array $arrayOfTLDs The array of the TLDs to validate
*
* @return bool true or false (Depending on if it validates or if it does not)
*/
public static function executeFullEmailValidation(
string $email,
array $arrayOfTLDs
array $arrayOfTLDs,
): bool {
$emailEnding = explode('.', $email);
$emailEnding = $emailEnding[count($emailEnding) - 1];
$emailEnding = $emailEnding[\count($emailEnding) - 1];
foreach ($arrayOfTLDs as $validator => $keys) {
if (in_array($emailEnding, $keys)) {
if (\in_array($emailEnding, $keys)) {
return true;
}
}
@ -511,18 +514,19 @@ class Validate
* 'VALIDATE_CCTLD_EMAILS' => 'true',
* 'VALIDATE_ITLD_EMAILS' => 'true',
* ];
*
* @return bool true if valid email, false if not
* @param null|mixed $options
*
* @throws Exception
*
* @return bool true if valid email, false if not
*/
public static function email(string $email, $options = null): bool
{
$check_domain = false;
$use_rfc822 = false;
if (is_bool($options)) {
if (\is_bool($options)) {
$check_domain = $options;
} elseif (is_array($options)) {
} elseif (\is_array($options)) {
extract($options);
}
@ -538,7 +542,7 @@ class Validate
}
if ($hasIDNA === true) {
if (strpos($email, '@') !== false) {
if (str_contains($email, '@')) {
$tmpEmail = explode('@', $email);
$domain = array_pop($tmpEmail);
@ -546,11 +550,11 @@ class Validate
// it's an idn domain name.
$chars = count_chars($domain, 1);
if (!empty($chars) && max(array_keys($chars)) > 127) {
$idna =& Net_IDNA2::singleton();
$idna = &Net_IDNA2::singleton();
$domain = $idna->encode($domain);
}
array_push($tmpEmail, $domain);
$tmpEmail[] = $domain;
$email = implode('@', $tmpEmail);
}
}
@ -580,14 +584,11 @@ class Validate
$&xi';
//checks if exists the domain (MX or A)
if ($use_rfc822 ? self::emailRFC822($email, $options) :
preg_match($regex, $email)) {
if ($check_domain && function_exists('checkdnsrr')) {
if ($use_rfc822 ? self::emailRFC822($email, $options)
: preg_match($regex, $email)) {
if ($check_domain && \function_exists('checkdnsrr')) {
$domain = preg_replace('/[^-a-z.0-9]/i', '', array_pop(explode('@', $email)));
if (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')) {
return true;
}
return false;
return (bool) (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A'));
}
return true;
}
@ -612,23 +613,19 @@ class Validate
$min_length = 0;
$max_length = 0;
if (is_array($options)) {
if (\is_array($options)) {
extract($options);
}
if ($format && !preg_match("|^[$format]*\$|s", $string)) {
if ($format && !preg_match("|^[{$format}]*\$|s", $string)) {
return false;
}
if ($min_length && strlen($string) < $min_length) {
if ($min_length && mb_strlen($string) < $min_length) {
return false;
}
if ($max_length && strlen($string) > $max_length) {
return false;
}
return true;
return !($max_length && mb_strlen($string) > $max_length);
}
/**
@ -652,7 +649,7 @@ class Validate
* if not urlencoded, refer to the option "strict'"
*
* @param string $url URI to validate
* @param array|null $options Options used by the validation method.
* @param null|array $options Options used by the validation method.
* key => type
* 'domain_check' => boolean
* Whether to check the DNS entry or not
@ -664,22 +661,22 @@ class Validate
* default: ';/?:@$,'
* empty: accept all rfc2396 foreseen chars
*
* @return bool true if valid uri, false if not
*
* @throws Exception
*
* @return bool true if valid uri, false if not
*/
public static function uri(string $url, ?array $options = null): bool
{
$strict = ';/?:@$,';
$domain_check = false;
$allowed_schemes = null;
if (is_array($options)) {
if (\is_array($options)) {
extract($options);
}
if (is_array($allowed_schemes) &&
in_array("tag", $allowed_schemes)
if (\is_array($allowed_schemes)
&& \in_array('tag', $allowed_schemes)
) {
if (strpos($url, "tag:") === 0) {
if (str_starts_with($url, 'tag:')) {
return self::uriRFC4151($url);
}
}
@ -696,12 +693,12 @@ class Validate
(?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();/?:@\&=+$,])*))? # 8. fragment
$&xi',
$url,
$matches
$matches,
)) {
$scheme = isset($matches[1]) ? $matches[1] : '';
$authority = isset($matches[3]) ? $matches[3] : '';
if (is_array($allowed_schemes) &&
!in_array($scheme, $allowed_schemes)
$scheme = $matches[1] ?? '';
$authority = $matches[3] ?? '';
if (\is_array($allowed_schemes)
&& !\in_array($scheme, $allowed_schemes)
) {
return false;
}
@ -712,7 +709,7 @@ class Validate
return false;
}
}
} elseif ($domain_check && function_exists('checkdnsrr')) {
} elseif ($domain_check && \function_exists('checkdnsrr')) {
if (!checkdnsrr($authority, 'A')) {
return false;
}
@ -734,38 +731,36 @@ class Validate
*
* @param string &$date Date
* @param string $num Length
* @param string|false $opt Unknown
*
* @return string
* @param false|string $opt Unknown
*/
private static function substr(
string &$date,
string $num,
$opt = false
$opt = false,
): string {
if (
$opt
&& strlen($date) >= $opt
&& mb_strlen($date) >= $opt
&& preg_match('/^[0-9]{' . $opt . '}/', $date, $m)
) {
$ret = $m[0];
} else {
$ret = substr($date, 0, $num);
$ret = mb_substr($date, 0, $num);
}
$date = substr($date, strlen($ret));
$date = mb_substr($date, mb_strlen($ret));
return $ret;
}
protected static function modf($val, $div)
{
if (function_exists('bcmod')) {
if (\function_exists('bcmod')) {
return bcmod($val, $div);
} elseif (function_exists('fmod')) {
} elseif (\function_exists('fmod')) {
return fmod($val, $div);
}
$r = $val / $div;
$i = intval($r);
return intval($val - $i * $div + .1);
$i = (int) $r;
return (int) ($val - $i * $div + .1);
}
/**
@ -778,19 +773,19 @@ class Validate
*/
protected static function multWeights(
string $number,
array &$weights
array &$weights,
): int {
if (!is_array($weights)) {
if (!\is_array($weights)) {
return -1;
}
$sum = 0;
$count = min(count($weights), strlen($number));
$count = min(\count($weights), mb_strlen($number));
if ($count == 0) { // empty string or weights array
return -1;
}
for ($i = 0; $i < $count; ++$i) {
$sum += intval(substr($number, $i, 1)) * $weights[$i];
$sum += (int) (mb_substr($number, $i, 1)) * $weights[$i];
}
return $sum;
@ -812,7 +807,7 @@ class Validate
array &$weights,
int $modulo = 10,
int $subtract = 0,
bool $allow_high = false
bool $allow_high = false,
): int {
// calc sum
$sum = self::multWeights($number, $weights);
@ -844,19 +839,18 @@ class Validate
string $number,
array &$weights,
int $modulo = 10,
int $subtract = 0
): bool
{
if (strlen($number) < count($weights)) {
int $subtract = 0,
): bool {
if (mb_strlen($number) < \count($weights)) {
return false;
}
$target_digit = substr($number, count($weights), 1);
$target_digit = mb_substr($number, \count($weights), 1);
$control_digit = self::getControlNumber(
$number,
$weights,
$modulo,
$subtract,
($modulo > 10)
($modulo > 10),
);
if ($control_digit == -1) {
@ -865,10 +859,7 @@ class Validate
if ($target_digit === 'X' && $control_digit == 10) {
return true;
}
if ($control_digit != $target_digit) {
return false;
}
return true;
return !($control_digit != $target_digit);
}
/**
@ -889,7 +880,7 @@ class Validate
public static function multiple(
array &$data,
array &$val_type,
bool $remove = false
bool $remove = false,
): array {
$keys = array_keys($data);
$valid = [];
@ -905,41 +896,41 @@ class Validate
$methods = get_class_methods('Validate');
$val2check = $data[$var_name];
// core validation method
if (in_array(strtolower($opt['type']), $methods)) {
if (\in_array(mb_strtolower($opt['type']), $methods)) {
//$opt[$opt['type']] = $data[$var_name];
$method = $opt['type'];
unset($opt['type']);
if (sizeof($opt) == 1 && is_array(reset($opt))) {
if (sizeof($opt) == 1 && \is_array(reset($opt))) {
$opt = array_pop($opt);
}
$valid[$var_name] = call_user_func(['Validate', $method], $val2check, $opt);
$valid[$var_name] = \call_user_func(['Validate', $method], $val2check, $opt);
/**
* external validation method in the form:
* "<class name><underscore><method name>"
* Ex: us_ssn will include class Validate/US.php and call method ssn()
*/
} elseif (strpos($opt['type'], '_') !== false) {
} elseif (str_contains($opt['type'], '_')) {
$validateType = explode('_', $opt['type']);
$method = array_pop($validateType);
$class = implode('_', $validateType);
$classPath = str_replace('_', DIRECTORY_SEPARATOR, $class);
$classPath = str_replace('_', \DIRECTORY_SEPARATOR, $class);
$class = 'Validate_' . $class;
if (self::includePathFileExists("Validate/{$classPath}.php")) {
include_once "Validate/{$classPath}.php";
} else {
trigger_error("$class isn't installed or you may have some permission issues", E_USER_ERROR);
trigger_error("{$class} isn't installed or you may have some permission issues", \E_USER_ERROR);
}
$ce = substr(phpversion(), 0, 1) > 4 ?
class_exists($class, false) : class_exists($class);
if (!$ce ||
!in_array($method, get_class_methods($class))
$ce = mb_substr(phpversion(), 0, 1) > 4
? class_exists($class, false) : class_exists($class);
if (!$ce
|| !\in_array($method, get_class_methods($class))
) {
trigger_error(
"Invalid validation type $class::$method",
E_USER_WARNING
"Invalid validation type {$class}::{$method}",
\E_USER_WARNING,
);
continue;
}
@ -947,15 +938,15 @@ class Validate
if (sizeof($opt) == 1) {
$opt = array_pop($opt);
}
$valid[$var_name] = call_user_func(
array($class, $method),
$valid[$var_name] = \call_user_func(
[$class, $method],
$data[$var_name],
$opt
$opt,
);
} else {
trigger_error(
"Invalid validation type {$opt['type']}",
E_USER_WARNING
\E_USER_WARNING,
);
}
}
@ -971,11 +962,11 @@ class Validate
*/
private static function includePathFileExists(string $filename): bool
{
$paths = explode(":", ini_get("include_path"));
$paths = explode(':', ini_get('include_path'));
$result = false;
foreach ($paths as $val) {
$result = file_exists($val . "/" . $filename);
$result = file_exists($val . '/' . $filename);
if ($result) {
break;
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub;
use App\Core\Event;
@ -23,9 +25,7 @@ class ActivityPub extends Plugin
* This code executes when GNU social creates the page routing, and we hook
* on this event to add our Inbox and Outbox handler for ActivityPub.
*
* @param RouteLoader $r the router that was initialized.
*
* @return bool
* @param RouteLoader $r the router that was initialized
*/
public function onAddRoute(RouteLoader $r): bool
{
@ -33,19 +33,19 @@ class ActivityPub extends Plugin
'activitypub_actor_inbox',
'/actor/{gsactor_id<\d+>}/inbox.json',
[Inbox::class, 'handle'],
options: ['accept' => self::$accept_headers]
options: ['accept' => self::$accept_headers],
);
$r->connect(
'activitypub_actor_outbox',
'/actor/{gsactor_id<\d+>}/outbox.json',
[Inbox::class, 'handle'],
options: ['accept' => self::$accept_headers]
options: ['accept' => self::$accept_headers],
);
$r->connect(
'activitypub_inbox',
'/inbox.json',
[Inbox::class, 'handle'],
options: ['accept' => self::$accept_headers]
options: ['accept' => self::$accept_headers],
);
return Event::next;
}
@ -53,23 +53,19 @@ class ActivityPub extends Plugin
/**
* Validate HTTP Accept headers
*
* @param null|array|string $accept
* @param bool $strict Strict mode
*
* @throws Exception when strict mode enabled
*
* @return bool
*
*/
public static function validateAcceptHeader(array|string|null $accept, bool $strict): bool
{
if (is_string($accept)
&& in_array($accept, self::$accept_headers)
if (\is_string($accept)
&& \in_array($accept, self::$accept_headers)
) {
return true;
} elseif (is_array($accept)
&& count(
array_intersect($accept, self::$accept_headers)
} elseif (\is_array($accept)
&& \count(
array_intersect($accept, self::$accept_headers),
) > 0
) {
return true;
@ -82,8 +78,8 @@ class ActivityPub extends Plugin
throw new Exception(
sprintf(
"HTTP Accept header error. Given: '%s'",
$accept
)
$accept,
),
);
}
@ -95,20 +91,11 @@ class ActivityPub extends Plugin
];
/**
* @param string $route
* @param array $accept_header
* @param array $vars
* @param null|TypeResponse $response
*
* @throws Exception
*
* @return bool
*
*
*/
public function onControllerResponseInFormat(string $route, array $accept_header, array $vars, ?TypeResponse &$response = null): bool
{
if (count(array_intersect(self::$accept_headers, $accept_header)) === 0) {
if (\count(array_intersect(self::$accept_headers, $accept_header)) === 0) {
return Event::next;
}
switch ($route) {

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -38,9 +40,9 @@ class Inbox extends Controller
*/
public function handle(?int $gsactor_id = null)
{
if (!is_null($gsactor_id)) {
if (!\is_null($gsactor_id)) {
$user = DB::find('local_user', ['id' => $gsactor_id]);
if (is_null($user)) {
if (\is_null($user)) {
throw new ClientException(_m('No such actor.'), 404);
}
}
@ -48,14 +50,14 @@ class Inbox extends Controller
// Check accept header
ActivityPub::validateAcceptHeader(
$this->request->headers->get('accept'),
true
true,
);
// TODO: Check if Actor can post
// Get content
$payload = Util::decodeJson(
(string) $this->request->getContent()
(string) $this->request->getContent(),
);
// Cast as an ActivityStreams type

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -49,8 +51,8 @@ class ActivitypubActivity extends Entity
private string $object_uri;
private bool $is_local;
private ?string $source;
private \DateTimeInterface $created;
private \DateTimeInterface $modified;
private DateTimeInterface $created;
private DateTimeInterface $modified;
public function setId(int $id): self
{

View File

@ -1,4 +1,6 @@
<?php
declare(strict_types = 1);
// {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social
@ -48,100 +50,64 @@ class ActivitypubActor extends Entity
private int $actor_id;
private string $inbox_uri;
private ?string $inbox_shared_uri = null;
private \DateTimeInterface $created;
private \DateTimeInterface $modified;
private DateTimeInterface $created;
private DateTimeInterface $modified;
/**
* @return string
*/
public function getUri(): string
{
return $this->uri;
}
/**
* @param string $uri
*/
public function setUri(string $uri): void
{
$this->uri = $uri;
}
/**
* @return int
*/
public function getActorId(): int
{
return $this->actor_id;
}
/**
* @param int $actor_id
*/
public function setActorId(int $actor_id): void
{
$this->actor_id = $actor_id;
}
/**
* @return string
*/
public function getInboxUri(): string
{
return $this->inbox_uri;
}
/**
* @param string $inbox_uri
*/
public function setInboxUri(string $inbox_uri): void
{
$this->inbox_uri = $inbox_uri;
}
/**
* @return string
*/
public function getInboxSharedUri(): string
{
return $this->inbox_shared_uri;
}
/**
* @param string $inbox_shared_uri
*/
public function setInboxSharedUri(string $inbox_shared_uri): void
{
$this->inbox_shared_uri = $inbox_shared_uri;
}
/**
* @return DateTimeInterface
*/
public function getCreated(): DateTimeInterface
{
return $this->created;
}
/**
* @param DateTimeInterface $created
*/
public function setCreated(DateTimeInterface $created): void
{
$this->created = $created;
}
/**
* @return DateTimeInterface
*/
public function getModified(): DateTimeInterface
{
return $this->modified;
}
/**
* @param DateTimeInterface $modified
*/
public function setModified(DateTimeInterface $modified): void
{
$this->modified = $modified;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Model\AS2ToEntity;
use App\Core\DB\DB;
@ -29,12 +31,7 @@ abstract class AS2ToEntity
}
/**
* @param array $activity
* @param null|string $source
*
* @throws ClientException
*
* @return array
*/
public static function store(array $activity, ?string $source = null): array
{
@ -58,7 +55,7 @@ abstract class AS2ToEntity
$obj = null;
switch ($activity['object']['type']) {
case'Note':
case 'Note':
$obj = AS2ToNote::translate($activity['object'], $source);
break;
default:

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Model\AS2ToEntity;
use App\Core\Event;
@ -7,13 +9,12 @@ use App\Entity\Actor;
use App\Entity\Note;
use App\Util\Formatting;
use DateTime;
use Exception;
abstract class AS2ToGSActor
{
/**
* @param array $args
*
* @throws \Exception
* @throws Exception
*
* @return Note
*/

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Model\AS2ToEntity;
use App\Core\Event;
@ -8,16 +10,12 @@ use App\Entity\Note;
use App\Util\Formatting;
use Component\FreeNetwork\Entity\FreenetworkActor;
use DateTime;
use Exception;
abstract class AS2ToNote
{
/**
* @param array $object
*
*@throws \Exception
*
* @return Note
*
*@throws Exception
*/
public static function translate(array $object, ?string $source = null): Note
{
@ -27,7 +25,7 @@ abstract class AS2ToNote
'created' => new DateTime($object['published'] ?? 'now'),
'content' => $object['content'] ?? null,
'content_type' => 'text/html',
'url' => array_key_exists('url', $object) ? $object['url'] : $object['id'],
'url' => \array_key_exists('url', $object) ? $object['url'] : $object['id'],
'actor_id' => $actor_id,
'modified' => new DateTime(),
'source' => $source,

View File

@ -1,20 +1,19 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Model\EntityToType;
use App\Core\Entity;
use Exception;
use Plugin\ActivityPub\Util\Type;
abstract class EntityToType
{
/**
* @param Entity $entity
*
* @throws \Exception
*
* @return Type
* @throws Exception
*/
public static function translate($entity)
public static function translate(Entity $entity): Type
{
switch ($entity::class) {
case 'Note':

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Model\EntityToType;
use App\Core\Event;
@ -14,14 +16,9 @@ use Plugin\ActivityPub\Util\Type;
class GSActorToType
{
/**
* @param Actor $gsactor
*
*@throws Exception
*
* @return Type
*
*/
public static function translate(Actor $gsactor)
public static function translate(Actor $gsactor): Type
{
$uri = null;
Event::handle('FreeNetworkGenerateLocalActorUri', ['source' => 'ActivityPub', 'actor_id' => $gsactor->getId(), 'actor_uri' => &$attributedTo]);

View File

@ -1,23 +1,22 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Model\EntityToType;
use App\Core\Event;
use App\Core\Router\Router;
use App\Entity\Note;
use DateTimeInterface;
use Exception;
use Plugin\ActivityPub\Util\Type;
class NoteToType
{
/**
* @param Note $note
*
* @throws \Exception
*
* @return Type
* @throws Exception
*/
public static function translate(Note $note)
public static function translate(Note $note): Type
{
$attributedTo = null;
Event::handle('FreeNetworkGenerateLocalActorUri', ['source' => 'ActivityPub', 'actor_id' => $note->getActorId(), 'actor_uri' => &$attributedTo]);

View File

@ -1,7 +1,10 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Response;
use Exception;
use Plugin\ActivityPub\Util\Model\EntityToType\EntityToType;
abstract class AbstractResponse
@ -10,17 +13,14 @@ abstract class AbstractResponse
* param Type $type // What is this `Type`
*
* @param int $status The response status code
* @param mixed $type
*
* @throws \Exception
*
* @return TypeResponse
* @throws Exception
*/
public static function handle($type, int $status = 200): TypeResponse
{
return new TypeResponse(
data: EntityToType::translate($type),
status: $status
status: $status,
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Response;
use App\Entity\Actor;
@ -9,13 +11,9 @@ use Plugin\ActivityPub\Util\Model\EntityToType\GSActorToType;
abstract class ActorResponse
{
/**
* @param Actor $gsactor
* @param int $status The response status code
*
*@throws Exception
*
* @return TypeResponse
*
*/
public static function handle(Actor $gsactor, int $status = 200): TypeResponse
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Response;
use App\Entity\Note;
@ -10,12 +12,9 @@ abstract class NoteResponse
//class NoteResponse extends Controller
{
/**
* @param Note $note
* @param int $status The response status code
*
* @throws Exception
*
* @return TypeResponse
*/
public static function handle(Note $note, int $status = 200): TypeResponse
// public function handle(Request $request, int $id): JsonResponse

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
@ -17,10 +19,10 @@ class TypeResponse extends JsonResponse
public function __construct($data = null, int $status = 202)
{
parent::__construct(
data: !is_null($data) ? $data->toJson() : null,
data: !\is_null($data) ? $data->toJson() : null,
status: $status,
headers: ['content-type' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"'],
json: true
json: true,
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -42,22 +44,20 @@ abstract class Type
* @param array<string,mixed> $attributes
*
* @throws Exception
*
* @return mixed
*/
public static function create($type, array $attributes = [])
public static function create($type, array $attributes = []): mixed
{
if (!is_string($type) && !is_array($type)) {
if (!\is_string($type) && !\is_array($type)) {
throw new Exception(
'Type parameter must be a string or an array. Given='
. gettype($type)
. \gettype($type),
);
}
if (is_array($type)) {
if (\is_array($type)) {
if (!isset($type['type'])) {
throw new Exception(
"Type parameter must have a 'type' key"
"Type parameter must have a 'type' key",
);
}
@ -65,17 +65,17 @@ abstract class Type
}
try {
$class = is_array($type)
$class = \is_array($type)
? TypeResolver::getClass($type['type'])
: TypeResolver::getClass($type);
} catch (Exception $exception) {
$message = json_encode($attributes, JSON_PRETTY_PRINT);
$message = json_encode($attributes, \JSON_PRETTY_PRINT);
throw new Exception(
$exception->getMessage() . "\n{$message}"
$exception->getMessage() . "\n{$message}",
);
}
if (is_string($class)) {
if (\is_string($class)) {
$class = new $class();
}
@ -97,8 +97,8 @@ abstract class Type
{
$data = json_decode($json, true);
if (json_last_error() === JSON_ERROR_NONE
&& is_array($data)
if (json_last_error() === \JSON_ERROR_NONE
&& \is_array($data)
) {
return self::create($data);
}
@ -106,8 +106,8 @@ abstract class Type
throw new Exception(
sprintf(
"An error occurred during the JSON decoding.\n '%s'",
$json
)
$json,
),
);
}
@ -115,7 +115,7 @@ abstract class Type
* Add a custom validator for an attribute.
* It checks that it implements Validator\Interface
*
* @param string $name An attribute name to validate.
* @param string $name an attribute name to validate
* @param string $class A validator class name
*/
public static function addValidator(string $name, string $class): void

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -11,10 +13,10 @@
namespace Plugin\ActivityPub\Util\Type;
use function array_key_exists;
use Exception;
use Plugin\ActivityPub\Util\Type;
use ReflectionClass;
use ReflectionProperty;
/**
* \ActivityPhp\Type\ObjectAbstract is an abstract class for all
@ -26,8 +28,6 @@ abstract class AbstractObject
{
/**
* Keep all properties values that have been set
*
* @var array
*/
private array $_props = [];
@ -37,9 +37,6 @@ abstract class AbstractObject
* Standard setter method
* - Perform content validation if a validator exists
*
* @param string $name
* @param mixed $value
*
* @throws Exception
*
* @return $this
@ -59,9 +56,9 @@ abstract class AbstractObject
$message,
static::class,
$name,
print_r($value, true)
print_r($value, true),
)
. PHP_EOL
. \PHP_EOL,
);
}
@ -85,26 +82,22 @@ abstract class AbstractObject
/**
* Affect a value to a property or an extended property
*
* @param mixed $value
*
* @throws Exception
*
* @return mixed
*/
private function transform(mixed $value): mixed
{
// Deep typing
if (is_array($value)) {
if (\is_array($value)) {
if (isset($value['type'])) {
return Type::create($value);
} elseif (is_int(key($value))) {
} elseif (\is_int(key($value))) {
return array_map(
static function ($value) {
return is_array($value) && isset($value['type'])
return \is_array($value) && isset($value['type'])
? Type::create($value)
: $value;
},
$value
$value,
);
// Empty array, array that should not be cast as ActivityStreams types
} else {
@ -119,11 +112,7 @@ abstract class AbstractObject
/**
* Standard getter method
*
* @param string $name
*
* @throws Exception
*
* @return mixed
*/
public function get(string $name): mixed
{
@ -136,43 +125,39 @@ abstract class AbstractObject
/**
* Checks that property exists
*
* @param string $name
*
* @throws Exception
*
* @return bool
*/
public function has(string $name): bool
{
if (isset($this->{$name})) {
if (!array_key_exists($name, $this->_props)) {
if (!\array_key_exists($name, $this->_props)) {
$this->_props[$name] = $this->{$name};
}
return true;
}
if (array_key_exists($name, $this->_props)) {
if (\array_key_exists($name, $this->_props)) {
return true;
}
$reflect = new ReflectionClass(Type::create($this->type));
$allowed_props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED);
$allowed_props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
$allowed = [];
foreach ($allowed_props as $prop) {
$allowed[] = $prop->getName();
}
if (!in_array($name, $allowed)) {
if (!\in_array($name, $allowed)) {
sort($allowed);
throw new Exception(
sprintf(
'Property "%s" is not defined. Type="%s", ' .
'Class="%s"' . PHP_EOL . 'Allowed properties: %s',
'Property "%s" is not defined. Type="%s", '
. 'Class="%s"' . \PHP_EOL . 'Allowed properties: %s',
$name,
$this->get('type'),
static::class,
implode(', ', $allowed)
)
implode(', ', $allowed),
),
);
} else {
return false;
@ -181,8 +166,6 @@ abstract class AbstractObject
/**
* Get a list of all properties names
*
* @return array
*/
public function getProperties(): array
{
@ -193,11 +176,11 @@ abstract class AbstractObject
array_keys(
array_diff_key(
get_object_vars($this),
['_props' => '1']
)
)
)
)
['_props' => '1'],
),
),
),
),
);
}
@ -211,11 +194,9 @@ abstract class AbstractObject
$keys = array_keys(
array_filter(
get_object_vars($this),
static function ($value, $key): bool {
return !is_null($value) && $key !== '_props';
},
ARRAY_FILTER_USE_BOTH
)
static fn ($value, $key): bool => !\is_null($value) && $key !== '_props',
\ARRAY_FILTER_USE_BOTH,
),
);
$stack = [];
@ -224,17 +205,17 @@ abstract class AbstractObject
foreach ($keys as $key) {
if ($this->{$key} instanceof self) {
$stack[$key] = $this->{$key}->toArray();
} elseif (!is_array($this->{$key})) {
} elseif (!\is_array($this->{$key})) {
$stack[$key] = $this->{$key};
} elseif (is_array($this->{$key})) {
if (is_int(key($this->{$key}))) {
} elseif (\is_array($this->{$key})) {
if (\is_int(key($this->{$key}))) {
$stack[$key] = array_map(
static function ($value) {
return $value instanceof self
? $value->toArray()
: $value;
},
$this->{$key}
$this->{$key},
);
} else {
$stack[$key] = $this->{$key};
@ -244,23 +225,23 @@ abstract class AbstractObject
// _props
foreach ($this->_props as $key => $value) {
if (is_null($value)) {
if (\is_null($value)) {
continue;
}
if ($value instanceof self) {
$stack[$key] = $value->toArray();
} elseif (!is_array($value)) {
} elseif (!\is_array($value)) {
$stack[$key] = $value;
} else {
if (is_int(key($value))) {
if (\is_int(key($value))) {
$stack[$key] = array_map(
static function ($value) {
return $value instanceof self
? $value->toArray()
: $value;
},
$value
$value,
);
} else {
$stack[$key] = $value;
@ -275,14 +256,12 @@ abstract class AbstractObject
* Get a JSON
*
* @param null|int $options PHP JSON options
*
* @return string
*/
public function toJson(?int $options = null): string
{
return json_encode(
$this->toArray(),
(int) $options
(int) $options,
);
}
@ -297,14 +276,13 @@ abstract class AbstractObject
{
return Type::create(
$this->type,
$this->toArray()
$this->toArray(),
);
}
/**
* Extend current type properties
*
* @param string $property
* @param mixed $default
*
* @throws Exception
@ -315,7 +293,7 @@ abstract class AbstractObject
return;
}
if (!array_key_exists($property, $this->_props)) {
if (!\array_key_exists($property, $this->_props)) {
$this->_props[$property] = $default;
}
}
@ -326,15 +304,12 @@ abstract class AbstractObject
public function __isset(string $name): bool
{
return property_exists($this, $name)
|| array_key_exists($name, $this->_props);
|| \array_key_exists($name, $this->_props);
}
/**
* Magical setter method
*
* @param string $name
* @param mixed $value
*
* @throws Exception
*/
public function __set(string $name, mixed $value): void
@ -345,11 +320,7 @@ abstract class AbstractObject
/**
* Magical getter method
*
* @param string $name
*
* @throws Exception
*
* @return mixed
*/
public function __get(string $name): mixed
{
@ -359,32 +330,27 @@ abstract class AbstractObject
/**
* Overloading methods
*
* @param string $name
* @param null|array $arguments
*
* @throws Exception
*
* @return mixed
*/
public function __call(string $name, ?array $arguments = [])
public function __call(string $name, ?array $arguments = []): mixed
{
// Getters
if (str_starts_with($name, 'get')) {
$attr = lcfirst(substr($name, 3));
$attr = lcfirst(mb_substr($name, 3));
return $this->get($attr);
}
// Setters
if (str_starts_with($name, 'set')) {
if (count($arguments) === 1) {
$attr = lcfirst(substr($name, 3));
if (\count($arguments) === 1) {
$attr = lcfirst(mb_substr($name, 3));
return $this->set($attr, $arguments[0]);
} else {
throw new Exception(
sprintf(
'Expected exactly one argument for method "%s()"',
$name
)
$name,
),
);
}
}
@ -392,8 +358,8 @@ abstract class AbstractObject
throw new Exception(
sprintf(
'Method "%s" is not defined',
$name
)
$name,
),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,9 +26,6 @@ namespace Plugin\ActivityPub\Util\Type\Core;
*/
abstract class AbstractActivity extends ObjectType
{
/**
* @var string
*/
public string $id;
/**

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,9 +25,6 @@ namespace Plugin\ActivityPub\Util\Type\Core;
*/
class Activity extends AbstractActivity
{
/**
* @var string
*/
protected string $type = 'Activity';
/**

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -22,14 +24,8 @@ namespace Plugin\ActivityPub\Util\Type\Core;
*/
class Collection extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Collection';
/**
* @var string
*/
public string $id;
/**
@ -39,8 +35,6 @@ class Collection extends ObjectType
* serialized within the Collection object instance.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-totalitems
*
* @var int
*/
protected int $totalItems;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -21,14 +23,8 @@ namespace Plugin\ActivityPub\Util\Type\Core;
*/
class CollectionPage extends Collection
{
/**
* @var string
*/
protected string $type = 'CollectionPage';
/**
* @var string
*/
public string $id;
/**

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ namespace Plugin\ActivityPub\Util\Type\Core;
*/
class IntransitiveActivity extends AbstractActivity
{
/**
* @var string
*/
protected string $type = 'IntransitiveActivity';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -26,14 +28,8 @@ use Plugin\ActivityPub\Util\Type\AbstractObject;
*/
class Link extends AbstractObject
{
/**
* @var string
*/
protected string $type = 'Link';
/**
* @var string
*/
protected string $id;
/**
@ -59,8 +55,6 @@ class Link extends AbstractObject
* The target resource pointed to by a Link.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-href
*
* @var null|string
*/
protected ?string $href;
@ -69,8 +63,6 @@ class Link extends AbstractObject
* Value MUST be a BCP47 Language-Tag.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-hreflang
*
* @var null|string
*/
protected ?string $hreflang;
@ -78,8 +70,6 @@ class Link extends AbstractObject
* The MIME media type of the referenced resource.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-mediatype
*
* @var null|string
*/
protected ?string $mediaType;
@ -89,8 +79,6 @@ class Link extends AbstractObject
* and RFC5988 "link relation" definitions.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-rel
*
* @var null|array|string
*/
protected string|array|null $rel;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -31,14 +33,9 @@ class ObjectType extends AbstractObject
* The object's unique global identifier
*
* @see https://www.w3.org/TR/activitypub/#obj-id
*
* @var string
*/
public string $id;
/**
* @var string
*/
protected string $type = 'Object';
/**
@ -99,8 +96,6 @@ class ObjectType extends AbstractObject
* values.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-content
*
* @var null|string
*/
protected ?string $content;
@ -127,8 +122,6 @@ class ObjectType extends AbstractObject
* values.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-content
*
* @var null|array
*/
protected ?array $contentMap;
@ -159,15 +152,11 @@ class ObjectType extends AbstractObject
* is expected to conclude.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-endtime
*
* @var null|string
*/
protected ?string $endTime;
/**
* The entity (e.g. an application) that generated the object.
*
* @var null|string
*/
protected ?string $generator;
@ -408,8 +397,6 @@ class ObjectType extends AbstractObject
* text/html content.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-mediatype
*
* @var null|string
*/
protected ?string $mediaType;
@ -422,8 +409,6 @@ class ObjectType extends AbstractObject
* represented as "PT5S").
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
*
* @var null|string
*/
protected ?string $duration;
@ -433,8 +418,6 @@ class ObjectType extends AbstractObject
* future editing by clients.
*
* @see https://www.w3.org/TR/activitypub/#source-property
*
* @var ObjectType
*/
protected ObjectType $source;
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -22,8 +24,5 @@ namespace Plugin\ActivityPub\Util\Type\Core;
*/
class OrderedCollection extends Collection
{
/**
* @var string
*/
protected string $type = 'OrderedCollection';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -26,16 +28,11 @@ namespace Plugin\ActivityPub\Util\Type\Core;
*/
class OrderedCollectionPage extends CollectionPage
{
/**
* @var string
*/
protected string $type = 'OrderedCollectionPage';
/**
* A non-negative integer value identifying the relative position
* within the logical view of a strictly ordered collection.
*
* @var int
*/
protected int $startIndex;
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -49,8 +51,6 @@ abstract class AbstractActor extends ObjectType
* actor is following.
*
* @see https://www.w3.org/TR/activitypub/#following
*
* @var string
*/
protected string $following;
@ -59,8 +59,6 @@ abstract class AbstractActor extends ObjectType
* follow this actor.
*
* @see https://www.w3.org/TR/activitypub/#followers
*
* @var string
*/
protected string $followers;
@ -69,8 +67,6 @@ abstract class AbstractActor extends ObjectType
* liked.
*
* @see https://www.w3.org/TR/activitypub/#liked
*
* @var string
*/
protected string $liked;
@ -78,8 +74,6 @@ abstract class AbstractActor extends ObjectType
* A list of supplementary Collections which may be of interest.
*
* @see https://www.w3.org/TR/activitypub/#streams-property
*
* @var array
*/
protected array $streams = [];
@ -88,8 +82,6 @@ abstract class AbstractActor extends ObjectType
* uniqueness guarantees.
*
* @see https://www.w3.org/TR/activitypub/#preferredUsername
*
* @var null|string
*/
protected ?string $preferredUsername;
@ -101,8 +93,6 @@ abstract class AbstractActor extends ObjectType
* document with these properties.
*
* @see https://www.w3.org/TR/activitypub/#endpoints
*
* @var null|array|string
*/
protected string|array|null $endpoints;
@ -119,8 +109,6 @@ abstract class AbstractActor extends ObjectType
* ]
*
* @see https://www.w3.org/wiki/SocialCG/ActivityPub/Authentication_Authorization#Signing_requests_using_HTTP_Signatures
*
* @var null|array|string
*/
protected string|array|null $publicKey;
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -25,8 +27,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Accept extends Activity
{
/**
* @var string
*/
protected string $type = 'Accept';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Announce extends Activity
{
/**
* @var string
*/
protected string $type = 'Announce';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ namespace Plugin\ActivityPub\Util\Type\Extended\Activity;
*/
class Block extends Ignore
{
/**
* @var string
*/
protected string $type = 'Block';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Create extends Activity
{
/**
* @var string
*/
protected string $type = 'Create';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Delete extends Activity
{
/**
* @var string
*/
protected string $type = 'Delete';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -27,8 +29,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Follow extends Activity
{
/**
* @var string
*/
protected string $type = 'Follow';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Ignore extends Activity
{
/**
* @var string
*/
protected string $type = 'Ignore';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Join extends Activity
{
/**
* @var string
*/
protected string $type = 'Join';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Leave extends Activity
{
/**
* @var string
*/
protected string $type = 'Leave';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Like extends Activity
{
/**
* @var string
*/
protected string $type = 'Like';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -30,9 +32,6 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Question extends IntransitiveActivity
{
/**
* @var string
*/
protected string $type = 'Question';
/**

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Reject extends Activity
{
/**
* @var string
*/
protected string $type = 'Reject';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -25,8 +27,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Remove extends Activity
{
/**
* @var string
*/
protected string $type = 'Remove';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -29,8 +31,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Undo extends Activity
{
/**
* @var string
*/
protected string $type = 'Undo';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -27,8 +29,5 @@ use Plugin\ActivityPub\Util\Type\Core\Activity;
*/
class Update extends Activity
{
/**
* @var string
*/
protected string $type = 'Update';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Extended\AbstractActor;
*/
class Application extends AbstractActor
{
/**
* @var string
*/
protected string $type = 'Application';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Extended\AbstractActor;
*/
class Group extends AbstractActor
{
/**
* @var string
*/
protected string $type = 'Group';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Extended\AbstractActor;
*/
class Organization extends AbstractActor
{
/**
* @var string
*/
protected string $type = 'Organization';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Extended\AbstractActor;
*/
class Person extends AbstractActor
{
/**
* @var string
*/
protected string $type = 'Person';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Extended\AbstractActor;
*/
class Service extends AbstractActor
{
/**
* @var string
*/
protected string $type = 'Service';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Article extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Article';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -21,8 +23,5 @@ namespace Plugin\ActivityPub\Util\Type\Extended\Object;
*/
class Audio extends Document
{
/**
* @var string
*/
protected string $type = 'Audio';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Document extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Document';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Event extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Event';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -21,8 +23,5 @@ namespace Plugin\ActivityPub\Util\Type\Extended\Object;
*/
class Image extends Document
{
/**
* @var string
*/
protected string $type = 'Image';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,8 +25,5 @@ use Plugin\ActivityPub\Util\Type\Core\Link;
*/
class Mention extends Link
{
/**
* @var string
*/
protected string $type = 'Mention';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -24,8 +26,5 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Note extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Note';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -21,8 +23,5 @@ namespace Plugin\ActivityPub\Util\Type\Extended\Object;
*/
class Page extends Document
{
/**
* @var string
*/
protected string $type = 'Page';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,9 +25,6 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Place extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Place';
/**
@ -34,8 +33,6 @@ class Place extends ObjectType
* e.g. "94.0" means "94.0% accurate".
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-accuracy
*
* @var null|float
*/
protected ?float $accuracy;
@ -46,8 +43,6 @@ class Place extends ObjectType
* indicating meters.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-altitude
*
* @var null|float
*/
protected ?float $altitude;
@ -55,8 +50,6 @@ class Place extends ObjectType
* The latitude of a place.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-latitude
*
* @var null|float|int
*/
protected int|null|float $latitude;
@ -64,8 +57,6 @@ class Place extends ObjectType
* The longitude of a place.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-longitude
*
* @var null|float|int
*/
protected int|null|float $longitude;
@ -76,8 +67,6 @@ class Place extends ObjectType
* indicating "meters".
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-radius
*
* @var null|float|int
*/
protected int|null|float $radius;
@ -89,8 +78,6 @@ class Place extends ObjectType
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-units
*
* "cm" | " feet" | " inches" | " km" | " m" | " miles" | xsd:anyURI
*
* @var string
*/
protected string $units;
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -26,15 +28,10 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Profile extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Profile';
/**
* Identify the object described by the Profile.
*
* @var ObjectType
*/
protected ObjectType $describes;
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -25,17 +27,12 @@ use Plugin\ActivityPub\Util\Type\Core\ObjectType;
*/
class Tombstone extends ObjectType
{
/**
* @var string
*/
protected string $type = 'Tombstone';
/**
* The type of the object that was deleted.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-formertype
*
* @var null|string
*/
protected ?string $formerType;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -21,8 +23,5 @@ namespace Plugin\ActivityPub\Util\Type\Extended\Object;
*/
class Video extends Document
{
/**
* @var string
*/
protected string $type = 'Video';
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -21,8 +23,6 @@ abstract class TypeResolver
{
/**
* A list of core types
*
* @var array
*/
protected static array $coreTypes = [
'Activity', 'Collection', 'CollectionPage',
@ -33,8 +33,6 @@ abstract class TypeResolver
/**
* A list of actor types
*
* @var array
*/
protected static array $actorTypes = [
'Application', 'Group', 'Organization', 'Person', 'Service',
@ -42,8 +40,6 @@ abstract class TypeResolver
/**
* A list of activity types
*
* @var array
*/
protected static array $activityTypes = [
'Accept', 'Add', 'Announce', 'Block',
@ -54,8 +50,6 @@ abstract class TypeResolver
/**
* A list of object types
*
* @var array
*/
protected static array $objectTypes = [
'Article', 'Audio', 'Document', 'Event', 'Image',
@ -66,8 +60,6 @@ abstract class TypeResolver
/**
* Get namespaced class for a given short type
*
* @param string $type
*
* @throws Exception
*
* @return string Related namespace
@ -82,21 +74,21 @@ abstract class TypeResolver
}
switch ($type) {
case in_array($type, self::$coreTypes):
case \in_array($type, self::$coreTypes):
$ns .= '\Core';
break;
case in_array($type, self::$activityTypes):
case \in_array($type, self::$activityTypes):
$ns .= '\Extended\Activity';
break;
case in_array($type, self::$actorTypes):
case \in_array($type, self::$actorTypes):
$ns .= '\Extended\Actor';
break;
case in_array($type, self::$objectTypes):
case \in_array($type, self::$objectTypes):
$ns .= '\Extended\Object';
break;
default:
throw new Exception(
"Undefined scope for type '{$type}'"
"Undefined scope for type '{$type}'",
);
}
@ -106,44 +98,37 @@ abstract class TypeResolver
/**
* Validate an object pool type with type attribute
*
* @param object $item
* @param string $poolname An expected pool name
*
* @return bool
*/
public static function isScope(object $item, string $poolname = 'all'): bool
{
if (!is_object($item)
if (!\is_object($item)
|| !isset($item->type)
|| !is_string($item->type)
|| !\is_string($item->type)
) {
return false;
}
return match (strtolower($poolname)) {
return match (mb_strtolower($poolname)) {
'all' => self::exists($item->type),
'actor' => in_array($item->type, self::$actorTypes),
'actor' => \in_array($item->type, self::$actorTypes),
default => false,
};
}
/**
* Verify that a type exists
*
* @param string $name
*
* @return bool
*/
public static function exists(string $name): bool
{
return in_array(
return \in_array(
$name,
array_merge(
self::$coreTypes,
self::$activityTypes,
self::$actorTypes,
self::$objectTypes
)
self::$objectTypes,
),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -34,12 +36,10 @@ abstract class Util
/**
* Transform an array into an ActivityStreams type
*
* @param array $item
*
* @throws Exception
*
* @return AbstractObject|array An ActivityStreams
* type or given array if type key is not defined.
* @return AbstractObject|array an ActivityStreams
* type or given array if type key is not defined
*/
public static function arrayToType(array $item): AbstractObject|array
{
@ -54,57 +54,44 @@ abstract class Util
/**
* Validate an URL
*
* @param mixed $value
*
* @return bool
*/
public static function validateUrl(mixed $value): bool
{
return is_string($value)
&& filter_var($value, FILTER_VALIDATE_URL) !== false
&& in_array(
parse_url($value, PHP_URL_SCHEME),
['http', 'https', 'magnet']
return \is_string($value)
&& filter_var($value, \FILTER_VALIDATE_URL) !== false
&& \in_array(
parse_url($value, \PHP_URL_SCHEME),
['http', 'https', 'magnet'],
);
}
/**
* Validate a magnet link
*
* @param mixed $value
*
* @return bool
*
* @see https://en.wikipedia.org/wiki/Magnet_URI_scheme
*
* @todo Make a better validation as xs is not the only parameter
*/
public static function validateMagnet(mixed $value): bool
{
return is_string($value)
&& strlen($value) < 262144
return \is_string($value)
&& mb_strlen($value) < 262144
&& preg_match(
'#^magnet:\?xs=(https?)://.*$#iu',
urldecode($value)
urldecode($value),
);
}
/**
* Validate an OStatus tag string
*
* @param mixed $value
*
* @return bool
*/
public static function validateOstatusTag(mixed $value): bool
{
return is_string($value)
&& strlen($value) < 262144
return \is_string($value)
&& mb_strlen($value) < 262144
&& preg_match(
'#^tag:([\w\-\.]+),([\d]{4}-[\d]{2}-[\d]{2}):([\w])+Id=([\d]+):objectType=([\w]+)#iu',
$value
$value,
);
}
@ -112,36 +99,24 @@ abstract class Util
* Validate a rel attribute value.
*
* @see https://tools.ietf.org/html/rfc5988
*
* @param string $value
*
* @return bool
*/
public static function validateRel(string $value): bool
{
return is_string($value)
return \is_string($value)
&& preg_match("/^[^\\s\r\n\\,]+\\z/i", $value);
}
/**
* Validate a non negative integer.
*
* @param int $value
*
* @return bool
*/
public static function validateNonNegativeInteger(int $value): bool
{
return is_int($value)
return \is_int($value)
&& $value >= 0;
}
/**
* Validate a non negative number.
*
* @param float|int $value
*
* @return bool
*/
public static function validateNonNegativeNumber(float|int $value): bool
{
@ -151,15 +126,11 @@ abstract class Util
/**
* Validate units format.
*
* @param string $value
*
* @return bool
*/
public static function validateUnits(string $value): bool
{
if (is_string($value)) {
if (in_array($value, self::$units)
if (\is_string($value)) {
if (\in_array($value, self::$units)
|| self::validateUrl($value)
) {
return true;
@ -172,16 +143,12 @@ abstract class Util
/**
* Validate an Object type
*
* @param object $item
*
* @throws Exception
*
* @return bool
*/
public static function validateObject(object $item): bool
{
return self::hasProperties($item, ['type'])
&& is_string($item->type)
&& \is_string($item->type)
&& $item->type === 'Object';
}
@ -194,9 +161,9 @@ abstract class Util
{
$json = json_decode($value, true);
if (json_last_error() !== JSON_ERROR_NONE) {
if (json_last_error() !== \JSON_ERROR_NONE) {
throw new Exception(
'JSON decoding failed for string: ' . $value
'JSON decoding failed for string: ' . $value,
);
}
@ -206,19 +173,15 @@ abstract class Util
/**
* Checks that all properties exist for a stdClass
*
* @param object $item
* @param array $properties
* @param bool $strict If true throws an \Exception,
* otherwise, returns false
*
* @throws Exception if a property is not set
*
* @return bool
*/
public static function hasProperties(
object $item,
array $properties,
bool $strict = false
bool $strict = false,
): bool {
foreach ($properties as $property) {
if (!property_exists($item, $property)) {
@ -227,8 +190,8 @@ abstract class Util
sprintf(
'Attribute "%s" MUST be set for item: %s',
$property,
print_r($item, true)
)
print_r($item, true),
),
);
}
@ -242,11 +205,7 @@ abstract class Util
/**
* Validate a reference with a Link or an Object with a URL
*
* @param object $item
*
* @throws Exception
*
* @return bool
*/
public static function isLinkOrUrlObject(object $item): bool
{
@ -266,19 +225,15 @@ abstract class Util
/**
* Validate a reference as Link
*
* @param array|object $item
*
* @throws Exception
*
* @return bool
*/
public static function validateLink(object|array $item): bool
{
if (is_array($item)) {
if (\is_array($item)) {
$item = (object) $item;
}
if (!is_object($item)) {
if (!\is_object($item)) {
return false;
}
@ -298,15 +253,13 @@ abstract class Util
/**
* Validate a datetime
*
* @param mixed $value
*/
public static function validateDatetime($value): bool
{
if (!is_string($value)
if (!\is_string($value)
|| !preg_match(
'/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(.*)$/',
$value
$value,
)
) {
return false;
@ -323,22 +276,18 @@ abstract class Util
/**
* Check that container class is a subclass of a given class
*
* @param object $container
* @param array|string $classes
* @param bool $strict If true, throws an exception
*
* @throws Exception
*
* @return bool
*/
public static function subclassOf(object $container, array|string $classes, bool $strict = false): bool
{
if (!is_array($classes)) {
if (!\is_array($classes)) {
$classes = [$classes];
}
foreach ($classes as $class) {
if (get_class($container) === $class
if (\get_class($container) === $class
|| is_subclass_of($container, $class)
) {
return true;
@ -349,9 +298,9 @@ abstract class Util
throw new Exception(
sprintf(
'Class "%s" MUST be a subclass of "%s"',
get_class($container),
implode(', ', $classes)
)
\get_class($container),
implode(', ', $classes),
),
);
}
@ -362,12 +311,6 @@ abstract class Util
* Checks that a numeric value is part of a range.
* If a minimal value is null, value has to be inferior to max value
* If a maximum value is null, value has to be superior to min value
*
* @param float|int $value
* @param null|float|int $min
* @param null|float|int $max
*
* @return bool
*/
public static function between(float|int $value, float|int|null $min, float|int|null $max): bool
{
@ -376,9 +319,9 @@ abstract class Util
}
return match (true) {
is_null($min) && is_null($max) => false,
is_null($min) => $value <= $max,
is_null($max) => $value >= $min,
\is_null($min) && \is_null($max) => false,
\is_null($min) => $value <= $max,
\is_null($max) => $value >= $min,
default => $value >= $min
&& $value <= $max,
};
@ -387,12 +330,9 @@ abstract class Util
/**
* Check that a given string is a valid XML Schema xsd:duration
*
* @param string $duration
* @param bool $strict If true, throws an exception
*
* @throws Exception
*
* @return bool
*/
public static function isDuration(string $duration, bool $strict = false): bool
{
@ -404,8 +344,8 @@ abstract class Util
throw new Exception(
sprintf(
'Duration "%s" MUST respect xsd:duration',
$duration
)
$duration,
),
);
}
}
@ -415,10 +355,6 @@ abstract class Util
/**
* Checks that it's an object type
*
* @param object $item
*
* @return bool
*/
public static function isObjectType(object $item): bool
{
@ -427,10 +363,6 @@ abstract class Util
/**
* Checks that it's an actor type
*
* @param object $item
*
* @return bool
*/
public static function isActorType(object $item): bool
{
@ -440,84 +372,62 @@ abstract class Util
/**
* Validate an object type with type attribute
*
* @param object $item
* @param string $type An expected type
*
* @return bool
*/
public static function isType(object $item, string $type): bool
{
// Validate that container is a certain type
if (!is_object($item)) {
if (!\is_object($item)) {
return false;
}
if (property_exists($item, 'type')
&& is_string($item->type)
return (bool) (
property_exists($item, 'type')
&& \is_string($item->type)
&& $item->type === $type
) {
return true;
}
return false;
);
}
/**
* Validate a BCP 47 language value
*
* @param string $value
*
* @return bool
*/
public static function validateBcp47(string $value): bool
{
return is_string($value)
return \is_string($value)
&& preg_match(
'/^(((en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)|(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|zh-min|zh-min-nan|zh-xiang))|((([A-Za-z]{2,3}(-([A-Za-z]{3}(-[A-Za-z]{3}){0,2}))?)|[A-Za-z]{4}|[A-Za-z]{5,8})(-([A-Za-z]{4}))?(-([A-Za-z]{2}|[0-9]{3}))?(-([A-Za-z0-9]{5,8}|[0-9][A-Za-z0-9]{3}))*(-([0-9A-WY-Za-wy-z](-[A-Za-z0-9]{2,8})+))*(-(x(-[A-Za-z0-9]{1,8})+))?)|(x(-[A-Za-z0-9]{1,8})+))$/',
$value
$value,
);
}
/**
* Validate a plain text value
*
* @param string $value
*
* @return bool
*/
public static function validatePlainText(string $value): bool
{
return is_string($value)
return \is_string($value)
&& preg_match(
'/^([^<]+)$/',
$value
$value,
);
}
/**
* Validate mediaType format
*
* @param string $value
*
* @return bool
*/
public static function validateMediaType(string $value): bool
{
return is_string($value)
return \is_string($value)
&& preg_match(
'#^(([\w]+[\w\-]+[\w+])/(([\w]+[\w\-\.\+]+[\w]+)|(\*));?)+$#',
$value
$value,
);
}
/**
* Validate a Collection type
*
* @param object $item
*
* @throws Exception
*
* @return bool
*/
public static function validateCollection(object $item): bool
{
@ -525,14 +435,14 @@ abstract class Util
return false;
}
if (!is_object($item)) {
if (!\is_object($item)) {
$item = (object) $item;
}
self::hasProperties(
$item,
[/*totalItems', 'current', 'first', 'last', */ 'items'],
true
true,
);
return true;
@ -541,11 +451,7 @@ abstract class Util
/**
* Validate a CollectionPage type
*
* @param object $item
*
* @throws Exception
*
* @return bool
*/
public static function validateCollectionPage(object $item): bool
{
@ -558,7 +464,7 @@ abstract class Util
self::hasProperties(
$item,
['partOf'/*, 'next', 'prev'*/],
true
true,
);
return true;

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -32,19 +34,15 @@ abstract class Validator
* Validate an attribute value for given attribute name and
* container object.
*
* @param string $name
* @param mixed $value
* @param mixed $container An object
*
* @throws Exception if $container is not an object
*
* @return bool
*/
public static function validate(string $name, mixed $value, mixed $container): bool
{
if (!is_object($container)) {
if (!\is_object($container)) {
throw new Exception(
'Given container is not an object'
'Given container is not an object',
);
}
@ -52,14 +50,14 @@ abstract class Validator
if (isset(self::$validators[$name])) {
return self::$validators[$name]->validate(
$value,
$container
$container,
);
}
// Try to load a default validator
$validatorName = sprintf(
'\Plugin\ActivityPub\Util\Type\Validator\%sValidator',
ucfirst($name)
ucfirst($name),
);
if (class_exists($validatorName)) {
@ -75,7 +73,7 @@ abstract class Validator
* Add a new validator in the pool.
* It checks that it implements Validator\Interface
*
* @param string $name An attribute name to validate.
* @param string $name an attribute name to validate
* @param object|string $class A validator class name
*
* @throws Exception if validator class does not implement
@ -89,9 +87,9 @@ abstract class Validator
throw new Exception(
sprintf(
'Validator "%s" MUST implement "%s" interface',
get_class($validator),
ValidatorInterface::class
)
\get_class($validator),
ValidatorInterface::class,
),
);
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -22,10 +24,7 @@ class AccuracyValidator implements ValidatorInterface
/**
* Validate an ACCURACY attribute value
*
* @param mixed $value
* @param mixed $container An object
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -27,31 +29,28 @@ class ActorValidator implements ValidatorInterface
/**
* Validate an ACTOR attribute value
*
* @param mixed $value
* @param mixed $container An object
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
// Can be an indirect link
if (is_string($value) && Util::validateUrl($value)) {
if (\is_string($value) && Util::validateUrl($value)) {
return true;
}
if (is_array($value)) {
if (\is_array($value)) {
$value = Util::arrayToType($value);
}
// A collection
if (is_array($value)) {
if (\is_array($value)) {
return $this->validateObjectCollection($value);
}
// Must be an object
if (!is_object($value)) {
if (!\is_object($value)) {
return false;
}
@ -62,25 +61,22 @@ class ActorValidator implements ValidatorInterface
/**
* Validate an Actor object type
*
* @param array|object $item
*
* @throws Exception
*
* @return bool
*/
protected function validateObject(object|array $item): bool
{
if (is_array($item)) {
if (\is_array($item)) {
$item = Util::arrayToType($item);
}
Util::subclassOf(
$item, [
$item,
[
AbstractActor::class,
Link::class,
Collection::class,
],
true
true,
);
return true;
@ -98,19 +94,19 @@ class ActorValidator implements ValidatorInterface
protected function validateObjectCollection(array $collection): bool
{
foreach ($collection as $item) {
if (is_array($item) && $this->validateObject($item)) {
if (\is_array($item) && $this->validateObject($item)) {
continue;
}
if (is_object($item) && $this->validateObject($item)) {
if (\is_object($item) && $this->validateObject($item)) {
continue;
}
if (is_string($item) && Util::validateUrl($item)) {
if (\is_string($item) && Util::validateUrl($item)) {
continue;
}
return false;
}
return count($collection) > 0;
return \count($collection) > 0;
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -22,17 +24,10 @@ class AltitudeValidator implements ValidatorInterface
/**
* Validate an ALTITUDE attribute value
*
* @param mixed $value
* @param mixed $container An object
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
if (is_float($value) || is_int($value)) {
return true;
}
return false;
return (bool) (\is_float($value) || \is_int($value));
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -25,13 +27,10 @@ class AnyOfValidator extends ValidatorTools
/**
* Validate an ANYOF attribute value
*
* @param mixed $value
* @param mixed $container An object
*
* @throws Exception
*
* @return bool
*
* @todo Choices can contain Indirect references.
* This validation should validate this kind of usage.
*/
@ -41,17 +40,17 @@ class AnyOfValidator extends ValidatorTools
Util::subclassOf($container, Question::class, true);
// A collection
if (!is_array($value)) {
if (!\is_array($value)) {
return false;
}
if (!count($value)) {
if (!\count($value)) {
return false;
}
return $this->validateObjectCollection(
$value,
$this->getQuestionAnswerValidator()
$this->getQuestionAnswerValidator(),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,23 +25,20 @@ class AttachmentValidator extends ValidatorTools
/**
* Validate an attachment value
*
* @param mixed $value
* @param mixed $container An Object type
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
if (is_array($value) && !count($value)) {
if (\is_array($value) && !\count($value)) {
return true;
}
return $this->validateListOrObject(
$value,
$container,
$this->getAttachmentValidator()
$this->getAttachmentValidator(),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,19 +25,16 @@ class AttributedToValidator extends ValidatorTools
/**
* Validate an attributedTo value
*
* @param mixed $value
* @param mixed $container An Object type
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
return $this->validateListOrObject(
$value,
$container,
$this->getCollectionActorsValidator()
$this->getCollectionActorsValidator(),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,19 +25,16 @@ class AudienceValidator extends ValidatorTools
/**
* Validate an audience value
*
* @param mixed $value
* @param mixed $container An Object type
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
return $this->validateListOrObject(
$value,
$container,
$this->getLinkOrNamedObjectValidator()
$this->getLinkOrNamedObjectValidator(),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,19 +25,16 @@ class BccValidator extends ValidatorTools
/**
* Validate a bcc value
*
* @param mixed $value
* @param mixed $container An Object type
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
return $this->validateListOrObject(
$value,
$container,
$this->getLinkOrUrlObjectValidator()
$this->getLinkOrUrlObjectValidator(),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,19 +25,16 @@ class BtoValidator extends ValidatorTools
/**
* Validate a bto value
*
* @param mixed $value
* @param mixed $container An Object type
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
return $this->validateListOrObject(
$value,
$container,
$this->getLinkOrUrlObjectValidator()
$this->getLinkOrUrlObjectValidator(),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,19 +25,16 @@ class CcValidator extends ValidatorTools
/**
* Validate a cc value
*
* @param mixed $value
* @param mixed $container An Object type
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
return $this->validateListOrObject(
$value,
$container,
$this->getLinkOrUrlObjectValidator()
$this->getLinkOrUrlObjectValidator(),
);
}
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -25,12 +27,9 @@ class ClosedValidator implements ValidatorInterface
/**
* Validate an CLOSED attribute value
*
* @param mixed $value
* @param mixed $container A Question type
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{
@ -38,11 +37,11 @@ class ClosedValidator implements ValidatorInterface
Util::subclassOf($container, Question::class, true);
// Can be a boolean
if (is_bool($value)) {
if (\is_bool($value)) {
return true;
}
if (is_string($value)) {
if (\is_string($value)) {
// Can be a datetime
if (Util::validateDatetime($value)) {
return true;
@ -54,12 +53,12 @@ class ClosedValidator implements ValidatorInterface
}
}
if (is_array($value)) {
if (\is_array($value)) {
$value = Util::arrayToType($value);
}
// An Object or a Link
if (is_object($value)) {
if (\is_object($value)) {
return Util::validateLink($value)
|| Util::validateObject($value);
}

View File

@ -1,5 +1,7 @@
<?php
declare(strict_types = 1);
/*
* This file is part of the ActivityPhp package.
*
@ -23,12 +25,7 @@ class ContentMapValidator extends ValidatorTools
/**
* Validate a contentMap value
*
* @param mixed $value
* @param mixed $container
*
* @throws Exception
*
* @return bool
*/
public function validate(mixed $value, mixed $container): bool
{

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