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