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