1
0

Helpers.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. <?php
  2. namespace App\Util\ActivityPub;
  3. use DB, Cache, Purify, Storage, Request, Validator;
  4. use App\{
  5. Activity,
  6. Follower,
  7. Instance,
  8. Like,
  9. Media,
  10. Notification,
  11. Profile,
  12. Status
  13. };
  14. use Zttp\Zttp;
  15. use Carbon\Carbon;
  16. use GuzzleHttp\Client;
  17. use Illuminate\Http\File;
  18. use Illuminate\Validation\Rule;
  19. use App\Jobs\AvatarPipeline\CreateAvatar;
  20. use App\Jobs\RemoteFollowPipeline\RemoteFollowImportRecent;
  21. use App\Jobs\ImageOptimizePipeline\{ImageOptimize,ImageThumbnail};
  22. use App\Jobs\StatusPipeline\NewStatusPipeline;
  23. use App\Jobs\StatusPipeline\StatusReplyPipeline;
  24. use App\Util\ActivityPub\HttpSignature;
  25. use Illuminate\Support\Str;
  26. use App\Services\ActivityPubFetchService;
  27. use App\Services\ActivityPubDeliveryService;
  28. use App\Services\InstanceService;
  29. use App\Services\MediaPathService;
  30. use App\Services\MediaStorageService;
  31. use App\Jobs\MediaPipeline\MediaStoragePipeline;
  32. use App\Jobs\AvatarPipeline\RemoteAvatarFetch;
  33. use App\Util\Media\License;
  34. use App\Models\Poll;
  35. class Helpers {
  36. public static function validateObject($data)
  37. {
  38. $verbs = ['Create', 'Announce', 'Like', 'Follow', 'Delete', 'Accept', 'Reject', 'Undo', 'Tombstone'];
  39. $valid = Validator::make($data, [
  40. 'type' => [
  41. 'required',
  42. 'string',
  43. Rule::in($verbs)
  44. ],
  45. 'id' => 'required|string',
  46. 'actor' => 'required|string|url',
  47. 'object' => 'required',
  48. 'object.type' => 'required_if:type,Create',
  49. 'object.attributedTo' => 'required_if:type,Create|url',
  50. 'published' => 'required_if:type,Create|date'
  51. ])->passes();
  52. return $valid;
  53. }
  54. public static function verifyAttachments($data)
  55. {
  56. if(!isset($data['object']) || empty($data['object'])) {
  57. $data = ['object'=>$data];
  58. }
  59. $activity = $data['object'];
  60. $mimeTypes = explode(',', config_cache('pixelfed.media_types'));
  61. $mediaTypes = in_array('video/mp4', $mimeTypes) ? ['Document', 'Image', 'Video'] : ['Document', 'Image'];
  62. if(!isset($activity['attachment']) || empty($activity['attachment'])) {
  63. return false;
  64. }
  65. $attachment = $activity['attachment'];
  66. $valid = Validator::make($attachment, [
  67. '*.type' => [
  68. 'required',
  69. 'string',
  70. Rule::in($mediaTypes)
  71. ],
  72. '*.url' => 'required|url|max:255',
  73. '*.mediaType' => [
  74. 'required',
  75. 'string',
  76. Rule::in($mimeTypes)
  77. ],
  78. '*.name' => 'nullable|string|max:255'
  79. ])->passes();
  80. return $valid;
  81. }
  82. public static function normalizeAudience($data, $localOnly = true)
  83. {
  84. if(!isset($data['to'])) {
  85. return;
  86. }
  87. $audience = [];
  88. $audience['to'] = [];
  89. $audience['cc'] = [];
  90. $scope = 'private';
  91. if(is_array($data['to']) && !empty($data['to'])) {
  92. foreach ($data['to'] as $to) {
  93. if($to == 'https://www.w3.org/ns/activitystreams#Public') {
  94. $scope = 'public';
  95. continue;
  96. }
  97. $url = $localOnly ? self::validateLocalUrl($to) : self::validateUrl($to);
  98. if($url != false) {
  99. array_push($audience['to'], $url);
  100. }
  101. }
  102. }
  103. if(is_array($data['cc']) && !empty($data['cc'])) {
  104. foreach ($data['cc'] as $cc) {
  105. if($cc == 'https://www.w3.org/ns/activitystreams#Public') {
  106. $scope = 'unlisted';
  107. continue;
  108. }
  109. $url = $localOnly ? self::validateLocalUrl($cc) : self::validateUrl($cc);
  110. if($url != false) {
  111. array_push($audience['cc'], $url);
  112. }
  113. }
  114. }
  115. $audience['scope'] = $scope;
  116. return $audience;
  117. }
  118. public static function userInAudience($profile, $data)
  119. {
  120. $audience = self::normalizeAudience($data);
  121. $url = $profile->permalink();
  122. return in_array($url, $audience['to']) || in_array($url, $audience['cc']);
  123. }
  124. public static function validateUrl($url)
  125. {
  126. if(is_array($url)) {
  127. $url = $url[0];
  128. }
  129. $hash = hash('sha256', $url);
  130. $key = "helpers:url:valid:sha256-{$hash}";
  131. $ttl = now()->addMinutes(5);
  132. $valid = Cache::remember($key, $ttl, function() use($url) {
  133. $localhosts = [
  134. '127.0.0.1', 'localhost', '::1'
  135. ];
  136. if(mb_substr($url, 0, 8) !== 'https://') {
  137. return false;
  138. }
  139. $valid = filter_var($url, FILTER_VALIDATE_URL);
  140. if(!$valid) {
  141. return false;
  142. }
  143. $host = parse_url($valid, PHP_URL_HOST);
  144. // if(count(dns_get_record($host, DNS_A | DNS_AAAA)) == 0) {
  145. // return false;
  146. // }
  147. if(config('costar.enabled') == true) {
  148. if(
  149. (config('costar.domain.block') != null && Str::contains($host, config('costar.domain.block')) == true) ||
  150. (config('costar.actor.block') != null && in_array($url, config('costar.actor.block')) == true)
  151. ) {
  152. return false;
  153. }
  154. }
  155. if(app()->environment() === 'production') {
  156. $bannedInstances = InstanceService::getBannedDomains();
  157. if(in_array($host, $bannedInstances)) {
  158. return false;
  159. }
  160. }
  161. if(in_array($host, $localhosts)) {
  162. return false;
  163. }
  164. return $url;
  165. });
  166. return $valid;
  167. }
  168. public static function validateLocalUrl($url)
  169. {
  170. $url = self::validateUrl($url);
  171. if($url == true) {
  172. $domain = config('pixelfed.domain.app');
  173. $host = parse_url($url, PHP_URL_HOST);
  174. $url = $domain === $host ? $url : false;
  175. return $url;
  176. }
  177. return false;
  178. }
  179. public static function zttpUserAgent()
  180. {
  181. $version = config('pixelfed.version');
  182. $url = config('app.url');
  183. return [
  184. 'Accept' => 'application/activity+json',
  185. 'User-Agent' => "(Pixelfed/{$version}; +{$url})",
  186. ];
  187. }
  188. public static function fetchFromUrl($url = false)
  189. {
  190. if(self::validateUrl($url) == false) {
  191. return;
  192. }
  193. $hash = hash('sha256', $url);
  194. $key = "helpers:url:fetcher:sha256-{$hash}";
  195. $ttl = now()->addMinutes(5);
  196. return Cache::remember($key, $ttl, function() use($url) {
  197. $res = ActivityPubFetchService::get($url);
  198. $res = json_decode($res, true, 8);
  199. if(json_last_error() == JSON_ERROR_NONE) {
  200. return $res;
  201. } else {
  202. return false;
  203. }
  204. });
  205. }
  206. public static function fetchProfileFromUrl($url)
  207. {
  208. return self::fetchFromUrl($url);
  209. }
  210. public static function statusFirstOrFetch($url, $replyTo = false)
  211. {
  212. $url = self::validateUrl($url);
  213. if($url == false) {
  214. return;
  215. }
  216. $host = parse_url($url, PHP_URL_HOST);
  217. $local = config('pixelfed.domain.app') == $host ? true : false;
  218. if($local) {
  219. $id = (int) last(explode('/', $url));
  220. return Status::whereNotIn('scope', ['draft','archived'])->findOrFail($id);
  221. }
  222. $cached = Status::whereNotIn('scope', ['draft','archived'])
  223. ->whereUri($url)
  224. ->orWhere('object_url', $url)
  225. ->first();
  226. if($cached) {
  227. return $cached;
  228. }
  229. $res = self::fetchFromUrl($url);
  230. if(!$res || empty($res) || isset($res['error']) || !isset($res['@context']) ) {
  231. return;
  232. }
  233. if(isset($res['object'])) {
  234. $activity = $res;
  235. } else {
  236. $activity = ['object' => $res];
  237. }
  238. $scope = 'private';
  239. $cw = isset($res['sensitive']) ? (bool) $res['sensitive'] : false;
  240. if(isset($res['to']) == true) {
  241. if(is_array($res['to']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['to'])) {
  242. $scope = 'public';
  243. }
  244. if(is_string($res['to']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['to']) {
  245. $scope = 'public';
  246. }
  247. }
  248. if(isset($res['cc']) == true) {
  249. if(is_array($res['cc']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['cc'])) {
  250. $scope = 'unlisted';
  251. }
  252. if(is_string($res['cc']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['cc']) {
  253. $scope = 'unlisted';
  254. }
  255. }
  256. if(config('costar.enabled') == true) {
  257. $blockedKeywords = config('costar.keyword.block');
  258. if($blockedKeywords !== null) {
  259. $keywords = config('costar.keyword.block');
  260. foreach($keywords as $kw) {
  261. if(Str::contains($res['content'], $kw) == true) {
  262. return;
  263. }
  264. }
  265. }
  266. $unlisted = config('costar.domain.unlisted');
  267. if(in_array(parse_url($url, PHP_URL_HOST), $unlisted) == true) {
  268. $unlisted = true;
  269. $scope = 'unlisted';
  270. } else {
  271. $unlisted = false;
  272. }
  273. $cwDomains = config('costar.domain.cw');
  274. if(in_array(parse_url($url, PHP_URL_HOST), $cwDomains) == true) {
  275. $cw = true;
  276. }
  277. }
  278. $id = isset($res['id']) ? $res['id'] : $url;
  279. $idDomain = parse_url($id, PHP_URL_HOST);
  280. $urlDomain = parse_url($url, PHP_URL_HOST);
  281. if(!self::validateUrl($id)) {
  282. return;
  283. }
  284. if(isset($activity['object']['attributedTo'])) {
  285. $actorDomain = parse_url($activity['object']['attributedTo'], PHP_URL_HOST);
  286. if(!self::validateUrl($activity['object']['attributedTo']) ||
  287. $idDomain !== $actorDomain ||
  288. $actorDomain !== $urlDomain
  289. )
  290. {
  291. return;
  292. }
  293. }
  294. if($idDomain !== $urlDomain) {
  295. return;
  296. }
  297. $profile = self::profileFirstOrNew($activity['object']['attributedTo']);
  298. if(isset($activity['object']['inReplyTo']) && !empty($activity['object']['inReplyTo']) || $replyTo == true) {
  299. $reply_to = self::statusFirstOrFetch($activity['object']['inReplyTo'], false);
  300. $reply_to = optional($reply_to)->id;
  301. } else {
  302. $reply_to = null;
  303. }
  304. $ts = is_array($res['published']) ? $res['published'][0] : $res['published'];
  305. if($scope == 'public' && in_array($urlDomain, InstanceService::getUnlistedDomains())) {
  306. $scope = 'unlisted';
  307. }
  308. if(in_array($urlDomain, InstanceService::getNsfwDomains())) {
  309. $cw = true;
  310. }
  311. $statusLockKey = 'helpers:status-lock:' . hash('sha256', $res['id']);
  312. $status = Cache::lock($statusLockKey)
  313. ->get(function () use(
  314. $profile,
  315. $res,
  316. $url,
  317. $ts,
  318. $reply_to,
  319. $cw,
  320. $scope,
  321. $id
  322. ) {
  323. if($res['type'] === 'Question') {
  324. $status = self::storePoll(
  325. $profile,
  326. $res,
  327. $url,
  328. $ts,
  329. $reply_to,
  330. $cw,
  331. $scope,
  332. $id
  333. );
  334. return $status;
  335. }
  336. return DB::transaction(function() use($profile, $res, $url, $ts, $reply_to, $cw, $scope, $id) {
  337. $status = new Status;
  338. $status->profile_id = $profile->id;
  339. $status->url = isset($res['url']) ? $res['url'] : $url;
  340. $status->uri = isset($res['url']) ? $res['url'] : $url;
  341. $status->object_url = $id;
  342. $status->caption = strip_tags($res['content']);
  343. $status->rendered = Purify::clean($res['content']);
  344. $status->created_at = Carbon::parse($ts);
  345. $status->in_reply_to_id = $reply_to;
  346. $status->local = false;
  347. $status->is_nsfw = $cw;
  348. $status->scope = $scope;
  349. $status->visibility = $scope;
  350. $status->cw_summary = $cw == true && isset($res['summary']) ?
  351. Purify::clean(strip_tags($res['summary'])) : null;
  352. $status->save();
  353. if($reply_to == null) {
  354. self::importNoteAttachment($res, $status);
  355. } else {
  356. StatusReplyPipeline::dispatch($status);
  357. }
  358. return $status;
  359. });
  360. });
  361. return $status;
  362. }
  363. private static function storePoll($profile, $res, $url, $ts, $reply_to, $cw, $scope, $id)
  364. {
  365. if(!isset($res['endTime']) || !isset($res['oneOf']) || !is_array($res['oneOf']) || count($res['oneOf']) > 4) {
  366. return;
  367. }
  368. $options = collect($res['oneOf'])->map(function($option) {
  369. return $option['name'];
  370. })->toArray();
  371. $cachedTallies = collect($res['oneOf'])->map(function($option) {
  372. return $option['replies']['totalItems'] ?? 0;
  373. })->toArray();
  374. $status = new Status;
  375. $status->profile_id = $profile->id;
  376. $status->url = isset($res['url']) ? $res['url'] : $url;
  377. $status->uri = isset($res['url']) ? $res['url'] : $url;
  378. $status->object_url = $id;
  379. $status->caption = strip_tags($res['content']);
  380. $status->rendered = Purify::clean($res['content']);
  381. $status->created_at = Carbon::parse($ts);
  382. $status->in_reply_to_id = null;
  383. $status->local = false;
  384. $status->is_nsfw = $cw;
  385. $status->scope = 'draft';
  386. $status->visibility = 'draft';
  387. $status->cw_summary = $cw == true && isset($res['summary']) ?
  388. Purify::clean(strip_tags($res['summary'])) : null;
  389. $status->save();
  390. $poll = new Poll;
  391. $poll->status_id = $status->id;
  392. $poll->profile_id = $status->profile_id;
  393. $poll->poll_options = $options;
  394. $poll->cached_tallies = $cachedTallies;
  395. $poll->votes_count = array_sum($cachedTallies);
  396. $poll->expires_at = now()->parse($res['endTime']);
  397. $poll->last_fetched_at = now();
  398. $poll->save();
  399. $status->type = 'poll';
  400. $status->scope = $scope;
  401. $status->visibility = $scope;
  402. $status->save();
  403. return $status;
  404. }
  405. public static function statusFetch($url)
  406. {
  407. return self::statusFirstOrFetch($url);
  408. }
  409. public static function importNoteAttachment($data, Status $status)
  410. {
  411. if(self::verifyAttachments($data) == false) {
  412. $status->viewType();
  413. return;
  414. }
  415. $attachments = isset($data['object']) ? $data['object']['attachment'] : $data['attachment'];
  416. $user = $status->profile;
  417. $storagePath = MediaPathService::get($user, 2);
  418. $allowed = explode(',', config_cache('pixelfed.media_types'));
  419. foreach($attachments as $media) {
  420. $type = $media['mediaType'];
  421. $url = $media['url'];
  422. $blurhash = isset($media['blurhash']) ? $media['blurhash'] : null;
  423. $license = isset($media['license']) ? License::nameToId($media['license']) : null;
  424. $valid = self::validateUrl($url);
  425. if(in_array($type, $allowed) == false || $valid == false) {
  426. continue;
  427. }
  428. $media = new Media();
  429. $media->blurhash = $blurhash;
  430. $media->remote_media = true;
  431. $media->status_id = $status->id;
  432. $media->profile_id = $status->profile_id;
  433. $media->user_id = null;
  434. $media->media_path = $url;
  435. $media->remote_url = $url;
  436. if($license) {
  437. $media->license = $license;
  438. }
  439. $media->mime = $type;
  440. $media->version = 3;
  441. $media->save();
  442. if(config_cache('pixelfed.cloud_storage') == true) {
  443. MediaStoragePipeline::dispatch($media);
  444. }
  445. }
  446. $status->viewType();
  447. return;
  448. }
  449. public static function profileFirstOrNew($url, $runJobs = false)
  450. {
  451. $url = self::validateUrl($url);
  452. if($url == false || strlen($url) > 190) {
  453. return;
  454. }
  455. $hash = base64_encode($url);
  456. $key = 'ap:profile:by_url:' . $hash;
  457. $ttl = now()->addMinutes(5);
  458. $profile = Cache::remember($key, $ttl, function() use($url, $runJobs) {
  459. $host = parse_url($url, PHP_URL_HOST);
  460. $local = config('pixelfed.domain.app') == $host ? true : false;
  461. if($local == true) {
  462. $id = last(explode('/', $url));
  463. return Profile::whereNull('status')
  464. ->whereNull('domain')
  465. ->whereUsername($id)
  466. ->firstOrFail();
  467. }
  468. $res = self::fetchProfileFromUrl($url);
  469. if(isset($res['id']) == false) {
  470. return;
  471. }
  472. $domain = parse_url($res['id'], PHP_URL_HOST);
  473. if(!isset($res['preferredUsername']) && !isset($res['nickname'])) {
  474. return;
  475. }
  476. $username = (string) Purify::clean($res['preferredUsername'] ?? $res['nickname']);
  477. if(empty($username)) {
  478. return;
  479. }
  480. $remoteUsername = $username;
  481. $webfinger = "@{$username}@{$domain}";
  482. abort_if(!self::validateUrl($res['inbox']), 400);
  483. abort_if(!self::validateUrl($res['id']), 400);
  484. $profile = Profile::whereRemoteUrl($res['id'])->first();
  485. if(!$profile) {
  486. $instance = Instance::firstOrCreate([
  487. 'domain' => $domain
  488. ]);
  489. if($instance->wasRecentlyCreated == true) {
  490. \App\Jobs\InstancePipeline\FetchNodeinfoPipeline::dispatch($instance)->onQueue('low');
  491. }
  492. $profileLockKey = 'helpers:profile-lock:' . hash('sha256', $res['id']);
  493. $profile = Cache::lock($profileLockKey)->get(function () use($domain, $webfinger, $res, $runJobs) {
  494. return DB::transaction(function() use($domain, $webfinger, $res, $runJobs) {
  495. $profile = new Profile();
  496. $profile->domain = strtolower($domain);
  497. $profile->username = Purify::clean($webfinger);
  498. $profile->name = isset($res['name']) ? Purify::clean($res['name']) : 'user';
  499. $profile->bio = isset($res['summary']) ? Purify::clean($res['summary']) : null;
  500. $profile->sharedInbox = isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null;
  501. $profile->inbox_url = $res['inbox'];
  502. $profile->outbox_url = $res['outbox'];
  503. $profile->remote_url = $res['id'];
  504. $profile->public_key = $res['publicKey']['publicKeyPem'];
  505. $profile->key_id = $res['publicKey']['id'];
  506. $profile->webfinger = Purify::clean($webfinger);
  507. $profile->last_fetched_at = now();
  508. $profile->save();
  509. if(config_cache('pixelfed.cloud_storage') == true) {
  510. RemoteAvatarFetch::dispatch($profile);
  511. }
  512. return $profile;
  513. });
  514. });
  515. } else {
  516. // Update info after 24 hours
  517. if($profile->last_fetched_at == null ||
  518. $profile->last_fetched_at->lt(now()->subHours(24)) == true
  519. ) {
  520. $profile->name = isset($res['name']) ? Purify::clean($res['name']) : 'user';
  521. $profile->bio = isset($res['summary']) ? Purify::clean($res['summary']) : null;
  522. $profile->last_fetched_at = now();
  523. $profile->sharedInbox = isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) && Helpers::validateUrl($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null;
  524. $profile->save();
  525. }
  526. if(config_cache('pixelfed.cloud_storage') == true) {
  527. RemoteAvatarFetch::dispatch($profile);
  528. }
  529. }
  530. return $profile;
  531. });
  532. return $profile;
  533. }
  534. public static function profileFetch($url)
  535. {
  536. return self::profileFirstOrNew($url);
  537. }
  538. public static function sendSignedObject($profile, $url, $body)
  539. {
  540. ActivityPubDeliveryService::queue()
  541. ->from($profile)
  542. ->to($url)
  543. ->payload($body)
  544. ->send();
  545. }
  546. }