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