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