1
0

Helpers.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. <?php
  2. namespace App\Util\ActivityPub;
  3. use App\Instance;
  4. use App\Jobs\AvatarPipeline\RemoteAvatarFetch;
  5. use App\Jobs\HomeFeedPipeline\FeedInsertRemotePipeline;
  6. use App\Jobs\MediaPipeline\MediaStoragePipeline;
  7. use App\Jobs\StatusPipeline\StatusReplyPipeline;
  8. use App\Jobs\StatusPipeline\StatusTagsPipeline;
  9. use App\Media;
  10. use App\Models\ModeratedProfile;
  11. use App\Models\Poll;
  12. use App\Profile;
  13. use App\Services\Account\AccountStatService;
  14. use App\Services\ActivityPubDeliveryService;
  15. use App\Services\ActivityPubFetchService;
  16. use App\Services\DomainService;
  17. use App\Services\InstanceService;
  18. use App\Services\MediaPathService;
  19. use App\Services\NetworkTimelineService;
  20. use App\Services\UserFilterService;
  21. use App\Status;
  22. use App\Util\Media\License;
  23. use Cache;
  24. use Carbon\Carbon;
  25. use Illuminate\Validation\Rule;
  26. use League\Uri\Exceptions\UriException;
  27. use League\Uri\Uri;
  28. use Purify;
  29. use Validator;
  30. class Helpers
  31. {
  32. private const PUBLIC_TIMELINE = 'https://www.w3.org/ns/activitystreams#Public';
  33. private const CACHE_TTL = 14440;
  34. private const URL_CACHE_PREFIX = 'helpers:url:';
  35. private const FETCH_CACHE_TTL = 15;
  36. private const LOCALHOST_DOMAINS = [
  37. 'localhost',
  38. '127.0.0.1',
  39. '::1',
  40. 'broadcasthost',
  41. 'ip6-localhost',
  42. 'ip6-loopback',
  43. ];
  44. /**
  45. * Validate an ActivityPub object
  46. */
  47. public static function validateObject(array $data): bool
  48. {
  49. $verbs = ['Create', 'Announce', 'Like', 'Follow', 'Delete', 'Accept', 'Reject', 'Undo', 'Tombstone'];
  50. return Validator::make($data, [
  51. 'type' => ['required', 'string', Rule::in($verbs)],
  52. 'id' => 'required|string',
  53. 'actor' => 'required|string|url',
  54. 'object' => 'required',
  55. 'object.type' => 'required_if:type,Create',
  56. 'object.attributedTo' => 'required_if:type,Create|url',
  57. 'published' => 'required_if:type,Create|date',
  58. ])->passes();
  59. }
  60. /**
  61. * Validate media attachments
  62. */
  63. public static function verifyAttachments(array $data): bool
  64. {
  65. if (! isset($data['object']) || empty($data['object'])) {
  66. $data = ['object' => $data];
  67. }
  68. $activity = $data['object'];
  69. $mimeTypes = explode(',', config_cache('pixelfed.media_types'));
  70. $mediaTypes = in_array('video/mp4', $mimeTypes) ?
  71. ['Document', 'Image', 'Video'] :
  72. ['Document', 'Image'];
  73. if (! isset($activity['attachment']) || empty($activity['attachment'])) {
  74. return false;
  75. }
  76. return Validator::make($activity['attachment'], [
  77. '*.type' => ['required', 'string', Rule::in($mediaTypes)],
  78. '*.url' => 'required|url',
  79. '*.mediaType' => ['required', 'string', Rule::in($mimeTypes)],
  80. '*.name' => 'sometimes|nullable|string',
  81. '*.blurhash' => 'sometimes|nullable|string|min:6|max:164',
  82. '*.width' => 'sometimes|nullable|integer|min:1|max:5000',
  83. '*.height' => 'sometimes|nullable|integer|min:1|max:5000',
  84. ])->passes();
  85. }
  86. /**
  87. * Normalize ActivityPub audience
  88. */
  89. public static function normalizeAudience(array $data, bool $localOnly = true): ?array
  90. {
  91. if (! isset($data['to'])) {
  92. return null;
  93. }
  94. $audience = [
  95. 'to' => [],
  96. 'cc' => [],
  97. 'scope' => 'private',
  98. ];
  99. if (is_array($data['to']) && ! empty($data['to'])) {
  100. foreach ($data['to'] as $to) {
  101. if ($to == self::PUBLIC_TIMELINE) {
  102. $audience['scope'] = 'public';
  103. continue;
  104. }
  105. $url = $localOnly ? self::validateLocalUrl($to) : self::validateUrl($to);
  106. if ($url) {
  107. $audience['to'][] = $url;
  108. }
  109. }
  110. }
  111. if (is_array($data['cc']) && ! empty($data['cc'])) {
  112. foreach ($data['cc'] as $cc) {
  113. if ($cc == self::PUBLIC_TIMELINE) {
  114. $audience['scope'] = 'unlisted';
  115. continue;
  116. }
  117. $url = $localOnly ? self::validateLocalUrl($cc) : self::validateUrl($cc);
  118. if ($url) {
  119. $audience['cc'][] = $url;
  120. }
  121. }
  122. }
  123. return $audience;
  124. }
  125. /**
  126. * Check if user is in audience
  127. */
  128. public static function userInAudience(Profile $profile, array $data): bool
  129. {
  130. $audience = self::normalizeAudience($data);
  131. $url = $profile->permalink();
  132. return in_array($url, $audience['to']) || in_array($url, $audience['cc']);
  133. }
  134. /**
  135. * Validate URL with various security and format checks
  136. */
  137. public static function validateUrl(?string $url, bool $disableDNSCheck = false, bool $forceBanCheck = false): string|bool
  138. {
  139. if (! $normalizedUrl = self::normalizeUrl($url)) {
  140. return false;
  141. }
  142. try {
  143. $uri = Uri::new($normalizedUrl);
  144. if (! self::isValidUri($uri)) {
  145. return false;
  146. }
  147. $host = $uri->getHost();
  148. if (! self::isValidHost($host)) {
  149. return false;
  150. }
  151. if (!$disableDNSCheck && ! self::passesSecurityChecks($host, $disableDNSCheck, $forceBanCheck)) {
  152. return false;
  153. }
  154. return $uri->toString();
  155. } catch (UriException $e) {
  156. return false;
  157. }
  158. }
  159. /**
  160. * Normalize URL input
  161. */
  162. public static function normalizeUrl(?string $url): ?string
  163. {
  164. if (is_array($url) && ! empty($url)) {
  165. $url = $url[0];
  166. }
  167. return (! $url || strlen($url) === 0) ? null : $url;
  168. }
  169. /**
  170. * Validate basic URI requirements
  171. */
  172. public static function isValidUri(Uri $uri): bool
  173. {
  174. return $uri && $uri->getScheme() === 'https';
  175. }
  176. /**
  177. * Validate host requirements
  178. */
  179. public static function isValidHost(?string $host): bool
  180. {
  181. if (! $host || $host === '') {
  182. return false;
  183. }
  184. if (! filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
  185. return false;
  186. }
  187. if (! str_contains($host, '.')) {
  188. return false;
  189. }
  190. if (in_array($host, self::LOCALHOST_DOMAINS)) {
  191. return false;
  192. }
  193. return true;
  194. }
  195. /**
  196. * Check DNS and banned status if required
  197. */
  198. public static function passesSecurityChecks(string $host, bool $disableDNSCheck, bool $forceBanCheck): bool
  199. {
  200. if ($disableDNSCheck !== true && self::shouldCheckDNS()) {
  201. if (! self::hasValidDNS($host)) {
  202. return false;
  203. }
  204. }
  205. if ($forceBanCheck || self::shouldCheckBans()) {
  206. if (self::isHostBanned($host)) {
  207. return false;
  208. }
  209. }
  210. return true;
  211. }
  212. /**
  213. * Check if DNS validation is required
  214. */
  215. public static function shouldCheckDNS(): bool
  216. {
  217. return app()->environment() === 'production' &&
  218. (bool) config('security.url.verify_dns');
  219. }
  220. /**
  221. * Validate domain DNS records
  222. */
  223. public static function hasValidDNS(string $host): bool
  224. {
  225. $hash = hash('sha256', $host);
  226. $key = self::URL_CACHE_PREFIX."valid-dns:sha256-{$hash}";
  227. return Cache::remember($key, self::CACHE_TTL, function () use ($host) {
  228. return DomainService::hasValidDns($host);
  229. });
  230. }
  231. /**
  232. * Check if domain bans should be validated
  233. */
  234. public static function shouldCheckBans(): bool
  235. {
  236. return app()->environment() === 'production';
  237. }
  238. /**
  239. * Check if host is in banned domains list
  240. */
  241. public static function isHostBanned(string $host): bool
  242. {
  243. $bannedInstances = InstanceService::getBannedDomains();
  244. return in_array($host, $bannedInstances);
  245. }
  246. /**
  247. * Validate local URL
  248. */
  249. public static function validateLocalUrl(string $url): string|bool
  250. {
  251. $url = self::validateUrl($url);
  252. if ($url) {
  253. $domain = config('pixelfed.domain.app');
  254. $uri = Uri::new($url);
  255. $host = $uri->getHost();
  256. if (! $host || empty($host)) {
  257. return false;
  258. }
  259. return strtolower($domain) === strtolower($host) ? $url : false;
  260. }
  261. return false;
  262. }
  263. /**
  264. * Get user agent string
  265. */
  266. public static function zttpUserAgent(): array
  267. {
  268. $version = config('pixelfed.version');
  269. $url = config('app.url');
  270. return [
  271. 'Accept' => 'application/activity+json',
  272. 'User-Agent' => "(Pixelfed/{$version}; +{$url})",
  273. ];
  274. }
  275. public static function fetchFromUrl($url = false)
  276. {
  277. if (self::validateUrl($url) == false) {
  278. return;
  279. }
  280. $hash = hash('sha256', $url);
  281. $key = "helpers:url:fetcher:sha256-{$hash}";
  282. $ttl = now()->addMinutes(15);
  283. return Cache::remember($key, $ttl, function () use ($url) {
  284. $res = ActivityPubFetchService::get($url);
  285. if (! $res || empty($res)) {
  286. return false;
  287. }
  288. $res = json_decode($res, true, 8);
  289. if (json_last_error() == JSON_ERROR_NONE) {
  290. return $res;
  291. } else {
  292. return false;
  293. }
  294. });
  295. }
  296. public static function fetchProfileFromUrl($url)
  297. {
  298. return self::fetchFromUrl($url);
  299. }
  300. public static function pluckval($val)
  301. {
  302. if (is_string($val)) {
  303. return $val;
  304. }
  305. if (is_array($val)) {
  306. return ! empty($val) ? head($val) : null;
  307. }
  308. return null;
  309. }
  310. public static function validateTimestamp($timestamp)
  311. {
  312. try {
  313. $date = Carbon::parse($timestamp);
  314. $now = Carbon::now();
  315. $tenYearsAgo = $now->copy()->subYears(20);
  316. $isMoreThanTenYearsOld = $date->lt($tenYearsAgo);
  317. $tomorrow = $now->copy()->addDay();
  318. $isMoreThanOneDayFuture = $date->gt($tomorrow);
  319. return ! ($isMoreThanTenYearsOld || $isMoreThanOneDayFuture);
  320. } catch (\Exception $e) {
  321. return false;
  322. }
  323. }
  324. /**
  325. * Fetch or create a status from URL
  326. */
  327. public static function statusFirstOrFetch(string $url, bool $replyTo = false): ?Status
  328. {
  329. if (! $validUrl = self::validateUrl($url)) {
  330. return null;
  331. }
  332. if ($status = self::findExistingStatus($url)) {
  333. return $status;
  334. }
  335. return self::createStatusFromUrl($url, $replyTo);
  336. }
  337. /**
  338. * Find existing status by URL
  339. */
  340. public static function findExistingStatus(string $url): ?Status
  341. {
  342. $host = parse_url($url, PHP_URL_HOST);
  343. if (self::isLocalDomain($host)) {
  344. $id = (int) last(explode('/', $url));
  345. return Status::whereNotIn('scope', ['draft', 'archived'])
  346. ->findOrFail($id);
  347. }
  348. return Status::whereNotIn('scope', ['draft', 'archived'])
  349. ->where(function ($query) use ($url) {
  350. $query->whereUri($url)
  351. ->orWhere('object_url', $url);
  352. })
  353. ->first();
  354. }
  355. /**
  356. * Create a new status from ActivityPub data
  357. */
  358. public static function createStatusFromUrl(string $url, bool $replyTo): ?Status
  359. {
  360. $res = self::fetchFromUrl($url);
  361. if (! $res || ! self::isValidStatusData($res)) {
  362. return null;
  363. }
  364. if (! self::validateTimestamp($res['published'])) {
  365. return null;
  366. }
  367. if (! self::passesContentFilters($res)) {
  368. return null;
  369. }
  370. $activity = isset($res['object']) ? $res : ['object' => $res];
  371. if (! $profile = self::getStatusProfile($activity)) {
  372. return null;
  373. }
  374. if (! self::validateStatusUrls($url, $activity)) {
  375. return null;
  376. }
  377. $reply_to = self::getReplyToId($activity, $profile, $replyTo);
  378. $scope = self::getScope($activity, $url);
  379. $cw = self::getSensitive($activity, $url);
  380. if ($res['type'] === 'Question') {
  381. return self::storePoll(
  382. $profile,
  383. $res,
  384. $url,
  385. $res['published'],
  386. $reply_to,
  387. $cw,
  388. $scope,
  389. $activity['id'] ?? $url
  390. );
  391. }
  392. return self::storeStatus($url, $profile, $res);
  393. }
  394. /**
  395. * Validate status data
  396. */
  397. public static function isValidStatusData(?array $res): bool
  398. {
  399. return $res &&
  400. ! empty($res) &&
  401. ! isset($res['error']) &&
  402. isset($res['@context']) &&
  403. isset($res['published']);
  404. }
  405. /**
  406. * Check if content passes filters
  407. */
  408. public static function passesContentFilters(array $res): bool
  409. {
  410. if (! config('autospam.live_filters.enabled')) {
  411. return true;
  412. }
  413. $filters = config('autospam.live_filters.filters');
  414. if (empty($filters) || ! isset($res['content']) || strlen($filters) <= 3) {
  415. return true;
  416. }
  417. $filters = array_map('trim', explode(',', $filters));
  418. $content = strtolower($res['content']);
  419. foreach ($filters as $filter) {
  420. $filter = trim(strtolower($filter));
  421. if ($filter && str_contains($content, $filter)) {
  422. return false;
  423. }
  424. }
  425. return true;
  426. }
  427. /**
  428. * Get profile for status
  429. */
  430. public static function getStatusProfile(array $activity): ?Profile
  431. {
  432. if (! isset($activity['object']['attributedTo'])) {
  433. return null;
  434. }
  435. $attributedTo = self::extractAttributedTo($activity['object']['attributedTo']);
  436. return $attributedTo ? self::profileFirstOrNew($attributedTo) : null;
  437. }
  438. /**
  439. * Extract attributed to value
  440. */
  441. public static function extractAttributedTo(string|array $attributedTo): ?string
  442. {
  443. if (is_string($attributedTo)) {
  444. return $attributedTo;
  445. }
  446. if (is_array($attributedTo)) {
  447. return collect($attributedTo)
  448. ->filter(fn ($o) => $o && isset($o['type']) && $o['type'] == 'Person')
  449. ->pluck('id')
  450. ->first();
  451. }
  452. return null;
  453. }
  454. /**
  455. * Validate status URLs match
  456. */
  457. public static function validateStatusUrls(string $url, array $activity): bool
  458. {
  459. $id = isset($activity['id']) ?
  460. self::pluckval($activity['id']) :
  461. self::pluckval($url);
  462. $idDomain = parse_url($id, PHP_URL_HOST);
  463. $urlDomain = parse_url($url, PHP_URL_HOST);
  464. return $idDomain && $urlDomain;
  465. }
  466. /**
  467. * Get reply-to status ID
  468. */
  469. public static function getReplyToId(array $activity, Profile $profile, bool $replyTo): ?int
  470. {
  471. $inReplyTo = $activity['object']['inReplyTo'] ?? null;
  472. if (! $inReplyTo && ! $replyTo) {
  473. return null;
  474. }
  475. $reply = self::statusFirstOrFetch(self::pluckval($inReplyTo), false);
  476. if (! $reply) {
  477. return null;
  478. }
  479. $blocks = UserFilterService::blocks($reply->profile_id);
  480. return in_array($profile->id, $blocks) ? null : $reply->id;
  481. }
  482. /**
  483. * Store a new regular status
  484. */
  485. public static function storeStatus(string $url, Profile $profile, array $activity): Status
  486. {
  487. $id = self::getStatusId($activity, $url);
  488. $url = self::getStatusUrl($activity, $id);
  489. if ((! isset($activity['type']) ||
  490. in_array($activity['type'], ['Create', 'Note'])) &&
  491. ! self::validateStatusDomains($id, $url)) {
  492. throw new \Exception('Invalid status domains');
  493. }
  494. $reply_to = self::getReplyTo($activity);
  495. $ts = self::pluckval($activity['published']);
  496. $scope = self::getScope($activity, $url);
  497. $commentsDisabled = isset($activity['commentsEnabled']) ? (bool) $activity['commentsEnabled'] == false : false;
  498. $cw = self::getSensitive($activity, $url);
  499. if ($profile->unlisted) {
  500. $scope = 'unlisted';
  501. }
  502. $status = self::createOrUpdateStatus($url, $profile, $id, $activity, $ts, $reply_to, $cw, $scope, $commentsDisabled);
  503. if ($reply_to === null) {
  504. self::importNoteAttachment($activity, $status);
  505. } else {
  506. if (isset($activity['attachment']) && ! empty($activity['attachment'])) {
  507. self::importNoteAttachment($activity, $status);
  508. }
  509. StatusReplyPipeline::dispatch($status);
  510. }
  511. if (isset($activity['tag']) && is_array($activity['tag']) && ! empty($activity['tag'])) {
  512. StatusTagsPipeline::dispatch($activity, $status);
  513. }
  514. self::handleStatusPostProcessing($status, $profile->id, $url);
  515. return $status;
  516. }
  517. /**
  518. * Get status ID from activity
  519. */
  520. public static function getStatusId(array $activity, string $url): string
  521. {
  522. return isset($activity['id']) ?
  523. self::pluckval($activity['id']) :
  524. self::pluckval($url);
  525. }
  526. /**
  527. * Get status URL from activity
  528. */
  529. public static function getStatusUrl(array $activity, string $id): string
  530. {
  531. return isset($activity['url']) && is_string($activity['url']) ?
  532. self::pluckval($activity['url']) :
  533. self::pluckval($id);
  534. }
  535. /**
  536. * Validate the status URL and ID are valid
  537. */
  538. public static function validateStatusDomains(string $id, string $url): bool
  539. {
  540. return self::validateUrl($id) && self::validateUrl($url);
  541. }
  542. /**
  543. * Create or update status record
  544. */
  545. public static function createOrUpdateStatus(
  546. string $url,
  547. Profile $profile,
  548. string $id,
  549. array $activity,
  550. string $ts,
  551. ?int $reply_to,
  552. bool $cw,
  553. string $scope,
  554. bool $commentsDisabled
  555. ): Status {
  556. $caption = isset($activity['content']) ?
  557. Purify::clean($activity['content']) :
  558. '';
  559. return Status::updateOrCreate(
  560. ['uri' => $url],
  561. [
  562. 'profile_id' => $profile->id,
  563. 'url' => $url,
  564. 'object_url' => $id,
  565. 'caption' => strip_tags($caption),
  566. 'rendered' => $caption,
  567. 'created_at' => Carbon::parse($ts)->tz('UTC'),
  568. 'in_reply_to_id' => $reply_to,
  569. 'local' => false,
  570. 'is_nsfw' => $cw,
  571. 'scope' => $scope,
  572. 'visibility' => $scope,
  573. 'cw_summary' => ($cw && isset($activity['summary'])) ?
  574. Purify::clean(strip_tags($activity['summary'])) :
  575. null,
  576. 'comments_disabled' => $commentsDisabled,
  577. ]
  578. );
  579. }
  580. /**
  581. * Handle post-creation status processing
  582. */
  583. public static function handleStatusPostProcessing(Status $status, int $profileId, string $url): void
  584. {
  585. if (config('instance.timeline.network.cached') &&
  586. self::isEligibleForNetwork($status)
  587. ) {
  588. $urlDomain = parse_url($url, PHP_URL_HOST);
  589. $filteredDomains = self::getFilteredDomains();
  590. if (! in_array($urlDomain, $filteredDomains)) {
  591. NetworkTimelineService::add($status->id);
  592. }
  593. }
  594. AccountStatService::incrementPostCount($profileId);
  595. if ($status->in_reply_to_id === null &&
  596. in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album'])
  597. ) {
  598. FeedInsertRemotePipeline::dispatch($status->id, $profileId)
  599. ->onQueue('feed');
  600. }
  601. }
  602. /**
  603. * Check if status is eligible for network timeline
  604. */
  605. public static function isEligibleForNetwork(Status $status): bool
  606. {
  607. return $status->in_reply_to_id === null &&
  608. $status->reblog_of_id === null &&
  609. in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']) &&
  610. $status->created_at->gt(now()->subHours(config('instance.timeline.network.max_hours_old'))) &&
  611. (config('instance.hide_nsfw_on_public_feeds') ? ! $status->is_nsfw : true);
  612. }
  613. /**
  614. * Get filtered domains list
  615. */
  616. public static function getFilteredDomains(): array
  617. {
  618. return collect(InstanceService::getBannedDomains())
  619. ->merge(InstanceService::getUnlistedDomains())
  620. ->unique()
  621. ->values()
  622. ->toArray();
  623. }
  624. public static function getSensitive($activity, $url)
  625. {
  626. if (! $url || ! strlen($url)) {
  627. return true;
  628. }
  629. $urlDomain = parse_url($url, PHP_URL_HOST);
  630. $cw = isset($activity['sensitive']) ? (bool) $activity['sensitive'] : false;
  631. if (in_array($urlDomain, InstanceService::getNsfwDomains())) {
  632. $cw = true;
  633. }
  634. return $cw;
  635. }
  636. public static function getReplyTo($activity)
  637. {
  638. $reply_to = null;
  639. $inReplyTo = isset($activity['inReplyTo']) && ! empty($activity['inReplyTo']) ?
  640. self::pluckval($activity['inReplyTo']) :
  641. false;
  642. if ($inReplyTo) {
  643. $reply_to = self::statusFirstOrFetch($inReplyTo);
  644. if ($reply_to) {
  645. $reply_to = optional($reply_to)->id;
  646. }
  647. } else {
  648. $reply_to = null;
  649. }
  650. return $reply_to;
  651. }
  652. public static function getScope($activity, $url)
  653. {
  654. $id = isset($activity['id']) ? self::pluckval($activity['id']) : self::pluckval($url);
  655. $url = isset($activity['url']) ? self::pluckval($activity['url']) : self::pluckval($id);
  656. $urlDomain = parse_url(self::pluckval($url), PHP_URL_HOST);
  657. $scope = 'private';
  658. if (isset($activity['to']) == true) {
  659. if (is_array($activity['to']) && in_array('https://www.w3.org/ns/activitystreams#Public', $activity['to'])) {
  660. $scope = 'public';
  661. }
  662. if (is_string($activity['to']) && $activity['to'] == 'https://www.w3.org/ns/activitystreams#Public') {
  663. $scope = 'public';
  664. }
  665. }
  666. if (isset($activity['cc']) == true) {
  667. if (is_array($activity['cc']) && in_array('https://www.w3.org/ns/activitystreams#Public', $activity['cc'])) {
  668. $scope = 'unlisted';
  669. }
  670. if (is_string($activity['cc']) && $activity['cc'] == 'https://www.w3.org/ns/activitystreams#Public') {
  671. $scope = 'unlisted';
  672. }
  673. }
  674. if ($scope == 'public' && in_array($urlDomain, InstanceService::getUnlistedDomains())) {
  675. $scope = 'unlisted';
  676. }
  677. return $scope;
  678. }
  679. public static function storePoll($profile, $res, $url, $ts, $reply_to, $cw, $scope, $id)
  680. {
  681. if (! isset($res['endTime']) || ! isset($res['oneOf']) || ! is_array($res['oneOf']) || count($res['oneOf']) > 4) {
  682. return;
  683. }
  684. $options = collect($res['oneOf'])->map(function ($option) {
  685. return $option['name'];
  686. })->toArray();
  687. $cachedTallies = collect($res['oneOf'])->map(function ($option) {
  688. return $option['replies']['totalItems'] ?? 0;
  689. })->toArray();
  690. $defaultCaption = '';
  691. $status = new Status;
  692. $status->profile_id = $profile->id;
  693. $status->url = isset($res['url']) ? $res['url'] : $url;
  694. $status->uri = isset($res['url']) ? $res['url'] : $url;
  695. $status->object_url = $id;
  696. $status->caption = strip_tags(Purify::clean($res['content'])) ?? $defaultCaption;
  697. $status->rendered = Purify::clean($res['content'] ?? $defaultCaption);
  698. $status->created_at = Carbon::parse($ts)->tz('UTC');
  699. $status->in_reply_to_id = null;
  700. $status->local = false;
  701. $status->is_nsfw = $cw;
  702. $status->scope = 'draft';
  703. $status->visibility = 'draft';
  704. $status->cw_summary = $cw == true && isset($res['summary']) ?
  705. Purify::clean(strip_tags($res['summary'])) : null;
  706. $status->save();
  707. $poll = new Poll;
  708. $poll->status_id = $status->id;
  709. $poll->profile_id = $status->profile_id;
  710. $poll->poll_options = $options;
  711. $poll->cached_tallies = $cachedTallies;
  712. $poll->votes_count = array_sum($cachedTallies);
  713. $poll->expires_at = now()->parse($res['endTime']);
  714. $poll->last_fetched_at = now();
  715. $poll->save();
  716. $status->type = 'poll';
  717. $status->scope = $scope;
  718. $status->visibility = $scope;
  719. $status->save();
  720. return $status;
  721. }
  722. public static function statusFetch($url)
  723. {
  724. return self::statusFirstOrFetch($url);
  725. }
  726. /**
  727. * Process and store note attachments
  728. */
  729. public static function importNoteAttachment(array $data, Status $status): void
  730. {
  731. if (! self::verifyAttachments($data)) {
  732. $status->viewType();
  733. return;
  734. }
  735. $attachments = self::getAttachments($data);
  736. $profile = $status->profile;
  737. $storagePath = MediaPathService::get($profile, 2);
  738. $allowedTypes = explode(',', config_cache('pixelfed.media_types'));
  739. foreach ($attachments as $key => $media) {
  740. if (! self::isValidAttachment($media, $allowedTypes)) {
  741. continue;
  742. }
  743. $mediaModel = self::createMediaAttachment($media, $status, $key);
  744. self::handleMediaStorage($mediaModel);
  745. }
  746. $status->viewType();
  747. }
  748. /**
  749. * Get attachments from ActivityPub data
  750. */
  751. public static function getAttachments(array $data): array
  752. {
  753. return isset($data['object']) ?
  754. $data['object']['attachment'] :
  755. $data['attachment'];
  756. }
  757. /**
  758. * Validate individual attachment
  759. */
  760. public static function isValidAttachment(array $media, array $allowedTypes): bool
  761. {
  762. $type = $media['mediaType'];
  763. $url = $media['url'];
  764. return in_array($type, $allowedTypes) &&
  765. self::validateUrl($url);
  766. }
  767. /**
  768. * Create media attachment record
  769. */
  770. public static function createMediaAttachment(array $media, Status $status, int $key): Media
  771. {
  772. $mediaModel = new Media;
  773. self::setBasicMediaAttributes($mediaModel, $media, $status, $key);
  774. self::setOptionalMediaAttributes($mediaModel, $media);
  775. $mediaModel->save();
  776. return $mediaModel;
  777. }
  778. /**
  779. * Set basic media attributes
  780. */
  781. public static function setBasicMediaAttributes(Media $media, array $data, Status $status, int $key): void
  782. {
  783. $media->remote_media = true;
  784. $media->status_id = $status->id;
  785. $media->profile_id = $status->profile_id;
  786. $media->user_id = null;
  787. $media->media_path = $data['url'];
  788. $media->remote_url = $data['url'];
  789. $media->mime = $data['mediaType'];
  790. $media->version = 3;
  791. $media->order = $key + 1;
  792. }
  793. /**
  794. * Set optional media attributes
  795. */
  796. public static function setOptionalMediaAttributes(Media $media, array $data): void
  797. {
  798. $media->blurhash = $data['blurhash'] ?? null;
  799. $media->caption = isset($data['name']) ?
  800. Purify::clean($data['name']) :
  801. null;
  802. if (isset($data['width'])) {
  803. $media->width = $data['width'];
  804. }
  805. if (isset($data['height'])) {
  806. $media->height = $data['height'];
  807. }
  808. if (isset($data['license'])) {
  809. $media->license = License::nameToId($data['license']);
  810. }
  811. }
  812. /**
  813. * Handle media storage processing
  814. */
  815. public static function handleMediaStorage(Media $media): void
  816. {
  817. if ((bool) config_cache('pixelfed.cloud_storage')) {
  818. MediaStoragePipeline::dispatch($media);
  819. }
  820. }
  821. /**
  822. * Validate attachment collection
  823. */
  824. public static function validateAttachmentCollection(array $attachments, array $mediaTypes, array $mimeTypes): bool
  825. {
  826. return Validator::make($attachments, [
  827. '*.type' => [
  828. 'required',
  829. 'string',
  830. Rule::in($mediaTypes),
  831. ],
  832. '*.url' => 'required|url',
  833. '*.mediaType' => [
  834. 'required',
  835. 'string',
  836. Rule::in($mimeTypes),
  837. ],
  838. '*.name' => 'sometimes|nullable|string',
  839. '*.blurhash' => 'sometimes|nullable|string|min:6|max:164',
  840. '*.width' => 'sometimes|nullable|integer|min:1|max:5000',
  841. '*.height' => 'sometimes|nullable|integer|min:1|max:5000',
  842. ])->passes();
  843. }
  844. /**
  845. * Get supported media types
  846. */
  847. public static function getSupportedMediaTypes(): array
  848. {
  849. $mimeTypes = explode(',', config_cache('pixelfed.media_types'));
  850. return in_array('video/mp4', $mimeTypes) ?
  851. ['Document', 'Image', 'Video'] :
  852. ['Document', 'Image'];
  853. }
  854. /**
  855. * Process specific media type attachment
  856. */
  857. public static function processMediaTypeAttachment(array $media, Status $status, int $order): ?Media
  858. {
  859. if (! self::isValidMediaType($media)) {
  860. return null;
  861. }
  862. $mediaModel = new Media;
  863. self::setMediaAttributes($mediaModel, $media, $status, $order);
  864. $mediaModel->save();
  865. return $mediaModel;
  866. }
  867. /**
  868. * Validate media type
  869. */
  870. public static function isValidMediaType(array $media): bool
  871. {
  872. $requiredFields = ['mediaType', 'url'];
  873. foreach ($requiredFields as $field) {
  874. if (! isset($media[$field]) || empty($media[$field])) {
  875. return false;
  876. }
  877. }
  878. return true;
  879. }
  880. /**
  881. * Set media attributes
  882. */
  883. public static function setMediaAttributes(Media $media, array $data, Status $status, int $order): void
  884. {
  885. $media->remote_media = true;
  886. $media->status_id = $status->id;
  887. $media->profile_id = $status->profile_id;
  888. $media->user_id = null;
  889. $media->media_path = $data['url'];
  890. $media->remote_url = $data['url'];
  891. $media->mime = $data['mediaType'];
  892. $media->version = 3;
  893. $media->order = $order;
  894. // Optional attributes
  895. if (isset($data['blurhash'])) {
  896. $media->blurhash = $data['blurhash'];
  897. }
  898. if (isset($data['name'])) {
  899. $media->caption = Purify::clean($data['name']);
  900. }
  901. if (isset($data['width'])) {
  902. $media->width = $data['width'];
  903. }
  904. if (isset($data['height'])) {
  905. $media->height = $data['height'];
  906. }
  907. if (isset($data['license'])) {
  908. $media->license = License::nameToId($data['license']);
  909. }
  910. }
  911. /**
  912. * Fetch or create a profile from a URL
  913. */
  914. public static function profileFirstOrNew(string $url): ?Profile
  915. {
  916. if (! $validatedUrl = self::validateUrl($url)) {
  917. return null;
  918. }
  919. $host = parse_url($validatedUrl, PHP_URL_HOST);
  920. if (self::isLocalDomain($host)) {
  921. return self::getLocalProfile($validatedUrl);
  922. }
  923. return self::getOrFetchRemoteProfile($validatedUrl);
  924. }
  925. /**
  926. * Check if domain is local
  927. */
  928. public static function isLocalDomain(string $host): bool
  929. {
  930. return config('pixelfed.domain.app') == $host;
  931. }
  932. /**
  933. * Get local profile from URL
  934. */
  935. public static function getLocalProfile(string $url): ?Profile
  936. {
  937. $username = last(explode('/', $url));
  938. return Profile::whereNull('status')
  939. ->whereNull('domain')
  940. ->whereUsername($username)
  941. ->firstOrFail();
  942. }
  943. /**
  944. * Get existing or fetch new remote profile
  945. */
  946. public static function getOrFetchRemoteProfile(string $url): ?Profile
  947. {
  948. $profile = Profile::whereRemoteUrl($url)->first();
  949. if ($profile && ! self::needsFetch($profile)) {
  950. return $profile;
  951. }
  952. return self::profileUpdateOrCreate($url);
  953. }
  954. /**
  955. * Check if profile needs to be fetched
  956. */
  957. public static function needsFetch(?Profile $profile): bool
  958. {
  959. return ! $profile?->last_fetched_at ||
  960. $profile->last_fetched_at->lt(now()->subHours(24));
  961. }
  962. /**
  963. * Update or create a profile from ActivityPub data
  964. */
  965. public static function profileUpdateOrCreate(string $url, bool $movedToCheck = false): ?Profile
  966. {
  967. $res = self::fetchProfileFromUrl($url);
  968. if (! $res || ! self::isValidProfileData($res, $url)) {
  969. return null;
  970. }
  971. $domain = parse_url($res['id'], PHP_URL_HOST);
  972. $username = self::extractUsername($res);
  973. if (! $username || self::isProfileBanned($res['id'])) {
  974. return null;
  975. }
  976. $webfinger = "@{$username}@{$domain}";
  977. $instance = self::getOrCreateInstance($domain);
  978. $movedToPid = $movedToCheck ? null : self::handleMovedTo($res);
  979. $profile = Profile::updateOrCreate(
  980. [
  981. 'domain' => strtolower($domain),
  982. 'username' => Purify::clean($webfinger),
  983. ],
  984. self::buildProfileData($res, $webfinger, $movedToPid)
  985. );
  986. self::handleProfileAvatar($profile);
  987. return $profile;
  988. }
  989. /**
  990. * Validate profile data from ActivityPub
  991. */
  992. public static function isValidProfileData(?array $res, string $url): bool
  993. {
  994. if (! $res || ! isset($res['id']) || ! isset($res['inbox'])) {
  995. return false;
  996. }
  997. if (! self::validateUrl($res['inbox']) || ! self::validateUrl($res['id'])) {
  998. return false;
  999. }
  1000. $urlDomain = parse_url($url, PHP_URL_HOST);
  1001. $domain = parse_url($res['id'], PHP_URL_HOST);
  1002. return strtolower($urlDomain) === strtolower($domain);
  1003. }
  1004. /**
  1005. * Extract username from profile data
  1006. */
  1007. public static function extractUsername(array $res): ?string
  1008. {
  1009. $username = $res['preferredUsername'] ?? $res['nickname'] ?? null;
  1010. if (! $username || ! ctype_alnum(str_replace(['_', '.', '-'], '', $username))) {
  1011. return null;
  1012. }
  1013. return Purify::clean($username);
  1014. }
  1015. /**
  1016. * Check if profile is banned
  1017. */
  1018. public static function isProfileBanned(string $profileUrl): bool
  1019. {
  1020. return ModeratedProfile::whereProfileUrl($profileUrl)
  1021. ->whereIsBanned(true)
  1022. ->exists();
  1023. }
  1024. /**
  1025. * Get or create federation instance
  1026. */
  1027. public static function getOrCreateInstance(string $domain): Instance
  1028. {
  1029. $instance = Instance::updateOrCreate(['domain' => $domain]);
  1030. if ($instance->wasRecentlyCreated) {
  1031. \App\Jobs\InstancePipeline\FetchNodeinfoPipeline::dispatch($instance)
  1032. ->onQueue('low');
  1033. }
  1034. return $instance;
  1035. }
  1036. /**
  1037. * Handle moved profile references
  1038. */
  1039. public static function handleMovedTo(array $res): ?int
  1040. {
  1041. if (! isset($res['movedTo']) || ! self::validateUrl($res['movedTo'])) {
  1042. return null;
  1043. }
  1044. $movedTo = self::profileUpdateOrCreate($res['movedTo'], true);
  1045. return $movedTo?->id;
  1046. }
  1047. /**
  1048. * Build profile data array for database
  1049. */
  1050. public static function buildProfileData(array $res, string $webfinger, ?int $movedToPid): array
  1051. {
  1052. return [
  1053. 'webfinger' => Purify::clean($webfinger),
  1054. 'key_id' => $res['publicKey']['id'],
  1055. 'remote_url' => $res['id'],
  1056. 'name' => isset($res['name']) ? Purify::clean($res['name']) : 'user',
  1057. 'bio' => isset($res['summary']) ? Purify::clean($res['summary']) : null,
  1058. 'sharedInbox' => $res['endpoints']['sharedInbox'] ?? null,
  1059. 'inbox_url' => $res['inbox'],
  1060. 'outbox_url' => $res['outbox'] ?? null,
  1061. 'public_key' => $res['publicKey']['publicKeyPem'],
  1062. 'indexable' => isset($res['indexable']) ? (bool) $res['indexable'] : false,
  1063. 'moved_to_profile_id' => $movedToPid,
  1064. 'is_private' => isset($res['manuallyApprovesFollowers']) ? (bool) $res['manuallyApprovesFollowers'] : true,
  1065. ];
  1066. }
  1067. /**
  1068. * Handle profile avatar updates
  1069. */
  1070. public static function handleProfileAvatar(Profile $profile): void
  1071. {
  1072. if (! $profile->last_fetched_at ||
  1073. $profile->last_fetched_at->lt(now()->subMonths(3))
  1074. ) {
  1075. RemoteAvatarFetch::dispatch($profile);
  1076. }
  1077. $profile->last_fetched_at = now();
  1078. $profile->save();
  1079. }
  1080. public static function profileFetch($url): ?Profile
  1081. {
  1082. return self::profileFirstOrNew($url);
  1083. }
  1084. public static function getSignedFetch($url)
  1085. {
  1086. return ActivityPubFetchService::get($url);
  1087. }
  1088. public static function sendSignedObject($profile, $url, $body)
  1089. {
  1090. if (app()->environment() !== 'production') {
  1091. return;
  1092. }
  1093. ActivityPubDeliveryService::queue()
  1094. ->from($profile)
  1095. ->to($url)
  1096. ->payload($body)
  1097. ->send();
  1098. }
  1099. }