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