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