]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
d3c616a7e0d9bbd6f1abb3cc1334b6551cad1d40
[friendica.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub/Processor.php
4  */
5 namespace Friendica\Protocol\ActivityPub;
6
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Conversation;
13 use Friendica\Model\Contact;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Event;
17 use Friendica\Model\User;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\JsonLD;
21 use Friendica\Util\Strings;
22
23 /**
24  * ActivityPub Processor Protocol class
25  */
26 class Processor
27 {
28         /**
29          * Converts mentions from Pleroma into the Friendica format
30          *
31          * @param string $body
32          *
33          * @return converted body
34          */
35         private static function convertMentions($body)
36         {
37                 $URLSearchString = "^\[\]";
38                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
39
40                 return $body;
41         }
42
43         /**
44          * Replaces emojis in the body
45          *
46          * @param array $emojis
47          * @param string $body
48          *
49          * @return string with replaced emojis
50          */
51         public static function replaceEmojis($emojis, $body)
52         {
53                 foreach ($emojis as $emoji) {
54                         $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
55                         $body = str_replace($emoji['name'], $replace, $body);
56                 }
57                 return $body;
58         }
59
60         /**
61          * Constructs a string with tags for a given tag array
62          *
63          * @param array $tags
64          * @param boolean $sensitive
65          *
66          * @return string with tags
67          */
68         private static function constructTagList($tags, $sensitive)
69         {
70                 if (empty($tags)) {
71                         return '';
72                 }
73
74                 $tag_text = '';
75                 foreach ($tags as $tag) {
76                         if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag'])) {
77                                 if (!empty($tag_text)) {
78                                         $tag_text .= ',';
79                                 }
80
81                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
82                         }
83                 }
84
85                 /// @todo add nsfw for $sensitive
86
87                 return $tag_text;
88         }
89
90         /**
91          * Add attachment data to the item array
92          *
93          * @param array $attachments
94          * @param array $item
95          *
96          * @return item array
97          */
98         private static function constructAttachList($attachments, $item)
99         {
100                 if (empty($attachments)) {
101                         return $item;
102                 }
103
104                 foreach ($attachments as $attach) {
105                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
106                         if ($filetype == 'image') {
107                                 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
108                         } else {
109                                 if (!empty($item["attach"])) {
110                                         $item["attach"] .= ',';
111                                 } else {
112                                         $item["attach"] = '';
113                                 }
114                                 if (!isset($attach['length'])) {
115                                         $attach['length'] = "0";
116                                 }
117                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
118                         }
119                 }
120
121                 return $item;
122         }
123
124         /**
125          * Updates a message
126          *
127          * @param array  $activity Activity array
128          */
129         public static function updateItem($activity)
130         {
131                 $item = [];
132                 $item['changed'] = DateTimeFormat::utcNow();
133                 $item['edited'] = $activity['updated'];
134                 $item['title'] = HTML::toBBCode($activity['name']);
135                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
136                 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
137                 $item['body'] = self::convertMentions($content);
138                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
139
140                 Item::update($item, ['uri' => $activity['id']]);
141         }
142
143         /**
144          * Prepares data for a message
145          *
146          * @param array  $activity Activity array
147          */
148         public static function createItem($activity)
149         {
150                 $item = [];
151                 $item['verb'] = ACTIVITY_POST;
152                 $item['parent-uri'] = $activity['reply-to-id'];
153
154                 if ($activity['reply-to-id'] == $activity['id']) {
155                         $item['gravity'] = GRAVITY_PARENT;
156                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
157                 } else {
158                         $item['gravity'] = GRAVITY_COMMENT;
159                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
160                 }
161
162                 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
163                         Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
164                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
165                 }
166
167                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
168
169                 self::postItem($activity, $item);
170         }
171
172         /**
173          * Delete items
174          *
175          * @param array $activity
176          */
177         public static function deleteItem($activity)
178         {
179                 $owner = Contact::getIdForURL($activity['actor']);
180
181                 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
182                 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
183         }
184
185         /**
186          * Prepare the item array for an activity
187          *
188          * @param array  $activity Activity array
189          * @param string $verb     Activity verb
190          */
191         public static function createActivity($activity, $verb)
192         {
193                 $item = [];
194                 $item['verb'] = $verb;
195                 $item['parent-uri'] = $activity['object_id'];
196                 $item['gravity'] = GRAVITY_ACTIVITY;
197                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
198
199                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
200
201                 self::postItem($activity, $item);
202         }
203
204         /**
205          * Create an event
206          *
207          * @param array $activity Activity array
208          * @param array $item
209          */
210         public static function createEvent($activity, $item)
211         {
212                 $event['summary']  = HTML::toBBCode($activity['name']);
213                 $event['desc']     = HTML::toBBCode($activity['content']);
214                 $event['start']    = $activity['start-time'];
215                 $event['finish']   = $activity['end-time'];
216                 $event['nofinish'] = empty($event['finish']);
217                 $event['location'] = $activity['location'];
218                 $event['adjust']   = true;
219                 $event['cid']      = $item['contact-id'];
220                 $event['uid']      = $item['uid'];
221                 $event['uri']      = $item['uri'];
222                 $event['edited']   = $item['edited'];
223                 $event['private']  = $item['private'];
224                 $event['guid']     = $item['guid'];
225                 $event['plink']    = $item['plink'];
226
227                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
228                 $ev = DBA::selectFirst('event', ['id'], $condition);
229                 if (DBA::isResult($ev)) {
230                         $event['id'] = $ev['id'];
231                 }
232
233                 $event_id = Event::store($event);
234                 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
235         }
236
237         /**
238          * Creates an item post
239          *
240          * @param array  $activity Activity data
241          * @param array  $item     item array
242          */
243         private static function postItem($activity, $item)
244         {
245                 /// @todo What to do with $activity['context']?
246
247                 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
248                         Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
249                         return;
250                 }
251
252                 $item['network'] = Protocol::ACTIVITYPUB;
253                 $item['private'] = !in_array(0, $activity['receiver']);
254                 $item['author-link'] = $activity['author'];
255                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
256
257                 if (empty($activity['thread-completion'])) {
258                         $item['owner-link'] = $activity['actor'];
259                         $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
260                 } else {
261                         Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
262                         $item['owner-link'] = $item['author-link'];
263                         $item['owner-id'] = $item['author-id'];
264                 }
265
266                 $item['uri'] = $activity['id'];
267
268                 if (($item['parent-uri'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
269                         $item_private = !in_array(0, $activity['item_receiver']);
270                         $parent = Item::selectFirst(['private'], ['uri' => $item['parent-uri']]);
271                         if (!DBA::isResult($parent)) {
272                                 return;
273                         }
274                         if ($item_private && !$parent['private']) {
275                                 Logger::log('Item ' . $item['uri'] . ' is private but the parent ' . $item['parent-uri'] . ' is not. So we drop it.');
276                                 return;
277                         }
278                 }
279
280                 $item['created'] = $activity['published'];
281                 $item['edited'] = $activity['updated'];
282                 $item['guid'] = $activity['diaspora:guid'];
283                 $item['title'] = HTML::toBBCode($activity['name']);
284                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
285                 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
286                 $item['body'] = self::convertMentions($content);
287
288                 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
289                         $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
290                 }
291
292                 $item['location'] = $activity['location'];
293
294                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
295                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
296                 }
297
298                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
299                 $item['app'] = $activity['generator'];
300                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
301
302                 $item = self::constructAttachList($activity['attachments'], $item);
303
304                 if (!empty($activity['source'])) {
305                         $item['body'] = $activity['source'];
306                 }
307
308                 foreach ($activity['receiver'] as $receiver) {
309                         $item['uid'] = $receiver;
310                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
311
312                         if (($receiver != 0) && empty($item['contact-id'])) {
313                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
314                         }
315
316                         if ($activity['object_type'] == 'as:Event') {
317                                 self::createEvent($activity, $item);
318                         }
319
320                         $item_id = Item::insert($item);
321                         Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
322                 }
323         }
324
325         /**
326          * Fetches missing posts
327          *
328          * @param $url
329          * @param $child
330          */
331         private static function fetchMissingActivity($url, $child)
332         {
333                 if (Config::get('system', 'ostatus_full_threads')) {
334                         return;
335                 }
336
337                 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
338
339                 $object = ActivityPub::fetchContent($url, $uid);
340                 if (empty($object)) {
341                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
342                         return;
343                 }
344
345                 if (empty($object['id'])) {
346                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
347                         return;
348                 }
349
350                 $activity = [];
351                 $activity['@context'] = $object['@context'];
352                 unset($object['@context']);
353                 $activity['id'] = $object['id'];
354                 $activity['to'] = defaults($object, 'to', []);
355                 $activity['cc'] = defaults($object, 'cc', []);
356                 $activity['actor'] = $child['author'];
357                 $activity['object'] = $object;
358                 $activity['published'] = defaults($object, 'published', $child['published']);
359                 $activity['type'] = 'Create';
360
361                 $ldactivity = JsonLD::compact($activity);
362
363                 $ldactivity['thread-completion'] = true;
364
365                 ActivityPub\Receiver::processActivity($ldactivity);
366                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
367         }
368
369         /**
370          * perform a "follow" request
371          *
372          * @param array $activity
373          */
374         public static function followUser($activity)
375         {
376                 $uid = User::getIdForURL($activity['object_id']);
377                 if (empty($uid)) {
378                         return;
379                 }
380
381                 $owner = User::getOwnerDataById($uid);
382
383                 $cid = Contact::getIdForURL($activity['actor'], $uid);
384                 if (!empty($cid)) {
385                         self::switchContact($cid);
386                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
387                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
388                 } else {
389                         $contact = false;
390                 }
391
392                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
393                         'author-link' => $activity['actor']];
394
395                 // Ensure that the contact has got the right network type
396                 self::switchContact($item['author-id']);
397
398                 Contact::addRelationship($owner, $contact, $item);
399                 $cid = Contact::getIdForURL($activity['actor'], $uid);
400                 if (empty($cid)) {
401                         return;
402                 }
403
404                 if (empty($contact)) {
405                         DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
406                 }
407
408                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
409         }
410
411         /**
412          * Update the given profile
413          *
414          * @param array $activity
415          */
416         public static function updatePerson($activity)
417         {
418                 if (empty($activity['object_id'])) {
419                         return;
420                 }
421
422                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
423                 APContact::getByURL($activity['object_id'], true);
424         }
425
426         /**
427          * Delete the given profile
428          *
429          * @param array $activity
430          */
431         public static function deletePerson($activity)
432         {
433                 if (empty($activity['object_id']) || empty($activity['actor'])) {
434                         Logger::log('Empty object id or actor.', Logger::DEBUG);
435                         return;
436                 }
437
438                 if ($activity['object_id'] != $activity['actor']) {
439                         Logger::log('Object id does not match actor.', Logger::DEBUG);
440                         return;
441                 }
442
443                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
444                 while ($contact = DBA::fetch($contacts)) {
445                         Contact::remove($contact['id']);
446                 }
447                 DBA::close($contacts);
448
449                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
450         }
451
452         /**
453          * Accept a follow request
454          *
455          * @param array $activity
456          */
457         public static function acceptFollowUser($activity)
458         {
459                 $uid = User::getIdForURL($activity['object_actor']);
460                 if (empty($uid)) {
461                         return;
462                 }
463
464                 $owner = User::getOwnerDataById($uid);
465
466                 $cid = Contact::getIdForURL($activity['actor'], $uid);
467                 if (empty($cid)) {
468                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
469                         return;
470                 }
471
472                 self::switchContact($cid);
473
474                 $fields = ['pending' => false];
475
476                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
477                 if ($contact['rel'] == Contact::FOLLOWER) {
478                         $fields['rel'] = Contact::FRIEND;
479                 }
480
481                 $condition = ['id' => $cid];
482                 DBA::update('contact', $fields, $condition);
483                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
484         }
485
486         /**
487          * Reject a follow request
488          *
489          * @param array $activity
490          */
491         public static function rejectFollowUser($activity)
492         {
493                 $uid = User::getIdForURL($activity['object_actor']);
494                 if (empty($uid)) {
495                         return;
496                 }
497
498                 $owner = User::getOwnerDataById($uid);
499
500                 $cid = Contact::getIdForURL($activity['actor'], $uid);
501                 if (empty($cid)) {
502                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
503                         return;
504                 }
505
506                 self::switchContact($cid);
507
508                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
509                         Contact::remove($cid);
510                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
511                 } else {
512                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
513                 }
514         }
515
516         /**
517          * Undo activity like "like" or "dislike"
518          *
519          * @param array $activity
520          */
521         public static function undoActivity($activity)
522         {
523                 if (empty($activity['object_id'])) {
524                         return;
525                 }
526
527                 if (empty($activity['object_actor'])) {
528                         return;
529                 }
530
531                 $author_id = Contact::getIdForURL($activity['object_actor']);
532                 if (empty($author_id)) {
533                         return;
534                 }
535
536                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
537         }
538
539         /**
540          * Activity to remove a follower
541          *
542          * @param array $activity
543          */
544         public static function undoFollowUser($activity)
545         {
546                 $uid = User::getIdForURL($activity['object_object']);
547                 if (empty($uid)) {
548                         return;
549                 }
550
551                 $owner = User::getOwnerDataById($uid);
552
553                 $cid = Contact::getIdForURL($activity['actor'], $uid);
554                 if (empty($cid)) {
555                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
556                         return;
557                 }
558
559                 self::switchContact($cid);
560
561                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
562                 if (!DBA::isResult($contact)) {
563                         return;
564                 }
565
566                 Contact::removeFollower($owner, $contact);
567                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
568         }
569
570         /**
571          * Switches a contact to AP if needed
572          *
573          * @param integer $cid Contact ID
574          */
575         private static function switchContact($cid)
576         {
577                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
578                 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
579                         return;
580                 }
581
582                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
583                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
584         }
585 }