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