]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Issue 8067: Posts from Mastodon had been wrongly parsed
[friendica.git] / src / Protocol / ActivityPub / Receiver.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub/Receiver.php
4  */
5 namespace Friendica\Protocol\ActivityPub;
6
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Content\Text\Markdown;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Contact;
13 use Friendica\Model\APContact;
14 use Friendica\Model\Conversation;
15 use Friendica\Model\Item;
16 use Friendica\Model\User;
17 use Friendica\Protocol\Activity;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\HTTPSignature;
21 use Friendica\Util\JsonLD;
22 use Friendica\Util\LDSignature;
23 use Friendica\Util\Strings;
24
25 /**
26  * @brief ActivityPub Receiver Protocol class
27  *
28  * To-Do:
29  * - Undo Announce
30  *
31  * Check what this is meant to do:
32  * - Add
33  * - Block
34  * - Flag
35  * - Remove
36  * - Undo Block
37  */
38 class Receiver
39 {
40         const PUBLIC_COLLECTION = 'as:Public';
41         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
42         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event'];
43         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
44
45         /**
46          * Checks if the web request is done for the AP protocol
47          *
48          * @return bool is it AP?
49          */
50         public static function isRequest()
51         {
52                 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
53                         stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
54         }
55
56         /**
57          * Checks incoming message from the inbox
58          *
59          * @param         $body
60          * @param         $header
61          * @param integer $uid User ID
62          * @throws \Exception
63          */
64         public static function processInbox($body, $header, $uid)
65         {
66                 $http_signer = HTTPSignature::getSigner($body, $header);
67                 if (empty($http_signer)) {
68                         Logger::warning('Invalid HTTP signature, message will be discarded.');
69                         return;
70                 } else {
71                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
72                 }
73
74                 $activity = json_decode($body, true);
75
76                 if (empty($activity)) {
77                         Logger::warning('Invalid body.');
78                         return;
79                 }
80
81                 $ldactivity = JsonLD::compact($activity);
82
83                 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
84
85                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
86
87                 if (LDSignature::isSigned($activity)) {
88                         $ld_signer = LDSignature::getSigner($activity);
89                         if (empty($ld_signer)) {
90                                 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
91                         }
92                         if (!empty($ld_signer && ($actor == $http_signer))) {
93                                 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
94                                 $trust_source = true;
95                         } elseif (!empty($ld_signer)) {
96                                 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
97                                 $trust_source = true;
98                         } elseif ($actor == $http_signer) {
99                                 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
100                                 $trust_source = true;
101                         } else {
102                                 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
103                                 $trust_source = false;
104                         }
105                 } elseif ($actor == $http_signer) {
106                         Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
107                         $trust_source = true;
108                 } else {
109                         Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
110                         $trust_source = false;
111                 }
112
113                 self::processActivity($ldactivity, $body, $uid, $trust_source);
114         }
115
116         /**
117          * Fetches the object type for a given object id
118          *
119          * @param array   $activity
120          * @param string  $object_id Object ID of the the provided object
121          * @param integer $uid       User ID
122          *
123          * @return string with object type
124          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
125          * @throws \ImagickException
126          */
127         private static function fetchObjectType($activity, $object_id, $uid = 0)
128         {
129                 if (!empty($activity['as:object'])) {
130                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
131                         if (!empty($object_type)) {
132                                 return $object_type;
133                         }
134                 }
135
136                 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
137                         // We just assume "note" since it doesn't make a difference for the further processing
138                         return 'as:Note';
139                 }
140
141                 $profile = APContact::getByURL($object_id);
142                 if (!empty($profile['type'])) {
143                         return 'as:' . $profile['type'];
144                 }
145
146                 $data = ActivityPub::fetchContent($object_id, $uid);
147                 if (!empty($data)) {
148                         $object = JsonLD::compact($data);
149                         $type = JsonLD::fetchElement($object, '@type');
150                         if (!empty($type)) {
151                                 return $type;
152                         }
153                 }
154
155                 return null;
156         }
157
158         /**
159          * Prepare the object array
160          *
161          * @param array   $activity
162          * @param integer $uid User ID
163          * @param         $trust_source
164          *
165          * @return array with object data
166          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
167          * @throws \ImagickException
168          */
169         private static function prepareObjectData($activity, $uid, &$trust_source)
170         {
171                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
172                 if (empty($actor)) {
173                         Logger::log('Empty actor', Logger::DEBUG);
174                         return [];
175                 }
176
177                 $type = JsonLD::fetchElement($activity, '@type');
178
179                 // Fetch all receivers from to, cc, bto and bcc
180                 $receivers = self::getReceivers($activity, $actor);
181
182                 // When it is a delivery to a personal inbox we add that user to the receivers
183                 if (!empty($uid)) {
184                         $additional = ['uid:' . $uid => $uid];
185                         $receivers = array_merge($receivers, $additional);
186                 } else {
187                         // We possibly need some user to fetch private content,
188                         // so we fetch the first out ot the list.
189                         $uid = self::getFirstUserFromReceivers($receivers);
190                 }
191
192                 Logger::log('Receivers: ' . $uid . ' - ' . json_encode($receivers), Logger::DEBUG);
193
194                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
195                 if (empty($object_id)) {
196                         Logger::log('No object found', Logger::DEBUG);
197                         return [];
198                 }
199
200                 if (!is_string($object_id)) {
201                         Logger::info('Invalid object id', ['object' => $object_id]);
202                         return [];
203                 }
204
205                 $object_type = self::fetchObjectType($activity, $object_id, $uid);
206
207                 // Fetch the content only on activities where this matters
208                 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
209                         if ($type == 'as:Announce') {
210                                 $trust_source = false;
211                         }
212                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $uid);
213                         if (empty($object_data)) {
214                                 Logger::log("Object data couldn't be processed", Logger::DEBUG);
215                                 return [];
216                         }
217                         $object_data['object_id'] = $object_id;
218
219                         // Test if it is an answer to a mail
220                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
221                                 $object_data['directmessage'] = true;
222                         } else {
223                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
224                         }
225
226                         // We had been able to retrieve the object data - so we can trust the source
227                         $trust_source = true;
228                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
229                         // Create a mostly empty array out of the activity data (instead of the object).
230                         // This way we later don't have to check for the existence of ech individual array element.
231                         $object_data = self::processObject($activity);
232                         $object_data['name'] = $type;
233                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
234                         $object_data['object_id'] = $object_id;
235                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
236                 } elseif (in_array($type, ['as:Add'])) {
237                         $object_data = [];
238                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
239                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
240                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
241                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
242                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
243                 } else {
244                         $object_data = [];
245                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
246                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
247                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
248                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
249                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
250
251                         // An Undo is done on the object of an object, so we need that type as well
252                         if ($type == 'as:Undo') {
253                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
254                         }
255                 }
256
257                 $object_data = self::addActivityFields($object_data, $activity);
258
259                 if (empty($object_data['object_type'])) {
260                         $object_data['object_type'] = $object_type;
261                 }
262
263                 $object_data['type'] = $type;
264                 $object_data['actor'] = $actor;
265                 $object_data['item_receiver'] = $receivers;
266                 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
267
268                 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
269
270                 return $object_data;
271         }
272
273         /**
274          * Fetches the first user id from the receiver array
275          *
276          * @param array $receivers Array with receivers
277          * @return integer user id;
278          */
279         public static function getFirstUserFromReceivers($receivers)
280         {
281                 foreach ($receivers as $receiver) {
282                         if (!empty($receiver)) {
283                                 return $receiver;
284                         }
285                 }
286                 return 0;
287         }
288
289         /**
290          * Store the unprocessed data into the conversation table
291          * This has to be done outside the regular function,
292          * since we store everything - not only item posts.
293          *
294          * @param array  $activity Array with activity data
295          * @param string $body     The raw message
296          * @throws \Exception
297          */
298         private static function storeConversation($activity, $body)
299         {
300                 if (empty($body) || empty($activity['id'])) {
301                         return;
302                 }
303
304                 $conversation = [
305                         'protocol' => Conversation::PARCEL_ACTIVITYPUB,
306                         'item-uri' => $activity['id'],
307                         'reply-to-uri' => $activity['reply-to-id'] ?? '',
308                         'conversation-href' => $activity['context'] ?? '',
309                         'conversation-uri' => $activity['conversation'] ?? '',
310                         'source' => $body,
311                         'received' => DateTimeFormat::utcNow()];
312
313                 DBA::insert('conversation', $conversation, true);
314         }
315
316         /**
317          * Processes the activity object
318          *
319          * @param array   $activity     Array with activity data
320          * @param string  $body
321          * @param integer $uid          User ID
322          * @param boolean $trust_source Do we trust the source?
323          * @throws \Exception
324          */
325         public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
326         {
327                 $type = JsonLD::fetchElement($activity, '@type');
328                 if (!$type) {
329                         Logger::log('Empty type', Logger::DEBUG);
330                         return;
331                 }
332
333                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
334                         Logger::log('Empty object', Logger::DEBUG);
335                         return;
336                 }
337
338                 if (!JsonLD::fetchElement($activity, 'as:actor', '@id')) {
339                         Logger::log('Empty actor', Logger::DEBUG);
340                         return;
341
342                 }
343
344                 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
345                 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
346                         $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
347                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
348                         $trust_source = ($actor == $attributed_to);
349                         if (!$trust_source) {
350                                 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
351                         }
352                 }
353
354                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
355                 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
356                 if (empty($object_data)) {
357                         Logger::log('No object data found', Logger::DEBUG);
358                         return;
359                 }
360
361                 if (!$trust_source) {
362                         Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
363                         return;
364                 }
365
366                 // Only store content related stuff - and no announces, since they possibly overwrite the original content
367                 if (in_array($object_data['object_type'], self::CONTENT_TYPES) && ($type != 'as:Announce')) {
368                         self::storeConversation($object_data, $body);
369                 }
370
371                 // Internal flag for thread completion. See Processor.php
372                 if (!empty($activity['thread-completion'])) {
373                         $object_data['thread-completion'] = $activity['thread-completion'];
374                 }
375
376                 switch ($type) {
377                         case 'as:Create':
378                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
379                                         ActivityPub\Processor::createItem($object_data);
380                                 }
381                                 break;
382
383                         case 'as:Add':
384                                 if ($object_data['object_type'] == 'as:tag') {
385                                         ActivityPub\Processor::addTag($object_data);
386                                 }
387                                 break;
388
389                         case 'as:Announce':
390                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
391                                         $profile = APContact::getByURL($object_data['actor']);
392                                         // Reshared posts from persons appear as summary at the bottom
393                                         // If this isn't set, then a single reshare appears on top. This is used for groups.
394                                         $object_data['thread-completion'] = ($profile['type'] != 'Group');
395
396                                         ActivityPub\Processor::createItem($object_data);
397
398                                         // Add the bottom reshare information only for persons
399                                         if ($profile['type'] != 'Group') {
400                                                 $announce_object_data = self::processObject($activity);
401                                                 $announce_object_data['name'] = $type;
402                                                 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
403                                                 $announce_object_data['object_id'] = $object_data['object_id'];
404                                                 $announce_object_data['object_type'] = $object_data['object_type'];
405
406                                                 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
407                                         }
408                                 }
409                                 break;
410
411                         case 'as:Like':
412                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
413                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
414                                 }
415                                 break;
416
417                         case 'as:Dislike':
418                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
419                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
420                                 }
421                                 break;
422
423                         case 'as:TentativeAccept':
424                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
425                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
426                                 }
427                                 break;
428
429                         case 'as:Update':
430                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
431                                         ActivityPub\Processor::updateItem($object_data);
432                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
433                                         ActivityPub\Processor::updatePerson($object_data);
434                                 }
435                                 break;
436
437                         case 'as:Delete':
438                                 if ($object_data['object_type'] == 'as:Tombstone') {
439                                         ActivityPub\Processor::deleteItem($object_data);
440                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
441                                         ActivityPub\Processor::deletePerson($object_data);
442                                 }
443                                 break;
444
445                         case 'as:Follow':
446                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
447                                         ActivityPub\Processor::followUser($object_data);
448                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
449                                         $object_data['reply-to-id'] = $object_data['object_id'];
450                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
451                                 }
452                                 break;
453
454                         case 'as:Accept':
455                                 if ($object_data['object_type'] == 'as:Follow') {
456                                         ActivityPub\Processor::acceptFollowUser($object_data);
457                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
458                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
459                                 }
460                                 break;
461
462                         case 'as:Reject':
463                                 if ($object_data['object_type'] == 'as:Follow') {
464                                         ActivityPub\Processor::rejectFollowUser($object_data);
465                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
466                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
467                                 }
468                                 break;
469
470                         case 'as:Undo':
471                                 if (($object_data['object_type'] == 'as:Follow') &&
472                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
473                                         ActivityPub\Processor::undoFollowUser($object_data);
474                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
475                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
476                                         ActivityPub\Processor::rejectFollowUser($object_data);
477                                 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
478                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
479                                         ActivityPub\Processor::undoActivity($object_data);
480                                 }
481                                 break;
482
483                         default:
484                                 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
485                                 break;
486                 }
487         }
488
489         /**
490          * Fetch the receiver list from an activity array
491          *
492          * @param array  $activity
493          * @param string $actor
494          * @param array  $tags
495          *
496          * @return array with receivers (user id)
497          * @throws \Exception
498          */
499         private static function getReceivers($activity, $actor, $tags = [])
500         {
501                 $receivers = [];
502
503                 // When it is an answer, we inherite the receivers from the parent
504                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
505                 if (!empty($replyto)) {
506                         $parents = Item::select(['uid'], ['uri' => $replyto]);
507                         while ($parent = Item::fetch($parents)) {
508                                 $receivers['uid:' . $parent['uid']] = $parent['uid'];
509                         }
510                 }
511
512                 if (!empty($actor)) {
513                         $profile = APContact::getByURL($actor);
514                         $followers = $profile['followers'] ?? '';
515
516                         Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
517                 } else {
518                         Logger::log('Empty actor', Logger::DEBUG);
519                         $followers = '';
520                 }
521
522                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
523                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
524                         if (empty($receiver_list)) {
525                                 continue;
526                         }
527
528                         foreach ($receiver_list as $receiver) {
529                                 if ($receiver == self::PUBLIC_COLLECTION) {
530                                         $receivers['uid:0'] = 0;
531                                 }
532
533                                 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
534                                         // This will most likely catch all OStatus connections to Mastodon
535                                         $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
536                                                 , 'archive' => false, 'pending' => false];
537                                         $contacts = DBA::select('contact', ['uid'], $condition);
538                                         while ($contact = DBA::fetch($contacts)) {
539                                                 if ($contact['uid'] != 0) {
540                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
541                                                 }
542                                         }
543                                         DBA::close($contacts);
544                                 }
545
546                                 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
547                                         $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
548                                         continue;
549                                 }
550
551                                 // Fetching all directly addressed receivers
552                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
553                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
554                                 if (!DBA::isResult($contact)) {
555                                         continue;
556                                 }
557
558                                 // Check if the potential receiver is following the actor
559                                 // Exception: The receiver is targetted via "to" or this is a comment
560                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
561                                         $networks = Protocol::FEDERATED;
562                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
563                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
564
565                                         // Forum posts are only accepted from forum contacts
566                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
567                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
568                                         }
569
570                                         if (!DBA::exists('contact', $condition)) {
571                                                 continue;
572                                         }
573                                 }
574
575                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
576                         }
577                 }
578
579                 self::switchContacts($receivers, $actor);
580
581                 return $receivers;
582         }
583
584         /**
585          * Fetch the receiver list of a given actor
586          *
587          * @param string $actor
588          * @param array  $tags
589          *
590          * @return array with receivers (user id)
591          * @throws \Exception
592          */
593         public static function getReceiverForActor($actor, $tags)
594         {
595                 $receivers = [];
596                 $networks = Protocol::FEDERATED;
597                 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
598                         'network' => $networks, 'archive' => false, 'pending' => false];
599                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
600                 while ($contact = DBA::fetch($contacts)) {
601                         if (self::isValidReceiverForActor($contact, $actor, $tags)) {
602                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
603                         }
604                 }
605                 DBA::close($contacts);
606                 return $receivers;
607         }
608
609         /**
610          * Tests if the contact is a valid receiver for this actor
611          *
612          * @param array  $contact
613          * @param string $actor
614          * @param array  $tags
615          *
616          * @return bool with receivers (user id)
617          * @throws \Exception
618          */
619         private static function isValidReceiverForActor($contact, $actor, $tags)
620         {
621                 // Public contacts are no valid receiver
622                 if ($contact['uid'] == 0) {
623                         return false;
624                 }
625
626                 // Are we following the contact? Then this is a valid receiver
627                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
628                         return true;
629                 }
630
631                 // When the possible receiver isn't a community, then it is no valid receiver
632                 $owner = User::getOwnerDataById($contact['uid']);
633                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
634                         return false;
635                 }
636
637                 // Is the community account tagged?
638                 foreach ($tags as $tag) {
639                         if ($tag['type'] != 'Mention') {
640                                 continue;
641                         }
642
643                         if ($tag['href'] == $owner['url']) {
644                                 return true;
645                         }
646                 }
647
648                 return false;
649         }
650
651         /**
652          * Switches existing contacts to ActivityPub
653          *
654          * @param integer $cid Contact ID
655          * @param integer $uid User ID
656          * @param string  $url Profile URL
657          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
658          * @throws \ImagickException
659          */
660         public static function switchContact($cid, $uid, $url)
661         {
662                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
663                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
664                         return;
665                 }
666
667                 if (Contact::updateFromProbe($cid, '', true)) {
668                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
669                 }
670
671                 // Send a new follow request to be sure that the connection still exists
672                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
673                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
674                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
675                 }
676         }
677
678         /**
679          *
680          *
681          * @param $receivers
682          * @param $actor
683          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684          * @throws \ImagickException
685          */
686         private static function switchContacts($receivers, $actor)
687         {
688                 if (empty($actor)) {
689                         return;
690                 }
691
692                 foreach ($receivers as $receiver) {
693                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
694                         if (DBA::isResult($contact)) {
695                                 self::switchContact($contact['id'], $receiver, $actor);
696                         }
697
698                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
699                         if (DBA::isResult($contact)) {
700                                 self::switchContact($contact['id'], $receiver, $actor);
701                         }
702                 }
703         }
704
705         /**
706          *
707          *
708          * @param       $object_data
709          * @param array $activity
710          *
711          * @return mixed
712          */
713         private static function addActivityFields($object_data, $activity)
714         {
715                 if (!empty($activity['published']) && empty($object_data['published'])) {
716                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
717                 }
718
719                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
720                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
721                 }
722
723                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
724                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
725
726                 return $object_data;
727         }
728
729         /**
730          * Fetches the object data from external ressources if needed
731          *
732          * @param string  $object_id    Object ID of the the provided object
733          * @param array   $object       The provided object array
734          * @param boolean $trust_source Do we trust the provided object?
735          * @param integer $uid          User ID for the signature that we use to fetch data
736          *
737          * @return array|false with trusted and valid object data
738          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
739          * @throws \ImagickException
740          */
741         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
742         {
743                 // By fetching the type we check if the object is complete.
744                 $type = JsonLD::fetchElement($object, '@type');
745
746                 if (!$trust_source || empty($type)) {
747                         $data = ActivityPub::fetchContent($object_id, $uid);
748                         if (!empty($data)) {
749                                 $object = JsonLD::compact($data);
750                                 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
751                         } else {
752                                 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
753
754                                 $item = Item::selectFirst([], ['uri' => $object_id]);
755                                 if (!DBA::isResult($item)) {
756                                         Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
757                                         return false;
758                                 }
759                                 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
760                                 $data = ActivityPub\Transmitter::createNote($item);
761                                 $object = JsonLD::compact($data);
762                         }
763                 } else {
764                         Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
765                 }
766
767                 $type = JsonLD::fetchElement($object, '@type');
768
769                 if (empty($type)) {
770                         Logger::log('Empty type', Logger::DEBUG);
771                         return false;
772                 }
773
774                 if (in_array($type, self::CONTENT_TYPES)) {
775                         return self::processObject($object);
776                 }
777
778                 if ($type == 'as:Announce') {
779                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
780                         if (empty($object_id) || !is_string($object_id)) {
781                                 return false;
782                         }
783                         return self::fetchObject($object_id, [], false, $uid);
784                 }
785
786                 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
787                 return false;
788         }
789
790         /**
791          * Convert tags from JSON-LD format into a simplified format
792          *
793          * @param array $tags Tags in JSON-LD format
794          *
795          * @return array with tags in a simplified format
796          */
797         private static function processTags($tags)
798         {
799                 $taglist = [];
800
801                 if (empty($tags)) {
802                         return [];
803                 }
804
805                 foreach ($tags as $tag) {
806                         if (empty($tag)) {
807                                 continue;
808                         }
809
810                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
811                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
812                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
813
814                         if (empty($element['type'])) {
815                                 continue;
816                         }
817
818                         $taglist[] = $element;
819                 }
820                 return $taglist;
821         }
822
823         /**
824          * Convert emojis from JSON-LD format into a simplified format
825          *
826          * @param $emojis
827          * @return array with emojis in a simplified format
828          */
829         private static function processEmojis($emojis)
830         {
831                 $emojilist = [];
832
833                 if (empty($emojis)) {
834                         return [];
835                 }
836
837                 foreach ($emojis as $emoji) {
838                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
839                                 continue;
840                         }
841
842                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
843                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
844                                 'href' => $url];
845
846                         $emojilist[] = $element;
847                 }
848                 return $emojilist;
849         }
850
851         /**
852          * Convert attachments from JSON-LD format into a simplified format
853          *
854          * @param array $attachments Attachments in JSON-LD format
855          *
856          * @return array with attachmants in a simplified format
857          */
858         private static function processAttachments($attachments)
859         {
860                 $attachlist = [];
861
862                 if (empty($attachments)) {
863                         return [];
864                 }
865
866                 foreach ($attachments as $attachment) {
867                         if (empty($attachment)) {
868                                 continue;
869                         }
870
871                         $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
872                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
873                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
874                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
875                 }
876                 return $attachlist;
877         }
878
879         /**
880          * Fetch the original source or content with the "language" Markdown or HTML
881          *
882          * @param array $object
883          * @param array $object_data
884          *
885          * @return array
886          * @throws \Exception
887          */
888         private static function getSource($object, $object_data)
889         {
890                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
891                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
892                 if (!empty($object_data['source'])) {
893                         return $object_data;
894                 }
895
896                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
897                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
898                 if (!empty($object_data['source'])) {
899                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
900                         return $object_data;
901                 }
902
903                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
904                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
905                 if (!empty($object_data['source'])) {
906                         $object_data['source'] = HTML::toBBCode($object_data['source']);
907                         return $object_data;
908                 }
909
910                 return $object_data;
911         }
912
913         /**
914          * Fetches data from the object part of an activity
915          *
916          * @param array $object
917          *
918          * @return array
919          * @throws \Exception
920          */
921         private static function processObject($object)
922         {
923                 if (!JsonLD::fetchElement($object, '@id')) {
924                         return false;
925                 }
926
927                 $object_data = [];
928                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
929                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
930                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
931
932                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
933                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
934                         $object_data['reply-to-id'] = $object_data['id'];
935                 }
936
937                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
938                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
939
940                 if (empty($object_data['updated'])) {
941                         $object_data['updated'] = $object_data['published'];
942                 }
943
944                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
945                         $object_data['published'] = $object_data['updated'];
946                 }
947
948                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
949                 if (empty($actor)) {
950                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
951                 }
952
953                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
954                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
955                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
956                 $object_data['actor'] = $object_data['author'] = $actor;
957                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
958                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
959                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
960                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
961                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
962                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
963                 $object_data = self::getSource($object, $object_data);
964                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
965                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
966                 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
967                 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
968                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
969                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
970                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
971                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
972                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
973                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
974                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
975                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
976                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
977                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
978
979                 // Special treatment for Hubzilla links
980                 if (is_array($object_data['alternate-url'])) {
981                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
982
983                         if (!is_string($object_data['alternate-url'])) {
984                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
985                         }
986                 }
987
988                 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
989
990                 // Common object data:
991
992                 // Unhandled
993                 // @context, type, actor, signature, mediaType, duration, replies, icon
994
995                 // Also missing: (Defined in the standard, but currently unused)
996                 // audience, preview, endTime, startTime, image
997
998                 // Data in Notes:
999
1000                 // Unhandled
1001                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1002                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1003
1004                 // Data in video:
1005
1006                 // To-Do?
1007                 // category, licence, language, commentsEnabled
1008
1009                 // Unhandled
1010                 // views, waitTranscoding, state, support, subtitleLanguage
1011                 // likes, dislikes, shares, comments
1012
1013                 return $object_data;
1014         }
1015 }