[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 <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // 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 * @throws \App\Util\Exception\ClientException
*/ */
public function onPopulateProfileSettingsTabs(Request $request, &$tabs): bool 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 public static function getAvatar(?int $actor_id = null): Entity\Avatar
{ {
$actor_id = $actor_id ?: Common::userId(); $actor_id = $actor_id ?: Common::userId();
return GSFile::error(NoAvatarException::class, return GSFile::error(
NoAvatarException::class,
$actor_id, $actor_id,
Cache::get("avatar-{$actor_id}", Cache::get(
"avatar-{$actor_id}",
function () use ($actor_id) { function () use ($actor_id) {
return DB::dql('select a from Component\Avatar\Entity\Avatar a ' . return DB::dql(
'where a.actor_id = :actor_id', 'select a from Component\Avatar\Entity\Avatar a '
['actor_id' => $actor_id]); . '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 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) { function () use ($actor_id) {
return DB::dql('select f.id, f.filename, a.title, f.mimetype ' . return DB::dql(
'from App\Entity\Attachment f ' . 'select f.id, f.filename, a.title, f.mimetype '
'join Component\Avatar\Entity\Avatar a with f.id = a.attachment_id ' . . 'from App\Entity\Attachment f '
'where a.actor_id = :actor_id', . 'join Component\Avatar\Entity\Avatar a with f.id = a.attachment_id '
['actor_id' => $actor_id]); . 'where a.actor_id = :actor_id',
} ['actor_id' => $actor_id],
);
},
); );
if ($res === []) { // Avatar not found if ($res === []) { // Avatar not found
$filepath = INSTALLDIR . '/public/assets/default-avatar.svg'; $filepath = INSTALLDIR . '/public/assets/default-avatar.svg';

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // This file is part of GNU social - https://www.gnu.org/software/social
// //
@ -23,4 +25,4 @@ use App\Core\Modules\Component;
class FreeNetwork extends Component class FreeNetwork extends Component
{ {
} }

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // 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 * @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 public function onEndShowStyles(array &$styles, string $route): bool
{ {

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // 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_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 $geouri_paramchar_regex = $geouri_unreserved_regex . $geouri_punreserved_regex; //FIXME: add $geouri_pctencoded_regex here so it works
return '#' . return '#'
'(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])' . . '(?:^|[\s\<\>\(\)\[\]\{\}\\\'\\\";]+)(?![\@\!\#])'
'(' . . '('
'(?:' . . '(?:'
'(?:' . //Known protocols . '(?:' //Known protocols
'(?:' . . '(?:'
'(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)' . . '(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_DOUBLE_SLASH)) . ')://)'
'|' . . '|'
'(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_SINGLE_COLON)) . '):)' . . '(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_SINGLE_COLON)) . '):)'
')' . . ')'
'(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?' . //user:pass@ . '(?:[\pN\pL\-\_\+\%\~]+(?::[\pN\pL\-\_\+\%\~]+)?\@)?' //user:pass@
'(?:' . . '(?:'
'(?:' . . '(?:'
'\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]' . //[dns] . '\[[\pN\pL\-\_\:\.]+(?<![\.\:])\]' //[dns]
')|(?:' . . ')|(?:'
'[\pN\pL\-\_\:\.]+(?<![\.\:])' . //dns . '[\pN\pL\-\_\:\.]+(?<![\.\:])' //dns
')' . . ')'
')' . . ')'
')' . . ')'
'|(?:' . . '|(?:'
'(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_COLON_COORDINATES)) . '):' . . '(?:' . 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= // 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 'crsp' (;crs=$crsp) must match $geouri_labeltext_regex
// Also 'uval' (;u=$uval) must be a pnum: \-?[0-9]+ // 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} . '(?:[0-9]+(?:\.[0-9]+)?(?:\,[0-9]+(?:\.[0-9]+)?){1,2})' // 1(.23)?(,4(.56)){1,2}
'(?:\;(?:[' . $geouri_labeltext_regex . ']+)(?:\=[' . $geouri_paramchar_regex . ']+)*)*' . . '(?:\;(?:[' . $geouri_labeltext_regex . ']+)(?:\=[' . $geouri_paramchar_regex . ']+)*)*'
')' . . ')'
')' . . ')'
// URLs without domain name, like magnet:?xt=... // URLs without domain name, like magnet:?xt=...
'|(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_NO_DOMAIN)) . '):(?=\?))' . // zero-length lookahead requires ? after : . '|(?:(?:' . implode('|', $this->URLSchemes(self::URL_SCHEME_NO_DOMAIN)) . '):(?=\?))' // zero-length lookahead requires ? after :
(Common::config('linkify', 'ipv4') // Convert IPv4 addresses to hyperlinks . (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]?)' ? '|(?:(?: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 . (Common::config('linkify', 'ipv6') // Convert IPv6 addresses to hyperlinks
? '|(?:' . //IPv6 ? '|(?:' //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})))\]?(?<!:)' . . '\[?(?:(?:(?:[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') . (Common::config('linkify', 'bare_domains')
? '|(?:' . //DNS ? '|(?:' //DNS
'(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?' . //user:pass@ . '(?:[\pN\pL\-\_\+\%\~]+(?:\:[\pN\pL\-\_\+\%\~]+)?\@)?' //user:pass@
'[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.' . . '[\pN\pL\-\_]+(?:\.[\pN\pL\-\_]+)*\.'
//tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt, also added local, loc, and onion //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)' . . '(?: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\-\_])' . ')(?![\pN\pL\-\_])'
: '') . // if common_config('linkify', 'bare_domains') is false, don't add anything here : '') // if common_config('linkify', 'bare_domains') is false, don't add anything here
')' . . ')'
'(?:' . . '(?:'
'(?:\:\d+)?' . //:port . '(?:\:\d+)?' //:port
'(?:/[' . URL_REGEX_VALID_PATH_CHARS . ']*)?' . // path . '(?:/[' . URL_REGEX_VALID_PATH_CHARS . ']*)?' // path
'(?:\?[' . URL_REGEX_VALID_QSTRING_CHARS . ']*)?' . // ?query string . '(?:\?[' . URL_REGEX_VALID_QSTRING_CHARS . ']*)?' // ?query string
'(?:\#[' . URL_REGEX_VALID_FRAGMENT_CHARS . ']*)?' . // #fragment . '(?:\#[' . URL_REGEX_VALID_FRAGMENT_CHARS . ']*)?' // #fragment
')(?<![' . URL_REGEX_EXCLUDED_END_CHARS . '])' . . ')(?<![' . URL_REGEX_EXCLUDED_END_CHARS . '])'
')' . . ')'
'#ixu'; . '#ixu';
} }
const URL_SCHEME_COLON_DOUBLE_SLASH = 1; public const URL_SCHEME_COLON_DOUBLE_SLASH = 1;
const URL_SCHEME_SINGLE_COLON = 2; public const URL_SCHEME_SINGLE_COLON = 2;
const URL_SCHEME_NO_DOMAIN = 4; public const URL_SCHEME_NO_DOMAIN = 4;
const URL_SCHEME_COLON_COORDINATES = 8; public const URL_SCHEME_COLON_COORDINATES = 8;
public function URLSchemes($filter = null) public function URLSchemes($filter = null)
{ {
@ -162,13 +164,11 @@ class Link extends Component
'geo' => self::URL_SCHEME_COLON_COORDINATES, '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. * Find links in the given text and pass them to the given callback function.
*
* @param string $text
*/ */
public function replaceURLs(string $text): string public function replaceURLs(string $text): string
{ {
@ -180,16 +180,13 @@ class Link extends Component
* Intermediate callback for `replaceURLs()`, which helps resolve some * Intermediate callback for `replaceURLs()`, which helps resolve some
* ambiguous link forms before passing on to the final callback. * ambiguous link forms before passing on to the final callback.
* *
* @param array $matches
* @param callable(string $text): string $callback: return replacement text * @param callable(string $text): string $callback: return replacement text
*
* @return string
*/ */
private function callbackHelper(array $matches, callable $callback): string private function callbackHelper(array $matches, callable $callback): string
{ {
$url = $matches[1]; $url = $matches[1];
$left = strpos($matches[0], $url); $left = mb_strpos($matches[0], $url);
$right = $left + strlen($url); $right = $left + mb_strlen($url);
$groupSymbolSets = [ $groupSymbolSets = [
[ [
@ -214,23 +211,23 @@ class Link extends Component
do { do {
$original_url = $url; $original_url = $url;
foreach ($groupSymbolSets as $groupSymbolSet) { foreach ($groupSymbolSets as $groupSymbolSet) {
if (substr($url, -1) == $groupSymbolSet['right']) { if (mb_substr($url, -1) == $groupSymbolSet['right']) {
$group_left_count = substr_count($url, $groupSymbolSet['left']); $group_left_count = mb_substr_count($url, $groupSymbolSet['left']);
$group_right_count = substr_count($url, $groupSymbolSet['right']); $group_right_count = mb_substr_count($url, $groupSymbolSet['right']);
if ($group_left_count < $group_right_count) { if ($group_left_count < $group_right_count) {
--$right; --$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; --$right;
$url = substr($url, 0, -1); $url = mb_substr($url, 0, -1);
} }
} while ($original_url != $url); } while ($original_url != $url);
$result = $callback($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 // functions
$url = htmlspecialchars_decode($url); $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 is an email address without the mailto: protocol
$url = "mailto:{$email}"; $url = "mailto:{$email}";
} }

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // 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(); $actor_id = $user->getId();
$to_tags = []; $to_tags = [];
$tags = Cache::get("actor-circle-{$actor_id}", $tags = Cache::get(
fn () => DB::dql('select c.tag from App\Entity\ActorCircle c where c.tagger = :tagger', ['tagger' => $actor_id])); "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) { foreach ($tags as $t) {
$t = $t['tag']; $t = $t['tag'];
$to_tags[$t] = $t; $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)]]], ['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]], ['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, $form_params[] = ['content_type', ChoiceType::class,
[ [
'label' => _m('Text format:'), 'multiple' => false, 'expanded' => false, '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 * $actor_id, possibly as a reply to note $reply_to and with flag
* $is_local. Sanitizes $content and $attachments * $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 ClientException
* @throws ServerException * @throws ServerException
*/ */
@ -149,8 +146,8 @@ class Posting extends Component
$filesize = $f->getSize(); $filesize = $f->getSize();
$max_file_size = Common::config('attachments', 'file_quota'); $max_file_size = Common::config('attachments', 'file_quota');
if ($max_file_size < $filesize) { 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. ' . 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])); . 'Try to upload a smaller version.', ['quota' => $max_file_size, 'size' => $filesize], ));
} }
Event::handle('EnforceUserFileQuota', [$filesize, $actor->getId()]); Event::handle('EnforceUserFileQuota', [$filesize, $actor->getId()]);
$processed_attachments[] = [GSFile::storeFileAsAttachment($f), $f->getClientOriginalName()]; $processed_attachments[] = [GSFile::storeFileAsAttachment($f), $f->getClientOriginalName()];
@ -193,11 +190,6 @@ class Posting extends Component
* Get a unique representation of a file on disk * Get a unique representation of a file on disk
* *
* This can be used in the future to deduplicate images by visual content * 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 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 * 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 public function onGetAllowedThumbnailSizes(?array &$sizes): bool
{ {

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // 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 * @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 public function onEndShowStyles(array &$styles, string $route): bool
{ {

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
namespace Component\Tag\Controller; namespace Component\Tag\Controller;
use App\Core\Cache; 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: '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], query_args: ['canon' => $canonical],
actor: $user, actor: $user,
page: $page page: $page,
); );
return [ return [

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
// {{{ License // {{{ License
// This file is part of GNU social - https://www.gnu.org/software/social // 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 class Tag extends Component
{ {
const MAX_TAG_LENGTH = 64; public 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 public 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 TAG_SLUG_REGEX = '[A-Za-z0-9]{1,64}';
public function onAddRoute($r): bool 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; return Event::next;
} }
@ -60,7 +62,7 @@ class Tag extends Component
{ {
$matched_tags = []; $matched_tags = [];
$processed_tags = false; $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) { foreach ($matched_tags as $match) {
$tag = $match[2]; $tag = $match[2];
$canonical_tag = self::canonicalTag($tag); $canonical_tag = self::canonicalTag($tag);
@ -87,16 +89,13 @@ class Tag extends Component
public static function canonicalTag(string $tag): string 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 * 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 * $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) public function onSearchCreateExpression(ExpressionBuilder $eb, string $term, &$note_expr, &$actor_expr)
{ {

View File

@ -1,17 +1,19 @@
<?php <?php
declare(strict_types = 1);
use App\Core\ModuleManager; use App\Core\ModuleManager;
use Symfony\Component\Dotenv\Dotenv; 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 // Load cached env vars if the .env.local.php file exists
// Run "composer dump-env prod" to create it (requires symfony/flex >=1.2) // 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) { 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.'); throw new RuntimeException('Please run "composer require symfony/dotenv" to load the ".env" files configuring the application.');
} else { } else {
// load all the .env files // load all the .env files
@ -19,38 +21,38 @@ if (\is_array($env = @include dirname(__DIR__) . '/.env.local.php') && (!isset($
} }
$_SERVER += $_ENV; $_SERVER += $_ENV;
$_SERVER['APP_ENV'] = $_ENV['APP_ENV'] = ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null) ?: 'dev'; $_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'] ?? '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'] = (int) $_SERVER['APP_DEBUG'] || filter_var($_SERVER['APP_DEBUG'], \FILTER_VALIDATE_BOOLEAN) ? '1' : '0';
define('INSTALLDIR', dirname(__DIR__)); \define('INSTALLDIR', \dirname(__DIR__));
define('SRCDIR', INSTALLDIR . '/src'); \define('SRCDIR', INSTALLDIR . '/src');
define('PUBLICDIR', INSTALLDIR . '/public'); \define('PUBLICDIR', INSTALLDIR . '/public');
define('GNUSOCIAL_ENGINE_NAME', 'GNU social'); \define('GNUSOCIAL_ENGINE_NAME', 'GNU social');
// MERGE Change to https://gnu.io/social/ // MERGE Change to https://gnu.io/social/
define('GNUSOCIAL_PROJECT_URL', 'https://gnusocial.rocks/'); \define('GNUSOCIAL_PROJECT_URL', 'https://gnusocial.rocks/');
define('GNUSOCIAL_ENGINE_URL', GNUSOCIAL_PROJECT_URL); \define('GNUSOCIAL_ENGINE_URL', GNUSOCIAL_PROJECT_URL);
// MERGE Change to https://git.gnu.io/gnu/gnu-social // 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 // 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' // 'dev', 'alpha[0-9]+', 'beta[0-9]+', 'rc[0-9]+', 'release'
define('GNUSOCIAL_LIFECYCLE', 'dev'); \define('GNUSOCIAL_LIFECYCLE', 'dev');
define('GNUSOCIAL_VERSION', GNUSOCIAL_BASE_VERSION . '-' . GNUSOCIAL_LIFECYCLE); \define('GNUSOCIAL_VERSION', GNUSOCIAL_BASE_VERSION . '-' . GNUSOCIAL_LIFECYCLE);
define('GNUSOCIAL_CODENAME', 'Big bang'); \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\,\!\(\)\.\:\-\_\+\/\=\&\;\%\~\*\$\'\@' * 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/)" * 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. * 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_PATH_CHARS', '\pN\pL\,\!\.\:\-\_\+\/\@\=\;\%\~\*\(\)');
define('URL_REGEX_VALID_QSTRING_CHARS', URL_REGEX_VALID_PATH_CHARS . '\&'); \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_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_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_DOMAIN_NAME', '(?:(?!-)[A-Za-z0-9\-]{1,63}(?<!-)\.)+[A-Za-z]{2,10}');
// Work internally in UTC // Work internally in UTC
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
<?php <?php
if (file_exists(dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php')) { declare(strict_types = 1);
require dirname(__DIR__) . '/var/cache/prod/App_KernelProdContainer.preload.php';
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 <?php
declare(strict_types = 1);
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;
return function (RoutingConfigurator $routes) { return function (RoutingConfigurator $routes) {

View File

@ -1,4 +1,6 @@
<?php <?php
declare(strict_types = 1);
/** /**
* Validation class * Validation class
* *
@ -27,35 +29,38 @@
* *
* @category Validate * @category Validate
* @package Validate * @package Validate
*
* @author Tomas V.V.Cox <cox@idecnet.com> * @author Tomas V.V.Cox <cox@idecnet.com>
* @author Pierre-Alain Joye <pajoye@php.net> * @author Pierre-Alain Joye <pajoye@php.net>
* @author Amir Mohammad Saied <amir@php.net> * @author Amir Mohammad Saied <amir@php.net>
* @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied * @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 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*
* @version CVS: $Id$ * @version CVS: $Id$
* @link http://pear.php.net/package/Validate *
* @see http://pear.php.net/package/Validate
*/ */
// {{{ Constants // {{{ Constants
/** /**
* Methods for common data validations * Methods for common data validations
*/ */
define('VALIDATE_NUM', '0-9'); \define('VALIDATE_NUM', '0-9');
define('VALIDATE_SPACE', '\s'); \define('VALIDATE_SPACE', '\s');
define('VALIDATE_ALPHA_LOWER', 'a-z'); \define('VALIDATE_ALPHA_LOWER', 'a-z');
define('VALIDATE_ALPHA_UPPER', 'A-Z'); \define('VALIDATE_ALPHA_UPPER', 'A-Z');
define('VALIDATE_ALPHA', VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER); \define('VALIDATE_ALPHA', VALIDATE_ALPHA_LOWER . VALIDATE_ALPHA_UPPER);
define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß'); \define('VALIDATE_EALPHA_LOWER', VALIDATE_ALPHA_LOWER . 'áéíóúýàèìòùäëïöüÿâêîôûãñõ¨åæç½ðøþß');
define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖܾÂÊÎÔÛÃÑÕ¦ÅÆǼÐØÞ'); \define('VALIDATE_EALPHA_UPPER', VALIDATE_ALPHA_UPPER . 'ÁÉÍÓÚÝÀÈÌÒÙÄËÏÖܾÂÊÎÔÛÃÑÕ¦ÅÆǼÐØÞ');
define('VALIDATE_EALPHA', VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER); \define('VALIDATE_EALPHA', VALIDATE_EALPHA_LOWER . VALIDATE_EALPHA_UPPER);
define('VALIDATE_PUNCTUATION', VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)'); \define('VALIDATE_PUNCTUATION', VALIDATE_SPACE . '\.,;\:&"\'\?\!\(\)');
define('VALIDATE_NAME', VALIDATE_EALPHA . VALIDATE_SPACE . "'" . '\-'); \define('VALIDATE_NAME', VALIDATE_EALPHA . VALIDATE_SPACE . "'" . '\-');
define('VALIDATE_STREET', VALIDATE_NUM . VALIDATE_NAME . "/\\ºª\."); \define('VALIDATE_STREET', VALIDATE_NUM . VALIDATE_NAME . '/\\ºª\\.');
define('VALIDATE_ITLD_EMAILS', 1); \define('VALIDATE_ITLD_EMAILS', 1);
define('VALIDATE_GTLD_EMAILS', 2); \define('VALIDATE_GTLD_EMAILS', 2);
define('VALIDATE_CCTLD_EMAILS', 4); \define('VALIDATE_CCTLD_EMAILS', 4);
define('VALIDATE_ALL_EMAILS', 8); \define('VALIDATE_ALL_EMAILS', 8);
// }}} // }}}
/** /**
@ -71,14 +76,17 @@ define('VALIDATE_ALL_EMAILS', 8);
* *
* @category Validate * @category Validate
* @package Validate * @package Validate
*
* @author Tomas V.V.Cox <cox@idecnet.com> * @author Tomas V.V.Cox <cox@idecnet.com>
* @author Pierre-Alain Joye <pajoye@php.net> * @author Pierre-Alain Joye <pajoye@php.net>
* @author Amir Mohammad Saied <amir@php.net> * @author Amir Mohammad Saied <amir@php.net>
* @author Diogo Cordeiro <diogo@fc.up.pt> * @author Diogo Cordeiro <diogo@fc.up.pt>
* @copyright 1997-2006 Pierre-Alain Joye,Tomas V.V.Cox,Amir Mohammad Saied * @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 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
*
* @version Release: @package_version@ * @version Release: @package_version@
* @link http://pear.php.net/package/Validate *
* @see http://pear.php.net/package/Validate
*/ */
class Validate class Validate
{ {
@ -91,7 +99,7 @@ class Validate
* *
* @var array $itld (International top-level domains) * @var array $itld (International top-level domains)
*/ */
protected static $itld = [ protected static array $itld = [
'arpa', 'arpa',
'root', 'root',
]; ];
@ -104,7 +112,7 @@ class Validate
* *
* @var array $gtld (Generic top-level domains) * @var array $gtld (Generic top-level domains)
*/ */
protected static $gtld = [ protected static array $gtld = [
'aero', 'aero',
'biz', 'biz',
'cat', 'cat',
@ -137,7 +145,7 @@ class Validate
* *
* @var array $cctld (Country Code Top-Level Domain) * @var array $cctld (Country Code Top-Level Domain)
*/ */
protected static $cctld = [ protected static array $cctld = [
'ac', 'ac',
'ad', 'ae', 'af', 'ag', 'ad', 'ae', 'af', 'ag',
'ai', 'al', 'am', 'an', 'ai', 'al', 'am', 'an',
@ -210,10 +218,9 @@ class Validate
* *
* @param string $uri tag URI to validate * @param string $uri tag URI to validate
* *
* @return bool true if valid tag URI, false if not
*
* @access private
* @throws Exception * @throws Exception
*
* @return bool true if valid tag URI, false if not
*/ */
private static function uriRFC4151(string $uri): bool private static function uriRFC4151(string $uri): bool
{ {
@ -221,15 +228,15 @@ class Validate
if (preg_match( if (preg_match(
'/^tag:(?<name>.*),(?<date>\d{4}-?\d{0,2}-?\d{0,2}):(?<specific>.*)(.*:)*$/', '/^tag:(?<name>.*),(?<date>\d{4}-?\d{0,2}-?\d{0,2}):(?<specific>.*)(.*:)*$/',
$uri, $uri,
$matches $matches,
)) { )) {
$date = $matches['date']; $date = $matches['date'];
$date6 = strtotime($date); $date6 = strtotime($date);
if ((strlen($date) == 4) && $date <= date('Y')) { if ((mb_strlen($date) == 4) && $date <= date('Y')) {
$datevalid = true; $datevalid = true;
} elseif ((strlen($date) == 7) && ($date6 < strtotime("now"))) { } elseif ((mb_strlen($date) == 7) && ($date6 < strtotime('now'))) {
$datevalid = true; $datevalid = true;
} elseif ((strlen($date) == 10) && ($date6 < strtotime("now"))) { } elseif ((mb_strlen($date) == 10) && ($date6 < strtotime('now'))) {
$datevalid = true; $datevalid = true;
} }
if (self::email($matches['name'])) { if (self::email($matches['name'])) {
@ -246,28 +253,28 @@ class Validate
/** /**
* Validate a number * Validate a number
* *
* @param string $number Number to validate * @param string $number Number to validate
* @param array $options array where: * @param array $options array where:
* 'decimal' is the decimal char or false when decimal * 'decimal' is the decimal char or false when decimal
* not allowed. * not allowed.
* i.e. ',.' to allow both ',' and '.' * i.e. ',.' to allow both ',' and '.'
* 'dec_prec' Number of allowed decimals * 'dec_prec' Number of allowed decimals
* 'min' minimum value * 'min' minimum value
* 'max' maximum value * 'max' maximum value
* *
* @return bool true if valid number, false if not * @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; $decimal = $dec_prec = $min = $max = null;
if (is_array($options)) { if (\is_array($options)) {
extract($options); extract($options);
} }
$dec_prec = $dec_prec ? "{1,$dec_prec}" : '+'; $dec_prec = $dec_prec ? "{1,{$dec_prec}}" : '+';
$dec_regex = $decimal ? "[$decimal][0-9]$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; return false;
} }
@ -275,15 +282,12 @@ class Validate
$number = strtr($number, $decimal, '.'); $number = strtr($number, $decimal, '.');
} }
$number = (float)str_replace(' ', '', $number); $number = (float) str_replace(' ', '', $number);
if ($min !== null && $min > $number) { if ($min !== null && $min > $number) {
return false; return false;
} }
if ($max !== null && $max < $number) { return !($max !== null && $max < $number);
return false;
}
return true;
} }
/** /**
@ -291,29 +295,28 @@ class Validate
* *
* @param string $string string to be converted * @param string $string string to be converted
* *
* @return string converted string * @return string converted string
*/ */
private static function stringToUtf7(string $string): string private static function stringToUtf7(string $string): string
{ {
$return = ''; $return = '';
$utf7 = [ $utf7 = [
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '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; $state = 0;
if (!empty($string)) { if (!empty($string)) {
$i = 0; $i = 0;
while ($i <= strlen($string)) { while ($i <= mb_strlen($string)) {
$char = substr($string, $i, 1); $char = mb_substr($string, $i, 1);
if ($state == 0) { if ($state == 0) {
if ((ord($char) >= 0x7F) || (ord($char) <= 0x1F)) { if ((\ord($char) >= 0x7F) || (\ord($char) <= 0x1F)) {
if ($char) { if ($char) {
$return .= '&'; $return .= '&';
} }
@ -323,13 +326,13 @@ class Validate
} else { } else {
$return .= $char; $return .= $char;
} }
} elseif (($i == strlen($string) || } elseif (($i == mb_strlen($string)
!((ord($char) >= 0x7F)) || (ord($char) <= 0x1F))) { || !((\ord($char) >= 0x7F)) || (\ord($char) <= 0x1F))) {
if ($state != 1) { if ($state != 1) {
if (ord($char) > 64) { if (\ord($char) > 64) {
$return .= ''; $return .= '';
} else { } else {
$return .= $utf7[ord($char)]; $return .= $utf7[\ord($char)];
} }
} }
$return .= '-'; $return .= '-';
@ -337,23 +340,23 @@ class Validate
} else { } else {
switch ($state) { switch ($state) {
case 1: case 1:
$return .= $utf7[ord($char) >> 2]; $return .= $utf7[\ord($char) >> 2];
$residue = (ord($char) & 0x03) << 4; $residue = (\ord($char) & 0x03) << 4;
$state = 2; $state = 2;
break; break;
case 2: case 2:
$return .= $utf7[$residue | (ord($char) >> 4)]; $return .= $utf7[$residue | (\ord($char) >> 4)];
$residue = (ord($char) & 0x0F) << 2; $residue = (\ord($char) & 0x0F) << 2;
$state = 3; $state = 3;
break; break;
case 3: case 3:
$return .= $utf7[$residue | (ord($char) >> 6)]; $return .= $utf7[$residue | (\ord($char) >> 6)];
$return .= $utf7[ord($char) & 0x3F]; $return .= $utf7[\ord($char) & 0x3F];
$state = 1; $state = 1;
break; break;
} }
} }
$i++; ++$i;
} }
return $return; return $return;
} }
@ -363,15 +366,15 @@ class Validate
/** /**
* Validate an email according to full RFC822 (inclusive human readable part) * Validate an email according to full RFC822 (inclusive human readable part)
* *
* @param string $email email to validate, * @param string $email email to validate,
* will return the address for optional dns validation * will return the address for optional dns validation
* @param array $options email() options * @param array $options email() options
* *
* @return bool true if valid email, false if not * @return bool true if valid email, false if not
*/ */
private static function emailRFC822(string &$email, array &$options): bool private static function emailRFC822(string &$email, array &$options): bool
{ {
static $address = null; static $address = null;
static $uncomment = null; static $uncomment = null;
if (!$address) { if (!$address) {
// atom = 1*<any CHAR except specials, SPACE and CTLs> // atom = 1*<any CHAR except specials, SPACE and CTLs>
@ -416,9 +419,9 @@ class Validate
// / group ; named list // / group ; named list
$address = '/^\s*(?:' . $mailbox . '|' . $group . ')$/'; $address = '/^\s*(?:' . $mailbox . '|' . $group . ')$/';
$uncomment = $uncomment
'/((?:(?:\\\\"|[^("])*(?:' . $quoted_string . = '/((?:(?:\\\\"|[^("])*(?:' . $quoted_string
')?)*)((?<!\\\\)\((?:(?2)|.)*?(?<!\\\\)\))/'; . ')?)*)((?<!\\\\)\((?:(?2)|.)*?(?<!\\\\)\))/';
} }
// strip comments // strip comments
$email = preg_replace($uncomment, '$1 ', $email); $email = preg_replace($uncomment, '$1 ', $email);
@ -431,27 +434,27 @@ class Validate
* This function is used to make a much more proficient validation * This function is used to make a much more proficient validation
* against all types of official domain names. * 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 * @param array $options The options for validation
* *
* @return bool True if validating succeeds * @return bool True if validating succeeds
*/ */
protected static function fullTLDValidation( protected static function fullTLDValidation(
string $email, string $email,
array $options array $options,
): bool { ): bool {
$validate = []; $validate = [];
if (!empty($options["VALIDATE_ITLD_EMAILS"])) { if (!empty($options['VALIDATE_ITLD_EMAILS'])) {
array_push($validate, 'itld'); $validate[] = 'itld';
} }
if (!empty($options["VALIDATE_GTLD_EMAILS"])) { if (!empty($options['VALIDATE_GTLD_EMAILS'])) {
array_push($validate, 'gtld'); $validate[] = 'gtld';
} }
if (!empty($options["VALIDATE_CCTLD_EMAILS"])) { if (!empty($options['VALIDATE_CCTLD_EMAILS'])) {
array_push($validate, 'cctld'); $validate[] = 'cctld';
} }
if (count($validate) === 0) { if (\count($validate) === 0) {
array_push($validate, 'itld', 'gtld', 'cctld'); array_push($validate, 'itld', 'gtld', 'cctld');
} }
@ -460,7 +463,7 @@ class Validate
foreach ($validate as $valid) { foreach ($validate as $valid) {
$tmpVar = (string) $valid; $tmpVar = (string) $valid;
$toValidate[$valid] = self::$$tmpVar; $toValidate[$valid] = self::${$tmpVar};
} }
$e = self::executeFullEmailValidation($email, $toValidate); $e = self::executeFullEmailValidation($email, $toValidate);
@ -474,19 +477,19 @@ class Validate
* This function will execute the full email vs tld * This function will execute the full email vs tld
* validation using an array of tlds passed to it. * 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 * @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) * @return bool true or false (Depending on if it validates or if it does not)
*/ */
public static function executeFullEmailValidation( public static function executeFullEmailValidation(
string $email, string $email,
array $arrayOfTLDs array $arrayOfTLDs,
): bool { ): bool {
$emailEnding = explode('.', $email); $emailEnding = explode('.', $email);
$emailEnding = $emailEnding[count($emailEnding) - 1]; $emailEnding = $emailEnding[\count($emailEnding) - 1];
foreach ($arrayOfTLDs as $validator => $keys) { foreach ($arrayOfTLDs as $validator => $keys) {
if (in_array($emailEnding, $keys)) { if (\in_array($emailEnding, $keys)) {
return true; return true;
} }
} }
@ -511,18 +514,19 @@ class Validate
* 'VALIDATE_CCTLD_EMAILS' => 'true', * 'VALIDATE_CCTLD_EMAILS' => 'true',
* 'VALIDATE_ITLD_EMAILS' => 'true', * 'VALIDATE_ITLD_EMAILS' => 'true',
* ]; * ];
* * @param null|mixed $options
* @return bool true if valid email, false if not
* *
* @throws Exception * @throws Exception
*
* @return bool true if valid email, false if not
*/ */
public static function email(string $email, $options = null): bool public static function email(string $email, $options = null): bool
{ {
$check_domain = false; $check_domain = false;
$use_rfc822 = false; $use_rfc822 = false;
if (is_bool($options)) { if (\is_bool($options)) {
$check_domain = $options; $check_domain = $options;
} elseif (is_array($options)) { } elseif (\is_array($options)) {
extract($options); extract($options);
} }
@ -538,20 +542,20 @@ class Validate
} }
if ($hasIDNA === true) { if ($hasIDNA === true) {
if (strpos($email, '@') !== false) { if (str_contains($email, '@')) {
$tmpEmail = explode('@', $email); $tmpEmail = explode('@', $email);
$domain = array_pop($tmpEmail); $domain = array_pop($tmpEmail);
// Check if the domain contains characters > 127 which means // Check if the domain contains characters > 127 which means
// it's an idn domain name. // it's an idn domain name.
$chars = count_chars($domain, 1); $chars = count_chars($domain, 1);
if (!empty($chars) && max(array_keys($chars)) > 127) { if (!empty($chars) && max(array_keys($chars)) > 127) {
$idna =& Net_IDNA2::singleton(); $idna = &Net_IDNA2::singleton();
$domain = $idna->encode($domain); $domain = $idna->encode($domain);
} }
array_push($tmpEmail, $domain); $tmpEmail[] = $domain;
$email = implode('@', $tmpEmail); $email = implode('@', $tmpEmail);
} }
} }
@ -580,14 +584,11 @@ class Validate
$&xi'; $&xi';
//checks if exists the domain (MX or A) //checks if exists the domain (MX or A)
if ($use_rfc822 ? self::emailRFC822($email, $options) : if ($use_rfc822 ? self::emailRFC822($email, $options)
preg_match($regex, $email)) { : preg_match($regex, $email)) {
if ($check_domain && function_exists('checkdnsrr')) { if ($check_domain && \function_exists('checkdnsrr')) {
$domain = preg_replace('/[^-a-z.0-9]/i', '', array_pop(explode('@', $email))); $domain = preg_replace('/[^-a-z.0-9]/i', '', array_pop(explode('@', $email)));
if (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')) { return (bool) (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A'));
return true;
}
return false;
} }
return true; return true;
} }
@ -597,38 +598,34 @@ class Validate
/** /**
* Validate a string using the given format 'format' * Validate a string using the given format 'format'
* *
* @param string $string String to validate * @param string $string String to validate
* @param array|string $options Options array where: * @param array|string $options Options array where:
* 'format' is the format of the string * 'format' is the format of the string
* Ex:VALIDATE_NUM . VALIDATE_ALPHA (see constants) * Ex:VALIDATE_NUM . VALIDATE_ALPHA (see constants)
* 'min_length' minimum length * 'min_length' minimum length
* 'max_length' maximum length * 'max_length' maximum length
* *
* @return bool true if valid string, false if not * @return bool true if valid string, false if not
*/ */
public static function string(string $string, $options): bool public static function string(string $string, $options): bool
{ {
$format = null; $format = null;
$min_length = 0; $min_length = 0;
$max_length = 0; $max_length = 0;
if (is_array($options)) { if (\is_array($options)) {
extract($options); extract($options);
} }
if ($format && !preg_match("|^[$format]*\$|s", $string)) { if ($format && !preg_match("|^[{$format}]*\$|s", $string)) {
return false; return false;
} }
if ($min_length && strlen($string) < $min_length) { if ($min_length && mb_strlen($string) < $min_length) {
return false; return false;
} }
if ($max_length && strlen($string) > $max_length) { return !($max_length && mb_strlen($string) > $max_length);
return false;
}
return true;
} }
/** /**
@ -651,35 +648,35 @@ class Validate
* the characters ';/?:@$,' will not be accepted in the query part * the characters ';/?:@$,' will not be accepted in the query part
* if not urlencoded, refer to the option "strict'" * if not urlencoded, refer to the option "strict'"
* *
* @param string $url URI to validate * @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 * key => type
* 'domain_check' => boolean * 'domain_check' => boolean
* Whether to check the DNS entry or not * Whether to check the DNS entry or not
* 'allowed_schemes' => array, list of protocols * 'allowed_schemes' => array, list of protocols
* List of allowed schemes ('http', * List of allowed schemes ('http',
* 'ssh+svn', 'mms') * 'ssh+svn', 'mms')
* 'strict' => string the refused chars * 'strict' => string the refused chars
* in query and fragment parts * in query and fragment parts
* default: ';/?:@$,' * default: ';/?:@$,'
* empty: accept all rfc2396 foreseen chars * empty: accept all rfc2396 foreseen chars
*
* @return bool true if valid uri, false if not
* *
* @throws Exception * @throws Exception
*
* @return bool true if valid uri, false if not
*/ */
public static function uri(string $url, ?array $options = null): bool public static function uri(string $url, ?array $options = null): bool
{ {
$strict = ';/?:@$,'; $strict = ';/?:@$,';
$domain_check = false; $domain_check = false;
$allowed_schemes = null; $allowed_schemes = null;
if (is_array($options)) { if (\is_array($options)) {
extract($options); extract($options);
} }
if (is_array($allowed_schemes) && if (\is_array($allowed_schemes)
in_array("tag", $allowed_schemes) && \in_array('tag', $allowed_schemes)
) { ) {
if (strpos($url, "tag:") === 0) { if (str_starts_with($url, 'tag:')) {
return self::uriRFC4151($url); return self::uriRFC4151($url);
} }
} }
@ -696,12 +693,12 @@ class Validate
(?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();/?:@\&=+$,])*))? # 8. fragment (?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();/?:@\&=+$,])*))? # 8. fragment
$&xi', $&xi',
$url, $url,
$matches $matches,
)) { )) {
$scheme = isset($matches[1]) ? $matches[1] : ''; $scheme = $matches[1] ?? '';
$authority = isset($matches[3]) ? $matches[3] : ''; $authority = $matches[3] ?? '';
if (is_array($allowed_schemes) && if (\is_array($allowed_schemes)
!in_array($scheme, $allowed_schemes) && !\in_array($scheme, $allowed_schemes)
) { ) {
return false; return false;
} }
@ -712,7 +709,7 @@ class Validate
return false; return false;
} }
} }
} elseif ($domain_check && function_exists('checkdnsrr')) { } elseif ($domain_check && \function_exists('checkdnsrr')) {
if (!checkdnsrr($authority, 'A')) { if (!checkdnsrr($authority, 'A')) {
return false; return false;
} }
@ -732,65 +729,63 @@ class Validate
/** /**
* Substr * Substr
* *
* @param string &$date Date * @param string &$date Date
* @param string $num Length * @param string $num Length
* @param string|false $opt Unknown * @param false|string $opt Unknown
*
* @return string
*/ */
private static function substr( private static function substr(
string &$date, string &$date,
string $num, string $num,
$opt = false $opt = false,
): string { ): string {
if ( if (
$opt $opt
&& strlen($date) >= $opt && mb_strlen($date) >= $opt
&& preg_match('/^[0-9]{' . $opt . '}/', $date, $m) && preg_match('/^[0-9]{' . $opt . '}/', $date, $m)
) { ) {
$ret = $m[0]; $ret = $m[0];
} else { } 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; return $ret;
} }
protected static function modf($val, $div) protected static function modf($val, $div)
{ {
if (function_exists('bcmod')) { if (\function_exists('bcmod')) {
return bcmod($val, $div); return bcmod($val, $div);
} elseif (function_exists('fmod')) { } elseif (\function_exists('fmod')) {
return fmod($val, $div); return fmod($val, $div);
} }
$r = $val / $div; $r = $val / $div;
$i = intval($r); $i = (int) $r;
return intval($val - $i * $div + .1); return (int) ($val - $i * $div + .1);
} }
/** /**
* Calculates sum of product of number digits with weights * Calculates sum of product of number digits with weights
* *
* @param string $number number string * @param string $number number string
* @param array $weights reference to array of weights * @param array $weights reference to array of weights
* *
* @return int returns product of number digits with weights * @return int returns product of number digits with weights
*/ */
protected static function multWeights( protected static function multWeights(
string $number, string $number,
array &$weights array &$weights,
): int { ): int {
if (!is_array($weights)) { if (!\is_array($weights)) {
return -1; return -1;
} }
$sum = 0; $sum = 0;
$count = min(count($weights), strlen($number)); $count = min(\count($weights), mb_strlen($number));
if ($count == 0) { // empty string or weights array if ($count == 0) { // empty string or weights array
return -1; return -1;
} }
for ($i = 0; $i < $count; ++$i) { 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; return $sum;
@ -799,20 +794,20 @@ class Validate
/** /**
* Calculates control digit for a given number * Calculates control digit for a given number
* *
* @param string $number number string * @param string $number number string
* @param array $weights reference to array of weights * @param array $weights reference to array of weights
* @param int $modulo (optionsl) number * @param int $modulo (optionsl) number
* @param int $subtract (optional) number * @param int $subtract (optional) number
* @param bool $allow_high (optional) true if function can return number higher than 10 * @param bool $allow_high (optional) true if function can return number higher than 10
* *
* @return int -1 calculated control number is returned * @return int -1 calculated control number is returned
*/ */
protected static function getControlNumber( protected static function getControlNumber(
string $number, string $number,
array &$weights, array &$weights,
int $modulo = 10, int $modulo = 10,
int $subtract = 0, int $subtract = 0,
bool $allow_high = false bool $allow_high = false,
): int { ): int {
// calc sum // calc sum
$sum = self::multWeights($number, $weights); $sum = self::multWeights($number, $weights);
@ -833,30 +828,29 @@ class Validate
/** /**
* Validates a number * Validates a number
* *
* @param string $number number to validate * @param string $number number to validate
* @param array $weights reference to array of weights * @param array $weights reference to array of weights
* @param int $modulo (optional) number * @param int $modulo (optional) number
* @param int $subtract (optional) number * @param int $subtract (optional) number
* *
* @return bool true if valid, false if not * @return bool true if valid, false if not
*/ */
protected static function checkControlNumber( protected static function checkControlNumber(
string $number, string $number,
array &$weights, array &$weights,
int $modulo = 10, int $modulo = 10,
int $subtract = 0 int $subtract = 0,
): bool ): bool {
{ if (mb_strlen($number) < \count($weights)) {
if (strlen($number) < count($weights)) {
return false; return false;
} }
$target_digit = substr($number, count($weights), 1); $target_digit = mb_substr($number, \count($weights), 1);
$control_digit = self::getControlNumber( $control_digit = self::getControlNumber(
$number, $number,
$weights, $weights,
$modulo, $modulo,
$subtract, $subtract,
($modulo > 10) ($modulo > 10),
); );
if ($control_digit == -1) { if ($control_digit == -1) {
@ -865,10 +859,7 @@ class Validate
if ($target_digit === 'X' && $control_digit == 10) { if ($target_digit === 'X' && $control_digit == 10) {
return true; return true;
} }
if ($control_digit != $target_digit) { return !($control_digit != $target_digit);
return false;
}
return true;
} }
/** /**
@ -876,22 +867,22 @@ class Validate
* assoc array in the form $var_name => $value. * assoc array in the form $var_name => $value.
* Can be used on any of Validate subpackages * Can be used on any of Validate subpackages
* *
* @param array $data Ex: ['name' => 'toto', 'email' => 'toto@thing.info']; * @param array $data Ex: ['name' => 'toto', 'email' => 'toto@thing.info'];
* @param array $val_type Contains the validation type and all parameters used in. * @param array $val_type Contains the validation type and all parameters used in.
* 'val_type' is not optional * 'val_type' is not optional
* others validations properties must have the same name as the function * others validations properties must have the same name as the function
* parameters. * parameters.
* Ex: ['toto' => ['type'=>'string','format'='toto@thing.info','min_length'=>5]]; * Ex: ['toto' => ['type'=>'string','format'='toto@thing.info','min_length'=>5]];
* @param bool $remove if set, the elements not listed in data will be removed * @param bool $remove if set, the elements not listed in data will be removed
* *
* @return array value name => true|false the value name comes from the data key * @return array value name => true|false the value name comes from the data key
*/ */
public static function multiple( public static function multiple(
array &$data, array &$data,
array &$val_type, array &$val_type,
bool $remove = false bool $remove = false,
): array { ): array {
$keys = array_keys($data); $keys = array_keys($data);
$valid = []; $valid = [];
foreach ($keys as $var_name) { foreach ($keys as $var_name) {
@ -901,45 +892,45 @@ class Validate
} }
continue; continue;
} }
$opt = $val_type[$var_name]; $opt = $val_type[$var_name];
$methods = get_class_methods('Validate'); $methods = get_class_methods('Validate');
$val2check = $data[$var_name]; $val2check = $data[$var_name];
// core validation method // core validation method
if (in_array(strtolower($opt['type']), $methods)) { if (\in_array(mb_strtolower($opt['type']), $methods)) {
//$opt[$opt['type']] = $data[$var_name]; //$opt[$opt['type']] = $data[$var_name];
$method = $opt['type']; $method = $opt['type'];
unset($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); $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: * external validation method in the form:
* "<class name><underscore><method name>" * "<class name><underscore><method name>"
* Ex: us_ssn will include class Validate/US.php and call method ssn() * 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']); $validateType = explode('_', $opt['type']);
$method = array_pop($validateType); $method = array_pop($validateType);
$class = implode('_', $validateType); $class = implode('_', $validateType);
$classPath = str_replace('_', DIRECTORY_SEPARATOR, $class); $classPath = str_replace('_', \DIRECTORY_SEPARATOR, $class);
$class = 'Validate_' . $class; $class = 'Validate_' . $class;
if (self::includePathFileExists("Validate/{$classPath}.php")) { if (self::includePathFileExists("Validate/{$classPath}.php")) {
include_once "Validate/{$classPath}.php"; include_once "Validate/{$classPath}.php";
} else { } 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 ? $ce = mb_substr(phpversion(), 0, 1) > 4
class_exists($class, false) : class_exists($class); ? class_exists($class, false) : class_exists($class);
if (!$ce || if (!$ce
!in_array($method, get_class_methods($class)) || !\in_array($method, get_class_methods($class))
) { ) {
trigger_error( trigger_error(
"Invalid validation type $class::$method", "Invalid validation type {$class}::{$method}",
E_USER_WARNING \E_USER_WARNING,
); );
continue; continue;
} }
@ -947,15 +938,15 @@ class Validate
if (sizeof($opt) == 1) { if (sizeof($opt) == 1) {
$opt = array_pop($opt); $opt = array_pop($opt);
} }
$valid[$var_name] = call_user_func( $valid[$var_name] = \call_user_func(
array($class, $method), [$class, $method],
$data[$var_name], $data[$var_name],
$opt $opt,
); );
} else { } else {
trigger_error( trigger_error(
"Invalid validation type {$opt['type']}", "Invalid validation type {$opt['type']}",
E_USER_WARNING \E_USER_WARNING,
); );
} }
} }
@ -971,11 +962,11 @@ class Validate
*/ */
private static function includePathFileExists(string $filename): bool private static function includePathFileExists(string $filename): bool
{ {
$paths = explode(":", ini_get("include_path")); $paths = explode(':', ini_get('include_path'));
$result = false; $result = false;
foreach ($paths as $val) { foreach ($paths as $val) {
$result = file_exists($val . "/" . $filename); $result = file_exists($val . '/' . $filename);
if ($result) { if ($result) {
break; break;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,7 @@
<?php <?php
declare(strict_types = 1);
namespace Plugin\ActivityPub\Util\Response; namespace Plugin\ActivityPub\Util\Response;
use App\Entity\Actor; use App\Entity\Actor;
@ -9,17 +11,13 @@ use Plugin\ActivityPub\Util\Model\EntityToType\GSActorToType;
abstract class ActorResponse abstract class ActorResponse
{ {
/** /**
* @param Actor $gsactor * @param int $status The response status code
* @param int $status The response status code
* *
*@throws Exception *@throws Exception
*
* @return TypeResponse
*
*/ */
public static function handle(Actor $gsactor, int $status = 200): TypeResponse public static function handle(Actor $gsactor, int $status = 200): TypeResponse
{ {
$gsactor->getLocalUser(); // This throws exception if not a local user, which is intended $gsactor->getLocalUser(); // This throws exception if not a local user, which is intended
return new TypeResponse(data: GSActorToType::translate($gsactor), status: $status); return new TypeResponse(data: GSActorToType::translate($gsactor), status: $status);
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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