]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Merge pull request #8222 from annando/ap-gnusocial
[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  * 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                         // Fix possibly wrong item URI (could be an answer to a plink uri)
507                         $fixedReplyTo = Item::getURIByLink($replyto);
508                         $replyto = $fixedReplyTo ?: $replyto;
509
510                         $parents = Item::select(['uid'], ['uri' => $replyto]);
511                         while ($parent = Item::fetch($parents)) {
512                                 $receivers['uid:' . $parent['uid']] = $parent['uid'];
513                         }
514                 }
515
516                 if (!empty($actor)) {
517                         $profile = APContact::getByURL($actor);
518                         $followers = $profile['followers'] ?? '';
519
520                         Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
521                 } else {
522                         Logger::log('Empty actor', Logger::DEBUG);
523                         $followers = '';
524                 }
525
526                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
527                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
528                         if (empty($receiver_list)) {
529                                 continue;
530                         }
531
532                         foreach ($receiver_list as $receiver) {
533                                 if ($receiver == self::PUBLIC_COLLECTION) {
534                                         $receivers['uid:0'] = 0;
535                                 }
536
537                                 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
538                                         // This will most likely catch all OStatus connections to Mastodon
539                                         $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
540                                                 , 'archive' => false, 'pending' => false];
541                                         $contacts = DBA::select('contact', ['uid'], $condition);
542                                         while ($contact = DBA::fetch($contacts)) {
543                                                 if ($contact['uid'] != 0) {
544                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
545                                                 }
546                                         }
547                                         DBA::close($contacts);
548                                 }
549
550                                 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
551                                         $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
552                                         continue;
553                                 }
554
555                                 // Fetching all directly addressed receivers
556                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
557                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
558                                 if (!DBA::isResult($contact)) {
559                                         continue;
560                                 }
561
562                                 // Check if the potential receiver is following the actor
563                                 // Exception: The receiver is targetted via "to" or this is a comment
564                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
565                                         $networks = Protocol::FEDERATED;
566                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
567                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
568
569                                         // Forum posts are only accepted from forum contacts
570                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
571                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
572                                         }
573
574                                         if (!DBA::exists('contact', $condition)) {
575                                                 continue;
576                                         }
577                                 }
578
579                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
580                         }
581                 }
582
583                 self::switchContacts($receivers, $actor);
584
585                 return $receivers;
586         }
587
588         /**
589          * Fetch the receiver list of a given actor
590          *
591          * @param string $actor
592          * @param array  $tags
593          *
594          * @return array with receivers (user id)
595          * @throws \Exception
596          */
597         public static function getReceiverForActor($actor, $tags)
598         {
599                 $receivers = [];
600                 $networks = Protocol::FEDERATED;
601                 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
602                         'network' => $networks, 'archive' => false, 'pending' => false];
603                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
604                 while ($contact = DBA::fetch($contacts)) {
605                         if (self::isValidReceiverForActor($contact, $actor, $tags)) {
606                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
607                         }
608                 }
609                 DBA::close($contacts);
610                 return $receivers;
611         }
612
613         /**
614          * Tests if the contact is a valid receiver for this actor
615          *
616          * @param array  $contact
617          * @param string $actor
618          * @param array  $tags
619          *
620          * @return bool with receivers (user id)
621          * @throws \Exception
622          */
623         private static function isValidReceiverForActor($contact, $actor, $tags)
624         {
625                 // Public contacts are no valid receiver
626                 if ($contact['uid'] == 0) {
627                         return false;
628                 }
629
630                 // Are we following the contact? Then this is a valid receiver
631                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
632                         return true;
633                 }
634
635                 // When the possible receiver isn't a community, then it is no valid receiver
636                 $owner = User::getOwnerDataById($contact['uid']);
637                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
638                         return false;
639                 }
640
641                 // Is the community account tagged?
642                 foreach ($tags as $tag) {
643                         if ($tag['type'] != 'Mention') {
644                                 continue;
645                         }
646
647                         if ($tag['href'] == $owner['url']) {
648                                 return true;
649                         }
650                 }
651
652                 return false;
653         }
654
655         /**
656          * Switches existing contacts to ActivityPub
657          *
658          * @param integer $cid Contact ID
659          * @param integer $uid User ID
660          * @param string  $url Profile URL
661          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662          * @throws \ImagickException
663          */
664         public static function switchContact($cid, $uid, $url)
665         {
666                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
667                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
668                         return;
669                 }
670
671                 if (Contact::updateFromProbe($cid, '', true)) {
672                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
673                 }
674
675                 // Send a new follow request to be sure that the connection still exists
676                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
677                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
678                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
679                 }
680         }
681
682         /**
683          *
684          *
685          * @param $receivers
686          * @param $actor
687          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
688          * @throws \ImagickException
689          */
690         private static function switchContacts($receivers, $actor)
691         {
692                 if (empty($actor)) {
693                         return;
694                 }
695
696                 foreach ($receivers as $receiver) {
697                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
698                         if (DBA::isResult($contact)) {
699                                 self::switchContact($contact['id'], $receiver, $actor);
700                         }
701
702                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
703                         if (DBA::isResult($contact)) {
704                                 self::switchContact($contact['id'], $receiver, $actor);
705                         }
706                 }
707         }
708
709         /**
710          *
711          *
712          * @param       $object_data
713          * @param array $activity
714          *
715          * @return mixed
716          */
717         private static function addActivityFields($object_data, $activity)
718         {
719                 if (!empty($activity['published']) && empty($object_data['published'])) {
720                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
721                 }
722
723                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
724                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
725                 }
726
727                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
728                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
729
730                 if (!empty($object_data['object_id'])) {
731                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
732                         $objectId = Item::getURIByLink($object_data['object_id']);
733                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
734                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
735                                 $object_data['object_id'] = $objectId;
736                         }
737                 }
738
739                 return $object_data;
740         }
741
742         /**
743          * Fetches the object data from external ressources if needed
744          *
745          * @param string  $object_id    Object ID of the the provided object
746          * @param array   $object       The provided object array
747          * @param boolean $trust_source Do we trust the provided object?
748          * @param integer $uid          User ID for the signature that we use to fetch data
749          *
750          * @return array|false with trusted and valid object data
751          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
752          * @throws \ImagickException
753          */
754         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
755         {
756                 // By fetching the type we check if the object is complete.
757                 $type = JsonLD::fetchElement($object, '@type');
758
759                 if (!$trust_source || empty($type)) {
760                         $data = ActivityPub::fetchContent($object_id, $uid);
761                         if (!empty($data)) {
762                                 $object = JsonLD::compact($data);
763                                 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
764                         } else {
765                                 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
766
767                                 $item = Item::selectFirst([], ['uri' => $object_id]);
768                                 if (!DBA::isResult($item)) {
769                                         Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
770                                         return false;
771                                 }
772                                 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
773                                 $data = ActivityPub\Transmitter::createNote($item);
774                                 $object = JsonLD::compact($data);
775                         }
776                 } else {
777                         Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
778                 }
779
780                 $type = JsonLD::fetchElement($object, '@type');
781
782                 if (empty($type)) {
783                         Logger::log('Empty type', Logger::DEBUG);
784                         return false;
785                 }
786
787                 if (in_array($type, self::CONTENT_TYPES)) {
788                         return self::processObject($object);
789                 }
790
791                 if ($type == 'as:Announce') {
792                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
793                         if (empty($object_id) || !is_string($object_id)) {
794                                 return false;
795                         }
796                         return self::fetchObject($object_id, [], false, $uid);
797                 }
798
799                 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
800                 return false;
801         }
802
803         /**
804          * Convert tags from JSON-LD format into a simplified format
805          *
806          * @param array $tags Tags in JSON-LD format
807          *
808          * @return array with tags in a simplified format
809          */
810         private static function processTags($tags)
811         {
812                 $taglist = [];
813
814                 if (empty($tags)) {
815                         return [];
816                 }
817
818                 foreach ($tags as $tag) {
819                         if (empty($tag)) {
820                                 continue;
821                         }
822
823                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
824                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
825                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
826
827                         if (empty($element['type'])) {
828                                 continue;
829                         }
830
831                         $taglist[] = $element;
832                 }
833                 return $taglist;
834         }
835
836         /**
837          * Convert emojis from JSON-LD format into a simplified format
838          *
839          * @param $emojis
840          * @return array with emojis in a simplified format
841          */
842         private static function processEmojis($emojis)
843         {
844                 $emojilist = [];
845
846                 if (empty($emojis)) {
847                         return [];
848                 }
849
850                 foreach ($emojis as $emoji) {
851                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
852                                 continue;
853                         }
854
855                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
856                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
857                                 'href' => $url];
858
859                         $emojilist[] = $element;
860                 }
861                 return $emojilist;
862         }
863
864         /**
865          * Convert attachments from JSON-LD format into a simplified format
866          *
867          * @param array $attachments Attachments in JSON-LD format
868          *
869          * @return array with attachmants in a simplified format
870          */
871         private static function processAttachments($attachments)
872         {
873                 $attachlist = [];
874
875                 if (empty($attachments)) {
876                         return [];
877                 }
878
879                 foreach ($attachments as $attachment) {
880                         if (empty($attachment)) {
881                                 continue;
882                         }
883
884                         $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
885                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
886                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
887                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
888                 }
889                 return $attachlist;
890         }
891
892         /**
893          * Fetch the original source or content with the "language" Markdown or HTML
894          *
895          * @param array $object
896          * @param array $object_data
897          *
898          * @return array
899          * @throws \Exception
900          */
901         private static function getSource($object, $object_data)
902         {
903                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
904                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
905                 if (!empty($object_data['source'])) {
906                         return $object_data;
907                 }
908
909                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
910                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
911                 if (!empty($object_data['source'])) {
912                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
913                         return $object_data;
914                 }
915
916                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
917                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
918                 if (!empty($object_data['source'])) {
919                         $object_data['source'] = HTML::toBBCode($object_data['source']);
920                         return $object_data;
921                 }
922
923                 return $object_data;
924         }
925
926         /**
927          * Fetches data from the object part of an activity
928          *
929          * @param array $object
930          *
931          * @return array
932          * @throws \Exception
933          */
934         private static function processObject($object)
935         {
936                 if (!JsonLD::fetchElement($object, '@id')) {
937                         return false;
938                 }
939
940                 $object_data = [];
941                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
942                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
943                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
944
945                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
946                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
947                         $object_data['reply-to-id'] = $object_data['id'];
948                 } else {
949                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
950                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
951                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
952                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
953                                 $object_data['reply-to-id'] = $replyToId;
954                         }
955                 }
956
957                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
958                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
959
960                 if (empty($object_data['updated'])) {
961                         $object_data['updated'] = $object_data['published'];
962                 }
963
964                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
965                         $object_data['published'] = $object_data['updated'];
966                 }
967
968                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
969                 if (empty($actor)) {
970                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
971                 }
972
973                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
974                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
975                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
976                 $object_data['actor'] = $object_data['author'] = $actor;
977                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
978                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
979                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
980                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
981                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
982                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
983                 $object_data = self::getSource($object, $object_data);
984                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
985                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
986                 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
987                 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
988                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
989                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
990                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
991                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
992                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
993                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
994                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
995                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
996                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
997                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
998
999                 // Special treatment for Hubzilla links
1000                 if (is_array($object_data['alternate-url'])) {
1001                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1002
1003                         if (!is_string($object_data['alternate-url'])) {
1004                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1005                         }
1006                 }
1007
1008                 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
1009
1010                 // Common object data:
1011
1012                 // Unhandled
1013                 // @context, type, actor, signature, mediaType, duration, replies, icon
1014
1015                 // Also missing: (Defined in the standard, but currently unused)
1016                 // audience, preview, endTime, startTime, image
1017
1018                 // Data in Notes:
1019
1020                 // Unhandled
1021                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1022                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1023
1024                 // Data in video:
1025
1026                 // To-Do?
1027                 // category, licence, language, commentsEnabled
1028
1029                 // Unhandled
1030                 // views, waitTranscoding, state, support, subtitleLanguage
1031                 // likes, dislikes, shares, comments
1032
1033                 return $object_data;
1034         }
1035 }