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