Helpers.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. namespace App\Util\ActivityPub;
  3. use Cache, Purify, Storage, Request, Validator;
  4. use App\{
  5. Activity,
  6. Follower,
  7. Like,
  8. Media,
  9. Notification,
  10. Profile,
  11. Status
  12. };
  13. use Zttp\Zttp;
  14. use Carbon\Carbon;
  15. use GuzzleHttp\Client;
  16. use Illuminate\Http\File;
  17. use Illuminate\Validation\Rule;
  18. use App\Jobs\AvatarPipeline\CreateAvatar;
  19. use App\Jobs\RemoteFollowPipeline\RemoteFollowImportRecent;
  20. use App\Jobs\ImageOptimizePipeline\{ImageOptimize,ImageThumbnail};
  21. use App\Jobs\StatusPipeline\NewStatusPipeline;
  22. use App\Util\HttpSignatures\{GuzzleHttpSignatures, KeyStore, Context, Verifier};
  23. use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
  24. use App\Util\ActivityPub\HttpSignature;
  25. class Helpers {
  26. public static function validateObject($data)
  27. {
  28. $verbs = ['Create', 'Announce', 'Like', 'Follow', 'Delete', 'Accept', 'Reject', 'Undo'];
  29. $valid = Validator::make($data, [
  30. 'type' => [
  31. 'required',
  32. Rule::in($verbs)
  33. ],
  34. 'id' => 'required|string',
  35. 'actor' => 'required|string',
  36. 'object' => 'required',
  37. 'object.type' => 'required_if:type,Create',
  38. 'object.attachment' => 'required_if:type,Create',
  39. 'object.attributedTo' => 'required_if:type,Create',
  40. 'published' => 'required_if:type,Create|date'
  41. ])->passes();
  42. return $valid;
  43. }
  44. public static function verifyAttachments($data)
  45. {
  46. if(!isset($data['object']) || empty($data['object'])) {
  47. $data = ['object'=>$data];
  48. }
  49. $activity = $data['object'];
  50. $mediaTypes = ['Document', 'Image', 'Video'];
  51. $mimeTypes = ['image/jpeg', 'image/png', 'video/mp4'];
  52. if(!isset($activity['attachment']) || empty($activity['attachment'])) {
  53. return false;
  54. }
  55. $attachment = $activity['attachment'];
  56. $valid = Validator::make($attachment, [
  57. '*.type' => [
  58. 'required',
  59. 'string',
  60. Rule::in($mediaTypes)
  61. ],
  62. '*.url' => 'required|max:255',
  63. '*.mediaType' => [
  64. 'required',
  65. 'string',
  66. Rule::in($mimeTypes)
  67. ],
  68. '*.name' => 'nullable|string|max:255'
  69. ])->passes();
  70. return $valid;
  71. }
  72. public static function normalizeAudience($data, $localOnly = true)
  73. {
  74. if(!isset($data['to'])) {
  75. return;
  76. }
  77. $audience = [];
  78. $audience['to'] = [];
  79. $audience['cc'] = [];
  80. $scope = 'private';
  81. if(is_array($data['to']) && !empty($data['to'])) {
  82. foreach ($data['to'] as $to) {
  83. if($to == 'https://www.w3.org/ns/activitystreams#Public') {
  84. $scope = 'public';
  85. continue;
  86. }
  87. $url = $localOnly ? self::validateLocalUrl($to) : self::validateUrl($to);
  88. if($url != false) {
  89. array_push($audience['to'], $url);
  90. }
  91. }
  92. }
  93. if(is_array($data['cc']) && !empty($data['cc'])) {
  94. foreach ($data['cc'] as $cc) {
  95. if($cc == 'https://www.w3.org/ns/activitystreams#Public') {
  96. $scope = 'unlisted';
  97. continue;
  98. }
  99. $url = $localOnly ? self::validateLocalUrl($cc) : self::validateUrl($cc);
  100. if($url != false) {
  101. array_push($audience['cc'], $url);
  102. }
  103. }
  104. }
  105. $audience['scope'] = $scope;
  106. return $audience;
  107. }
  108. public static function userInAudience($profile, $data)
  109. {
  110. $audience = self::normalizeAudience($data);
  111. $url = $profile->permalink();
  112. return in_array($url, $audience);
  113. }
  114. public static function validateUrl($url)
  115. {
  116. $localhosts = [
  117. '127.0.0.1', 'localhost', '::1'
  118. ];
  119. $valid = filter_var($url, FILTER_VALIDATE_URL);
  120. if(in_array(parse_url($valid, PHP_URL_HOST), $localhosts)) {
  121. return false;
  122. }
  123. return $valid;
  124. }
  125. public static function validateLocalUrl($url)
  126. {
  127. $url = self::validateUrl($url);
  128. if($url) {
  129. $domain = config('pixelfed.domain.app');
  130. $host = parse_url($url, PHP_URL_HOST);
  131. $url = $domain === $host ? $url : false;
  132. return $url;
  133. }
  134. return false;
  135. }
  136. public static function zttpUserAgent()
  137. {
  138. return [
  139. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  140. 'User-Agent' => 'PixelFedBot - https://pixelfed.org',
  141. ];
  142. }
  143. public static function fetchFromUrl($url)
  144. {
  145. $res = Zttp::withHeaders(self::zttpUserAgent())->get($url);
  146. $res = json_decode($res->body(), true, 8);
  147. if(json_last_error() == JSON_ERROR_NONE) {
  148. return $res;
  149. } else {
  150. return false;
  151. }
  152. }
  153. public static function fetchProfileFromUrl($url)
  154. {
  155. return self::fetchFromUrl($url);
  156. }
  157. public static function statusFirstOrFetch($url, $replyTo = true)
  158. {
  159. $url = self::validateUrl($url);
  160. if($url == false) {
  161. return;
  162. }
  163. $host = parse_url($url, PHP_URL_HOST);
  164. $local = config('pixelfed.domain.app') == $host ? true : false;
  165. if($local) {
  166. $id = (int) last(explode('/', $url));
  167. return Status::findOrFail($id);
  168. } else {
  169. $cached = Status::whereUrl($url)->first();
  170. if($cached) {
  171. return $cached;
  172. }
  173. $res = self::fetchFromUrl($url);
  174. if(!$res || empty($res)) {
  175. return;
  176. }
  177. if(isset($res['object'])) {
  178. $activity = $res;
  179. } else {
  180. $activity = ['object' => $res];
  181. }
  182. $idDomain = parse_url($res['id'], PHP_URL_HOST);
  183. $urlDomain = parse_url($url, PHP_URL_HOST);
  184. $actorDomain = parse_url($activity['object']['attributedTo'], PHP_URL_HOST);
  185. if(
  186. $idDomain !== $urlDomain ||
  187. $actorDomain !== $urlDomain ||
  188. $idDomain !== $actorDomain
  189. ) {
  190. abort(400, 'Invalid object');
  191. }
  192. $profile = self::profileFirstOrNew($activity['object']['attributedTo']);
  193. if(isset($activity['object']['inReplyTo']) && !empty($activity['object']['inReplyTo']) && $replyTo == true) {
  194. $reply_to = self::statusFirstOrFetch($activity['object']['inReplyTo'], false);
  195. $reply_to = $reply_to->id;
  196. } else {
  197. $reply_to = null;
  198. }
  199. $ts = is_array($res['published']) ? $res['published'][0] : $res['published'];
  200. $status = new Status;
  201. $status->profile_id = $profile->id;
  202. $status->url = isset($res['url']) ? $res['url'] : $url;
  203. $status->uri = isset($res['url']) ? $res['url'] : $url;
  204. $status->caption = strip_tags($res['content']);
  205. $status->rendered = Purify::clean($res['content']);
  206. $status->created_at = Carbon::parse($ts);
  207. $status->in_reply_to_id = $reply_to;
  208. $status->local = false;
  209. $status->save();
  210. self::importNoteAttachment($res, $status);
  211. return $status;
  212. }
  213. }
  214. public static function importNoteAttachment($data, Status $status)
  215. {
  216. if(self::verifyAttachments($data) == false) {
  217. return;
  218. }
  219. $attachments = isset($data['object']) ? $data['object']['attachment'] : $data['attachment'];
  220. $user = $status->profile;
  221. $monthHash = hash('sha1', date('Y').date('m'));
  222. $userHash = hash('sha1', $user->id.(string) $user->created_at);
  223. $storagePath = "public/m/{$monthHash}/{$userHash}";
  224. $allowed = explode(',', config('pixelfed.media_types'));
  225. foreach($attachments as $media) {
  226. $type = $media['mediaType'];
  227. $url = $media['url'];
  228. $valid = self::validateUrl($url);
  229. if(in_array($type, $allowed) == false || $valid == false) {
  230. continue;
  231. }
  232. $info = pathinfo($url);
  233. // pleroma attachment fix
  234. $url = str_replace(' ', '%20', $url);
  235. $img = file_get_contents($url, false, stream_context_create(['ssl' => ["verify_peer"=>false,"verify_peer_name"=>false]]));
  236. $file = '/tmp/'.str_random(16).$info['basename'];
  237. file_put_contents($file, $img);
  238. $fdata = new File($file);
  239. $path = Storage::putFile($storagePath, $fdata, 'public');
  240. $media = new Media();
  241. $media->status_id = $status->id;
  242. $media->profile_id = $status->profile_id;
  243. $media->user_id = null;
  244. $media->media_path = $path;
  245. $media->size = $fdata->getSize();
  246. $media->mime = $fdata->getMimeType();
  247. $media->save();
  248. ImageThumbnail::dispatch($media);
  249. ImageOptimize::dispatch($media);
  250. unlink($file);
  251. }
  252. return;
  253. }
  254. public static function profileFirstOrNew($url, $runJobs = false)
  255. {
  256. $url = self::validateUrl($url);
  257. $host = parse_url($url, PHP_URL_HOST);
  258. $local = config('pixelfed.domain.app') == $host ? true : false;
  259. if($local == true) {
  260. $id = last(explode('/', $url));
  261. return Profile::whereUsername($id)->firstOrFail();
  262. }
  263. $res = self::fetchProfileFromUrl($url);
  264. if(isset($res['id']) == false) {
  265. return;
  266. }
  267. $domain = parse_url($res['id'], PHP_URL_HOST);
  268. $username = $res['preferredUsername'];
  269. $remoteUsername = "@{$username}@{$domain}";
  270. $profile = Profile::whereRemoteUrl($res['id'])->first();
  271. if(!$profile) {
  272. $profile = new Profile;
  273. $profile->domain = $domain;
  274. $profile->username = $remoteUsername;
  275. $profile->name = strip_tags($res['name']);
  276. $profile->bio = Purify::clean($res['summary']);
  277. $profile->sharedInbox = isset($res['endpoints']) && isset($res['endpoints']['sharedInbox']) ? $res['endpoints']['sharedInbox'] : null;
  278. $profile->inbox_url = $res['inbox'];
  279. $profile->outbox_url = $res['outbox'];
  280. $profile->remote_url = $res['id'];
  281. $profile->public_key = $res['publicKey']['publicKeyPem'];
  282. $profile->key_id = $res['publicKey']['id'];
  283. $profile->save();
  284. if($runJobs == true) {
  285. RemoteFollowImportRecent::dispatch($res, $profile);
  286. CreateAvatar::dispatch($profile);
  287. }
  288. }
  289. return $profile;
  290. }
  291. public static function sendSignedObject($senderProfile, $url, $body)
  292. {
  293. $payload = json_encode($body);
  294. $headers = HttpSignature::sign($senderProfile, $url, $body);
  295. $ch = curl_init($url);
  296. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  297. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  298. curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
  299. curl_setopt($ch, CURLOPT_HEADER, true);
  300. $response = curl_exec($ch);
  301. return;
  302. }
  303. private static function _headersToSigningString($headers) {
  304. }
  305. public static function validateSignature($request, $payload = null)
  306. {
  307. }
  308. public static function fetchPublicKey()
  309. {
  310. $profile = $this->profile;
  311. $is_url = $this->is_url;
  312. $valid = $this->validateUrl();
  313. if (!$valid) {
  314. throw new \Exception('Invalid URL provided');
  315. }
  316. if ($is_url && isset($profile->public_key) && $profile->public_key) {
  317. return $profile->public_key;
  318. }
  319. try {
  320. $url = $this->profile;
  321. $res = Zttp::timeout(30)->withHeaders([
  322. 'Accept' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
  323. 'User-Agent' => 'PixelFedBot v0.1 - https://pixelfed.org',
  324. ])->get($url);
  325. $actor = json_decode($res->getBody(), true);
  326. } catch (Exception $e) {
  327. throw new Exception('Unable to fetch public key');
  328. }
  329. if($actor['publicKey']['owner'] != $profile) {
  330. throw new Exception('Invalid key match');
  331. }
  332. $this->public_key = $actor['publicKey']['publicKeyPem'];
  333. $this->key_id = $actor['publicKey']['id'];
  334. return $this;
  335. }
  336. }