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