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