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