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