Helpers.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  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\Jobs\StatusPipeline\StatusTagsPipeline;
  25. use App\Util\ActivityPub\HttpSignature;
  26. use Illuminate\Support\Str;
  27. use App\Services\ActivityPubFetchService;
  28. use App\Services\ActivityPubDeliveryService;
  29. use App\Services\CustomEmojiService;
  30. use App\Services\InstanceService;
  31. use App\Services\MediaPathService;
  32. use App\Services\MediaStorageService;
  33. use App\Services\NetworkTimelineService;
  34. use App\Jobs\MediaPipeline\MediaStoragePipeline;
  35. use App\Jobs\AvatarPipeline\RemoteAvatarFetch;
  36. use App\Util\Media\License;
  37. use App\Models\Poll;
  38. use Illuminate\Contracts\Cache\LockTimeoutException;
  39. use App\Jobs\ProfilePipeline\IncrementPostCount;
  40. use App\Jobs\ProfilePipeline\DecrementPostCount;
  41. use App\Services\DomainService;
  42. use App\Services\UserFilterService;
  43. class Helpers {
  44. public static function validateObject($data)
  45. {
  46. $verbs = ['Create', 'Announce', 'Like', 'Follow', 'Delete', 'Accept', 'Reject', 'Undo', 'Tombstone'];
  47. $valid = Validator::make($data, [
  48. 'type' => [
  49. 'required',
  50. 'string',
  51. Rule::in($verbs)
  52. ],
  53. 'id' => 'required|string',
  54. 'actor' => 'required|string|url',
  55. 'object' => 'required',
  56. 'object.type' => 'required_if:type,Create',
  57. 'object.attributedTo' => 'required_if:type,Create|url',
  58. 'published' => 'required_if:type,Create|date'
  59. ])->passes();
  60. return $valid;
  61. }
  62. public static function verifyAttachments($data)
  63. {
  64. if(!isset($data['object']) || empty($data['object'])) {
  65. $data = ['object'=>$data];
  66. }
  67. $activity = $data['object'];
  68. $mimeTypes = explode(',', config_cache('pixelfed.media_types'));
  69. $mediaTypes = in_array('video/mp4', $mimeTypes) ? ['Document', 'Image', 'Video'] : ['Document', 'Image'];
  70. // Peertube
  71. // $mediaTypes = in_array('video/mp4', $mimeTypes) ? ['Document', 'Image', 'Video', 'Link'] : ['Document', 'Image'];
  72. if(!isset($activity['attachment']) || empty($activity['attachment'])) {
  73. return false;
  74. }
  75. // peertube
  76. // $attachment = is_array($activity['url']) ?
  77. // collect($activity['url'])
  78. // ->filter(function($media) {
  79. // return $media['type'] == 'Link' && $media['mediaType'] == 'video/mp4';
  80. // })
  81. // ->take(1)
  82. // ->values()
  83. // ->toArray()[0] : $activity['attachment'];
  84. $attachment = $activity['attachment'];
  85. $valid = Validator::make($attachment, [
  86. '*.type' => [
  87. 'required',
  88. 'string',
  89. Rule::in($mediaTypes)
  90. ],
  91. '*.url' => 'required|url',
  92. '*.mediaType' => [
  93. 'required',
  94. 'string',
  95. Rule::in($mimeTypes)
  96. ],
  97. '*.name' => 'sometimes|nullable|string',
  98. '*.blurhash' => 'sometimes|nullable|string|min:6|max:164',
  99. '*.width' => 'sometimes|nullable|integer|min:1|max:5000',
  100. '*.height' => 'sometimes|nullable|integer|min:1|max:5000',
  101. ])->passes();
  102. return $valid;
  103. }
  104. public static function normalizeAudience($data, $localOnly = true)
  105. {
  106. if(!isset($data['to'])) {
  107. return;
  108. }
  109. $audience = [];
  110. $audience['to'] = [];
  111. $audience['cc'] = [];
  112. $scope = 'private';
  113. if(is_array($data['to']) && !empty($data['to'])) {
  114. foreach ($data['to'] as $to) {
  115. if($to == 'https://www.w3.org/ns/activitystreams#Public') {
  116. $scope = 'public';
  117. continue;
  118. }
  119. $url = $localOnly ? self::validateLocalUrl($to) : self::validateUrl($to);
  120. if($url != false) {
  121. array_push($audience['to'], $url);
  122. }
  123. }
  124. }
  125. if(is_array($data['cc']) && !empty($data['cc'])) {
  126. foreach ($data['cc'] as $cc) {
  127. if($cc == 'https://www.w3.org/ns/activitystreams#Public') {
  128. $scope = 'unlisted';
  129. continue;
  130. }
  131. $url = $localOnly ? self::validateLocalUrl($cc) : self::validateUrl($cc);
  132. if($url != false) {
  133. array_push($audience['cc'], $url);
  134. }
  135. }
  136. }
  137. $audience['scope'] = $scope;
  138. return $audience;
  139. }
  140. public static function userInAudience($profile, $data)
  141. {
  142. $audience = self::normalizeAudience($data);
  143. $url = $profile->permalink();
  144. return in_array($url, $audience['to']) || in_array($url, $audience['cc']);
  145. }
  146. public static function validateUrl($url)
  147. {
  148. if(is_array($url)) {
  149. $url = $url[0];
  150. }
  151. $hash = hash('sha256', $url);
  152. $key = "helpers:url:valid:sha256-{$hash}";
  153. $valid = Cache::remember($key, 900, function() use($url) {
  154. $localhosts = [
  155. '127.0.0.1', 'localhost', '::1'
  156. ];
  157. if(strtolower(mb_substr($url, 0, 8)) !== 'https://') {
  158. return false;
  159. }
  160. if(substr_count($url, '://') !== 1) {
  161. return false;
  162. }
  163. if(mb_substr($url, 0, 8) !== 'https://') {
  164. $url = 'https://' . substr($url, 8);
  165. }
  166. $valid = filter_var($url, FILTER_VALIDATE_URL);
  167. if(!$valid) {
  168. return false;
  169. }
  170. $host = parse_url($valid, PHP_URL_HOST);
  171. if(in_array($host, $localhosts)) {
  172. return false;
  173. }
  174. if(config('security.url.verify_dns')) {
  175. if(DomainService::hasValidDns($host) === false) {
  176. return false;
  177. }
  178. }
  179. if(app()->environment() === 'production') {
  180. $bannedInstances = InstanceService::getBannedDomains();
  181. if(in_array($host, $bannedInstances)) {
  182. return false;
  183. }
  184. }
  185. return $url;
  186. });
  187. return $valid;
  188. }
  189. public static function validateLocalUrl($url)
  190. {
  191. $url = self::validateUrl($url);
  192. if($url == true) {
  193. $domain = config('pixelfed.domain.app');
  194. $host = parse_url($url, PHP_URL_HOST);
  195. $url = strtolower($domain) === strtolower($host) ? $url : false;
  196. return $url;
  197. }
  198. return false;
  199. }
  200. public static function zttpUserAgent()
  201. {
  202. $version = config('pixelfed.version');
  203. $url = config('app.url');
  204. return [
  205. 'Accept' => 'application/activity+json',
  206. 'User-Agent' => "(Pixelfed/{$version}; +{$url})",
  207. ];
  208. }
  209. public static function fetchFromUrl($url = false)
  210. {
  211. if(self::validateUrl($url) == false) {
  212. return;
  213. }
  214. $hash = hash('sha256', $url);
  215. $key = "helpers:url:fetcher:sha256-{$hash}";
  216. $ttl = now()->addMinutes(15);
  217. return Cache::remember($key, $ttl, function() use($url) {
  218. $res = ActivityPubFetchService::get($url);
  219. if(!$res || empty($res)) {
  220. return false;
  221. }
  222. $res = json_decode($res, true, 8);
  223. if(json_last_error() == JSON_ERROR_NONE) {
  224. return $res;
  225. } else {
  226. return false;
  227. }
  228. });
  229. }
  230. public static function fetchProfileFromUrl($url)
  231. {
  232. return self::fetchFromUrl($url);
  233. }
  234. public static function pluckval($val)
  235. {
  236. if(is_string($val)) {
  237. return $val;
  238. }
  239. if(is_array($val)) {
  240. return !empty($val) ? head($val) : null;
  241. }
  242. return null;
  243. }
  244. public static function statusFirstOrFetch($url, $replyTo = false)
  245. {
  246. $url = self::validateUrl($url);
  247. if($url == false) {
  248. return;
  249. }
  250. $host = parse_url($url, PHP_URL_HOST);
  251. $local = config('pixelfed.domain.app') == $host ? true : false;
  252. if($local) {
  253. $id = (int) last(explode('/', $url));
  254. return Status::whereNotIn('scope', ['draft','archived'])->findOrFail($id);
  255. }
  256. $cached = Status::whereNotIn('scope', ['draft','archived'])
  257. ->whereUri($url)
  258. ->orWhere('object_url', $url)
  259. ->first();
  260. if($cached) {
  261. return $cached;
  262. }
  263. $res = self::fetchFromUrl($url);
  264. if(!$res || empty($res) || isset($res['error']) || !isset($res['@context']) || !isset($res['published']) ) {
  265. return;
  266. }
  267. if(isset($res['object'])) {
  268. $activity = $res;
  269. } else {
  270. $activity = ['object' => $res];
  271. }
  272. $scope = 'private';
  273. $cw = isset($res['sensitive']) ? (bool) $res['sensitive'] : false;
  274. if(isset($res['to']) == true) {
  275. if(is_array($res['to']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['to'])) {
  276. $scope = 'public';
  277. }
  278. if(is_string($res['to']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['to']) {
  279. $scope = 'public';
  280. }
  281. }
  282. if(isset($res['cc']) == true) {
  283. if(is_array($res['cc']) && in_array('https://www.w3.org/ns/activitystreams#Public', $res['cc'])) {
  284. $scope = 'unlisted';
  285. }
  286. if(is_string($res['cc']) && 'https://www.w3.org/ns/activitystreams#Public' == $res['cc']) {
  287. $scope = 'unlisted';
  288. }
  289. }
  290. if(config('costar.enabled') == true) {
  291. $blockedKeywords = config('costar.keyword.block');
  292. if($blockedKeywords !== null) {
  293. $keywords = config('costar.keyword.block');
  294. foreach($keywords as $kw) {
  295. if(Str::contains($res['content'], $kw) == true) {
  296. return;
  297. }
  298. }
  299. }
  300. $unlisted = config('costar.domain.unlisted');
  301. if(in_array(parse_url($url, PHP_URL_HOST), $unlisted) == true) {
  302. $unlisted = true;
  303. $scope = 'unlisted';
  304. } else {
  305. $unlisted = false;
  306. }
  307. $cwDomains = config('costar.domain.cw');
  308. if(in_array(parse_url($url, PHP_URL_HOST), $cwDomains) == true) {
  309. $cw = true;
  310. }
  311. }
  312. $id = isset($res['id']) ? self::pluckval($res['id']) : self::pluckval($url);
  313. $idDomain = parse_url($id, PHP_URL_HOST);
  314. $urlDomain = parse_url($url, PHP_URL_HOST);
  315. if(!self::validateUrl($id)) {
  316. return;
  317. }
  318. if(!isset($activity['object']['attributedTo'])) {
  319. return;
  320. }
  321. $attributedTo = is_string($activity['object']['attributedTo']) ?
  322. $activity['object']['attributedTo'] :
  323. (is_array($activity['object']['attributedTo']) ?
  324. collect($activity['object']['attributedTo'])
  325. ->filter(function($o) {
  326. return $o && isset($o['type']) && $o['type'] == 'Person';
  327. })
  328. ->pluck('id')
  329. ->first() : null
  330. );
  331. if($attributedTo) {
  332. $actorDomain = parse_url($attributedTo, PHP_URL_HOST);
  333. if(!self::validateUrl($attributedTo) ||
  334. $idDomain !== $actorDomain ||
  335. $actorDomain !== $urlDomain
  336. )
  337. {
  338. return;
  339. }
  340. }
  341. if($idDomain !== $urlDomain) {
  342. return;
  343. }
  344. $profile = self::profileFirstOrNew($attributedTo);
  345. if(!$profile) {
  346. return;
  347. }
  348. if(isset($activity['object']['inReplyTo']) && !empty($activity['object']['inReplyTo']) || $replyTo == true) {
  349. $reply_to = self::statusFirstOrFetch(self::pluckval($activity['object']['inReplyTo']), false);
  350. if($reply_to) {
  351. $blocks = UserFilterService::blocks($reply_to->profile_id);
  352. if(in_array($profile->id, $blocks)) {
  353. return;
  354. }
  355. }
  356. $reply_to = optional($reply_to)->id;
  357. } else {
  358. $reply_to = null;
  359. }
  360. $ts = self::pluckval($res['published']);
  361. if($scope == 'public' && in_array($urlDomain, InstanceService::getUnlistedDomains())) {
  362. $scope = 'unlisted';
  363. }
  364. if(in_array($urlDomain, InstanceService::getNsfwDomains())) {
  365. $cw = true;
  366. }
  367. if($res['type'] === 'Question') {
  368. $status = self::storePoll(
  369. $profile,
  370. $res,
  371. $url,
  372. $ts,
  373. $reply_to,
  374. $cw,
  375. $scope,
  376. $id
  377. );
  378. return $status;
  379. } else {
  380. $status = self::storeStatus($url, $profile, $res);
  381. }
  382. return $status;
  383. }
  384. public static function storeStatus($url, $profile, $activity)
  385. {
  386. $id = isset($activity['id']) ? self::pluckval($activity['id']) : self::pluckval($activity['url']);
  387. $url = isset($activity['url']) && is_string($activity['url']) ? self::pluckval($activity['url']) : self::pluckval($id);
  388. $idDomain = parse_url($id, PHP_URL_HOST);
  389. $urlDomain = parse_url($url, PHP_URL_HOST);
  390. if(!self::validateUrl($id) || !self::validateUrl($url)) {
  391. return;
  392. }
  393. $reply_to = self::getReplyTo($activity);
  394. $ts = self::pluckval($activity['published']);
  395. $scope = self::getScope($activity, $url);
  396. $cw = self::getSensitive($activity, $url);
  397. $pid = is_object($profile) ? $profile->id : (is_array($profile) ? $profile['id'] : null);
  398. $isUnlisted = is_object($profile) ? $profile->unlisted : (is_array($profile) ? $profile['unlisted'] : false);
  399. $commentsDisabled = isset($activity['commentsEnabled']) ? !boolval($activity['commentsEnabled']) : false;
  400. if(!$pid) {
  401. return;
  402. }
  403. if($scope == 'public') {
  404. if($isUnlisted == true) {
  405. $scope = 'unlisted';
  406. }
  407. }
  408. $status = Status::updateOrCreate(
  409. [
  410. 'uri' => $url
  411. ], [
  412. 'profile_id' => $pid,
  413. 'url' => $url,
  414. 'object_url' => $id,
  415. 'caption' => isset($activity['content']) ? Purify::clean(strip_tags($activity['content'])) : null,
  416. 'rendered' => isset($activity['content']) ? Purify::clean($activity['content']) : null,
  417. 'created_at' => Carbon::parse($ts)->tz('UTC'),
  418. 'in_reply_to_id' => $reply_to,
  419. 'local' => false,
  420. 'is_nsfw' => $cw,
  421. 'scope' => $scope,
  422. 'visibility' => $scope,
  423. 'cw_summary' => ($cw == true && isset($activity['summary']) ?
  424. Purify::clean(strip_tags($activity['summary'])) : null),
  425. 'comments_disabled' => $commentsDisabled
  426. ]
  427. );
  428. if($reply_to == null) {
  429. self::importNoteAttachment($activity, $status);
  430. } else {
  431. if(isset($activity['attachment']) && !empty($activity['attachment'])) {
  432. self::importNoteAttachment($activity, $status);
  433. }
  434. StatusReplyPipeline::dispatch($status);
  435. }
  436. if(isset($activity['tag']) && is_array($activity['tag']) && !empty($activity['tag'])) {
  437. StatusTagsPipeline::dispatch($activity, $status);
  438. }
  439. if( config('instance.timeline.network.cached') &&
  440. $status->in_reply_to_id === null &&
  441. $status->reblog_of_id === null &&
  442. in_array($status->type, ['photo', 'photo:album', 'video', 'video:album', 'photo:video:album']) &&
  443. $status->created_at->gt(now()->subHours(config('instance.timeline.network.max_hours_old'))) &&
  444. (config('instance.hide_nsfw_on_public_feeds') == true ? $status->is_nsfw == false : true)
  445. ) {
  446. $filteredDomains = collect(InstanceService::getBannedDomains())
  447. ->merge(InstanceService::getUnlistedDomains())
  448. ->unique()
  449. ->values()
  450. ->toArray();
  451. if(!in_array($urlDomain, $filteredDomains)) {
  452. if(!$isUnlisted) {
  453. NetworkTimelineService::add($status->id);
  454. }
  455. }
  456. }
  457. IncrementPostCount::dispatch($pid)->onQueue('low');
  458. return $status;
  459. }
  460. public static function getSensitive($activity, $url)
  461. {
  462. $id = isset($activity['id']) ? self::pluckval($activity['id']) : self::pluckval($url);
  463. $url = isset($activity['url']) ? self::pluckval($activity['url']) : $id;
  464. $urlDomain = parse_url($url, PHP_URL_HOST);
  465. $cw = isset($activity['sensitive']) ? (bool) $activity['sensitive'] : false;
  466. if(in_array($urlDomain, InstanceService::getNsfwDomains())) {
  467. $cw = true;
  468. }
  469. return $cw;
  470. }
  471. public static function getReplyTo($activity)
  472. {
  473. $reply_to = null;
  474. $inReplyTo = isset($activity['inReplyTo']) && !empty($activity['inReplyTo']) ?
  475. self::pluckval($activity['inReplyTo']) :
  476. false;
  477. if($inReplyTo) {
  478. $reply_to = self::statusFirstOrFetch($inReplyTo);
  479. if($reply_to) {
  480. $reply_to = optional($reply_to)->id;
  481. }
  482. } else {
  483. $reply_to = null;
  484. }
  485. return $reply_to;
  486. }
  487. public static function getScope($activity, $url)
  488. {
  489. $id = isset($activity['id']) ? self::pluckval($activity['id']) : self::pluckval($url);
  490. $url = isset($activity['url']) ? self::pluckval($activity['url']) : self::pluckval($id);
  491. $urlDomain = parse_url(self::pluckval($url), PHP_URL_HOST);
  492. $scope = 'private';
  493. if(isset($activity['to']) == true) {
  494. if(is_array($activity['to']) && in_array('https://www.w3.org/ns/activitystreams#Public', $activity['to'])) {
  495. $scope = 'public';
  496. }
  497. if(is_string($activity['to']) && 'https://www.w3.org/ns/activitystreams#Public' == $activity['to']) {
  498. $scope = 'public';
  499. }
  500. }
  501. if(isset($activity['cc']) == true) {
  502. if(is_array($activity['cc']) && in_array('https://www.w3.org/ns/activitystreams#Public', $activity['cc'])) {
  503. $scope = 'unlisted';
  504. }
  505. if(is_string($activity['cc']) && 'https://www.w3.org/ns/activitystreams#Public' == $activity['cc']) {
  506. $scope = 'unlisted';
  507. }
  508. }
  509. if($scope == 'public' && in_array($urlDomain, InstanceService::getUnlistedDomains())) {
  510. $scope = 'unlisted';
  511. }
  512. return $scope;
  513. }
  514. private static function storePoll($profile, $res, $url, $ts, $reply_to, $cw, $scope, $id)
  515. {
  516. if(!isset($res['endTime']) || !isset($res['oneOf']) || !is_array($res['oneOf']) || count($res['oneOf']) > 4) {
  517. return;
  518. }
  519. $options = collect($res['oneOf'])->map(function($option) {
  520. return $option['name'];
  521. })->toArray();
  522. $cachedTallies = collect($res['oneOf'])->map(function($option) {
  523. return $option['replies']['totalItems'] ?? 0;
  524. })->toArray();
  525. $status = new Status;
  526. $status->profile_id = $profile->id;
  527. $status->url = isset($res['url']) ? $res['url'] : $url;
  528. $status->uri = isset($res['url']) ? $res['url'] : $url;
  529. $status->object_url = $id;
  530. $status->caption = strip_tags($res['content']);
  531. $status->rendered = Purify::clean($res['content']);
  532. $status->created_at = Carbon::parse($ts)->tz('UTC');
  533. $status->in_reply_to_id = null;
  534. $status->local = false;
  535. $status->is_nsfw = $cw;
  536. $status->scope = 'draft';
  537. $status->visibility = 'draft';
  538. $status->cw_summary = $cw == true && isset($res['summary']) ?
  539. Purify::clean(strip_tags($res['summary'])) : null;
  540. $status->save();
  541. $poll = new Poll;
  542. $poll->status_id = $status->id;
  543. $poll->profile_id = $status->profile_id;
  544. $poll->poll_options = $options;
  545. $poll->cached_tallies = $cachedTallies;
  546. $poll->votes_count = array_sum($cachedTallies);
  547. $poll->expires_at = now()->parse($res['endTime']);
  548. $poll->last_fetched_at = now();
  549. $poll->save();
  550. $status->type = 'poll';
  551. $status->scope = $scope;
  552. $status->visibility = $scope;
  553. $status->save();
  554. return $status;
  555. }
  556. public static function statusFetch($url)
  557. {
  558. return self::statusFirstOrFetch($url);
  559. }
  560. public static function importNoteAttachment($data, Status $status)
  561. {
  562. if(self::verifyAttachments($data) == false) {
  563. // \Log::info('importNoteAttachment::failedVerification.', [$data['id']]);
  564. $status->viewType();
  565. return;
  566. }
  567. $attachments = isset($data['object']) ? $data['object']['attachment'] : $data['attachment'];
  568. // peertube
  569. // if(!$attachments) {
  570. // $obj = isset($data['object']) ? $data['object'] : $data;
  571. // $attachments = is_array($obj['url']) ? $obj['url'] : null;
  572. // }
  573. $user = $status->profile;
  574. $storagePath = MediaPathService::get($user, 2);
  575. $allowed = explode(',', config_cache('pixelfed.media_types'));
  576. foreach($attachments as $key => $media) {
  577. $type = $media['mediaType'];
  578. $url = $media['url'];
  579. $valid = self::validateUrl($url);
  580. if(in_array($type, $allowed) == false || $valid == false) {
  581. continue;
  582. }
  583. $blurhash = isset($media['blurhash']) ? $media['blurhash'] : null;
  584. $license = isset($media['license']) ? License::nameToId($media['license']) : null;
  585. $caption = isset($media['name']) ? Purify::clean($media['name']) : null;
  586. $width = isset($media['width']) ? $media['width'] : false;
  587. $height = isset($media['height']) ? $media['height'] : false;
  588. $media = new Media();
  589. $media->blurhash = $blurhash;
  590. $media->remote_media = true;
  591. $media->status_id = $status->id;
  592. $media->profile_id = $status->profile_id;
  593. $media->user_id = null;
  594. $media->media_path = $url;
  595. $media->remote_url = $url;
  596. $media->caption = $caption;
  597. $media->order = $key + 1;
  598. if($width) {
  599. $media->width = $width;
  600. }
  601. if($height) {
  602. $media->height = $height;
  603. }
  604. if($license) {
  605. $media->license = $license;
  606. }
  607. $media->mime = $type;
  608. $media->version = 3;
  609. $media->save();
  610. if(config_cache('pixelfed.cloud_storage') == true) {
  611. MediaStoragePipeline::dispatch($media);
  612. }
  613. }
  614. $status->viewType();
  615. return;
  616. }
  617. public static function profileFirstOrNew($url)
  618. {
  619. $url = self::validateUrl($url);
  620. if($url == false) {
  621. return;
  622. }
  623. $host = parse_url($url, PHP_URL_HOST);
  624. $local = config('pixelfed.domain.app') == $host ? true : false;
  625. if($local == true) {
  626. $id = last(explode('/', $url));
  627. return Profile::whereNull('status')
  628. ->whereNull('domain')
  629. ->whereUsername($id)
  630. ->firstOrFail();
  631. }
  632. if($profile = Profile::whereRemoteUrl($url)->first()) {
  633. if($profile->last_fetched_at && $profile->last_fetched_at->lt(now()->subHours(24))) {
  634. return self::profileUpdateOrCreate($url);
  635. }
  636. return $profile;
  637. }
  638. return self::profileUpdateOrCreate($url);
  639. }
  640. public static function profileUpdateOrCreate($url)
  641. {
  642. $res = self::fetchProfileFromUrl($url);
  643. if(!$res || isset($res['id']) == false) {
  644. return;
  645. }
  646. $domain = parse_url($res['id'], PHP_URL_HOST);
  647. if(!isset($res['preferredUsername']) && !isset($res['nickname'])) {
  648. return;
  649. }
  650. $username = (string) Purify::clean($res['preferredUsername'] ?? $res['nickname']);
  651. if(empty($username)) {
  652. return;
  653. }
  654. $remoteUsername = $username;
  655. $webfinger = "@{$username}@{$domain}";
  656. if(!self::validateUrl($res['inbox'])) {
  657. return;
  658. }
  659. if(!self::validateUrl($res['id'])) {
  660. return;
  661. }
  662. $instance = Instance::updateOrCreate([
  663. 'domain' => $domain
  664. ]);
  665. if($instance->wasRecentlyCreated == true) {
  666. \App\Jobs\InstancePipeline\FetchNodeinfoPipeline::dispatch($instance)->onQueue('low');
  667. }
  668. $profile = Profile::updateOrCreate(
  669. [
  670. 'domain' => strtolower($domain),
  671. 'username' => Purify::clean($webfinger),
  672. ],
  673. [
  674. 'webfinger' => Purify::clean($webfinger),
  675. 'key_id' => $res['publicKey']['id'],
  676. 'remote_url' => $res['id'],
  677. 'name' => isset($res['name']) ? Purify::clean($res['name']) : 'user',
  678. 'bio' => isset($res['summary']) ? Purify::clean($res['summary']) : null,
  679. 'sharedInbox' => isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null,
  680. 'inbox_url' => $res['inbox'],
  681. 'outbox_url' => isset($res['outbox']) ? $res['outbox'] : null,
  682. 'public_key' => $res['publicKey']['publicKeyPem'],
  683. 'indexable' => isset($res['indexable']) && is_bool($res['indexable']) ? $res['indexable'] : false,
  684. ]
  685. );
  686. if( $profile->last_fetched_at == null ||
  687. $profile->last_fetched_at->lt(now()->subMonths(3))
  688. ) {
  689. RemoteAvatarFetch::dispatch($profile);
  690. }
  691. $profile->last_fetched_at = now();
  692. $profile->save();
  693. return $profile;
  694. }
  695. public static function profileFetch($url)
  696. {
  697. return self::profileFirstOrNew($url);
  698. }
  699. public static function sendSignedObject($profile, $url, $body)
  700. {
  701. ActivityPubDeliveryService::queue()
  702. ->from($profile)
  703. ->to($url)
  704. ->payload($body)
  705. ->send();
  706. }
  707. }