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