]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
3c0f4862e6d212475771012f3a4d62ce23b30847
[friendica.git] / src / Protocol / ActivityPub / Receiver.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Model\Contact;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Item;
33 use Friendica\Model\User;
34 use Friendica\Protocol\Activity;
35 use Friendica\Protocol\ActivityPub;
36 use Friendica\Util\HTTPSignature;
37 use Friendica\Util\JsonLD;
38 use Friendica\Util\LDSignature;
39 use Friendica\Util\Strings;
40
41 /**
42  * ActivityPub Receiver Protocol class
43  *
44  * To-Do:
45  * @todo Undo Announce
46  *
47  * Check what this is meant to do:
48  * - Add
49  * - Block
50  * - Flag
51  * - Remove
52  * - Undo Block
53  */
54 class Receiver
55 {
56         const PUBLIC_COLLECTION = 'as:Public';
57         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
58         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio'];
59         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
60
61         const TARGET_UNKNOWN = 0;
62         const TARGET_TO = 1;
63         const TARGET_CC = 2;
64         const TARGET_BTO = 3;
65         const TARGET_BCC = 4;
66         const TARGET_FOLLOWER = 5;
67         const TARGET_ANSWER = 6;
68         const TARGET_GLOBAL = 7;
69
70         /**
71          * Checks if the web request is done for the AP protocol
72          *
73          * @return bool is it AP?
74          */
75         public static function isRequest()
76         {
77                 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
78                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
79         }
80
81         /**
82          * Checks incoming message from the inbox
83          *
84          * @param         $body
85          * @param         $header
86          * @param integer $uid User ID
87          * @throws \Exception
88          */
89         public static function processInbox($body, $header, $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                 if (!empty($apcontact) && ($apcontact['type'] == 'Application') && ($apcontact['nick'] == 'relay')) {
103                         self::processRelayPost($ldactivity, $actor);
104                         return;
105                 }
106
107                 $http_signer = HTTPSignature::getSigner($body, $header);
108                 if (empty($http_signer)) {
109                         Logger::warning('Invalid HTTP signature, message will be discarded.');
110                         return;
111                 } else {
112                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
113                 }
114
115                 $signer = [$http_signer];
116
117                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
118
119                 if (LDSignature::isSigned($activity)) {
120                         $ld_signer = LDSignature::getSigner($activity);
121                         if (empty($ld_signer)) {
122                                 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
123                         } elseif ($ld_signer != $http_signer) {
124                                 $signer[] = $ld_signer;
125                         }
126                         if (!empty($ld_signer && ($actor == $http_signer))) {
127                                 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
128                                 $trust_source = true;
129                         } elseif (!empty($ld_signer)) {
130                                 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
131                                 $trust_source = true;
132                         } elseif ($actor == $http_signer) {
133                                 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
134                                 $trust_source = true;
135                         } else {
136                                 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
137                                 $trust_source = false;
138                         }
139                 } elseif ($actor == $http_signer) {
140                         Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
141                         $trust_source = true;
142                 } else {
143                         Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
144                         $trust_source = false;
145                 }
146
147                 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
148         }
149
150         /**
151          * Process incoming posts from relays
152          *
153          * @param array  $activity
154          * @param string $actor
155          * @return void
156          */
157         private static function processRelayPost(array $activity, string $actor)
158         {
159                 $type = JsonLD::fetchElement($activity, '@type');
160                 if (!$type) {
161                         Logger::info('Empty type', ['activity' => $activity]);
162                         return;
163                 }
164
165                 if ($type != 'as:Announce') {
166                         Logger::info('Not an announcement', ['activity' => $activity]);
167                         return;
168                 }
169
170                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
171                 if (empty($object_id)) {
172                         Logger::info('No object id found', ['activity' => $activity]);
173                         return;
174                 }
175
176                 $contact = Contact::getByURL($actor);
177                 if (empty($contact)) {
178                         Logger::info('Relay contact not found', ['actor' => $actor]);
179                         return;
180                 }
181
182                 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
183                         Logger::notice('Relay is no sharer', ['actor' => $actor]);
184                         return;
185                 }
186
187                 Logger::info('Got relayed message id', ['id' => $object_id]);
188
189                 $item_id = Item::searchByLink($object_id);
190                 if ($item_id) {
191                         Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
192                         return;
193                 }
194
195                 $id = Processor::fetchMissingActivity($object_id, [], $actor);
196                 if (empty($id)) {
197                         Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
198                         return;
199                 }
200
201                 $item_id = Item::searchByLink($object_id);
202                 if ($item_id) {
203                         Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
204                 } else {
205                         Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
206                 }
207         }
208
209         /**
210          * Fetches the object type for a given object id
211          *
212          * @param array   $activity
213          * @param string  $object_id Object ID of the the provided object
214          * @param integer $uid       User ID
215          *
216          * @return string with object type
217          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218          * @throws \ImagickException
219          */
220         private static function fetchObjectType($activity, $object_id, $uid = 0)
221         {
222                 if (!empty($activity['as:object'])) {
223                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
224                         if (!empty($object_type)) {
225                                 return $object_type;
226                         }
227                 }
228
229                 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
230                         // We just assume "note" since it doesn't make a difference for the further processing
231                         return 'as:Note';
232                 }
233
234                 $profile = APContact::getByURL($object_id);
235                 if (!empty($profile['type'])) {
236                         return 'as:' . $profile['type'];
237                 }
238
239                 $data = ActivityPub::fetchContent($object_id, $uid);
240                 if (!empty($data)) {
241                         $object = JsonLD::compact($data);
242                         $type = JsonLD::fetchElement($object, '@type');
243                         if (!empty($type)) {
244                                 return $type;
245                         }
246                 }
247
248                 return null;
249         }
250
251         /**
252          * Prepare the object array
253          *
254          * @param array   $activity     Array with activity data
255          * @param integer $uid          User ID
256          * @param boolean $push         Message had been pushed to our system
257          * @param boolean $trust_source Do we trust the source?
258          *
259          * @return array with object data
260          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
261          * @throws \ImagickException
262          */
263         public static function prepareObjectData($activity, $uid, $push, &$trust_source)
264         {
265                 $id = JsonLD::fetchElement($activity, '@id');
266                 if (!empty($id) && !$trust_source) {
267                         $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
268                         if (!empty($fetched_activity)) {
269                                 $object = JsonLD::compact($fetched_activity);
270                                 $fetched_id = JsonLD::fetchElement($object, '@id');
271                                 if ($fetched_id == $id) {
272                                         Logger::info('Activity had been fetched successfully', ['id' => $id]);
273                                         $trust_source = true;
274                                         $activity = $object;
275                                 } else {
276                                         Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
277                                 }
278                         } else {
279                                 Logger::info('Activity could not been fetched', ['id' => $id]);
280                         }
281                 }
282
283                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
284                 if (empty($actor)) {
285                         Logger::info('Empty actor', ['activity' => $activity]);
286                         return [];
287                 }
288
289                 $type = JsonLD::fetchElement($activity, '@type');
290
291                 // Fetch all receivers from to, cc, bto and bcc
292                 $receiverdata = self::getReceivers($activity, $actor);
293                 $receivers = $reception_types = [];
294                 foreach ($receiverdata as $key => $data) {
295                         $receivers[$key] = $data['uid'];
296                         $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
297                 }
298
299                 // When it is a delivery to a personal inbox we add that user to the receivers
300                 if (!empty($uid)) {
301                         $additional = [$uid => $uid];
302                         $receivers = array_replace($receivers, $additional);
303                         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]))) {
304                                 $reception_types[$uid] = self::TARGET_BCC;
305                         }
306                 } else {
307                         // We possibly need some user to fetch private content,
308                         // so we fetch the first out ot the list.
309                         $uid = self::getFirstUserFromReceivers($receivers);
310                 }
311
312                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
313                 if (empty($object_id)) {
314                         Logger::log('No object found', Logger::DEBUG);
315                         return [];
316                 }
317
318                 if (!is_string($object_id)) {
319                         Logger::info('Invalid object id', ['object' => $object_id]);
320                         return [];
321                 }
322
323                 $object_type = self::fetchObjectType($activity, $object_id, $uid);
324
325                 // Fetch the content only on activities where this matters
326                 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
327                         // Always fetch on "Announce"
328                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
329                         if (empty($object_data)) {
330                                 Logger::log("Object data couldn't be processed", Logger::DEBUG);
331                                 return [];
332                         }
333
334                         $object_data['object_id'] = $object_id;
335
336                         if ($type == 'as:Announce') {
337                                 $object_data['push'] = false;
338                         } else {
339                                 $object_data['push'] = $push;
340                         }
341
342                         // Test if it is an answer to a mail
343                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
344                                 $object_data['directmessage'] = true;
345                         } else {
346                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
347                         }
348                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
349                         // Create a mostly empty array out of the activity data (instead of the object).
350                         // This way we later don't have to check for the existence of ech individual array element.
351                         $object_data = self::processObject($activity);
352                         $object_data['name'] = $type;
353                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
354                         $object_data['object_id'] = $object_id;
355                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
356                 } elseif (in_array($type, ['as:Add'])) {
357                         $object_data = [];
358                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
359                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
360                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
361                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
362                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
363                 } else {
364                         $object_data = [];
365                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
366                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
367                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
368                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
369                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
370
371                         // An Undo is done on the object of an object, so we need that type as well
372                         if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
373                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
374                         }
375                 }
376
377                 $object_data = self::addActivityFields($object_data, $activity);
378
379                 if (empty($object_data['object_type'])) {
380                         $object_data['object_type'] = $object_type;
381                 }
382
383                 $object_data['type'] = $type;
384                 $object_data['actor'] = $actor;
385                 $object_data['item_receiver'] = $receivers;
386                 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
387                 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
388
389                 $author = $object_data['author'] ?? $actor;
390                 if (!empty($author) && !empty($object_data['id'])) {
391                         $author_host = parse_url($author, PHP_URL_HOST);
392                         $id_host = parse_url($object_data['id'], PHP_URL_HOST);
393                         if ($author_host == $id_host) {
394                                 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
395                         } else {
396                                 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
397                                 $trust_source = false;
398                         }
399                 }
400
401                 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
402
403                 return $object_data;
404         }
405
406         /**
407          * Fetches the first user id from the receiver array
408          *
409          * @param array $receivers Array with receivers
410          * @return integer user id;
411          */
412         public static function getFirstUserFromReceivers($receivers)
413         {
414                 foreach ($receivers as $receiver) {
415                         if (!empty($receiver)) {
416                                 return $receiver;
417                         }
418                 }
419                 return 0;
420         }
421
422         /**
423          * Processes the activity object
424          *
425          * @param array   $activity     Array with activity data
426          * @param string  $body
427          * @param integer $uid          User ID
428          * @param boolean $trust_source Do we trust the source?
429          * @param boolean $push         Message had been pushed to our system
430          * @throws \Exception
431          */
432         public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
433         {
434                 $type = JsonLD::fetchElement($activity, '@type');
435                 if (!$type) {
436                         Logger::info('Empty type', ['activity' => $activity]);
437                         return;
438                 }
439
440                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
441                         Logger::info('Empty object', ['activity' => $activity]);
442                         return;
443                 }
444
445                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
446                 if (empty($actor)) {
447                         Logger::info('Empty actor', ['activity' => $activity]);
448                         return;
449                 }
450
451                 if (is_array($activity['as:object'])) {
452                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
453                 } else {
454                         $attributed_to = '';
455                 }
456
457                 // Test the provided signatures against the actor and "attributedTo"
458                 if ($trust_source) {
459                         if (!empty($attributed_to) && !empty($actor)) {
460                                 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
461                         } else {
462                                 $trust_source = in_array($actor, $signer);
463                         }
464                 }
465
466                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
467                 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
468                 if (empty($object_data)) {
469                         Logger::info('No object data found', ['activity' => $activity]);
470                         return;
471                 }
472
473                 if (!$trust_source) {
474                         Logger::info('Activity trust could not be achieved.',  ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
475                         return;
476                 }
477
478                 if (!empty($body) && empty($object_data['raw'])) {
479                         $object_data['raw'] = $body;
480                 }
481
482                 // Internal flag for thread completion. See Processor.php
483                 if (!empty($activity['thread-completion'])) {
484                         $object_data['thread-completion'] = $activity['thread-completion'];
485                 }
486
487                 // Internal flag for posts that arrived via relay
488                 if (!empty($activity['from-relay'])) {
489                         $object_data['from-relay'] = $activity['from-relay'];
490                 }
491                 
492                 switch ($type) {
493                         case 'as:Create':
494                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
495                                         $item = ActivityPub\Processor::createItem($object_data);
496                                         ActivityPub\Processor::postItem($object_data, $item);
497                                 }
498                                 break;
499
500                         case 'as:Add':
501                                 if ($object_data['object_type'] == 'as:tag') {
502                                         ActivityPub\Processor::addTag($object_data);
503                                 }
504                                 break;
505
506                         case 'as:Announce':
507                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
508                                         $object_data['thread-completion'] = Contact::getIdForURL($actor);
509
510                                         $item = ActivityPub\Processor::createItem($object_data);
511                                         if (empty($item)) {
512                                                 return;
513                                         }
514
515                                         $item['post-type'] = Item::PT_ANNOUNCEMENT;
516                                         ActivityPub\Processor::postItem($object_data, $item);
517
518                                         $announce_object_data = self::processObject($activity);
519                                         $announce_object_data['name'] = $type;
520                                         $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
521                                         $announce_object_data['object_id'] = $object_data['object_id'];
522                                         $announce_object_data['object_type'] = $object_data['object_type'];
523                                         $announce_object_data['push'] = $push;
524
525                                         if (!empty($body)) {
526                                                 $announce_object_data['raw'] = $body;
527                                         }
528
529                                         ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
530                                 }
531                                 break;
532
533                         case 'as:Like':
534                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
535                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
536                                 }
537                                 break;
538
539                         case 'as:Dislike':
540                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
541                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
542                                 }
543                                 break;
544
545                         case 'as:TentativeAccept':
546                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
547                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
548                                 }
549                                 break;
550
551                         case 'as:Update':
552                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
553                                         ActivityPub\Processor::updateItem($object_data);
554                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
555                                         ActivityPub\Processor::updatePerson($object_data);
556                                 }
557                                 break;
558
559                         case 'as:Delete':
560                                 if ($object_data['object_type'] == 'as:Tombstone') {
561                                         ActivityPub\Processor::deleteItem($object_data);
562                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
563                                         ActivityPub\Processor::deletePerson($object_data);
564                                 }
565                                 break;
566
567                         case 'as:Follow':
568                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
569                                         ActivityPub\Processor::followUser($object_data);
570                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
571                                         $object_data['reply-to-id'] = $object_data['object_id'];
572                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
573                                 }
574                                 break;
575
576                         case 'as:Accept':
577                                 if ($object_data['object_type'] == 'as:Follow') {
578                                         ActivityPub\Processor::acceptFollowUser($object_data);
579                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
580                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
581                                 }
582                                 break;
583
584                         case 'as:Reject':
585                                 if ($object_data['object_type'] == 'as:Follow') {
586                                         ActivityPub\Processor::rejectFollowUser($object_data);
587                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
588                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
589                                 }
590                                 break;
591
592                         case 'as:Undo':
593                                 if (($object_data['object_type'] == 'as:Follow') &&
594                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
595                                         ActivityPub\Processor::undoFollowUser($object_data);
596                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
597                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
598                                         ActivityPub\Processor::rejectFollowUser($object_data);
599                                 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
600                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
601                                         ActivityPub\Processor::undoActivity($object_data);
602                                 }
603                                 break;
604
605                         default:
606                                 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
607                                 break;
608                 }
609         }
610
611         /**
612          * Fetch the receiver list from an activity array
613          *
614          * @param array   $activity
615          * @param string  $actor
616          * @param array   $tags
617          * @param boolean $fetch_unlisted 
618          *
619          * @return array with receivers (user id)
620          * @throws \Exception
621          */
622         private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
623         {
624                 $reply = $receivers = [];
625
626                 // When it is an answer, we inherite the receivers from the parent
627                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
628                 if (!empty($replyto)) {
629                         $reply = [$replyto];
630
631                         // Fix possibly wrong item URI (could be an answer to a plink uri)
632                         $fixedReplyTo = Item::getURIByLink($replyto);
633                         if (!empty($fixedReplyTo)) {
634                                 $reply[] = $fixedReplyTo;
635                         }
636                 }
637
638                 // Fetch all posts that refer to the object id
639                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
640                 if (!empty($object_id)) {
641                         $reply[] = $object_id;
642                 }
643
644                 if (!empty($reply)) {
645                         $parents = Item::select(['uid'], ['uri' => $reply]);
646                         while ($parent = Item::fetch($parents)) {
647                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
648                         }
649                 }
650
651                 if (!empty($actor)) {
652                         $profile = APContact::getByURL($actor);
653                         $followers = $profile['followers'] ?? '';
654
655                         Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
656                 } else {
657                         Logger::info('Empty actor', ['activity' => $activity]);
658                         $followers = '';
659                 }
660
661                 // We have to prevent false follower assumptions upon thread completions
662                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
663
664                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
665                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
666                         if (empty($receiver_list)) {
667                                 continue;
668                         }
669
670                         foreach ($receiver_list as $receiver) {
671                                 if ($receiver == self::PUBLIC_COLLECTION) {
672                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
673                                 }
674
675                                 // Add receiver "-1" for unlisted posts 
676                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
677                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
678                                 }
679
680                                 // Fetch the receivers for the public and the followers collection
681                                 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
682                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
683                                         continue;
684                                 }
685
686                                 // Fetching all directly addressed receivers
687                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
688                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
689                                 if (!DBA::isResult($contact)) {
690                                         continue;
691                                 }
692
693                                 // Check if the potential receiver is following the actor
694                                 // Exception: The receiver is targetted via "to" or this is a comment
695                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
696                                         $networks = Protocol::FEDERATED;
697                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
698                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
699
700                                         // Forum posts are only accepted from forum contacts
701                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
702                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
703                                         }
704
705                                         if (!DBA::exists('contact', $condition)) {
706                                                 continue;
707                                         }
708                                 }
709
710                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
711                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
712                                         switch ($element) {
713                                                 case 'as:to':
714                                                         $type = self::TARGET_TO;
715                                                         break;
716                                                 case 'as:cc':
717                                                         $type = self::TARGET_CC;
718                                                         break;
719                                                 case 'as:bto':
720                                                         $type = self::TARGET_BTO;
721                                                         break;
722                                                 case 'as:bcc':
723                                                         $type = self::TARGET_BCC;
724                                                         break;
725                                         }
726
727                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
728                                 }
729                         }
730                 }
731
732                 self::switchContacts($receivers, $actor);
733
734                 return $receivers;
735         }
736
737         /**
738          * Fetch the receiver list of a given actor
739          *
740          * @param string  $actor
741          * @param array   $tags
742          * @param array   $receivers
743          * @param integer $target_type
744          *
745          * @return array with receivers (user id)
746          * @throws \Exception
747          */
748         private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
749         {
750                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
751                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
752
753                 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
754                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
755                 while ($contact = DBA::fetch($contacts)) {
756                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
757                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
758                         }
759                 }
760                 DBA::close($contacts);
761
762                 // The queries are split because of performance issues
763                 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
764                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
765                 while ($contact = DBA::fetch($contacts)) {
766                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
767                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
768                         }
769                 }
770                 DBA::close($contacts);
771                 return $receivers;
772         }
773
774         /**
775          * Tests if the contact is a valid receiver for this actor
776          *
777          * @param array  $contact
778          * @param string $actor
779          * @param array  $tags
780          *
781          * @return bool with receivers (user id)
782          * @throws \Exception
783          */
784         private static function isValidReceiverForActor($contact, $tags)
785         {
786                 // Are we following the contact? Then this is a valid receiver
787                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
788                         return true;
789                 }
790
791                 // When the possible receiver isn't a community, then it is no valid receiver
792                 $owner = User::getOwnerDataById($contact['uid']);
793                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
794                         return false;
795                 }
796
797                 // Is the community account tagged?
798                 foreach ($tags as $tag) {
799                         if ($tag['type'] != 'Mention') {
800                                 continue;
801                         }
802
803                         if (Strings::compareLink($tag['href'], $owner['url'])) {
804                                 return true;
805                         }
806                 }
807
808                 return false;
809         }
810
811         /**
812          * Switches existing contacts to ActivityPub
813          *
814          * @param integer $cid Contact ID
815          * @param integer $uid User ID
816          * @param string  $url Profile URL
817          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818          * @throws \ImagickException
819          */
820         public static function switchContact($cid, $uid, $url)
821         {
822                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
823                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
824                         return;
825                 }
826
827                 if (Contact::updateFromProbe($cid)) {
828                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
829                 }
830
831                 // Send a new follow request to be sure that the connection still exists
832                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
833                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
834                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
835                 }
836         }
837
838         /**
839          *
840          *
841          * @param $receivers
842          * @param $actor
843          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
844          * @throws \ImagickException
845          */
846         private static function switchContacts($receivers, $actor)
847         {
848                 if (empty($actor)) {
849                         return;
850                 }
851
852                 foreach ($receivers as $receiver) {
853                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
854                         if (DBA::isResult($contact)) {
855                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
856                         }
857
858                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
859                         if (DBA::isResult($contact)) {
860                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
861                         }
862                 }
863         }
864
865         /**
866          *
867          *
868          * @param       $object_data
869          * @param array $activity
870          *
871          * @return mixed
872          */
873         private static function addActivityFields($object_data, $activity)
874         {
875                 if (!empty($activity['published']) && empty($object_data['published'])) {
876                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
877                 }
878
879                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
880                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
881                 }
882
883                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
884                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
885
886                 if (!empty($object_data['object_id'])) {
887                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
888                         $objectId = Item::getURIByLink($object_data['object_id']);
889                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
890                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
891                                 $object_data['object_id'] = $objectId;
892                         }
893                 }
894
895                 return $object_data;
896         }
897
898         /**
899          * Fetches the object data from external ressources if needed
900          *
901          * @param string  $object_id    Object ID of the the provided object
902          * @param array   $object       The provided object array
903          * @param boolean $trust_source Do we trust the provided object?
904          * @param integer $uid          User ID for the signature that we use to fetch data
905          *
906          * @return array|false with trusted and valid object data
907          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908          * @throws \ImagickException
909          */
910         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
911         {
912                 // By fetching the type we check if the object is complete.
913                 $type = JsonLD::fetchElement($object, '@type');
914
915                 if (!$trust_source || empty($type)) {
916                         $data = ActivityPub::fetchContent($object_id, $uid);
917                         if (!empty($data)) {
918                                 $object = JsonLD::compact($data);
919                                 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
920                         } else {
921                                 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
922
923                                 $item = Item::selectFirst([], ['uri' => $object_id]);
924                                 if (!DBA::isResult($item)) {
925                                         Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
926                                         return false;
927                                 }
928                                 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
929                                 $data = ActivityPub\Transmitter::createNote($item);
930                                 $object = JsonLD::compact($data);
931                         }
932
933                         $id = JsonLD::fetchElement($object, '@id');
934                         if (empty($id)) {
935                                 Logger::info('Empty id');
936                                 return false;
937                         }
938         
939                         if ($id != $object_id) {
940                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
941                                 return false;
942                         }
943                 } else {
944                         Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
945                 }
946
947                 $type = JsonLD::fetchElement($object, '@type');
948                 if (empty($type)) {
949                         Logger::info('Empty type');
950                         return false;
951                 }
952
953                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
954                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
955                         $object_data = self::processObject($object);
956
957                         if (!empty($data)) {
958                                 $object_data['raw'] = json_encode($data);
959                         }
960                         return $object_data;
961                 }
962
963                 if ($type == 'as:Announce') {
964                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
965                         if (empty($object_id) || !is_string($object_id)) {
966                                 return false;
967                         }
968                         return self::fetchObject($object_id, [], false, $uid);
969                 }
970
971                 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
972                 return false;
973         }
974
975         /**
976          * Convert tags from JSON-LD format into a simplified format
977          *
978          * @param array $tags Tags in JSON-LD format
979          *
980          * @return array with tags in a simplified format
981          */
982         public static function processTags(array $tags)
983         {
984                 $taglist = [];
985
986                 foreach ($tags as $tag) {
987                         if (empty($tag)) {
988                                 continue;
989                         }
990
991                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
992                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
993                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
994
995                         if (empty($element['type'])) {
996                                 continue;
997                         }
998
999                         if (empty($element['href'])) {
1000                                 $element['href'] = $element['name'];
1001                         }
1002
1003                         $taglist[] = $element;
1004                 }
1005                 return $taglist;
1006         }
1007
1008         /**
1009          * Convert emojis from JSON-LD format into a simplified format
1010          *
1011          * @param array $emojis
1012          * @return array with emojis in a simplified format
1013          */
1014         private static function processEmojis(array $emojis)
1015         {
1016                 $emojilist = [];
1017
1018                 foreach ($emojis as $emoji) {
1019                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1020                                 continue;
1021                         }
1022
1023                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1024                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1025                                 'href' => $url];
1026
1027                         $emojilist[] = $element;
1028                 }
1029
1030                 return $emojilist;
1031         }
1032
1033         /**
1034          * Convert attachments from JSON-LD format into a simplified format
1035          *
1036          * @param array $attachments Attachments in JSON-LD format
1037          *
1038          * @return array Attachments in a simplified format
1039          */
1040         private static function processAttachments(array $attachments)
1041         {
1042                 $attachlist = [];
1043
1044                 // Removes empty values
1045                 $attachments = array_filter($attachments);
1046
1047                 foreach ($attachments as $attachment) {
1048                         switch (JsonLD::fetchElement($attachment, '@type')) {
1049                                 case 'as:Page':
1050                                         $pageUrl = null;
1051                                         $pageImage = null;
1052
1053                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1054                                         foreach ($urls as $url) {
1055                                                 // Single scalar URL case
1056                                                 if (is_string($url)) {
1057                                                         $pageUrl = $url;
1058                                                         continue;
1059                                                 }
1060
1061                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1062                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1063                                                 if (Strings::startsWith($mediaType, 'image')) {
1064                                                         $pageImage = $href;
1065                                                 } else {
1066                                                         $pageUrl = $href;
1067                                                 }
1068                                         }
1069
1070                                         $attachlist[] = [
1071                                                 'type'  => 'link',
1072                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1073                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1074                                                 'url'   => $pageUrl,
1075                                                 'image' => $pageImage,
1076                                         ];
1077                                         break;
1078                                 case 'as:Link':
1079                                         $attachlist[] = [
1080                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1081                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1082                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1083                                                 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1084                                         ];
1085                                         break;
1086                                 case 'as:Image':
1087                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1088                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1089                                         $imagePreviewUrl = null;
1090                                         // Multiple URLs?
1091                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1092                                                 $imageVariants = [];
1093                                                 $previewVariants = [];
1094                                                 foreach ($urls as $url) {
1095                                                         // Scalar URL, no discrimination possible
1096                                                         if (is_string($url)) {
1097                                                                 $imageFullUrl = $url;
1098                                                                 continue;
1099                                                         }
1100
1101                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1102                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1103                                                                 continue;
1104                                                         }
1105
1106                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1107
1108                                                         // Default URL choice if no discriminating width is provided
1109                                                         $imageFullUrl = $href ?? $imageFullUrl;
1110
1111                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1112
1113                                                         if ($href && $width) {
1114                                                                 $imageVariants[$width] = $href;
1115                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1116                                                                 $previewVariants[abs(632 - $width)] = $href;
1117                                                         }
1118                                                 }
1119
1120                                                 if ($imageVariants) {
1121                                                         // Taking the maximum size image
1122                                                         ksort($imageVariants);
1123                                                         $imageFullUrl = array_pop($imageVariants);
1124
1125                                                         // Taking the minimum number distance to the target distance
1126                                                         ksort($previewVariants);
1127                                                         $imagePreviewUrl = array_shift($previewVariants);
1128                                                 }
1129
1130                                                 unset($imageVariants);
1131                                                 unset($previewVariants);
1132                                         }
1133
1134                                         $attachlist[] = [
1135                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1136                                                 'mediaType' => $mediaType,
1137                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1138                                                 'url'   => $imageFullUrl,
1139                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1140                                         ];
1141                                         break;
1142                                 default:
1143                                         $attachlist[] = [
1144                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1145                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1146                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1147                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1148                                         ];
1149                         }
1150                 }
1151
1152                 return $attachlist;
1153         }
1154
1155         /**
1156          * Fetch the original source or content with the "language" Markdown or HTML
1157          *
1158          * @param array $object
1159          * @param array $object_data
1160          *
1161          * @return array
1162          * @throws \Exception
1163          */
1164         private static function getSource($object, $object_data)
1165         {
1166                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1167                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1168                 if (!empty($object_data['source'])) {
1169                         return $object_data;
1170                 }
1171
1172                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1173                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1174                 if (!empty($object_data['source'])) {
1175                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1176                         return $object_data;
1177                 }
1178
1179                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1180                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1181                 if (!empty($object_data['source'])) {
1182                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1183                         return $object_data;
1184                 }
1185
1186                 return $object_data;
1187         }
1188
1189         /**
1190          * Check if the "as:url" element is an array with multiple links
1191          * This is the case with audio and video posts.
1192          * Then the links are added as attachments
1193          *
1194          * @param array $object      The raw object
1195          * @param array $object_data The parsed object data for later processing
1196          * @return array the object data
1197          */
1198         private static function processAttachmentUrls(array $object, array $object_data) {
1199                 // Check if this is some url with multiple links
1200                 if (empty($object['as:url'])) {
1201                         return $object_data;
1202                 }
1203                 
1204                 $urls = $object['as:url'];
1205                 $keys = array_keys($urls);
1206                 if (!is_numeric(array_pop($keys))) {
1207                         return $object_data;
1208                 }
1209
1210                 $attachments = [];
1211
1212                 foreach ($urls as $url) {
1213                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1214                                 continue;
1215                         }
1216
1217                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1218                         if (empty($href)) {
1219                                 continue;
1220                         }
1221
1222                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1223                         if (empty($mediatype)) {
1224                                 continue;
1225                         }
1226
1227                         if ($mediatype == 'text/html') {
1228                                 $object_data['alternate-url'] = $href;
1229                         }
1230
1231                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1232
1233                         if ($filetype == 'audio') {
1234                                 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1235                         } elseif ($filetype == 'video') {
1236                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1237                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1238
1239                                 // We save bandwidth by using a moderate height (alt least 480 pixel height)
1240                                 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1241                                 if (!empty($attachments[$filetype]['height']) &&
1242                                         ($height > $attachments[$filetype]['height']) && ($attachments[$filetype]['height'] >= 480)) {
1243                                         continue;
1244                                 }
1245
1246                                 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1247                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1248                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1249
1250                                 // For Torrent links we always store the highest resolution
1251                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1252                                         continue;
1253                                 }
1254
1255                                 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1256                         }
1257                 }
1258
1259                 foreach ($attachments as $type => $attachment) {
1260                         $object_data['attachments'][] = ['type' => $type,
1261                                 'mediaType' => $attachment['type'],
1262                                 'height' => $attachment['height'],
1263                                 'size' => $attachment['size'],
1264                                 'name' => '',
1265                                 'url' => $attachment['url']];
1266                 }
1267                 return $object_data;
1268         }
1269
1270         /**
1271          * Fetches data from the object part of an activity
1272          *
1273          * @param array $object
1274          *
1275          * @return array
1276          * @throws \Exception
1277          */
1278         private static function processObject($object)
1279         {
1280                 if (!JsonLD::fetchElement($object, '@id')) {
1281                         return false;
1282                 }
1283
1284                 $object_data = [];
1285                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1286                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1287                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1288
1289                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1290                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1291                         $object_data['reply-to-id'] = $object_data['id'];
1292                 } else {
1293                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1294                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1295                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1296                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1297                                 $object_data['reply-to-id'] = $replyToId;
1298                         }
1299                 }
1300
1301                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1302                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1303
1304                 if (empty($object_data['updated'])) {
1305                         $object_data['updated'] = $object_data['published'];
1306                 }
1307
1308                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1309                         $object_data['published'] = $object_data['updated'];
1310                 }
1311
1312                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1313                 if (empty($actor)) {
1314                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1315                 }
1316
1317                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1318                 $location = JsonLD::fetchElement($location, 'location', '@value');
1319                 if ($location) {
1320                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1321                         // down to HTML and then finally format to plaintext.
1322                         $location = Markdown::convert($location);
1323                         $location = BBCode::convert($location);
1324                         $location = HTML::toPlaintext($location);
1325                 }
1326
1327                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1328                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1329                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1330                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1331                 $object_data['actor'] = $object_data['author'] = $actor;
1332                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1333                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1334                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1335                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1336                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1337                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1338                 $object_data = self::getSource($object, $object_data);
1339                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1340                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1341                 $object_data['location'] = $location;
1342                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1343                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1344                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1345                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1346                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1347                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1348                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1349                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1350                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1351                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1352
1353                 // Special treatment for Hubzilla links
1354                 if (is_array($object_data['alternate-url'])) {
1355                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1356
1357                         if (!is_string($object_data['alternate-url'])) {
1358                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1359                         }
1360                 }
1361
1362                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1363                         $object_data = self::processAttachmentUrls($object, $object_data);
1364                 }
1365
1366                 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1367                 $receivers = $reception_types = [];
1368                 foreach ($receiverdata as $key => $data) {
1369                         $receivers[$key] = $data['uid'];
1370                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1371                 }
1372
1373                 $object_data['receiver'] = $receivers;
1374                 $object_data['reception_type'] = $reception_types;
1375
1376                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1377                 unset($object_data['receiver'][-1]);
1378                 unset($object_data['reception_type'][-1]);
1379
1380                 // Common object data:
1381
1382                 // Unhandled
1383                 // @context, type, actor, signature, mediaType, duration, replies, icon
1384
1385                 // Also missing: (Defined in the standard, but currently unused)
1386                 // audience, preview, endTime, startTime, image
1387
1388                 // Data in Notes:
1389
1390                 // Unhandled
1391                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1392                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1393
1394                 // Data in video:
1395
1396                 // To-Do?
1397                 // category, licence, language, commentsEnabled
1398
1399                 // Unhandled
1400                 // views, waitTranscoding, state, support, subtitleLanguage
1401                 // likes, dislikes, shares, comments
1402
1403                 return $object_data;
1404         }
1405 }