]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Issue 13535: Handle Firefish chat messages
[friendica.git] / src / Protocol / ActivityPub / Receiver.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\Database;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\APContact;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\User;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\HTTPSignature;
43 use Friendica\Util\JsonLD;
44 use Friendica\Util\LDSignature;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
47
48 /**
49  * ActivityPub Receiver Protocol class
50  *
51  * To-Do:
52  * @todo Undo Announce
53  *
54  * Check what this is meant to do:
55  * - Add
56  * - Block
57  * - Flag
58  * - Remove
59  * - Undo Block
60  */
61 class Receiver
62 {
63         const PUBLIC_COLLECTION = 'as:Public';
64         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
65         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
66         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept', 'as:View', 'as:Read', 'litepub:EmojiReact'];
67
68         const TARGET_UNKNOWN = 0;
69         const TARGET_TO = 1;
70         const TARGET_CC = 2;
71         const TARGET_BTO = 3;
72         const TARGET_BCC = 4;
73         const TARGET_FOLLOWER = 5;
74         const TARGET_ANSWER = 6;
75         const TARGET_GLOBAL = 7;
76         const TARGET_AUDIENCE = 8;
77
78         const COMPLETION_NONE     = 0;
79         const COMPLETION_ANNOUNCE = 1;
80         const COMPLETION_RELAY    = 2;
81         const COMPLETION_MANUAL   = 3;
82         const COMPLETION_AUTO     = 4;
83
84         /**
85          * Checks incoming message from the inbox
86          *
87          * @param string  $body Body string
88          * @param array   $header Header lines
89          * @param integer $uid User ID
90          * @return void
91          * @throws \Exception
92          */
93         public static function processInbox(string $body, array $header, int $uid)
94         {
95                 $activity = json_decode($body, true);
96                 if (empty($activity)) {
97                         Logger::warning('Invalid body.');
98                         return;
99                 }
100
101                 $ldactivity = JsonLD::compact($activity);
102
103                 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
104
105                 $apcontact = APContact::getByURL($actor);
106
107                 if (empty($apcontact)) {
108                         Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
109                         return;
110                 } elseif (APContact::isRelay($apcontact)) {
111                         self::processRelayPost($ldactivity, $actor);
112                         return;
113                 } else {
114                         APContact::unmarkForArchival($apcontact);
115                 }
116
117                 $sig_contact = HTTPSignature::getKeyIdContact($header);
118                 if (APContact::isRelay($sig_contact)) {
119                         Logger::info('Message from a relay', ['url' => $sig_contact['url']]);
120                         self::processRelayPost($ldactivity, $sig_contact['url']);
121                         return;
122                 }
123
124                 $http_signer = HTTPSignature::getSigner($body, $header);
125                 if ($http_signer === false) {
126                         Logger::notice('Invalid HTTP signature, message will not be trusted.', ['uid' => $uid, 'actor' => $actor, 'header' => $header, 'body' => $body]);
127                         $signer = [];
128                 } elseif (empty($http_signer)) {
129                         Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
130                         return;
131                 } else {
132                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
133                         $signer = [$http_signer];
134                 }
135
136                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
137
138                 if ($http_signer === false) {
139                         $trust_source = false;
140                 } elseif (LDSignature::isSigned($activity)) {
141                         $ld_signer = LDSignature::getSigner($activity);
142                         if (empty($ld_signer)) {
143                                 Logger::info('Invalid JSON-LD signature from ' . $actor);
144                         } elseif ($ld_signer != $http_signer) {
145                                 $signer[] = $ld_signer;
146                         }
147                         if (!empty($ld_signer && ($actor == $http_signer))) {
148                                 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
149                                 $trust_source = true;
150                         } elseif (!empty($ld_signer)) {
151                                 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
152                                 $trust_source = true;
153                         } elseif ($actor == $http_signer) {
154                                 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
155                                 $trust_source = true;
156                         } else {
157                                 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
158                                 $trust_source = false;
159                         }
160                 } elseif ($actor == $http_signer) {
161                         Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
162                         $trust_source = true;
163                 } else {
164                         Logger::info('No JSON-LD signature, different actor.');
165                         $trust_source = false;
166                 }
167
168                 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
169         }
170
171         /**
172          * Process incoming posts from relays
173          *
174          * @param array  $activity
175          * @param string $actor
176          * @return void
177          */
178         private static function processRelayPost(array $activity, string $actor)
179         {
180                 $type = JsonLD::fetchElement($activity, '@type');
181                 if (!$type) {
182                         Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]);
183                         return;
184                 }
185
186                 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
187
188                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
189                 if (empty($object_id)) {
190                         Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]);
191                         return;
192                 }
193
194                 $handle = ($type == 'as:Announce');
195
196                 if (!$handle && in_array($type, ['as:Create', 'as:Update'])) {
197                         $handle = in_array($object_type, self::CONTENT_TYPES);
198                 }
199
200                 if (!$handle) {
201                         $trust_source = false;
202                         $object_data = self::prepareObjectData($activity, 0, false, $trust_source);
203
204                         if (!$trust_source) {
205                                 Logger::notice('Activity trust could not be achieved.',  ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
206                                 return;
207                         }
208
209                         if (empty($object_data)) {
210                                 Logger::notice('No object data found', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
211                                 return;
212                         }
213
214                         if (self::routeActivities($object_data, $type, true)) {
215                                 Logger::debug('Handled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]);
216                         } else {
217                                 Logger::info('Unhandled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
218                         }
219                         return;
220                 }
221
222                 $contact = Contact::getByURL($actor);
223                 if (empty($contact)) {
224                         Logger::info('Relay contact not found', ['actor' => $actor]);
225                         return;
226                 }
227
228                 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
229                         Logger::notice('Relay is no sharer', ['actor' => $actor]);
230                         return;
231                 }
232
233                 Logger::debug('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
234
235                 $item_id = Item::searchByLink($object_id);
236                 if ($item_id) {
237                         Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
238                         return;
239                 }
240
241                 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
242                 if (empty($id)) {
243                         Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
244                         return;
245                 }
246         }
247
248         /**
249          * Fetches the object type for a given object id
250          *
251          * @param array   $activity
252          * @param string  $object_id Object ID of the provided object
253          * @param integer $uid       User ID
254          *
255          * @return string with object type or NULL
256          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257          * @throws \ImagickException
258          */
259         public static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
260         {
261                 if (!empty($activity['as:object'])) {
262                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
263                         if (!empty($object_type)) {
264                                 return $object_type;
265                         }
266                 }
267
268                 if (Post::exists(['uri' => $object_id, 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]])) {
269                         // We just assume "note" since it doesn't make a difference for the further processing
270                         return 'as:Note';
271                 }
272
273                 $profile = APContact::getByURL($object_id);
274                 if (!empty($profile['type'])) {
275                         APContact::unmarkForArchival($profile);
276                         return 'as:' . $profile['type'];
277                 }
278
279                 $data = Processor::fetchCachedActivity($object_id, $uid);
280                 if (!empty($data)) {
281                         $object = JsonLD::compact($data);
282                         $type = JsonLD::fetchElement($object, '@type');
283                         if (!empty($type)) {
284                                 return $type;
285                         }
286                 }
287
288                 return null;
289         }
290
291         /**
292          * Prepare the object array
293          *
294          * @param array   $activity       Array with activity data
295          * @param integer $uid            User ID
296          * @param boolean $push           Message had been pushed to our system
297          * @param boolean $trust_source   Do we trust the source?
298          * @param string  $original_actor Actor of the original activity. Used for receiver detection. (Optional)
299          *
300          * @return array with object data
301          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302          * @throws \ImagickException
303          */
304         public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source, string $original_actor = ''): array
305         {
306                 $id        = JsonLD::fetchElement($activity, '@id');
307                 $type      = JsonLD::fetchElement($activity, '@type');
308                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
309
310                 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
311                         $fetch_id = $object_id;
312                 } else {
313                         $fetch_id = $id;
314                 }
315
316                 if (!empty($activity['as:object'])) {
317                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
318                 }
319
320                 $fetched = false;
321
322                 if (!empty($id) && !$trust_source) {
323                         $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
324
325                         $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
326                         if (!empty($fetched_activity)) {
327                                 $fetched = true;
328                                 $object  = JsonLD::compact($fetched_activity);
329
330                                 $fetched_id   = JsonLD::fetchElement($object, '@id');
331                                 $fetched_type = JsonLD::fetchElement($object, '@type');
332
333                                 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
334                                         Logger::info('Activity had been fetched successfully', ['id' => $id]);
335                                         $trust_source = true;
336                                         $activity = $object;
337                                 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
338                                         Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
339                                         $trust_source = true;
340                                         unset($object['@context']);
341                                         $activity['as:object'] = $object;
342                                 } else {
343                                         Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
344                                 }
345                         } else {
346                                 Logger::info('Activity could not been fetched', ['id' => $id]);
347                         }
348                 }
349
350                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
351                 if (empty($actor)) {
352                         Logger::info('Empty actor', ['activity' => $activity]);
353                         return [];
354                 }
355
356                 $type = JsonLD::fetchElement($activity, '@type');
357
358                 // Fetch all receivers from to, cc, bto and bcc
359                 $receiverdata = self::getReceivers($activity, $original_actor ?: $actor, [], false, $push || $fetched);
360                 $receivers = $reception_types = [];
361                 foreach ($receiverdata as $key => $data) {
362                         $receivers[$key] = $data['uid'];
363                         $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
364                 }
365
366                 $urls = self::getReceiverURL($activity);
367
368                 // When it is a delivery to a personal inbox we add that user to the receivers
369                 if (!empty($uid)) {
370                         $additional = [$uid => $uid];
371                         $receivers = array_replace($receivers, $additional);
372                         if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
373                                 $reception_types[$uid] = self::TARGET_BCC;
374                                 $owner = User::getOwnerDataById($uid);
375                                 if (!empty($owner['url'])) {
376                                         $urls['as:bcc'][] = $owner['url'];
377                                 }
378                         }
379                 }
380
381                 // We possibly need some user to fetch private content,
382                 // so we fetch one out of the receivers if no uid is provided.
383                 $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
384
385                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
386                 if (empty($object_id)) {
387                         Logger::info('No object found');
388                         return [];
389                 }
390
391                 if (!is_string($object_id)) {
392                         Logger::info('Invalid object id', ['object' => $object_id]);
393                         return [];
394                 }
395
396                 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
397
398                 // Any activities on account types must not be altered
399                 if (in_array($type, ['as:Flag'])) {
400                         $object_data = [];
401                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
402                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
403                         $object_data['object_ids'] = JsonLD::fetchElementArray($activity, 'as:object', '@id');
404                         $object_data['content'] = JsonLD::fetchElement($activity, 'as:content', '@type');
405                 } elseif (in_array($object_type, self::ACCOUNT_TYPES)) {
406                         $object_data = [];
407                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
408                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
409                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
410                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
411                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
412                         if (!$trust_source && ($type == 'as:Delete')) {
413                                 $apcontact = APContact::getByURL($object_data['object_id'], true);
414                                 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
415                         }
416                 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Invite']) || strpos($type, '#emojiReaction')) {
417                         // Fetch the content only on activities where this matters
418                         // We can receive "#emojiReaction" when fetching content from Hubzilla systems
419                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $fetch_uid);
420                         if (empty($object_data)) {
421                                 Logger::info("Object data couldn't be processed");
422                                 return [];
423                         }
424
425                         $object_data['object_id'] = $object_id;
426
427                         // Test if it is an answer to a mail
428                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
429                                 $object_data['directmessage'] = true;
430                         } else {
431                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
432
433                                 if (!empty(JsonLD::fetchElement($activity['as:object'], 'misskey:_misskey_talk'))) {
434                                         $object_data = self::setChatData($object_data, $receivers);
435                                 }
436                         }
437                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
438                         // Create a mostly empty array out of the activity data (instead of the object).
439                         // This way we later don't have to check for the existence of each individual array element.
440                         $object_data = self::processObject($activity, $original_actor);
441                         $object_data['name'] = $type;
442                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
443                         $object_data['object_id'] = $object_id;
444                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
445                 } elseif (in_array($type, ['as:Add', 'as:Remove', 'as:Move'])) {
446                         $object_data = [];
447                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
448                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
449                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
450                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
451                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
452                 } else {
453                         $object_data = [];
454                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
455                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
456                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
457                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
458                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
459
460                         // An Undo is done on the object of an object, so we need that type as well
461                         if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
462                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
463                         }
464
465                         if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
466                                 $trust_source = Processor::isActivityGone($object_data['object_id']);
467                                 if (!$trust_source) {
468                                         $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
469                                 }
470                         }
471                 }
472
473                 $object_data['push'] = $push;
474
475                 $object_data = self::addActivityFields($object_data, $activity);
476
477                 if (empty($object_data['object_type'])) {
478                         $object_data['object_type'] = $object_type;
479                 }
480
481                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
482                         if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
483                                 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
484                         }
485                 }
486
487                 $object_data['type'] = $type;
488                 $object_data['actor'] = $actor;
489                 $object_data['item_receiver'] = $receivers;
490                 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
491                 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
492
493 //              This check here interferes with Hubzilla posts where the author host differs from the host the post was created
494 //              $author = $object_data['author'] ?? $actor;
495 //              if (!empty($author) && !empty($object_data['id'])) {
496 //                      $author_host = parse_url($author, PHP_URL_HOST);
497 //                      $id_host = parse_url($object_data['id'], PHP_URL_HOST);
498 //                      if ($author_host == $id_host) {
499 //                              Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
500 //                      } else {
501 //                              Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
502 //                              $trust_source = false;
503 //                      }
504 //              }
505
506                 $account = Contact::selectFirstAccount(['platform'], ['nurl' => Strings::normaliseLink($actor)]);
507                 $platform = $account['platform'] ?? '';
508
509                 Logger::info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]);
510
511                 return $object_data;
512         }
513
514         private static function setChatData(array $object_data, array $receivers): array
515         {
516                 if (count($receivers) != 1) {
517                         return $object_data;
518                 }
519
520                 $user = User::getById(array_key_first($receivers), ['language']);
521                 $l10n = DI::l10n()->withLang($user['language']);
522                 $object_data['name'] = $l10n->t('Chat');
523
524                 $mail = DBA::selectFirst('mail', ['uri'], ['uid' => array_key_first($receivers), 'title' => $object_data['name']], ['order' => ['id' => true]]);
525                 if (!empty($mail['uri'])) {
526                         $object_data['reply-to-id'] = $mail['uri'];
527                 }
528
529                 $object_data['directmessage'] = true;
530                 Logger::debug('Got Misskey Chat');
531                 return $object_data;
532         }
533
534         /**
535          * Fetches the first user id from the receiver array
536          *
537          * @param array $receivers Array with receivers
538          * @return integer user id;
539          */
540         public static function getFirstUserFromReceivers(array $receivers): int
541         {
542                 foreach ($receivers as $receiver) {
543                         if (!empty($receiver)) {
544                                 return $receiver;
545                         }
546                 }
547                 return 0;
548         }
549
550         /**
551          * Processes the activity object
552          *
553          * @param array      $activity     Array with activity data
554          * @param string     $body         The unprocessed body
555          * @param int|null   $uid          User ID
556          * @param boolean    $trust_source Do we trust the source?
557          * @param boolean    $push         Message had been pushed to our system
558          * @param array      $signer       The signer of the post
559          *
560          * @return bool
561          *
562          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
563          * @throws \ImagickException
564          */
565         public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '', int $completion = Receiver::COMPLETION_AUTO): bool
566         {
567                 $type = JsonLD::fetchElement($activity, '@type');
568                 if (!$type) {
569                         Logger::info('Empty type', ['activity' => $activity]);
570                         return true;
571                 }
572
573                 if (!DI::config()->get('system', 'process_view') && ($type == 'as:View')) {
574                         Logger::info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]);
575                         return true;
576                 }
577
578                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
579                         Logger::info('Empty object', ['activity' => $activity]);
580                         return true;
581                 }
582
583                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
584                 if (empty($actor)) {
585                         Logger::info('Empty actor', ['activity' => $activity]);
586                         return true;
587                 }
588
589                 if (is_array($activity['as:object'])) {
590                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
591                 } else {
592                         $attributed_to = '';
593                 }
594
595                 // Test the provided signatures against the actor and "attributedTo"
596                 if ($trust_source) {
597                         if (!empty($attributed_to) && !empty($actor)) {
598                                 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
599                         } else {
600                                 $trust_source = in_array($actor, $signer);
601                         }
602                 }
603
604                 // Lemmy announces activities.
605                 // To simplify the further processing, we modify the received object.
606                 // For announced "create" activities we remove the middle layer.
607                 // For the rest (like, dislike, update, ...) we just process the activity directly.
608                 $original_actor = '';
609                 $object_type = JsonLD::fetchElement($activity['as:object'] ?? [], '@type');
610                 if (($type == 'as:Announce') && !empty($object_type) && !in_array($object_type, self::CONTENT_TYPES) && self::isGroup($actor)) {
611                         $object_object_type = JsonLD::fetchElement($activity['as:object']['as:object'] ?? [], '@type');
612                         if (in_array($object_type, ['as:Create']) && in_array($object_object_type, self::CONTENT_TYPES)) {
613                                 Logger::debug('Replace "create" activity with inner object', ['type' => $object_type, 'object_type' => $object_object_type]);
614                                 $activity['as:object'] = $activity['as:object']['as:object'];
615                         } elseif (in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
616                                 Logger::debug('Change announced activity to activity', ['type' => $object_type]);
617                                 $original_actor = $actor;
618                                 $type = $object_type;
619                                 $activity = $activity['as:object'];
620                         } else {
621                                 Logger::info('Unhandled announced activity', ['type' => $object_type, 'object_type' => $object_object_type]);
622                         }
623                 }
624
625                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
626                 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source, $original_actor);
627                 if (empty($object_data)) {
628                         Logger::info('No object data found', ['activity' => $activity, 'callstack' => System::callstack(20)]);
629                         return true;
630                 }
631
632                 if (!empty($body) && empty($object_data['raw'])) {
633                         $object_data['raw'] = $body;
634                 }
635
636                 // Internal flag for thread completion. See Processor.php
637                 if (!empty($activity['thread-completion'])) {
638                         $object_data['thread-completion'] = $activity['thread-completion'];
639                 }
640
641                 if (!empty($activity['completion-mode'])) {
642                         $object_data['completion-mode'] = $activity['completion-mode'];
643                 }
644
645                 if (!empty($activity['thread-children-type'])) {
646                         $object_data['thread-children-type'] = $activity['thread-children-type'];
647                 }
648
649                 // Internal flag for posts that arrived via relay
650                 if (!empty($activity['from-relay'])) {
651                         $object_data['from-relay'] = $activity['from-relay'];
652                 }
653
654                 if ($type == 'as:Announce') {
655                         $object_data['object_activity'] = $activity;
656                 }
657
658                 if (($type == 'as:Create') && $trust_source && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE])) {
659                         if (self::hasArrived($object_data['object_id'])) {
660                                 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
661                                 return true;
662                         }
663                         self::addArrivedId($object_data['object_id']);
664
665                         if (Queue::exists($object_data['object_id'], $type)) {
666                                 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
667                                 return true;
668                         }
669                 } elseif (($type == 'as:Create') && $trust_source && !self::hasArrived($object_data['object_id'])) {
670                         self::addArrivedId($object_data['object_id']);
671                 }
672
673                 $decouple = DI::config()->get('system', 'decoupled_receiver') && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE]);
674
675                 if ($decouple && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
676                         $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
677                 }
678
679                 if (!$trust_source) {
680                         Logger::info('Activity trust could not be achieved.',  ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
681                         return true;
682                 }
683
684                 if (!empty($object_data['entry-id']) && $decouple && ($push || ($completion == self::COMPLETION_RELAY))) {
685                         if (Queue::isProcessable($object_data['entry-id'])) {
686                                 // We delay by 5 seconds to allow to accumulate all receivers
687                                 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
688                                 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
689                                 $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
690                                 Queue::setWorkerId($object_data['entry-id'], $wid);
691                         } else {
692                                 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
693                         }
694                         return false;
695                 }
696
697                 if (!empty($activity['recursion-depth'])) {
698                         $object_data['recursion-depth'] = $activity['recursion-depth'];
699                 }
700
701                 if (!self::routeActivities($object_data, $type, $push, true, $uid)) {
702                         self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
703                         Queue::remove($object_data);
704                 }
705                 return true;
706         }
707
708         /**
709          * Checks if the provided actor is a group account
710          *
711          * @param string $actor
712          * @return boolean
713          */
714         private static function isGroup(string $actor): bool
715         {
716                 $profile = APContact::getByURL($actor);
717                 return ($profile['type'] ?? '') == 'Group';
718         }
719
720         /**
721          * Route activities
722          *
723          * @param array  $object_data
724          * @param string $type
725          * @param bool   $push
726          * @param bool   $fetch_parents
727          * @param int    $uid
728          *
729          * @return boolean Could the activity be routed?
730          */
731         public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true, int $uid = 0): bool
732         {
733                 switch ($type) {
734                         case 'as:Create':
735                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
736                                         $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
737                                         ActivityPub\Processor::postItem($object_data, $item);
738                                 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
739                                         // Unhandled Peertube activity
740                                         Queue::remove($object_data);
741                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
742                                         ActivityPub\Processor::updatePerson($object_data);
743                                 } else {
744                                         return false;
745                                 }
746                                 break;
747
748                         case 'as:Invite':
749                                 if (in_array($object_data['object_type'], ['as:Event'])) {
750                                         $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
751                                         ActivityPub\Processor::postItem($object_data, $item);
752                                 } else {
753                                         return false;
754                                 }
755                                 break;
756
757                         case 'as:Add':
758                                 if ($object_data['object_type'] == 'as:tag') {
759                                         ActivityPub\Processor::addTag($object_data);
760                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
761                                         ActivityPub\Processor::addToFeaturedCollection($object_data);
762                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
763                                         // We don't have the object here or it is deleted. We ignore this activity.
764                                         Queue::remove($object_data);
765                                 } else {
766                                         return false;
767                                 }
768                                 break;
769
770                         case 'as:Announce':
771                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
772                                         if (!Item::searchByLink($object_data['object_id'], $uid)) {
773                                                 if (ActivityPub\Processor::fetchMissingActivity($object_data['object_id'], [], $object_data['actor'], self::COMPLETION_ANNOUNCE, $uid)) {
774                                                         Logger::debug('Created announced id', ['uid' => $uid, 'id' => $object_data['object_id']]);
775                                                         Queue::remove($object_data);
776                                                 } else {
777                                                         Logger::debug('Announced id was not created', ['uid' => $uid, 'id' => $object_data['object_id']]);
778                                                         Queue::remove($object_data);
779                                                         return true;
780                                                 }
781                                         } else {
782                                                 Logger::info('Announced id already exists', ['uid' => $uid, 'id' => $object_data['object_id']]);
783                                                 Queue::remove($object_data);
784                                         }
785
786                                         ActivityPub\Processor::createActivity($object_data, Activity::ANNOUNCE);
787                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
788                                         // We don't have the object here or it is deleted. We ignore this activity.
789                                         Queue::remove($object_data);
790                                 } else {
791                                         return false;
792                                 }
793                                 break;
794
795                         case 'as:Like':
796                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
797                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
798                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
799                                         // We don't have the object here or it is deleted. We ignore this activity.
800                                         Queue::remove($object_data);
801                                 } else {
802                                         return false;
803                                 }
804                                 break;
805
806                         case 'as:Dislike':
807                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
808                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
809                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
810                                         // We don't have the object here or it is deleted. We ignore this activity.
811                                         Queue::remove($object_data);
812                                 } else {
813                                         return false;
814                                 }
815                                 break;
816
817                         case 'as:TentativeAccept':
818                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
819                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
820                                 } else {
821                                         return false;
822                                 }
823                                 break;
824
825                         case 'as:Update':
826                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
827                                         ActivityPub\Processor::updateItem($object_data);
828                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
829                                         ActivityPub\Processor::updatePerson($object_data);
830                                 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
831                                         // Unhandled Peertube activity
832                                         Queue::remove($object_data);
833                                 } else {
834                                         return false;
835                                 }
836                                 break;
837
838                         case 'as:Delete':
839                                 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
840                                         ActivityPub\Processor::deleteItem($object_data);
841                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
842                                         ActivityPub\Processor::deletePerson($object_data);
843                                 } elseif ($object_data['object_type'] == '') {
844                                         // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
845                                         Queue::remove($object_data);
846                                 } else {
847                                         return false;
848                                 }
849                                 break;
850
851                         case 'as:Move':
852                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
853                                         ActivityPub\Processor::movePerson($object_data);
854                                 } else {
855                                         return false;
856                                 }
857                                 break;
858
859                         case 'as:Block':
860                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
861                                         ActivityPub\Processor::blockAccount($object_data);
862                                 } else {
863                                         return false;
864                                 }
865                                 break;
866
867                         case 'as:Flag':
868                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
869                                         ActivityPub\Processor::ReportAccount($object_data);
870                                 } else {
871                                         return false;
872                                 }
873                                 break;
874
875                         case 'as:Remove':
876                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
877                                         ActivityPub\Processor::removeFromFeaturedCollection($object_data);
878                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
879                                         // We don't have the object here or it is deleted. We ignore this activity.
880                                         Queue::remove($object_data);
881                                 } else {
882                                         return false;
883                                 }
884                                 break;
885
886                         case 'as:Follow':
887                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
888                                         ActivityPub\Processor::followUser($object_data);
889                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
890                                         $object_data['reply-to-id'] = $object_data['object_id'];
891                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
892                                 } else {
893                                         return false;
894                                 }
895                                 break;
896
897                         case 'as:Accept':
898                                 if ($object_data['object_type'] == 'as:Follow') {
899                                         if (!empty($object_data['object_actor'])) {
900                                                 ActivityPub\Processor::acceptFollowUser($object_data);
901                                         } else {
902                                                 Logger::notice('Unhandled "accept follow" message.', ['object_data' => $object_data]);
903                                         }
904                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
905                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
906                                 } elseif (!empty($object_data['object_id']) && empty($object_data['object_actor']) && empty($object_data['object_type'])) {
907                                         // Follow acceptances from gup.pe only contain the object id
908                                         ActivityPub\Processor::acceptFollowUser($object_data);
909                                 } else {
910                                         return false;
911                                 }
912                                 break;
913
914                         case 'as:Reject':
915                                 if ($object_data['object_type'] == 'as:Follow') {
916                                         ActivityPub\Processor::rejectFollowUser($object_data);
917                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
918                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
919                                 } else {
920                                         return false;
921                                 }
922                                 break;
923
924                         case 'as:Undo':
925                                 if (($object_data['object_type'] == 'as:Follow') &&
926                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
927                                         ActivityPub\Processor::undoFollowUser($object_data);
928                                 } elseif (($object_data['object_type'] == 'as:Follow') &&
929                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
930                                         ActivityPub\Processor::undoActivity($object_data);
931                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
932                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
933                                         ActivityPub\Processor::rejectFollowUser($object_data);
934                                 } elseif (($object_data['object_type'] == 'as:Block') &&
935                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
936                                         ActivityPub\Processor::unblockAccount($object_data);
937                                 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
938                                         empty($object_data['object_object_type'])) {
939                                         // We cannot detect the target object. So we can ignore it.
940                                         Queue::remove($object_data);
941                                 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
942                                         in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
943                                         ActivityPub\Processor::undoActivity($object_data);
944                                 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
945                                         in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
946                                         // Unhandled Peertube activity
947                                         Queue::remove($object_data);
948                                 } elseif (in_array($object_data['object_type'], ['as:Delete'])) {
949                                         // We cannot undo deletions, so we just ignore this
950                                         Queue::remove($object_data);
951                                 } elseif (in_array($object_data['object_object_type'], ['as:Tombstone'])) {
952                                         // The object is a tombstone, we ignore any actions on it.
953                                         Queue::remove($object_data);
954                                 } else {
955                                         return false;
956                                 }
957                                 break;
958
959                         case 'as:View':
960                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
961                                         ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
962                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
963                                         // We don't have the object here or it is deleted. We ignore this activity.
964                                         Queue::remove($object_data);
965                                 } else {
966                                         return false;
967                                 }
968                                 break;
969                         case 'as:Read':
970                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
971                                         ActivityPub\Processor::createActivity($object_data, Activity::READ);
972                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
973                                         // We don't have the object here or it is deleted. We ignore this activity.
974                                         Queue::remove($object_data);
975                                 } else {
976                                         return false;
977                                 }
978                                 break;
979
980                         case 'litepub:EmojiReact':
981                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
982                                         ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
983                                 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
984                                         // We don't have the object here or it is deleted. We ignore this activity.
985                                         Queue::remove($object_data);
986                                 } else {
987                                         return false;
988                                 }
989                                 break;
990
991                         default:
992                                 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
993                                 return false;
994                 }
995                 return true;
996         }
997
998         /**
999          * Stores unhandled or unknown Activities as a file
1000          *
1001          * @param boolean $unknown      "true" if the activity is unknown, "false" if it is unhandled
1002          * @param string  $type         Activity type
1003          * @param array   $object_data  Preprocessed array that is generated out of the received activity
1004          * @param array   $activity     Array with activity data
1005          * @param string  $body         The unprocessed body
1006          * @param integer $uid          User ID
1007          * @param boolean $trust_source Do we trust the source?
1008          * @param boolean $push         Message had been pushed to our system
1009          * @param array   $signer       The signer of the post
1010          * @return void
1011          */
1012         private static function storeUnhandledActivity(bool $unknown, string $type, array $object_data, array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
1013         {
1014                 if (!DI::config()->get('debug', 'ap_log_unknown')) {
1015                         return;
1016                 }
1017
1018                 $file = ($unknown  ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
1019
1020                 if (!empty($object_data['object_type'])) {
1021                         $file .= str_replace(':', '-', $object_data['object_type']) . '-';
1022                 }
1023
1024                 if (!empty($object_data['object_object_type'])) {
1025                         $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
1026                 }
1027
1028                 $tempfile = tempnam(System::getTempPath(), $file);
1029                 file_put_contents($tempfile, json_encode(['activity' => $activity, 'body' => $body, 'uid' => $uid, 'trust_source' => $trust_source, 'push' => $push, 'signer' => $signer, 'object_data' => $object_data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
1030                 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
1031         }
1032
1033         /**
1034          * Fetch a user id from an activity array
1035          *
1036          * @param array  $activity
1037          * @param string $actor
1038          *
1039          * @return int   user id
1040          */
1041         public static function getBestUserForActivity(array $activity, string $actor = ''): int
1042         {
1043                 $uid = 0;
1044                 $actor = $actor ?: JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
1045
1046                 $receivers = self::getReceivers($activity, $actor, [], false, false);
1047                 foreach ($receivers as $receiver) {
1048                         if ($receiver['type'] == self::TARGET_GLOBAL) {
1049                                 return 0;
1050                         }
1051                         if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
1052                                 $uid = $receiver['uid'];
1053                         }
1054                 }
1055
1056                 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
1057                 if (empty($uid)) {
1058                         $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
1059                         if (!empty($contact['uid'])) {
1060                                 $uid = $contact['uid'];
1061                         }
1062                 }
1063
1064                 return $uid;
1065         }
1066
1067         // @TODO Missing documentation
1068         public static function getReceiverURL(array $activity): array
1069         {
1070                 $urls = [];
1071
1072                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
1073                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1074                         if (empty($receiver_list)) {
1075                                 continue;
1076                         }
1077
1078                         foreach ($receiver_list as $receiver) {
1079                                 if ($receiver == 'Public') {
1080                                         Logger::warning('Not compacted public collection found', ['activity' => $activity, 'callstack' => System::callstack(20)]);
1081                                         $receiver = ActivityPub::PUBLIC_COLLECTION;
1082                                 }
1083                                 if ($receiver == self::PUBLIC_COLLECTION) {
1084                                         $receiver = ActivityPub::PUBLIC_COLLECTION;
1085                                 }
1086                                 $urls[$element][] = $receiver;
1087                         }
1088                 }
1089
1090                 return $urls;
1091         }
1092
1093         /**
1094          * Fetch the receiver list from an activity array
1095          *
1096          * @param array   $activity
1097          * @param string $actor
1098          * @param array  $tags
1099          * @param bool   $fetch_unlisted
1100          * @param bool   $push
1101          *
1102          * @return array with receivers (user id)
1103          * @throws \Exception
1104          */
1105         private static function getReceivers(array $activity, string $actor, array $tags, bool $fetch_unlisted, bool $push): array
1106         {
1107                 $reply = $receivers = $profile = [];
1108
1109                 // When it is an answer, we inherit the receivers from the parent
1110                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1111                 if (!empty($replyto)) {
1112                         $reply = [$replyto];
1113
1114                         // Fix possibly wrong item URI (could be an answer to a plink uri)
1115                         $fixedReplyTo = Item::getURIByLink($replyto);
1116                         if (!empty($fixedReplyTo)) {
1117                                 $reply[] = $fixedReplyTo;
1118                         }
1119                 }
1120
1121                 // Fetch all posts that refer to the object id
1122                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1123                 if (!empty($object_id)) {
1124                         $reply[] = $object_id;
1125                 }
1126
1127                 if (!empty($actor)) {
1128                         $profile   = APContact::getByURL($actor);
1129                         $followers = $profile['followers'] ?? '';
1130                         $isGroup  = ($profile['type'] ?? '') == 'Group';
1131                         if ($push) {
1132                                 Contact::updateByUrlIfNeeded($actor);
1133                         }
1134                         Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1135                 } else {
1136                         Logger::info('Empty actor', ['activity' => $activity]);
1137                         $followers = '';
1138                         $isGroup  = false;
1139                 }
1140
1141                 // We have to prevent false follower assumptions upon thread completions
1142                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1143
1144                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc','as:audience'] as $element) {
1145                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1146                         if (empty($receiver_list)) {
1147                                 continue;
1148                         }
1149
1150                         foreach ($receiver_list as $receiver) {
1151                                 if ($receiver == self::PUBLIC_COLLECTION) {
1152                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1153                                 }
1154
1155                                 // Add receiver "-1" for unlisted posts
1156                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1157                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1158                                 }
1159
1160                                 // Fetch the receivers for the public and the followers collection
1161                                 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$isGroup) || ($isGroup && ($element == 'as:audience'))) && !empty($actor)) {
1162                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1163                                         continue;
1164                                 }
1165
1166                                 // Fetching all directly addressed receivers
1167                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1168                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1169                                 if (!DBA::isResult($contact)) {
1170                                         continue;
1171                                 }
1172
1173                                 // Check if the potential receiver is following the actor
1174                                 // Exception: The receiver is targetted via "to" or this is a comment
1175                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1176                                         $networks = Protocol::FEDERATED;
1177                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1178                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1179
1180                                         // Group posts are only accepted from group contacts
1181                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1182                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1183                                         }
1184
1185                                         if (!DBA::exists('contact', $condition)) {
1186                                                 continue;
1187                                         }
1188                                 }
1189
1190                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1191                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1192                                         switch ($element) {
1193                                                 case 'as:to':
1194                                                         $type = self::TARGET_TO;
1195                                                         break;
1196                                                 case 'as:cc':
1197                                                         $type = self::TARGET_CC;
1198                                                         break;
1199                                                 case 'as:bto':
1200                                                         $type = self::TARGET_BTO;
1201                                                         break;
1202                                                 case 'as:bcc':
1203                                                         $type = self::TARGET_BCC;
1204                                                         break;
1205                                                 case 'as:audience':
1206                                                         $type = self::TARGET_AUDIENCE;
1207                                                         break;
1208                                         }
1209
1210                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1211                                 }
1212                         }
1213                 }
1214
1215                 if (!empty($reply) && (!empty($receivers[0]) || !empty($receivers[-1]))) {
1216                         $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1217                         while ($parent = Post::fetch($parents)) {
1218                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1219                         }
1220                         DBA::close($parents);
1221                 }
1222
1223                 self::switchContacts($receivers, $actor);
1224
1225                 // "birdsitelive" is a service that mirrors tweets into the fediverse
1226                 // These posts can be fetched without authentication, but are not marked as public
1227                 // We treat them as unlisted posts to be able to handle them.
1228                 // We always process deletion activities.
1229                 $activity_type = JsonLD::fetchElement($activity, '@type');
1230                 if (empty($receivers) && $fetch_unlisted && Contact::isPlatform($actor, 'birdsitelive')) {
1231                         $receivers[0]  = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1232                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1233                         Logger::notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]);
1234                 } elseif (empty($receivers) && in_array($activity_type, ['as:Delete', 'as:Undo'])) {
1235                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1236                 } elseif (empty($receivers)) {
1237                         Logger::notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => $activity_type, 'callstack' => System::callstack(20)]);
1238                 }
1239
1240                 return $receivers;
1241         }
1242
1243         /**
1244          * Fetch the receiver list of a given actor
1245          *
1246          * @param string  $actor
1247          * @param array   $tags
1248          * @param array   $receivers
1249          * @param integer $target_type
1250          * @param array   $profile
1251          *
1252          * @return array with receivers (user id)
1253          * @throws \Exception
1254          */
1255         private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1256         {
1257                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1258                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1259
1260                 if (!empty($profile['uri-id'])) {
1261                         $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1262                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1263                         while ($contact = DBA::fetch($contacts)) {
1264                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1265                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1266                                 }
1267                         }
1268                         DBA::close($contacts);
1269                 } else {
1270                         // This part will only be called while post update 1426 wasn't finished
1271                         $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1272                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1273                         while ($contact = DBA::fetch($contacts)) {
1274                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1275                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1276                                 }
1277                         }
1278                         DBA::close($contacts);
1279
1280                         // The queries are split because of performance issues
1281                         $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1282                         $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1283                         while ($contact = DBA::fetch($contacts)) {
1284                                 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1285                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1286                                 }
1287                         }
1288                         DBA::close($contacts);
1289                 }
1290                 return $receivers;
1291         }
1292
1293         /**
1294          * Tests if the contact is a valid receiver for this actor
1295          *
1296          * @param array  $contact
1297          * @param array  $tags
1298          *
1299          * @return bool with receivers (user id)
1300          * @throws \Exception
1301          */
1302         private static function isValidReceiverForActor(array $contact, array $tags): bool
1303         {
1304                 // Are we following the contact? Then this is a valid receiver
1305                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1306                         return true;
1307                 }
1308
1309                 // When the possible receiver isn't a community, then it is no valid receiver
1310                 $owner = User::getOwnerDataById($contact['uid']);
1311                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1312                         return false;
1313                 }
1314
1315                 // Is the community account tagged?
1316                 foreach ($tags as $tag) {
1317                         if ($tag['type'] != 'Mention') {
1318                                 continue;
1319                         }
1320
1321                         if (Strings::compareLink($tag['href'], $owner['url'])) {
1322                                 return true;
1323                         }
1324                 }
1325
1326                 return false;
1327         }
1328
1329         /**
1330          * Switches existing contacts to ActivityPub
1331          *
1332          * @param integer $cid Contact ID
1333          * @param integer $uid User ID
1334          * @param string  $url Profile URL
1335          * @return void
1336          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1337          * @throws \ImagickException
1338          */
1339         public static function switchContact(int $cid, int $uid, string $url)
1340         {
1341                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1342                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1343                         return;
1344                 }
1345
1346                 if (Contact::updateFromProbe($cid)) {
1347                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1348                 }
1349
1350                 // Send a new follow request to be sure that the connection still exists
1351                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1352                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1353                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1354                 }
1355         }
1356
1357         /**
1358          * @TODO Fix documentation and type-hints
1359          *
1360          * @param $receivers
1361          * @param $actor
1362          * @return void
1363          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1364          * @throws \ImagickException
1365          */
1366         private static function switchContacts($receivers, $actor)
1367         {
1368                 if (empty($actor)) {
1369                         return;
1370                 }
1371
1372                 foreach ($receivers as $receiver) {
1373                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1374                         if (DBA::isResult($contact)) {
1375                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
1376                         }
1377
1378                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1379                         if (DBA::isResult($contact)) {
1380                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
1381                         }
1382                 }
1383         }
1384
1385         /**
1386          * @TODO Fix documentation and type-hints
1387          *
1388          * @param       $object_data
1389          * @param array $activity
1390          *
1391          * @return mixed
1392          */
1393         private static function addActivityFields($object_data, array $activity)
1394         {
1395                 if (!empty($activity['published']) && empty($object_data['published'])) {
1396                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1397                 }
1398
1399                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1400                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1401                 }
1402
1403                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1404                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1405
1406                 if (!empty($object_data['object_id'])) {
1407                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1408                         $objectId = Item::getURIByLink($object_data['object_id']);
1409                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1410                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1411                                 $object_data['object_id'] = $objectId;
1412                         }
1413                 }
1414
1415                 return $object_data;
1416         }
1417
1418         /**
1419          * Fetches the object data from external resources if needed
1420          *
1421          * @param string  $object_id    Object ID of the provided object
1422          * @param array   $object       The provided object array
1423          * @param boolean $trust_source Do we trust the provided object?
1424          * @param integer $uid          User ID for the signature that we use to fetch data
1425          *
1426          * @return array|false with trusted and valid object data
1427          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1428          * @throws \ImagickException
1429          */
1430         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1431         {
1432                 // By fetching the type we check if the object is complete.
1433                 $type = JsonLD::fetchElement($object, '@type');
1434
1435                 if (!$trust_source || empty($type)) {
1436                         $data = Processor::fetchCachedActivity($object_id, $uid);
1437                         if (!empty($data)) {
1438                                 $object = JsonLD::compact($data);
1439                                 Logger::info('Fetched content for ' . $object_id);
1440                         } else {
1441                                 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1442
1443                                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1444                                 if (!DBA::isResult($item)) {
1445                                         Logger::info('Object with url ' . $object_id . ' was not found locally.');
1446                                         return false;
1447                                 }
1448                                 Logger::info('Using already stored item for url ' . $object_id);
1449                                 $data = ActivityPub\Transmitter::createNote($item);
1450                                 $object = JsonLD::compact($data);
1451                         }
1452
1453                         $id = JsonLD::fetchElement($object, '@id');
1454                         if (empty($id)) {
1455                                 Logger::info('Empty id');
1456                                 return false;
1457                         }
1458
1459                         if ($id != $object_id) {
1460                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1461                                 return false;
1462                         }
1463                 } else {
1464                         Logger::info('Using original object for url ' . $object_id);
1465                 }
1466
1467                 $type = JsonLD::fetchElement($object, '@type');
1468                 if (empty($type)) {
1469                         Logger::info('Empty type');
1470                         return false;
1471                 }
1472
1473                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1474                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1475                         $object_data = self::processObject($object, '');
1476
1477                         if (!empty($data)) {
1478                                 $object_data['raw-object'] = json_encode($data);
1479                         }
1480                         return $object_data;
1481                 }
1482
1483                 Logger::info('Unhandled object type: ' . $type);
1484                 return false;
1485         }
1486
1487         /**
1488          * Converts the language element (Used by Peertube)
1489          *
1490          * @param array $languages
1491          * @return array Languages
1492          */
1493         public static function processLanguages(array $languages): array
1494         {
1495                 if (empty($languages)) {
1496                         return [];
1497                 }
1498
1499                 $language_list = [];
1500
1501                 foreach ($languages as $language) {
1502                         if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1503                                 $language_list[$language['_:identifier']] = $language['as:name'];
1504                         }
1505                 }
1506                 return $language_list;
1507         }
1508
1509         /**
1510          * Convert tags from JSON-LD format into a simplified format
1511          *
1512          * @param array $tags Tags in JSON-LD format
1513          *
1514          * @return array with tags in a simplified format
1515          */
1516         public static function processTags(array $tags): array
1517         {
1518                 $taglist = [];
1519
1520                 foreach ($tags as $tag) {
1521                         if (empty($tag)) {
1522                                 continue;
1523                         }
1524
1525                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type') ?? ''),
1526                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1527                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1528
1529                         if (empty($element['type'])) {
1530                                 continue;
1531                         }
1532
1533                         if (empty($element['href'])) {
1534                                 $element['href'] = $element['name'];
1535                         }
1536
1537                         $taglist[] = $element;
1538                 }
1539                 return $taglist;
1540         }
1541
1542         /**
1543          * Convert emojis from JSON-LD format into a simplified format
1544          *
1545          * @param array $emojis
1546          * @return array with emojis in a simplified format
1547          */
1548         private static function processEmojis(array $emojis): array
1549         {
1550                 $emojilist = [];
1551
1552                 foreach ($emojis as $emoji) {
1553                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1554                                 continue;
1555                         }
1556
1557                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1558                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1559                                 'href' => $url];
1560
1561                         $emojilist[] = $element;
1562                 }
1563
1564                 return $emojilist;
1565         }
1566
1567         /**
1568          * Convert attachments from JSON-LD format into a simplified format
1569          *
1570          * @param array $attachments Attachments in JSON-LD format
1571          *
1572          * @return array Attachments in a simplified format
1573          */
1574         private static function processAttachments(array $attachments): array
1575         {
1576                 $attachlist = [];
1577
1578                 // Removes empty values
1579                 $attachments = array_filter($attachments);
1580
1581                 foreach ($attachments as $attachment) {
1582                         switch (JsonLD::fetchElement($attachment, '@type')) {
1583                                 case 'as:Page':
1584                                         $pageUrl = null;
1585                                         $pageImage = null;
1586
1587                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1588                                         foreach ($urls as $url) {
1589                                                 // Single scalar URL case
1590                                                 if (is_string($url)) {
1591                                                         $pageUrl = $url;
1592                                                         continue;
1593                                                 }
1594
1595                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1596                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1597                                                 if (Strings::startsWith($mediaType, 'image')) {
1598                                                         $pageImage = $href;
1599                                                 } else {
1600                                                         $pageUrl = $href;
1601                                                 }
1602                                         }
1603
1604                                         $attachlist[] = [
1605                                                 'type'  => 'link',
1606                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1607                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1608                                                 'url'   => $pageUrl,
1609                                                 'image' => $pageImage,
1610                                         ];
1611                                         break;
1612                                 case 'as:Image':
1613                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1614                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1615                                         $imagePreviewUrl = null;
1616                                         // Multiple URLs?
1617                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1618                                                 $imageVariants = [];
1619                                                 $previewVariants = [];
1620                                                 foreach ($urls as $url) {
1621                                                         // Scalar URL, no discrimination possible
1622                                                         if (is_string($url)) {
1623                                                                 $imageFullUrl = $url;
1624                                                                 continue;
1625                                                         }
1626
1627                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1628                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1629                                                                 continue;
1630                                                         }
1631
1632                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1633
1634                                                         // Default URL choice if no discriminating width is provided
1635                                                         $imageFullUrl = $href ?? $imageFullUrl;
1636
1637                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1638
1639                                                         if ($href && $width) {
1640                                                                 $imageVariants[$width] = $href;
1641                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1642                                                                 $previewVariants[abs(632 - $width)] = $href;
1643                                                         }
1644                                                 }
1645
1646                                                 if ($imageVariants) {
1647                                                         // Taking the maximum size image
1648                                                         ksort($imageVariants);
1649                                                         $imageFullUrl = array_pop($imageVariants);
1650
1651                                                         // Taking the minimum number distance to the target distance
1652                                                         ksort($previewVariants);
1653                                                         $imagePreviewUrl = array_shift($previewVariants);
1654                                                 }
1655
1656                                                 unset($imageVariants);
1657                                                 unset($previewVariants);
1658                                         }
1659
1660                                         $attachlist[] = [
1661                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1662                                                 'mediaType' => $mediaType,
1663                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1664                                                 'url'   => $imageFullUrl,
1665                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1666                                         ];
1667                                         break;
1668                                 default:
1669                                         $attachlist[] = [
1670                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1671                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1672                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1673                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id') ?? JsonLD::fetchElement($attachment, 'as:href', '@id'),
1674                                                 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1675                                                 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1676                                                 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1677                                         ];
1678                         }
1679                 }
1680
1681                 return $attachlist;
1682         }
1683
1684         /**
1685          * Convert questions from JSON-LD format into a simplified format
1686          *
1687          * @param array $object
1688          *
1689          * @return array Questions in a simplified format
1690          */
1691         private static function processQuestion(array $object): array
1692         {
1693                 $question = [];
1694
1695                 if (!empty($object['as:oneOf'])) {
1696                         $question['multiple'] = false;
1697                         $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1698                 } elseif (!empty($object['as:anyOf'])) {
1699                         $question['multiple'] = true;
1700                         $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1701                 } else {
1702                         return [];
1703                 }
1704
1705                 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1706                 if (!empty($closed)) {
1707                         $question['end-time'] = $closed;
1708                 } else {
1709                         $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1710                 }
1711
1712                 $question['voters']  = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1713                 $question['options'] = [];
1714
1715                 $voters = 0;
1716
1717                 foreach ($options as $option) {
1718                         if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1719                                 continue;
1720                         }
1721
1722                         $name = JsonLD::fetchElement($option, 'as:name', '@value');
1723
1724                         if (empty($option['as:replies'])) {
1725                                 continue;
1726                         }
1727
1728                         $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1729
1730                         $question['options'][] = ['name' => $name, 'replies' => $replies];
1731
1732                         $voters += (int)$replies;
1733                 }
1734
1735                 // For single choice question we can count the number of voters if not provided (like with Misskey)
1736                 if (empty($question['voters']) && !$question['multiple']) {
1737                         $question['voters'] = $voters;
1738                 }
1739
1740                 return $question;
1741         }
1742
1743         /**
1744          * Fetch the original source or content with the "language" Markdown or HTML
1745          *
1746          * @param array $object
1747          * @param array $object_data
1748          *
1749          * @return array Object data (?)
1750          * @throws \Exception
1751          */
1752         private static function getSource(array $object, array $object_data): array
1753         {
1754                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1755                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1756                 if (!empty($object_data['source'])) {
1757                         return $object_data;
1758                 }
1759
1760                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1761                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1762                 if (!empty($object_data['source'])) {
1763                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1764                         return $object_data;
1765                 }
1766
1767                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1768                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1769                 if (!empty($object_data['source'])) {
1770                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1771                         return $object_data;
1772                 }
1773
1774                 return $object_data;
1775         }
1776
1777         /**
1778          * Extracts a potential alternate URL from a list of additional URL elements
1779          *
1780          * @param array $urls
1781          * @return string
1782          */
1783         private static function extractAlternateUrl(array $urls): string
1784         {
1785                 $alternateUrl = '';
1786                 foreach ($urls as $key => $url) {
1787                         // Not a list but a single URL element
1788                         if (!is_numeric($key)) {
1789                                 continue;
1790                         }
1791
1792                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1793                                 continue;
1794                         }
1795
1796                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1797                         if (empty($href)) {
1798                                 continue;
1799                         }
1800
1801                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1802                         if (empty($mediatype)) {
1803                                 continue;
1804                         }
1805
1806                         if ($mediatype == 'text/html') {
1807                                 $alternateUrl = $href;
1808                         }
1809                 }
1810
1811                 return $alternateUrl;
1812         }
1813
1814         /**
1815          * Check if the "as:url" element is an array with multiple links
1816          * This is the case with audio and video posts.
1817          * Then the links are added as attachments
1818          *
1819          * @param array $urls The object URL list
1820          * @return array an array of attachments
1821          */
1822         private static function processAttachmentUrls(array $urls): array
1823         {
1824                 $attachments = [];
1825                 foreach ($urls as $key => $url) {
1826                         // Not a list but a single URL element
1827                         if (!is_numeric($key)) {
1828                                 continue;
1829                         }
1830
1831                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1832                                 continue;
1833                         }
1834
1835                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1836                         if (empty($href)) {
1837                                 continue;
1838                         }
1839
1840                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1841                         if (empty($mediatype)) {
1842                                 continue;
1843                         }
1844
1845                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1846
1847                         if ($filetype == 'audio') {
1848                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1849                         } elseif ($filetype == 'video') {
1850                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1851                                 // PeerTube audio-only track
1852                                 if ($height === 0) {
1853                                         continue;
1854                                 }
1855
1856                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1857                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1858                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1859                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1860
1861                                 // For Torrent links we always store the highest resolution
1862                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1863                                         continue;
1864                                 }
1865
1866                                 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1867                         } elseif ($mediatype == 'application/x-mpegURL') {
1868                                 // PeerTube exception, actual video link is in the tags of this URL element
1869                                 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1870                         }
1871                 }
1872
1873                 return array_values($attachments);
1874         }
1875
1876         /**
1877          * Fetches data from the object part of an activity
1878          *
1879          * @param array  $object
1880          * @param string $actor
1881          *
1882          * @return array|bool Object data or FALSE if $object does not contain @id element
1883          * @throws \Exception
1884          */
1885         private static function processObject(array $object, string $actor)
1886         {
1887                 if (!JsonLD::fetchElement($object, '@id')) {
1888                         return false;
1889                 }
1890
1891                 $object_data = self::getObjectDataFromActivity($object);
1892
1893                 $receiverdata = self::getReceivers($object, $actor ?: $object_data['actor'] ?? '', $object_data['tags'], true, false);
1894                 $receivers = $reception_types = [];
1895                 foreach ($receiverdata as $key => $data) {
1896                         $receivers[$key] = $data['uid'];
1897                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1898                 }
1899
1900                 $object_data['receiver_urls']  = self::getReceiverURL($object);
1901                 $object_data['receiver']       = $receivers;
1902                 $object_data['reception_type'] = $reception_types;
1903
1904                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1905                 unset($object_data['receiver'][-1]);
1906                 unset($object_data['reception_type'][-1]);
1907
1908                 return $object_data;
1909         }
1910
1911         /**
1912          * Create an object data array from a given activity
1913          *
1914          * @param array $object
1915          *
1916          * @return array Object data
1917          */
1918         public static function getObjectDataFromActivity(array $object): array
1919         {
1920                 $object_data = [];
1921                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1922                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1923                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1924
1925                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1926                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1927                         $object_data['reply-to-id'] = $object_data['id'];
1928
1929                         // On activities the "reply to" is the id of the object it refers to
1930                         if (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce']))) {
1931                                 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1932                                 if (!empty($object_id)) {
1933                                         $object_data['reply-to-id'] = $object_id;
1934                                 }
1935                         }
1936                 } else {
1937                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1938                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1939                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1940                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1941                                 $object_data['reply-to-id'] = $replyToId;
1942                         }
1943                 }
1944
1945                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1946                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1947
1948                 if (empty($object_data['updated'])) {
1949                         $object_data['updated'] = $object_data['published'];
1950                 }
1951
1952                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1953                         $object_data['published'] = $object_data['updated'];
1954                 }
1955
1956                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1957                 if (empty($actor)) {
1958                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1959                 }
1960
1961                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1962                 $location = JsonLD::fetchElement($location, 'location', '@value');
1963                 if ($location) {
1964                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1965                         // down to HTML and then finally format to plaintext.
1966                         $location = Markdown::convert($location);
1967                         $location = BBCode::toPlaintext($location);
1968                 }
1969
1970                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1971                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1972                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1973                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1974                 $object_data['actor'] = $object_data['author'] = $actor;
1975                 $element = JsonLD::fetchElement($object, 'as:context', '@id');
1976                 $object_data['context'] = $element != './' ? $element : null;
1977                 $element = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1978                 $object_data['conversation'] = $element != './' ? $element : null;
1979                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1980                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1981                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1982                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1983                 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1984                 $object_data = self::getSource($object, $object_data);
1985                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1986                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1987                 $object_data['location'] = $location;
1988                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1989                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1990                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1991                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1992                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1993                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1994                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1995                 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1996                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1997                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1998                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1999
2000                 // Special treatment for Hubzilla links
2001                 if (is_array($object_data['alternate-url'])) {
2002                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
2003
2004                         if (!is_string($object_data['alternate-url'])) {
2005                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
2006                         }
2007                 }
2008
2009                 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
2010                         $object_data['alternate-url'] = null;
2011                 }
2012
2013                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
2014                         $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
2015                         $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
2016                 }
2017
2018                 // Support for quoted posts (Pleroma, Fedibird and Misskey)
2019                 $object_data['quote-url'] = JsonLD::fetchElement($object, 'as:quoteUrl', '@value');
2020                 if (empty($object_data['quote-url'])) {
2021                         $object_data['quote-url'] = JsonLD::fetchElement($object, 'fedibird:quoteUri', '@value');
2022                 }
2023                 if (empty($object_data['quote-url'])) {
2024                         $object_data['quote-url'] = JsonLD::fetchElement($object, 'misskey:_misskey_quote', '@value');
2025                 }
2026
2027                 // Misskey adds some data to the standard "content" value for quoted posts for backwards compatibility.
2028                 // Their own "_misskey_content" value does then contain the content without this extra data.
2029                 if (!empty($object_data['quote-url'])) {
2030                         $misskey_content = JsonLD::fetchElement($object, 'misskey:_misskey_content', '@value');
2031                         if (!empty($misskey_content)) {
2032                                 $object_data['content'] = $misskey_content;
2033                         }
2034                 }
2035
2036                 // For page types we expect that the alternate url posts to some page.
2037                 // So we add this to the attachments if it differs from the id.
2038                 // Currently only Lemmy is using the page type.
2039                 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
2040                         $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
2041                         $object_data['alternate-url'] = null;
2042                 }
2043
2044                 if ($object_data['object_type'] == 'as:Question') {
2045                         $object_data['question'] = self::processQuestion($object);
2046                 }
2047
2048                 return $object_data;
2049         }
2050
2051         /**
2052          * Add an object id to the list of arrived activities
2053          *
2054          * @param string $id
2055          *
2056          * @return void
2057          */
2058         private static function addArrivedId(string $id)
2059         {
2060                 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
2061                 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
2062         }
2063
2064         /**
2065          * Checks if the given object already arrived before
2066          *
2067          * @param string $id
2068          *
2069          * @return boolean
2070          */
2071         private static function hasArrived(string $id): bool
2072         {
2073                 return DBA::exists('arrived-activity', ['object-id' => $id]);
2074         }
2075 }