]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
The function is only needed in the same class
[friendica.git] / src / Protocol / ActivityPub / Receiver.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub.php
4  */
5 namespace Friendica\Protocol\ActivityPub;
6
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\Network;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\APContact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Profile;
18 use Friendica\Model\Term;
19 use Friendica\Model\User;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Crypto;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\HTML;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\LDSignature;
26 use Friendica\Core\Config;
27 use Friendica\Protocol\ActivityPub;
28
29 /**
30  * @brief ActivityPub Protocol class
31  */
32 class Receiver
33 {
34         /**
35          * @brief Checks if the web request is done for the AP protocol
36          *
37          * @return is it AP?
38          */
39         public static function isRequest()
40         {
41                 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
42                         stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
43         }
44
45         /**
46          * @brief 
47          *
48          * @param $body
49          * @param $header
50          * @param integer $uid User ID
51          */
52         public static function processInbox($body, $header, $uid)
53         {
54                 $http_signer = HTTPSignature::getSigner($body, $header);
55                 if (empty($http_signer)) {
56                         logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
57                         return;
58                 } else {
59                         logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
60                 }
61
62                 $activity = json_decode($body, true);
63
64                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
65                 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
66
67                 if (empty($activity)) {
68                         logger('Invalid body.', LOGGER_DEBUG);
69                         return;
70                 }
71
72                 if (LDSignature::isSigned($activity)) {
73                         $ld_signer = LDSignature::getSigner($activity);
74                         if (empty($ld_signer)) {
75                                 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
76                         }
77                         if (!empty($ld_signer && ($actor == $http_signer))) {
78                                 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
79                                 $trust_source = true;
80                         } elseif (!empty($ld_signer)) {
81                                 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
82                                 $trust_source = true;
83                         } elseif ($actor == $http_signer) {
84                                 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
85                                 $trust_source = true;
86                         } else {
87                                 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
88                                 $trust_source = false;
89                         }
90                 } elseif ($actor == $http_signer) {
91                         logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
92                         $trust_source = true;
93                 } else {
94                         logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
95                         $trust_source = false;
96                 }
97
98                 self::processActivity($activity, $body, $uid, $trust_source);
99         }
100
101         /**
102          * @brief 
103          *
104          * @param array $activity
105          * @param integer $uid User ID
106          * @param $trust_source
107          *
108          * @return 
109          */
110         private static function prepareObjectData($activity, $uid, &$trust_source)
111         {
112                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
113                 if (empty($actor)) {
114                         logger('Empty actor', LOGGER_DEBUG);
115                         return [];
116                 }
117
118                 // Fetch all receivers from to, cc, bto and bcc
119                 $receivers = self::getReceivers($activity, $actor);
120
121                 // When it is a delivery to a personal inbox we add that user to the receivers
122                 if (!empty($uid)) {
123                         $owner = User::getOwnerDataById($uid);
124                         $additional = ['uid:' . $uid => $uid];
125                         $receivers = array_merge($receivers, $additional);
126                 }
127
128                 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
129
130                 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
131                 if (empty($object_id)) {
132                         logger('No object found', LOGGER_DEBUG);
133                         return [];
134                 }
135
136                 // Fetch the content only on activities where this matters
137                 if (in_array($activity['type'], ['Create', 'Announce'])) {
138                         $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
139                         if (empty($object_data)) {
140                                 logger("Object data couldn't be processed", LOGGER_DEBUG);
141                                 return [];
142                         }
143                         // We had been able to retrieve the object data - so we can trust the source
144                         $trust_source = true;
145                 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
146                         // Create a mostly empty array out of the activity data (instead of the object).
147                         // This way we later don't have to check for the existence of ech individual array element.
148                         $object_data = self::processObject($activity);
149                         $object_data['name'] = $activity['type'];
150                         $object_data['author'] = $activity['actor'];
151                         $object_data['object'] = $object_id;
152                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
153                 } else {
154                         $object_data = [];
155                         $object_data['id'] = $activity['id'];
156                         $object_data['object'] = $activity['object'];
157                         $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
158                 }
159
160                 $object_data = self::addActivityFields($object_data, $activity);
161
162                 $object_data['type'] = $activity['type'];
163                 $object_data['owner'] = $actor;
164                 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
165
166                 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
167
168                 return $object_data;
169         }
170
171         /**
172          * @brief 
173          *
174          * @param array $activity
175          * @param $body
176          * @param integer $uid User ID
177          * @param $trust_source
178          */
179         public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
180         {
181                 if (empty($activity['type'])) {
182                         logger('Empty type', LOGGER_DEBUG);
183                         return;
184                 }
185
186                 if (empty($activity['object'])) {
187                         logger('Empty object', LOGGER_DEBUG);
188                         return;
189                 }
190
191                 if (empty($activity['actor'])) {
192                         logger('Empty actor', LOGGER_DEBUG);
193                         return;
194
195                 }
196
197                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
198                 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
199                 if (empty($object_data)) {
200                         logger('No object data found', LOGGER_DEBUG);
201                         return;
202                 }
203
204                 if (!$trust_source) {
205                         logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
206                 }
207
208                 switch ($activity['type']) {
209                         case 'Create':
210                         case 'Announce':
211                                 ActivityPub\Processor::createItem($object_data, $body);
212                                 break;
213
214                         case 'Like':
215                                 ActivityPub\Processor::likeItem($object_data, $body);
216                                 break;
217
218                         case 'Dislike':
219                                 ActivityPub\Processor::dislikeItem($object_data, $body);
220                                 break;
221
222                         case 'Update':
223                                 if (in_array($object_data['object_type'], ActivityPub::CONTENT_TYPES)) {
224                                         /// @todo
225                                 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
226                                         ActivityPub\Processor::updatePerson($object_data, $body);
227                                 }
228                                 break;
229
230                         case 'Delete':
231                                 if ($object_data['object_type'] == 'Tombstone') {
232                                         ActivityPub\Processor::deleteItem($object_data, $body);
233                                 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
234                                         ActivityPub\Processor::deletePerson($object_data, $body);
235                                 }
236                                 break;
237
238                         case 'Follow':
239                                 ActivityPub\Processor::followUser($object_data);
240                                 break;
241
242                         case 'Accept':
243                                 if ($object_data['object_type'] == 'Follow') {
244                                         ActivityPub\Processor::acceptFollowUser($object_data);
245                                 }
246                                 break;
247
248                         case 'Reject':
249                                 if ($object_data['object_type'] == 'Follow') {
250                                         ActivityPub\Processor::rejectFollowUser($object_data);
251                                 }
252                                 break;
253
254                         case 'Undo':
255                                 if ($object_data['object_type'] == 'Follow') {
256                                         ActivityPub\Processor::undoFollowUser($object_data);
257                                 } elseif (in_array($object_data['object_type'], ActivityPub::ACTIVITY_TYPES)) {
258                                         ActivityPub\Processor::undoActivity($object_data);
259                                 }
260                                 break;
261
262                         default:
263                                 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
264                                 break;
265                 }
266         }
267
268         /**
269          * @brief 
270          *
271          * @param array $activity
272          * @param $actor
273          *
274          * @return 
275          */
276         private static function getReceivers($activity, $actor)
277         {
278                 $receivers = [];
279
280                 // When it is an answer, we inherite the receivers from the parent
281                 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
282                 if (!empty($replyto)) {
283                         $parents = Item::select(['uid'], ['uri' => $replyto]);
284                         while ($parent = Item::fetch($parents)) {
285                                 $receivers['uid:' . $parent['uid']] = $parent['uid'];
286                         }
287                 }
288
289                 if (!empty($actor)) {
290                         $profile = APContact::getByURL($actor);
291                         $followers = defaults($profile, 'followers', '');
292
293                         logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
294                 } else {
295                         logger('Empty actor', LOGGER_DEBUG);
296                         $followers = '';
297                 }
298
299                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
300                         if (empty($activity[$element])) {
301                                 continue;
302                         }
303
304                         // The receiver can be an array or a string
305                         if (is_string($activity[$element])) {
306                                 $activity[$element] = [$activity[$element]];
307                         }
308
309                         foreach ($activity[$element] as $receiver) {
310                                 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
311                                         $receivers['uid:0'] = 0;
312                                 }
313
314                                 if (($receiver == ActivityPub::PUBLIC_COLLECTION) && !empty($actor)) {
315                                         // This will most likely catch all OStatus connections to Mastodon
316                                         $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
317                                                 , 'archive' => false, 'pending' => false];
318                                         $contacts = DBA::select('contact', ['uid'], $condition);
319                                         while ($contact = DBA::fetch($contacts)) {
320                                                 if ($contact['uid'] != 0) {
321                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
322                                                 }
323                                         }
324                                         DBA::close($contacts);
325                                 }
326
327                                 if (in_array($receiver, [$followers, ActivityPub::PUBLIC_COLLECTION]) && !empty($actor)) {
328                                         $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
329                                                 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
330                                         $contacts = DBA::select('contact', ['uid'], $condition);
331                                         while ($contact = DBA::fetch($contacts)) {
332                                                 if ($contact['uid'] != 0) {
333                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
334                                                 }
335                                         }
336                                         DBA::close($contacts);
337                                         continue;
338                                 }
339
340                                 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
341                                 $contact = DBA::selectFirst('contact', ['uid'], $condition);
342                                 if (!DBA::isResult($contact)) {
343                                         continue;
344                                 }
345                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
346                         }
347                 }
348
349                 self::switchContacts($receivers, $actor);
350
351                 return $receivers;
352         }
353
354         /**
355          * @brief 
356          *
357          * @param $cid
358          * @param integer $uid User ID
359          * @param $url
360          */
361         private static function switchContact($cid, $uid, $url)
362         {
363                 $profile = ActivityPub::probeProfile($url);
364                 if (empty($profile)) {
365                         return;
366                 }
367
368                 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
369
370                 $photo = $profile['photo'];
371                 unset($profile['photo']);
372                 unset($profile['baseurl']);
373
374                 $profile['nurl'] = normalise_link($profile['url']);
375                 DBA::update('contact', $profile, ['id' => $cid]);
376
377                 Contact::updateAvatar($photo, $uid, $cid);
378         }
379
380         /**
381          * @brief 
382          *
383          * @param $receivers
384          * @param $actor
385          */
386         private static function switchContacts($receivers, $actor)
387         {
388                 if (empty($actor)) {
389                         return;
390                 }
391
392                 foreach ($receivers as $receiver) {
393                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
394                         if (DBA::isResult($contact)) {
395                                 self::switchContact($contact['id'], $receiver, $actor);
396                         }
397
398                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
399                         if (DBA::isResult($contact)) {
400                                 self::switchContact($contact['id'], $receiver, $actor);
401                         }
402                 }
403         }
404
405         /**
406          * @brief 
407          *
408          * @param $object_data
409          * @param array $activity
410          *
411          * @return 
412          */
413         private static function addActivityFields($object_data, $activity)
414         {
415                 if (!empty($activity['published']) && empty($object_data['published'])) {
416                         $object_data['published'] = $activity['published'];
417                 }
418
419                 if (!empty($activity['updated']) && empty($object_data['updated'])) {
420                         $object_data['updated'] = $activity['updated'];
421                 }
422
423                 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
424                         $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
425                 }
426
427                 if (!empty($activity['instrument'])) {
428                         $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
429                 }
430                 return $object_data;
431         }
432
433         /**
434          * @brief 
435          *
436          * @param $object_id
437          * @param $object
438          * @param $trust_source
439          *
440          * @return 
441          */
442         private static function fetchObject($object_id, $object = [], $trust_source = false)
443         {
444                 if (!$trust_source || is_string($object)) {
445                         $data = ActivityPub::fetchContent($object_id);
446                         if (empty($data)) {
447                                 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
448                                 $data = $object_id;
449                         } else {
450                                 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
451                         }
452                 } else {
453                         logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
454                         $data = $object;
455                 }
456
457                 if (is_string($data)) {
458                         $item = Item::selectFirst([], ['uri' => $data]);
459                         if (!DBA::isResult($item)) {
460                                 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
461                                 return false;
462                         }
463                         logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
464                         $data = ActivityPub\Transmitter::createNote($item);
465                 }
466
467                 if (empty($data['type'])) {
468                         logger('Empty type', LOGGER_DEBUG);
469                         return false;
470                 }
471
472                 if (in_array($data['type'], ActivityPub::CONTENT_TYPES)) {
473                         return self::processObject($data);
474                 }
475
476                 if ($data['type'] == 'Announce') {
477                         if (empty($data['object'])) {
478                                 return false;
479                         }
480                         return self::fetchObject($data['object']);
481                 }
482
483                 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
484         }
485
486         /**
487          * @brief 
488          *
489          * @param $object
490          *
491          * @return 
492          */
493         private static function processObject($object)
494         {
495                 if (empty($object['id'])) {
496                         return false;
497                 }
498
499                 $object_data = [];
500                 $object_data['object_type'] = $object['type'];
501                 $object_data['id'] = $object['id'];
502
503                 if (!empty($object['inReplyTo'])) {
504                         $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
505                 } else {
506                         $object_data['reply-to-id'] = $object_data['id'];
507                 }
508
509                 $object_data['published'] = defaults($object, 'published', null);
510                 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
511
512                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
513                         $object_data['published'] = $object_data['updated'];
514                 }
515
516                 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
517                 if (empty($actor)) {
518                         $actor = defaults($object, 'actor', null);
519                 }
520
521                 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
522                 $object_data['owner'] = $object_data['author'] = $actor;
523                 $object_data['context'] = defaults($object, 'context', null);
524                 $object_data['conversation'] = defaults($object, 'conversation', null);
525                 $object_data['sensitive'] = defaults($object, 'sensitive', null);
526                 $object_data['name'] = defaults($object, 'title', null);
527                 $object_data['name'] = defaults($object, 'name', $object_data['name']);
528                 $object_data['summary'] = defaults($object, 'summary', null);
529                 $object_data['content'] = defaults($object, 'content', null);
530                 $object_data['source'] = defaults($object, 'source', null);
531                 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
532                 $object_data['attachments'] = defaults($object, 'attachment', null);
533                 $object_data['tags'] = defaults($object, 'tag', null);
534                 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
535                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
536                 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
537
538                 // Common object data:
539
540                 // Unhandled
541                 // @context, type, actor, signature, mediaType, duration, replies, icon
542
543                 // Also missing: (Defined in the standard, but currently unused)
544                 // audience, preview, endTime, startTime, generator, image
545
546                 // Data in Notes:
547
548                 // Unhandled
549                 // contentMap, announcement_count, announcements, context_id, likes, like_count
550                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
551
552                 // Data in video:
553
554                 // To-Do?
555                 // category, licence, language, commentsEnabled
556
557                 // Unhandled
558                 // views, waitTranscoding, state, support, subtitleLanguage
559                 // likes, dislikes, shares, comments
560
561                 return $object_data;
562         }
563 }