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