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