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