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