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