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