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