Fix the processing of event activities
[friendica.git/.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\ActivityPub;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\HTTPSignature;
18 use Friendica\Util\JsonLD;
19 use Friendica\Util\LDSignature;
20 use Friendica\Util\Strings;
21
22 /**
23  * @brief ActivityPub Receiver Protocol class
24  *
25  * To-Do:
26  * - Undo Announce
27  *
28  * Check what this is meant to do:
29  * - Add
30  * - Block
31  * - Flag
32  * - Remove
33  * - Undo Block
34  */
35 class Receiver
36 {
37         const PUBLIC_COLLECTION = 'as:Public';
38         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
39         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event'];
40         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
41
42         /**
43          * Checks if the web request is done for the AP protocol
44          *
45          * @return bool is it AP?
46          */
47         public static function isRequest()
48         {
49                 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
50                         stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
51         }
52
53         /**
54          * Checks incoming message from the inbox
55          *
56          * @param         $body
57          * @param         $header
58          * @param integer $uid User ID
59          * @throws \Exception
60          */
61         public static function processInbox($body, $header, $uid)
62         {
63                 $http_signer = HTTPSignature::getSigner($body, $header);
64                 if (empty($http_signer)) {
65                         Logger::warning('Invalid HTTP signature, message will be discarded.');
66                         return;
67                 } else {
68                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
69                 }
70
71                 $activity = json_decode($body, true);
72
73                 if (empty($activity)) {
74                         Logger::warning('Invalid body.');
75                         return;
76                 }
77
78                 $ldactivity = JsonLD::compact($activity);
79
80                 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
81
82                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
83
84                 if (LDSignature::isSigned($activity)) {
85                         $ld_signer = LDSignature::getSigner($activity);
86                         if (empty($ld_signer)) {
87                                 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
88                         }
89                         if (!empty($ld_signer && ($actor == $http_signer))) {
90                                 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
91                                 $trust_source = true;
92                         } elseif (!empty($ld_signer)) {
93                                 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
94                                 $trust_source = true;
95                         } elseif ($actor == $http_signer) {
96                                 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
97                                 $trust_source = true;
98                         } else {
99                                 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
100                                 $trust_source = false;
101                         }
102                 } elseif ($actor == $http_signer) {
103                         Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
104                         $trust_source = true;
105                 } else {
106                         Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
107                         $trust_source = false;
108                 }
109
110                 self::processActivity($ldactivity, $body, $uid, $trust_source);
111         }
112
113         /**
114          * Fetches the object type for a given object id
115          *
116          * @param array   $activity
117          * @param string  $object_id Object ID of the the provided object
118          * @param integer $uid       User ID
119          *
120          * @return string with object type
121          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
122          * @throws \ImagickException
123          */
124         private static function fetchObjectType($activity, $object_id, $uid = 0)
125         {
126                 if (!empty($activity['as:object'])) {
127                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
128                         if (!empty($object_type)) {
129                                 return $object_type;
130                         }
131                 }
132
133                 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
134                         // We just assume "note" since it doesn't make a difference for the further processing
135                         return 'as:Note';
136                 }
137
138                 $profile = APContact::getByURL($object_id);
139                 if (!empty($profile['type'])) {
140                         return 'as:' . $profile['type'];
141                 }
142
143                 $data = ActivityPub::fetchContent($object_id, $uid);
144                 if (!empty($data)) {
145                         $object = JsonLD::compact($data);
146                         $type = JsonLD::fetchElement($object, '@type');
147                         if (!empty($type)) {
148                                 return $type;
149                         }
150                 }
151
152                 return null;
153         }
154
155         /**
156          * Prepare the object array
157          *
158          * @param array   $activity
159          * @param integer $uid User ID
160          * @param         $trust_source
161          *
162          * @return array with object data
163          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
164          * @throws \ImagickException
165          */
166         private static function prepareObjectData($activity, $uid, &$trust_source)
167         {
168                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
169                 if (empty($actor)) {
170                         Logger::log('Empty actor', Logger::DEBUG);
171                         return [];
172                 }
173
174                 $type = JsonLD::fetchElement($activity, '@type');
175
176                 // Fetch all receivers from to, cc, bto and bcc
177                 $receivers = self::getReceivers($activity, $actor);
178
179                 // When it is a delivery to a personal inbox we add that user to the receivers
180                 if (!empty($uid)) {
181                         $additional = ['uid:' . $uid => $uid];
182                         $receivers = array_merge($receivers, $additional);
183                 } else {
184                         // We possibly need some user to fetch private content,
185                         // so we fetch the first out ot the list.
186                         $uid = self::getFirstUserFromReceivers($receivers);
187                 }
188
189                 Logger::log('Receivers: ' . $uid . ' - ' . json_encode($receivers), Logger::DEBUG);
190
191                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
192                 if (empty($object_id)) {
193                         Logger::log('No object found', Logger::DEBUG);
194                         return [];
195                 }
196
197                 if (!is_string($object_id)) {
198                         Logger::info('Invalid object id', ['object' => $object_id]);
199                         return [];
200                 }
201
202                 $object_type = self::fetchObjectType($activity, $object_id, $uid);
203
204                 // Fetch the content only on activities where this matters
205                 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
206                         if ($type == 'as:Announce') {
207                                 $trust_source = false;
208                         }
209                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $uid);
210                         if (empty($object_data)) {
211                                 Logger::log("Object data couldn't be processed", Logger::DEBUG);
212                                 return [];
213                         }
214                         $object_data['object_id'] = $object_id;
215
216                         // Test if it is an answer to a mail
217                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
218                                 $object_data['directmessage'] = true;
219                         } else {
220                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
221                         }
222
223                         // We had been able to retrieve the object data - so we can trust the source
224                         $trust_source = true;
225                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
226                         // Create a mostly empty array out of the activity data (instead of the object).
227                         // This way we later don't have to check for the existence of ech individual array element.
228                         $object_data = self::processObject($activity);
229                         $object_data['name'] = $type;
230                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
231                         $object_data['object_id'] = $object_id;
232                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
233                 } elseif (in_array($type, ['as:Add'])) {
234                         $object_data = [];
235                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
236                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
237                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
238                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
239                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
240                 } else {
241                         $object_data = [];
242                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
243                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
244                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
245                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
246                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
247
248                         // An Undo is done on the object of an object, so we need that type as well
249                         if ($type == 'as:Undo') {
250                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
251                         }
252                 }
253
254                 $object_data = self::addActivityFields($object_data, $activity);
255
256                 if (empty($object_data['object_type'])) {
257                         $object_data['object_type'] = $object_type;
258                 }
259
260                 $object_data['type'] = $type;
261                 $object_data['actor'] = $actor;
262                 $object_data['item_receiver'] = $receivers;
263                 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
264
265                 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
266
267                 return $object_data;
268         }
269
270         /**
271          * Fetches the first user id from the receiver array
272          *
273          * @param array $receivers Array with receivers
274          * @return integer user id;
275          */
276         public static function getFirstUserFromReceivers($receivers)
277         {
278                 foreach ($receivers as $receiver) {
279                         if (!empty($receiver)) {
280                                 return $receiver;
281                         }
282                 }
283                 return 0;
284         }
285
286         /**
287          * Store the unprocessed data into the conversation table
288          * This has to be done outside the regular function,
289          * since we store everything - not only item posts.
290          *
291          * @param array  $activity Array with activity data
292          * @param string $body     The raw message
293          * @throws \Exception
294          */
295         private static function storeConversation($activity, $body)
296         {
297                 if (empty($body) || empty($activity['id'])) {
298                         return;
299                 }
300
301                 $conversation = [
302                         'protocol' => Conversation::PARCEL_ACTIVITYPUB,
303                         'item-uri' => $activity['id'],
304                         'reply-to-uri' => defaults($activity, 'reply-to-id', ''),
305                         'conversation-href' => defaults($activity, 'context', ''),
306                         'conversation-uri' => defaults($activity, 'conversation', ''),
307                         'source' => $body,
308                         'received' => DateTimeFormat::utcNow()];
309
310                 DBA::insert('conversation', $conversation, true);
311         }
312
313         /**
314          * Processes the activity object
315          *
316          * @param array   $activity     Array with activity data
317          * @param string  $body
318          * @param integer $uid          User ID
319          * @param boolean $trust_source Do we trust the source?
320          * @throws \Exception
321          */
322         public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
323         {
324                 $type = JsonLD::fetchElement($activity, '@type');
325                 if (!$type) {
326                         Logger::log('Empty type', Logger::DEBUG);
327                         return;
328                 }
329
330                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
331                         Logger::log('Empty object', Logger::DEBUG);
332                         return;
333                 }
334
335                 if (!JsonLD::fetchElement($activity, 'as:actor', '@id')) {
336                         Logger::log('Empty actor', Logger::DEBUG);
337                         return;
338
339                 }
340
341                 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
342                 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
343                         $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
344                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
345                         $trust_source = ($actor == $attributed_to);
346                         if (!$trust_source) {
347                                 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
348                         }
349                 }
350
351                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
352                 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
353                 if (empty($object_data)) {
354                         Logger::log('No object data found', Logger::DEBUG);
355                         return;
356                 }
357
358                 if (!$trust_source) {
359                         Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
360                         return;
361                 }
362
363                 // Only store content related stuff - and no announces, since they possibly overwrite the original content
364                 if (in_array($object_data['object_type'], self::CONTENT_TYPES) && ($type != 'as:Announce')) {
365                         self::storeConversation($object_data, $body);
366                 }
367
368                 // Internal flag for thread completion. See Processor.php
369                 if (!empty($activity['thread-completion'])) {
370                         $object_data['thread-completion'] = $activity['thread-completion'];
371                 }
372
373                 switch ($type) {
374                         case 'as:Create':
375                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
376                                         ActivityPub\Processor::createItem($object_data);
377                                 }
378                                 break;
379
380                         case 'as:Add':
381                                 if ($object_data['object_type'] == 'as:tag') {
382                                         ActivityPub\Processor::addTag($object_data);
383                                 }
384                                 break;
385
386                         case 'as:Announce':
387                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
388                                         $profile = APContact::getByURL($object_data['actor']);
389                                         if ($profile['type'] == 'Person') {
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'] = true;
393                                         }
394                                         ActivityPub\Processor::createItem($object_data);
395
396                                         // Add the bottom reshare information only for persons
397                                         if ($profile['type'] == 'Person') {
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, ACTIVITY2_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 = defaults($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::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
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::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
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                 $profile = ActivityPub::probeProfile($url);
661                 if (empty($profile)) {
662                         return;
663                 }
664
665                 Logger::log('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
666
667                 $photo = defaults($profile, 'photo', null);
668                 unset($profile['photo']);
669                 unset($profile['baseurl']);
670                 unset($profile['guid']);
671
672                 $profile['nurl'] = Strings::normaliseLink($profile['url']);
673                 DBA::update('contact', $profile, ['id' => $cid]);
674
675                 Contact::updateAvatar($photo, $uid, $cid);
676
677                 // Send a new follow request to be sure that the connection still exists
678                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
679                         ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
680                         Logger::log('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, Logger::DEBUG);
681                 }
682         }
683
684         /**
685          *
686          *
687          * @param $receivers
688          * @param $actor
689          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
690          * @throws \ImagickException
691          */
692         private static function switchContacts($receivers, $actor)
693         {
694                 if (empty($actor)) {
695                         return;
696                 }
697
698                 foreach ($receivers as $receiver) {
699                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
700                         if (DBA::isResult($contact)) {
701                                 self::switchContact($contact['id'], $receiver, $actor);
702                         }
703
704                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
705                         if (DBA::isResult($contact)) {
706                                 self::switchContact($contact['id'], $receiver, $actor);
707                         }
708                 }
709         }
710
711         /**
712          *
713          *
714          * @param       $object_data
715          * @param array $activity
716          *
717          * @return mixed
718          */
719         private static function addActivityFields($object_data, $activity)
720         {
721                 if (!empty($activity['published']) && empty($object_data['published'])) {
722                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
723                 }
724
725                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
726                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
727                 }
728
729                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
730                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
731
732                 return $object_data;
733         }
734
735         /**
736          * Fetches the object data from external ressources if needed
737          *
738          * @param string  $object_id    Object ID of the the provided object
739          * @param array   $object       The provided object array
740          * @param boolean $trust_source Do we trust the provided object?
741          * @param integer $uid          User ID for the signature that we use to fetch data
742          *
743          * @return array|false with trusted and valid object data
744          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
745          * @throws \ImagickException
746          */
747         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
748         {
749                 // By fetching the type we check if the object is complete.
750                 $type = JsonLD::fetchElement($object, '@type');
751
752                 if (!$trust_source || empty($type)) {
753                         $data = ActivityPub::fetchContent($object_id, $uid);
754                         if (!empty($data)) {
755                                 $object = JsonLD::compact($data);
756                                 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
757                         } else {
758                                 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
759
760                                 $item = Item::selectFirst([], ['uri' => $object_id]);
761                                 if (!DBA::isResult($item)) {
762                                         Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
763                                         return false;
764                                 }
765                                 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
766                                 $data = ActivityPub\Transmitter::createNote($item);
767                                 $object = JsonLD::compact($data);
768                         }
769                 } else {
770                         Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
771                 }
772
773                 $type = JsonLD::fetchElement($object, '@type');
774
775                 if (empty($type)) {
776                         Logger::log('Empty type', Logger::DEBUG);
777                         return false;
778                 }
779
780                 if (in_array($type, self::CONTENT_TYPES)) {
781                         return self::processObject($object);
782                 }
783
784                 if ($type == 'as:Announce') {
785                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
786                         if (empty($object_id) || !is_string($object_id)) {
787                                 return false;
788                         }
789                         return self::fetchObject($object_id, [], false, $uid);
790                 }
791
792                 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
793                 return false;
794         }
795
796         /**
797          * Convert tags from JSON-LD format into a simplified format
798          *
799          * @param array $tags Tags in JSON-LD format
800          *
801          * @return array with tags in a simplified format
802          */
803         private static function processTags($tags)
804         {
805                 $taglist = [];
806
807                 if (empty($tags)) {
808                         return [];
809                 }
810
811                 foreach ($tags as $tag) {
812                         if (empty($tag)) {
813                                 continue;
814                         }
815
816                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
817                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
818                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
819
820                         if (empty($element['type'])) {
821                                 continue;
822                         }
823
824                         $taglist[] = $element;
825                 }
826                 return $taglist;
827         }
828
829         /**
830          * Convert emojis from JSON-LD format into a simplified format
831          *
832          * @param $emojis
833          * @return array with emojis in a simplified format
834          */
835         private static function processEmojis($emojis)
836         {
837                 $emojilist = [];
838
839                 if (empty($emojis)) {
840                         return [];
841                 }
842
843                 foreach ($emojis as $emoji) {
844                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
845                                 continue;
846                         }
847
848                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
849                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
850                                 'href' => $url];
851
852                         $emojilist[] = $element;
853                 }
854                 return $emojilist;
855         }
856
857         /**
858          * Convert attachments from JSON-LD format into a simplified format
859          *
860          * @param array $attachments Attachments in JSON-LD format
861          *
862          * @return array with attachmants in a simplified format
863          */
864         private static function processAttachments($attachments)
865         {
866                 $attachlist = [];
867
868                 if (empty($attachments)) {
869                         return [];
870                 }
871
872                 foreach ($attachments as $attachment) {
873                         if (empty($attachment)) {
874                                 continue;
875                         }
876
877                         $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
878                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
879                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
880                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
881                 }
882                 return $attachlist;
883         }
884
885         /**
886          * Fetches data from the object part of an activity
887          *
888          * @param array $object
889          *
890          * @return array
891          * @throws \Exception
892          */
893         private static function processObject($object)
894         {
895                 if (!JsonLD::fetchElement($object, '@id')) {
896                         return false;
897                 }
898
899                 $object_data = [];
900                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
901                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
902                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
903
904                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
905                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
906                         $object_data['reply-to-id'] = $object_data['id'];
907                 }
908
909                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
910                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
911
912                 if (empty($object_data['updated'])) {
913                         $object_data['updated'] = $object_data['published'];
914                 }
915
916                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
917                         $object_data['published'] = $object_data['updated'];
918                 }
919
920                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
921                 if (empty($actor)) {
922                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
923                 }
924
925                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
926                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
927                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
928                 $object_data['actor'] = $object_data['author'] = $actor;
929                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
930                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
931                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
932                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
933                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
934                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
935                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
936                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
937                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
938                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
939                 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
940                 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
941                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
942                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
943                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
944                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
945                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
946                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
947                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
948                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
949                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
950                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
951
952                 // Special treatment for Hubzilla links
953                 if (is_array($object_data['alternate-url'])) {
954                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
955
956                         if (!is_string($object_data['alternate-url'])) {
957                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
958                         }
959                 }
960
961                 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
962
963                 // Common object data:
964
965                 // Unhandled
966                 // @context, type, actor, signature, mediaType, duration, replies, icon
967
968                 // Also missing: (Defined in the standard, but currently unused)
969                 // audience, preview, endTime, startTime, image
970
971                 // Data in Notes:
972
973                 // Unhandled
974                 // contentMap, announcement_count, announcements, context_id, likes, like_count
975                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
976
977                 // Data in video:
978
979                 // To-Do?
980                 // category, licence, language, commentsEnabled
981
982                 // Unhandled
983                 // views, waitTranscoding, state, support, subtitleLanguage
984                 // likes, dislikes, shares, comments
985
986                 return $object_data;
987         }
988 }