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