]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Added to-do
[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          * @brief 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          * @brief 
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          * @brief 
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          * @brief 
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                 }
212
213                 switch ($activity['type']) {
214                         case 'Create':
215                         case 'Announce':
216                                 ActivityPub\Processor::createItem($object_data, $body);
217                                 break;
218
219                         case 'Like':
220                                 ActivityPub\Processor::likeItem($object_data, $body);
221                                 break;
222
223                         case 'Dislike':
224                                 ActivityPub\Processor::dislikeItem($object_data, $body);
225                                 break;
226
227                         case 'Update':
228                                 if (in_array($object_data['object_type'], ActivityPub::CONTENT_TYPES)) {
229                                         /// @todo
230                                 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
231                                         ActivityPub\Processor::updatePerson($object_data, $body);
232                                 }
233                                 break;
234
235                         case 'Delete':
236                                 if ($object_data['object_type'] == 'Tombstone') {
237                                         ActivityPub\Processor::deleteItem($object_data, $body);
238                                 } elseif (in_array($object_data['object_type'], ActivityPub::ACCOUNT_TYPES)) {
239                                         ActivityPub\Processor::deletePerson($object_data, $body);
240                                 }
241                                 break;
242
243                         case 'Follow':
244                                 ActivityPub\Processor::followUser($object_data);
245                                 break;
246
247                         case 'Accept':
248                                 if ($object_data['object_type'] == 'Follow') {
249                                         ActivityPub\Processor::acceptFollowUser($object_data);
250                                 }
251                                 break;
252
253                         case 'Reject':
254                                 if ($object_data['object_type'] == 'Follow') {
255                                         ActivityPub\Processor::rejectFollowUser($object_data);
256                                 }
257                                 break;
258
259                         case 'Undo':
260                                 if ($object_data['object_type'] == 'Follow') {
261                                         ActivityPub\Processor::undoFollowUser($object_data);
262                                 } elseif (in_array($object_data['object_type'], ActivityPub::ACTIVITY_TYPES)) {
263                                         ActivityPub\Processor::undoActivity($object_data);
264                                 }
265                                 break;
266
267                         default:
268                                 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
269                                 break;
270                 }
271         }
272
273         /**
274          * @brief 
275          *
276          * @param array $activity
277          * @param $actor
278          *
279          * @return 
280          */
281         private static function getReceivers($activity, $actor)
282         {
283                 $receivers = [];
284
285                 // When it is an answer, we inherite the receivers from the parent
286                 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
287                 if (!empty($replyto)) {
288                         $parents = Item::select(['uid'], ['uri' => $replyto]);
289                         while ($parent = Item::fetch($parents)) {
290                                 $receivers['uid:' . $parent['uid']] = $parent['uid'];
291                         }
292                 }
293
294                 if (!empty($actor)) {
295                         $profile = APContact::getByURL($actor);
296                         $followers = defaults($profile, 'followers', '');
297
298                         logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
299                 } else {
300                         logger('Empty actor', LOGGER_DEBUG);
301                         $followers = '';
302                 }
303
304                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
305                         if (empty($activity[$element])) {
306                                 continue;
307                         }
308
309                         // The receiver can be an array or a string
310                         if (is_string($activity[$element])) {
311                                 $activity[$element] = [$activity[$element]];
312                         }
313
314                         foreach ($activity[$element] as $receiver) {
315                                 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
316                                         $receivers['uid:0'] = 0;
317                                 }
318
319                                 if (($receiver == ActivityPub::PUBLIC_COLLECTION) && !empty($actor)) {
320                                         // This will most likely catch all OStatus connections to Mastodon
321                                         $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
322                                                 , 'archive' => false, 'pending' => false];
323                                         $contacts = DBA::select('contact', ['uid'], $condition);
324                                         while ($contact = DBA::fetch($contacts)) {
325                                                 if ($contact['uid'] != 0) {
326                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
327                                                 }
328                                         }
329                                         DBA::close($contacts);
330                                 }
331
332                                 if (in_array($receiver, [$followers, ActivityPub::PUBLIC_COLLECTION]) && !empty($actor)) {
333                                         $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
334                                                 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
335                                         $contacts = DBA::select('contact', ['uid'], $condition);
336                                         while ($contact = DBA::fetch($contacts)) {
337                                                 if ($contact['uid'] != 0) {
338                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
339                                                 }
340                                         }
341                                         DBA::close($contacts);
342                                         continue;
343                                 }
344
345                                 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
346                                 $contact = DBA::selectFirst('contact', ['uid'], $condition);
347                                 if (!DBA::isResult($contact)) {
348                                         continue;
349                                 }
350                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
351                         }
352                 }
353
354                 self::switchContacts($receivers, $actor);
355
356                 return $receivers;
357         }
358
359         /**
360          * @brief 
361          *
362          * @param $cid
363          * @param integer $uid User ID
364          * @param $url
365          */
366         private static function switchContact($cid, $uid, $url)
367         {
368                 $profile = ActivityPub::probeProfile($url);
369                 if (empty($profile)) {
370                         return;
371                 }
372
373                 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
374
375                 $photo = $profile['photo'];
376                 unset($profile['photo']);
377                 unset($profile['baseurl']);
378
379                 $profile['nurl'] = normalise_link($profile['url']);
380                 DBA::update('contact', $profile, ['id' => $cid]);
381
382                 Contact::updateAvatar($photo, $uid, $cid);
383
384                 /// @todo Send a new follow request to be sure that the connection still exists
385         }
386
387         /**
388          * @brief 
389          *
390          * @param $receivers
391          * @param $actor
392          */
393         private static function switchContacts($receivers, $actor)
394         {
395                 if (empty($actor)) {
396                         return;
397                 }
398
399                 foreach ($receivers as $receiver) {
400                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
401                         if (DBA::isResult($contact)) {
402                                 self::switchContact($contact['id'], $receiver, $actor);
403                         }
404
405                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
406                         if (DBA::isResult($contact)) {
407                                 self::switchContact($contact['id'], $receiver, $actor);
408                         }
409                 }
410         }
411
412         /**
413          * @brief 
414          *
415          * @param $object_data
416          * @param array $activity
417          *
418          * @return 
419          */
420         private static function addActivityFields($object_data, $activity)
421         {
422                 if (!empty($activity['published']) && empty($object_data['published'])) {
423                         $object_data['published'] = $activity['published'];
424                 }
425
426                 if (!empty($activity['updated']) && empty($object_data['updated'])) {
427                         $object_data['updated'] = $activity['updated'];
428                 }
429
430                 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
431                         $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
432                 }
433
434                 if (!empty($activity['instrument'])) {
435                         $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
436                 }
437                 return $object_data;
438         }
439
440         /**
441          * @brief 
442          *
443          * @param $object_id
444          * @param $object
445          * @param $trust_source
446          *
447          * @return 
448          */
449         private static function fetchObject($object_id, $object = [], $trust_source = false)
450         {
451                 if (!$trust_source || is_string($object)) {
452                         $data = ActivityPub::fetchContent($object_id);
453                         if (empty($data)) {
454                                 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
455                                 $data = $object_id;
456                         } else {
457                                 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
458                         }
459                 } else {
460                         logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
461                         $data = $object;
462                 }
463
464                 if (is_string($data)) {
465                         $item = Item::selectFirst([], ['uri' => $data]);
466                         if (!DBA::isResult($item)) {
467                                 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
468                                 return false;
469                         }
470                         logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
471                         $data = ActivityPub\Transmitter::createNote($item);
472                 }
473
474                 if (empty($data['type'])) {
475                         logger('Empty type', LOGGER_DEBUG);
476                         return false;
477                 }
478
479                 if (in_array($data['type'], ActivityPub::CONTENT_TYPES)) {
480                         return self::processObject($data);
481                 }
482
483                 if ($data['type'] == 'Announce') {
484                         if (empty($data['object'])) {
485                                 return false;
486                         }
487                         return self::fetchObject($data['object']);
488                 }
489
490                 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
491         }
492
493         /**
494          * @brief 
495          *
496          * @param $object
497          *
498          * @return 
499          */
500         private static function processObject($object)
501         {
502                 if (empty($object['id'])) {
503                         return false;
504                 }
505
506                 $object_data = [];
507                 $object_data['object_type'] = $object['type'];
508                 $object_data['id'] = $object['id'];
509
510                 if (!empty($object['inReplyTo'])) {
511                         $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
512                 } else {
513                         $object_data['reply-to-id'] = $object_data['id'];
514                 }
515
516                 $object_data['published'] = defaults($object, 'published', null);
517                 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
518
519                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
520                         $object_data['published'] = $object_data['updated'];
521                 }
522
523                 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
524                 if (empty($actor)) {
525                         $actor = defaults($object, 'actor', null);
526                 }
527
528                 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
529                 $object_data['owner'] = $object_data['author'] = $actor;
530                 $object_data['context'] = defaults($object, 'context', null);
531                 $object_data['conversation'] = defaults($object, 'conversation', null);
532                 $object_data['sensitive'] = defaults($object, 'sensitive', null);
533                 $object_data['name'] = defaults($object, 'title', null);
534                 $object_data['name'] = defaults($object, 'name', $object_data['name']);
535                 $object_data['summary'] = defaults($object, 'summary', null);
536                 $object_data['content'] = defaults($object, 'content', null);
537                 $object_data['source'] = defaults($object, 'source', null);
538                 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
539                 $object_data['attachments'] = defaults($object, 'attachment', null);
540                 $object_data['tags'] = defaults($object, 'tag', null);
541                 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
542                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
543                 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
544
545                 // Common object data:
546
547                 // Unhandled
548                 // @context, type, actor, signature, mediaType, duration, replies, icon
549
550                 // Also missing: (Defined in the standard, but currently unused)
551                 // audience, preview, endTime, startTime, generator, image
552
553                 // Data in Notes:
554
555                 // Unhandled
556                 // contentMap, announcement_count, announcements, context_id, likes, like_count
557                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
558
559                 // Data in video:
560
561                 // To-Do?
562                 // category, licence, language, commentsEnabled
563
564                 // Unhandled
565                 // views, waitTranscoding, state, support, subtitleLanguage
566                 // likes, dislikes, shares, comments
567
568                 return $object_data;
569         }
570 }