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