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