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