pixelfed/app/Util/ActivityPub/Helpers.php

516 lines
14 KiB
PHP
Raw Normal View History

2018-10-29 01:29:44 +00:00
<?php
namespace App\Util\ActivityPub;
2019-04-05 05:13:59 +00:00
use DB, Cache, Purify, Storage, Request, Validator;
2018-10-29 01:29:44 +00:00
use App\{
2019-03-08 06:46:38 +00:00
Activity,
Follower,
Like,
Media,
Notification,
Profile,
Status
2018-10-29 01:29:44 +00:00
};
use Zttp\Zttp;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\File;
use Illuminate\Validation\Rule;
use App\Jobs\AvatarPipeline\CreateAvatar;
use App\Jobs\RemoteFollowPipeline\RemoteFollowImportRecent;
use App\Jobs\ImageOptimizePipeline\{ImageOptimize,ImageThumbnail};
use App\Jobs\StatusPipeline\NewStatusPipeline;
2018-12-21 19:57:43 +00:00
use App\Util\ActivityPub\HttpSignature;
2019-04-05 04:44:08 +00:00
use Illuminate\Support\Str;
use App\Services\ActivityPubFetchService;
2020-02-01 18:42:24 +00:00
use App\Services\ActivityPubDeliveryService;
2020-07-20 14:39:48 +00:00
use App\Services\MediaPathService;
2021-01-07 03:34:55 +00:00
use App\Services\MediaStorageService;
use App\Jobs\MediaPipeline\MediaStoragePipeline;
use App\Jobs\AvatarPipeline\RemoteAvatarFetch;
2018-10-29 01:29:44 +00:00
class Helpers {
public static function validateObject($data)
{
2019-04-18 05:48:26 +00:00
$verbs = ['Create', 'Announce', 'Like', 'Follow', 'Delete', 'Accept', 'Reject', 'Undo', 'Tombstone'];
2018-10-29 01:29:44 +00:00
$valid = Validator::make($data, [
'type' => [
'required',
2019-04-18 06:32:27 +00:00
'string',
2018-10-29 01:29:44 +00:00
Rule::in($verbs)
],
'id' => 'required|string',
2019-04-18 05:29:22 +00:00
'actor' => 'required|string|url',
2018-10-29 01:29:44 +00:00
'object' => 'required',
'object.type' => 'required_if:type,Create',
2019-04-18 05:29:22 +00:00
'object.attributedTo' => 'required_if:type,Create|url',
2018-10-29 01:29:44 +00:00
'published' => 'required_if:type,Create|date'
])->passes();
return $valid;
}
public static function verifyAttachments($data)
{
if(!isset($data['object']) || empty($data['object'])) {
$data = ['object'=>$data];
}
$activity = $data['object'];
2019-06-12 19:21:41 +00:00
$mimeTypes = explode(',', config('pixelfed.media_types'));
$mediaTypes = in_array('video/mp4', $mimeTypes) ? ['Document', 'Image', 'Video'] : ['Document', 'Image'];
2019-03-08 06:46:38 +00:00
if(!isset($activity['attachment']) || empty($activity['attachment'])) {
return false;
}
$attachment = $activity['attachment'];
$valid = Validator::make($attachment, [
'*.type' => [
'required',
'string',
Rule::in($mediaTypes)
],
2019-04-18 05:29:22 +00:00
'*.url' => 'required|url|max:255',
2019-03-08 06:46:38 +00:00
'*.mediaType' => [
'required',
'string',
Rule::in($mimeTypes)
],
'*.name' => 'nullable|string|max:255'
])->passes();
return $valid;
2018-10-29 01:29:44 +00:00
}
public static function normalizeAudience($data, $localOnly = true)
{
if(!isset($data['to'])) {
return;
}
2019-03-08 06:46:38 +00:00
2018-10-29 01:29:44 +00:00
$audience = [];
$audience['to'] = [];
$audience['cc'] = [];
$scope = 'private';
if(is_array($data['to']) && !empty($data['to'])) {
foreach ($data['to'] as $to) {
if($to == 'https://www.w3.org/ns/activitystreams#Public') {
$scope = 'public';
continue;
}
$url = $localOnly ? self::validateLocalUrl($to) : self::validateUrl($to);
if($url != false) {
array_push($audience['to'], $url);
}
}
}
if(is_array($data['cc']) && !empty($data['cc'])) {
foreach ($data['cc'] as $cc) {
if($cc == 'https://www.w3.org/ns/activitystreams#Public') {
$scope = 'unlisted';
continue;
}
$url = $localOnly ? self::validateLocalUrl($cc) : self::validateUrl($cc);
if($url != false) {
array_push($audience['cc'], $url);
}
}
}
$audience['scope'] = $scope;
return $audience;
}
public static function userInAudience($profile, $data)
{
$audience = self::normalizeAudience($data);
$url = $profile->permalink();
2019-07-27 05:02:13 +00:00
return in_array($url, $audience['to']) || in_array($url, $audience['cc']);
2018-10-29 01:29:44 +00:00
}
public static function validateUrl($url)
{
2020-06-13 06:21:41 +00:00
if(is_array($url)) {
$url = $url[0];
}
2018-10-29 01:29:44 +00:00
2020-11-26 07:39:01 +00:00
$hash = hash('sha256', $url);
$key = "helpers:url:valid:sha256-{$hash}";
$ttl = now()->addMinutes(5);
2019-04-02 00:26:15 +00:00
2020-11-26 07:39:01 +00:00
$valid = Cache::remember($key, $ttl, function() use($url) {
$localhosts = [
'127.0.0.1', 'localhost', '::1'
];
2018-10-29 01:29:44 +00:00
2020-11-26 07:39:01 +00:00
if(mb_substr($url, 0, 8) !== 'https://') {
return false;
}
2019-04-05 01:57:13 +00:00
2020-11-26 07:39:01 +00:00
$valid = filter_var($url, FILTER_VALIDATE_URL);
2019-04-05 01:57:13 +00:00
2020-11-26 07:39:01 +00:00
if(!$valid) {
return false;
}
2019-06-24 04:22:23 +00:00
2020-11-26 07:39:01 +00:00
$host = parse_url($valid, PHP_URL_HOST);
if(count(dns_get_record($host, DNS_A | DNS_AAAA)) == 0) {
2019-04-05 01:57:13 +00:00
return false;
}
2020-11-26 07:39:01 +00:00
if(config('costar.enabled') == true) {
if(
(config('costar.domain.block') != null && Str::contains($host, config('costar.domain.block')) == true) ||
(config('costar.actor.block') != null && in_array($url, config('costar.actor.block')) == true)
) {
return false;
}
}
2018-10-29 01:29:44 +00:00
2020-11-26 07:39:01 +00:00
if(in_array($host, $localhosts)) {
return false;
}
2020-11-26 07:50:46 +00:00
return $url;
2020-11-26 07:39:01 +00:00
});
2020-11-26 07:50:46 +00:00
return $valid;
2018-10-29 01:29:44 +00:00
}
public static function validateLocalUrl($url)
{
$url = self::validateUrl($url);
2019-04-05 03:26:10 +00:00
if($url == true) {
2018-10-29 01:29:44 +00:00
$domain = config('pixelfed.domain.app');
$host = parse_url($url, PHP_URL_HOST);
$url = $domain === $host ? $url : false;
return $url;
}
return false;
}
public static function zttpUserAgent()
{
2020-04-29 19:31:47 +00:00
$version = config('pixelfed.version');
$url = config('app.url');
2018-10-29 01:29:44 +00:00
return [
2019-08-24 03:28:37 +00:00
'Accept' => 'application/activity+json',
2020-04-29 19:31:47 +00:00
'User-Agent' => "(Pixelfed/{$version}; +{$url})",
2019-03-08 06:46:38 +00:00
];
2018-10-29 01:29:44 +00:00
}
2020-11-26 07:39:01 +00:00
public static function fetchFromUrl($url = false)
2018-10-29 01:29:44 +00:00
{
2020-11-26 07:39:01 +00:00
if(self::validateUrl($url) == false) {
2019-04-02 00:29:59 +00:00
return;
}
2020-11-26 07:39:01 +00:00
$hash = hash('sha256', $url);
$key = "helpers:url:fetcher:sha256-{$hash}";
$ttl = now()->addMinutes(5);
return Cache::remember($key, $ttl, function() use($url) {
$res = ActivityPubFetchService::get($url);
$res = json_decode($res, true, 8);
2020-11-26 07:39:01 +00:00
if(json_last_error() == JSON_ERROR_NONE) {
return $res;
} else {
return false;
}
});
2018-10-29 01:29:44 +00:00
}
public static function fetchProfileFromUrl($url)
{
return self::fetchFromUrl($url);
}
2019-06-25 04:46:35 +00:00
public static function statusFirstOrFetch($url, $replyTo = false)
2018-10-29 01:29:44 +00:00
{
$url = self::validateUrl($url);
if($url == false) {
return;
}
$host = parse_url($url, PHP_URL_HOST);
$local = config('pixelfed.domain.app') == $host ? true : false;
if($local) {
$id = (int) last(explode('/', $url));
2021-01-07 03:34:55 +00:00
return Status::whereNotIn('scope', ['draft','archived'])->findOrFail($id);
2021-01-29 04:26:45 +00:00
}
2021-01-08 03:52:50 +00:00
2021-01-29 04:26:45 +00:00
$cached = Status::whereNotIn('scope', ['draft','archived'])
->whereUri($url)
->orWhere('object_url', $url)
->first();
2021-01-08 03:52:50 +00:00
2021-01-29 04:26:45 +00:00
if($cached) {
return $cached;
}
2018-10-29 01:29:44 +00:00
2021-01-29 04:26:45 +00:00
$res = self::fetchFromUrl($url);
if(!$res || empty($res)) {
return;
}
2018-10-29 01:29:44 +00:00
2021-01-29 04:26:45 +00:00
if(isset($res['object'])) {
$activity = $res;
} else {
$activity = ['object' => $res];
}
2019-04-05 04:44:08 +00:00
2021-01-29 04:26:45 +00:00
$scope = 'private';
$cw = isset($res['sensitive']) ? (bool) $res['sensitive'] : false;
if(isset($res['to']) == true) {
if(is_array($res['to']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['to'])) {
$scope = 'public';
}
if(is_string($res['to']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['to']) {
$scope = 'public';
2019-04-05 04:44:08 +00:00
}
2021-01-29 04:26:45 +00:00
}
2019-04-05 04:44:08 +00:00
2021-01-29 04:26:45 +00:00
if(isset($res['cc']) == true) {
if(is_array($res['cc']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['cc'])) {
$scope = 'unlisted';
}
if(is_string($res['cc']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['cc']) {
$scope = 'unlisted';
2019-04-05 04:44:08 +00:00
}
2021-01-29 04:26:45 +00:00
}
2019-04-05 04:44:08 +00:00
2021-01-29 04:26:45 +00:00
if(config('costar.enabled') == true) {
$blockedKeywords = config('costar.keyword.block');
if($blockedKeywords !== null) {
$keywords = config('costar.keyword.block');
foreach($keywords as $kw) {
if(Str::contains($res['content'], $kw) == true) {
return;
2019-04-05 04:44:08 +00:00
}
}
2021-01-29 04:26:45 +00:00
}
2019-04-05 04:44:08 +00:00
2021-01-29 04:26:45 +00:00
$unlisted = config('costar.domain.unlisted');
if(in_array(parse_url($url, PHP_URL_HOST), $unlisted) == true) {
$unlisted = true;
$scope = 'unlisted';
} else {
$unlisted = false;
2019-04-05 04:44:08 +00:00
}
2021-01-29 04:26:45 +00:00
$cwDomains = config('costar.domain.cw');
if(in_array(parse_url($url, PHP_URL_HOST), $cwDomains) == true) {
$cw = true;
}
}
2021-01-08 03:52:50 +00:00
2021-01-29 04:26:45 +00:00
$id = isset($res['id']) ? $res['id'] : $url;
$idDomain = parse_url($id, PHP_URL_HOST);
$urlDomain = parse_url($url, PHP_URL_HOST);
2019-06-16 05:30:12 +00:00
2021-01-29 04:26:45 +00:00
if(!self::validateUrl($id)) {
return;
}
2018-12-26 05:05:47 +00:00
2021-01-29 04:26:45 +00:00
if(isset($activity['object']['attributedTo'])) {
$actorDomain = parse_url($activity['object']['attributedTo'], PHP_URL_HOST);
if(!self::validateUrl($activity['object']['attributedTo']) ||
$idDomain !== $actorDomain)
{
2020-04-29 19:47:03 +00:00
return;
2018-12-26 05:05:47 +00:00
}
2021-01-29 04:26:45 +00:00
}
2018-12-26 05:05:47 +00:00
2021-01-29 04:26:45 +00:00
if(
$idDomain !== $urlDomain ||
$actorDomain !== $urlDomain
) {
return;
}
2018-10-29 01:29:44 +00:00
2021-01-29 04:26:45 +00:00
$profile = self::profileFirstOrNew($activity['object']['attributedTo']);
if(isset($activity['object']['inReplyTo']) && !empty($activity['object']['inReplyTo']) && $replyTo == true) {
$reply_to = self::statusFirstOrFetch($activity['object']['inReplyTo'], false);
$reply_to = optional($reply_to)->id;
} else {
$reply_to = null;
2018-10-29 01:29:44 +00:00
}
2021-01-29 04:26:45 +00:00
$ts = is_array($res['published']) ? $res['published'][0] : $res['published'];
$status = DB::transaction(function() use($profile, $res, $url, $ts, $reply_to, $cw, $scope, $id) {
$status = new Status;
$status->profile_id = $profile->id;
$status->url = isset($res['url']) ? $res['url'] : $url;
$status->uri = isset($res['url']) ? $res['url'] : $url;
$status->object_url = $id;
$status->caption = strip_tags($res['content']);
$status->rendered = Purify::clean($res['content']);
$status->created_at = Carbon::parse($ts);
$status->in_reply_to_id = $reply_to;
$status->local = false;
$status->is_nsfw = $cw;
$status->scope = $scope;
$status->visibility = $scope;
$status->cw_summary = $cw == true && isset($res['summary']) ?
Purify::clean(strip_tags($res['summary'])) : null;
$status->save();
if($reply_to == null) {
self::importNoteAttachment($res, $status);
}
return $status;
});
return $status;
2018-10-29 01:29:44 +00:00
}
2019-06-25 04:44:01 +00:00
public static function statusFetch($url)
{
return self::statusFirstOrFetch($url);
}
2018-10-29 01:29:44 +00:00
public static function importNoteAttachment($data, Status $status)
{
if(self::verifyAttachments($data) == false) {
return;
}
$attachments = isset($data['object']) ? $data['object']['attachment'] : $data['attachment'];
$user = $status->profile;
2020-07-20 14:39:48 +00:00
$storagePath = MediaPathService::get($user, 2);
2019-03-08 06:46:38 +00:00
$allowed = explode(',', config('pixelfed.media_types'));
2019-06-12 19:21:41 +00:00
2018-10-29 01:29:44 +00:00
foreach($attachments as $media) {
$type = $media['mediaType'];
$url = $media['url'];
$blurhash = isset($media['blurhash']) ? $media['blurhash'] : null;
2018-10-29 01:29:44 +00:00
$valid = self::validateUrl($url);
if(in_array($type, $allowed) == false || $valid == false) {
continue;
}
2019-06-09 18:53:32 +00:00
$media = new Media();
$media->blurhash = $blurhash;
2019-06-09 23:38:29 +00:00
$media->remote_media = true;
2019-06-09 18:53:32 +00:00
$media->status_id = $status->id;
$media->profile_id = $status->profile_id;
$media->user_id = null;
2019-07-19 04:08:39 +00:00
$media->media_path = $url;
$media->remote_url = $url;
$media->mime = $type;
$media->version = 3;
2019-06-09 18:53:32 +00:00
$media->save();
if(config('pixelfed.cloud_storage') == true) {
MediaStoragePipeline::dispatch($media);
}
2018-10-29 01:29:44 +00:00
}
2019-06-12 19:21:41 +00:00
$status->viewType();
2018-10-29 01:29:44 +00:00
return;
}
public static function profileFirstOrNew($url, $runJobs = false)
{
2019-03-06 02:52:12 +00:00
$url = self::validateUrl($url);
2021-01-07 07:25:45 +00:00
if($url == false || strlen($url) > 190) {
2019-03-08 06:46:38 +00:00
return;
}
2021-01-07 07:25:45 +00:00
$hash = base64_encode($url);
$key = 'ap:profile:by_url:' . $hash;
$ttl = now()->addMinutes(5);
$profile = Cache::remember($key, $ttl, function() use($url, $runJobs) {
$host = parse_url($url, PHP_URL_HOST);
$local = config('pixelfed.domain.app') == $host ? true : false;
if($local == true) {
$id = last(explode('/', $url));
return Profile::whereNull('status')
->whereNull('domain')
->whereUsername($id)
->firstOrFail();
2019-03-08 06:46:38 +00:00
}
2021-01-07 07:25:45 +00:00
$res = self::fetchProfileFromUrl($url);
if(isset($res['id']) == false) {
return;
2020-06-13 06:21:41 +00:00
}
2021-01-07 07:25:45 +00:00
$domain = parse_url($res['id'], PHP_URL_HOST);
if(!isset($res['preferredUsername']) && !isset($res['nickname'])) {
return;
}
$username = (string) Purify::clean($res['preferredUsername'] ?? $res['nickname']);
if(empty($username)) {
return;
}
$remoteUsername = $username;
$webfinger = "@{$username}@{$domain}";
abort_if(!self::validateUrl($res['inbox']), 400);
abort_if(!self::validateUrl($res['id']), 400);
$profile = Profile::whereRemoteUrl($res['id'])->first();
if(!$profile) {
$profile = DB::transaction(function() use($domain, $webfinger, $res, $runJobs) {
$profile = new Profile();
$profile->domain = strtolower($domain);
$profile->username = strtolower(Purify::clean($webfinger));
$profile->name = isset($res['name']) ? Purify::clean($res['name']) : 'user';
$profile->bio = isset($res['summary']) ? Purify::clean($res['summary']) : null;
$profile->sharedInbox = isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null;
$profile->inbox_url = strtolower($res['inbox']);
$profile->outbox_url = strtolower($res['outbox']);
$profile->remote_url = strtolower($res['id']);
$profile->public_key = $res['publicKey']['publicKeyPem'];
$profile->key_id = $res['publicKey']['id'];
$profile->webfinger = strtolower(Purify::clean($webfinger));
$profile->last_fetched_at = now();
$profile->save();
if(config('pixelfed.cloud_storage') == true) {
RemoteAvatarFetch::dispatch($profile);
}
2021-01-07 07:25:45 +00:00
return $profile;
});
} else {
// Update info after 24 hours
if($profile->last_fetched_at == null ||
$profile->last_fetched_at->lt(now()->subHours(24)) == true
) {
$profile->name = isset($res['name']) ? Purify::clean($res['name']) : 'user';
$profile->bio = isset($res['summary']) ? Purify::clean($res['summary']) : null;
$profile->last_fetched_at = now();
$profile->sharedInbox = isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) && Helpers::validateUrl($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null;
$profile->save();
}
if(config('pixelfed.cloud_storage') == true) {
RemoteAvatarFetch::dispatch($profile);
}
2021-01-07 07:25:45 +00:00
}
return $profile;
});
2018-10-29 01:29:44 +00:00
return $profile;
}
2019-06-25 04:44:01 +00:00
public static function profileFetch($url)
{
return self::profileFirstOrNew($url);
}
2020-02-01 18:42:24 +00:00
public static function sendSignedObject($profile, $url, $body)
2019-03-08 06:46:38 +00:00
{
2020-02-01 18:42:24 +00:00
ActivityPubDeliveryService::queue()
->from($profile)
->to($url)
->payload($body)
->send();
2019-03-08 06:46:38 +00:00
}
}