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