]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Merge pull request #6201 from JonnyTischbein/feature_admin_subsubpages
[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
603                 $profile['nurl'] = Strings::normaliseLink($profile['url']);
604                 DBA::update('contact', $profile, ['id' => $cid]);
605
606                 Contact::updateAvatar($photo, $uid, $cid);
607
608                 // Send a new follow request to be sure that the connection still exists
609                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
610                         ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
611                         Logger::log('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, Logger::DEBUG);
612                 }
613         }
614
615         /**
616          *
617          *
618          * @param $receivers
619          * @param $actor
620          */
621         private static function switchContacts($receivers, $actor)
622         {
623                 if (empty($actor)) {
624                         return;
625                 }
626
627                 foreach ($receivers as $receiver) {
628                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
629                         if (DBA::isResult($contact)) {
630                                 self::switchContact($contact['id'], $receiver, $actor);
631                         }
632
633                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
634                         if (DBA::isResult($contact)) {
635                                 self::switchContact($contact['id'], $receiver, $actor);
636                         }
637                 }
638         }
639
640         /**
641          *
642          *
643          * @param $object_data
644          * @param array $activity
645          *
646          * @return
647          */
648         private static function addActivityFields($object_data, $activity)
649         {
650                 if (!empty($activity['published']) && empty($object_data['published'])) {
651                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
652                 }
653
654                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
655                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid');
656                 }
657
658                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
659
660                 return $object_data;
661         }
662
663         /**
664          * Fetches the object data from external ressources if needed
665          *
666          * @param string  $object_id    Object ID of the the provided object
667          * @param array   $object       The provided object array
668          * @param boolean $trust_source Do we trust the provided object?
669          * @param integer $uid          User ID for the signature that we use to fetch data
670          *
671          * @return array with trusted and valid object data
672          */
673         private static function fetchObject($object_id, $object = [], $trust_source = false, $uid = 0)
674         {
675                 // By fetching the type we check if the object is complete.
676                 $type = JsonLD::fetchElement($object, '@type');
677
678                 if (!$trust_source || empty($type)) {
679                         $data = ActivityPub::fetchContent($object_id, $uid);
680                         if (!empty($data)) {
681                                 $object = JsonLD::compact($data);
682                                 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
683                         } else {
684                                 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
685
686                                 $item = Item::selectFirst([], ['uri' => $object_id]);
687                                 if (!DBA::isResult($item)) {
688                                         Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
689                                         return false;
690                                 }
691                                 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
692                                 $data = ActivityPub\Transmitter::createNote($item);
693                                 $object = JsonLD::compact($data);
694                         }
695                 } else {
696                         Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
697                 }
698
699                 $type = JsonLD::fetchElement($object, '@type');
700
701                 if (empty($type)) {
702                         Logger::log('Empty type', Logger::DEBUG);
703                         return false;
704                 }
705
706                 if (in_array($type, self::CONTENT_TYPES)) {
707                         return self::processObject($object);
708                 }
709
710                 if ($type == 'as:Announce') {
711                         $object_id = JsonLD::fetchElement($object, 'object');
712                         if (empty($object_id)) {
713                                 return false;
714                         }
715                         return self::fetchObject($object_id, [], false, $uid);
716                 }
717
718                 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
719         }
720
721         /**
722          * Convert tags from JSON-LD format into a simplified format
723          *
724          * @param array $tags Tags in JSON-LD format
725          *
726          * @return array with tags in a simplified format
727          */
728         private static function processTags($tags)
729         {
730                 $taglist = [];
731
732                 if (empty($tags)) {
733                         return [];
734                 }
735
736                 foreach ($tags as $tag) {
737                         if (empty($tag)) {
738                                 continue;
739                         }
740
741                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
742                                 'href' => JsonLD::fetchElement($tag, 'as:href'),
743                                 'name' => JsonLD::fetchElement($tag, 'as:name')];
744
745                         if (empty($element['type'])) {
746                                 continue;
747                         }
748
749                         $taglist[] = $element;
750                 }
751                 return $taglist;
752         }
753
754         /**
755          * Convert emojis from JSON-LD format into a simplified format
756          *
757          * @param array $tags Tags in JSON-LD format
758          *
759          * @return array with emojis in a simplified format
760          */
761         private static function processEmojis($emojis)
762         {
763                 $emojilist = [];
764
765                 if (empty($emojis)) {
766                         return [];
767                 }
768
769                 foreach ($emojis as $emoji) {
770                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
771                                 continue;
772                         }
773
774                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url');
775                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name'),
776                                 'href' => $url];
777
778                         $emojilist[] = $element;
779                 }
780                 return $emojilist;
781         }
782
783         /**
784          * Convert attachments from JSON-LD format into a simplified format
785          *
786          * @param array $attachments Attachments in JSON-LD format
787          *
788          * @return array with attachmants in a simplified format
789          */
790         private static function processAttachments($attachments)
791         {
792                 $attachlist = [];
793
794                 if (empty($attachments)) {
795                         return [];
796                 }
797
798                 foreach ($attachments as $attachment) {
799                         if (empty($attachment)) {
800                                 continue;
801                         }
802
803                         $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
804                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
805                                 'name' => JsonLD::fetchElement($attachment, 'as:name'),
806                                 'url' => JsonLD::fetchElement($attachment, 'as:url')];
807                 }
808                 return $attachlist;
809         }
810
811         /**
812          * Fetches data from the object part of an activity
813          *
814          * @param array $object
815          *
816          * @return array
817          */
818         private static function processObject($object)
819         {
820                 if (!JsonLD::fetchElement($object, '@id')) {
821                         return false;
822                 }
823
824                 $object_data = [];
825                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
826                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
827
828                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
829
830                 if (empty($object_data['reply-to-id'])) {
831                         $object_data['reply-to-id'] = $object_data['id'];
832                 }
833
834                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
835                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
836
837                 if (empty($object_data['updated'])) {
838                         $object_data['updated'] = $object_data['published'];
839                 }
840
841                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
842                         $object_data['published'] = $object_data['updated'];
843                 }
844
845                 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
846                 if (empty($actor)) {
847                         $actor = JsonLD::fetchElement($object, 'as:actor');
848                 }
849
850                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
851                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
852                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like');
853                 $object_data['actor'] = $object_data['author'] = $actor;
854                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
855                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
856                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
857                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
858                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
859                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
860                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
861                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
862                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
863                 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
864                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
865                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
866                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
867                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
868                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
869                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
870                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
871                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
872                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
873
874                 // Special treatment for Hubzilla links
875                 if (is_array($object_data['alternate-url'])) {
876                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href');
877
878                         if (!is_string($object_data['alternate-url'])) {
879                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
880                         }
881                 }
882
883                 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
884
885                 // Common object data:
886
887                 // Unhandled
888                 // @context, type, actor, signature, mediaType, duration, replies, icon
889
890                 // Also missing: (Defined in the standard, but currently unused)
891                 // audience, preview, endTime, startTime, image
892
893                 // Data in Notes:
894
895                 // Unhandled
896                 // contentMap, announcement_count, announcements, context_id, likes, like_count
897                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
898
899                 // Data in video:
900
901                 // To-Do?
902                 // category, licence, language, commentsEnabled
903
904                 // Unhandled
905                 // views, waitTranscoding, state, support, subtitleLanguage
906                 // likes, dislikes, shares, comments
907
908                 return $object_data;
909         }
910 }