]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Add docs
[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\Content\Text\BBCode;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\Protocol;
13 use Friendica\Database\DBA;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Event;
17 use Friendica\Model\Item;
18 use Friendica\Model\Mail;
19 use Friendica\Model\Term;
20 use Friendica\Model\User;
21 use Friendica\Protocol\Activity;
22 use Friendica\Protocol\ActivityPub;
23 use Friendica\Util\DateTimeFormat;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\Strings;
26
27 /**
28  * ActivityPub Processor Protocol class
29  */
30 class Processor
31 {
32         /**
33          * Converts mentions from Pleroma into the Friendica format
34          *
35          * @param string $body
36          *
37          * @return string converted body
38          */
39         private static function convertMentions($body)
40         {
41                 $URLSearchString = "^\[\]";
42                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
43
44                 return $body;
45         }
46
47         /**
48          * Replaces emojis in the body
49          *
50          * @param array $emojis
51          * @param string $body
52          *
53          * @return string with replaced emojis
54          */
55         private static function replaceEmojis($body, array $emojis)
56         {
57                 foreach ($emojis as $emoji) {
58                         $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
59                         $body = str_replace($emoji['name'], $replace, $body);
60                 }
61                 return $body;
62         }
63
64         /**
65          * Constructs a string with tags for a given tag array
66          *
67          * @param array   $tags
68          * @param boolean $sensitive
69          * @return string with tags
70          */
71         private static function constructTagString(array $tags = null, $sensitive = false)
72         {
73                 if (empty($tags)) {
74                         return '';
75                 }
76
77                 $tag_text = '';
78                 foreach ($tags as $tag) {
79                         if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
80                                 if (!empty($tag_text)) {
81                                         $tag_text .= ',';
82                                 }
83
84                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
85                         }
86                 }
87
88                 /// @todo add nsfw for $sensitive
89
90                 return $tag_text;
91         }
92
93         /**
94          * Add attachment data to the item array
95          *
96          * @param array   $attachments
97          * @param array   $item
98          * @param boolean $no_images
99          *
100          * @return array array
101          */
102         private static function constructAttachList($attachments, $item, $no_images)
103         {
104                 if (empty($attachments)) {
105                         return $item;
106                 }
107
108                 foreach ($attachments as $attach) {
109                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
110                         if ($filetype == 'image') {
111                                 if ($no_images) {
112                                         continue;
113                                 }
114
115                                 if (empty($attach['name'])) {
116                                         $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
117                                 } else {
118                                         $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
119                                 }
120                         } else {
121                                 if (!empty($item["attach"])) {
122                                         $item["attach"] .= ',';
123                                 } else {
124                                         $item["attach"] = '';
125                                 }
126                                 if (!isset($attach['length'])) {
127                                         $attach['length'] = "0";
128                                 }
129                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
130                         }
131                 }
132
133                 return $item;
134         }
135
136         /**
137          * Updates a message
138          *
139          * @param array $activity Activity array
140          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141          */
142         public static function updateItem($activity)
143         {
144                 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
145                 if (!DBA::isResult($item)) {
146                         Logger::warning('Unknown item', ['uri' => $activity['id']]);
147                         return;
148                 }
149
150                 $item['changed'] = DateTimeFormat::utcNow();
151                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
152
153                 $item = self::processContent($activity, $item);
154                 if (empty($item)) {
155                         return;
156                 }
157
158                 Item::update($item, ['uri' => $activity['id']]);
159         }
160
161         /**
162          * Prepares data for a message
163          *
164          * @param array $activity Activity array
165          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
166          * @throws \ImagickException
167          */
168         public static function createItem($activity)
169         {
170                 $item = [];
171                 $item['verb'] = Activity::POST;
172                 $item['thr-parent'] = $activity['reply-to-id'];
173
174                 if ($activity['reply-to-id'] == $activity['id']) {
175                         $item['gravity'] = GRAVITY_PARENT;
176                         $item['object-type'] = Activity\ObjectType::NOTE;
177                 } else {
178                         $item['gravity'] = GRAVITY_COMMENT;
179                         $item['object-type'] = Activity\ObjectType::COMMENT;
180                 }
181
182                 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
183                         Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
184                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
185                 }
186
187                 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
188
189                 self::postItem($activity, $item);
190         }
191
192         /**
193          * Delete items
194          *
195          * @param array $activity
196          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
197          * @throws \ImagickException
198          */
199         public static function deleteItem($activity)
200         {
201                 $owner = Contact::getIdForURL($activity['actor']);
202
203                 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
204                 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
205         }
206
207         /**
208          * Prepare the item array for an activity
209          *
210          * @param array $activity Activity array
211          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212          * @throws \ImagickException
213          */
214         public static function addTag($activity)
215         {
216                 if (empty($activity['object_content']) || empty($activity['object_id'])) {
217                         return;
218                 }
219
220                 foreach ($activity['receiver'] as $receiver) {
221                         $item = Item::selectFirst(['id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
222                         if (!DBA::isResult($item)) {
223                                 // We don't fetch missing content for this purpose
224                                 continue;
225                         }
226
227                         if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
228                                 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
229                                 continue;
230                         }
231
232                         // To-Do:
233                         // - Check if "blocktag" is set
234                         // - Check if actor is a contact
235
236                         if (!stristr($item['tag'], trim($activity['object_content']))) {
237                                 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
238                                 Item::update(['tag' => $tag], ['id' => $item['id']]);
239                                 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
240                         }
241                 }
242         }
243
244         /**
245          * Prepare the item array for an activity
246          *
247          * @param array  $activity Activity array
248          * @param string $verb     Activity verb
249          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250          * @throws \ImagickException
251          */
252         public static function createActivity($activity, $verb)
253         {
254                 $item = [];
255                 $item['verb'] = $verb;
256                 $item['thr-parent'] = $activity['object_id'];
257                 $item['gravity'] = GRAVITY_ACTIVITY;
258                 $item['object-type'] = Activity\ObjectType::NOTE;
259
260                 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
261
262                 self::postItem($activity, $item);
263         }
264
265         /**
266          * Create an event
267          *
268          * @param array $activity Activity array
269          * @param array $item
270          * @throws \Exception
271          */
272         public static function createEvent($activity, $item)
273         {
274                 $event['summary']  = HTML::toBBCode($activity['name']);
275                 $event['desc']     = HTML::toBBCode($activity['content']);
276                 $event['start']    = $activity['start-time'];
277                 $event['finish']   = $activity['end-time'];
278                 $event['nofinish'] = empty($event['finish']);
279                 $event['location'] = $activity['location'];
280                 $event['adjust']   = true;
281                 $event['cid']      = $item['contact-id'];
282                 $event['uid']      = $item['uid'];
283                 $event['uri']      = $item['uri'];
284                 $event['edited']   = $item['edited'];
285                 $event['private']  = $item['private'];
286                 $event['guid']     = $item['guid'];
287                 $event['plink']    = $item['plink'];
288
289                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
290                 $ev = DBA::selectFirst('event', ['id'], $condition);
291                 if (DBA::isResult($ev)) {
292                         $event['id'] = $ev['id'];
293                 }
294
295                 $event_id = Event::store($event);
296                 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
297         }
298
299         /**
300          * Process the content
301          *
302          * @param array $activity Activity array
303          * @param array $item
304          * @return array|bool Returns the item array or false if there was an unexpected occurrence
305          * @throws \Exception
306          */
307         private static function processContent($activity, $item)
308         {
309                 $item['title'] = HTML::toBBCode($activity['name']);
310
311                 if (!empty($activity['source'])) {
312                         $item['body'] = $activity['source'];
313                 } else {
314                         $content = HTML::toBBCode($activity['content']);
315
316                         if (!empty($activity['emojis'])) {
317                                 $content = self::replaceEmojis($content, $activity['emojis']);
318                         }
319
320                         $content = self::convertMentions($content);
321
322                         if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
323                                 $item_private = !in_array(0, $activity['item_receiver']);
324                                 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
325                                 if (!DBA::isResult($parent)) {
326                                         Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
327                                         return false;
328                                 }
329                                 if ($item_private && !$parent['private']) {
330                                         Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
331                                         return false;
332                                 }
333
334                                 $potential_implicit_mentions = self::getImplicitMentionList($parent);
335                                 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
336                                 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
337                         }
338                         $item['content-warning'] = HTML::toBBCode($activity['summary']);
339                         $item['body'] = $content;
340
341                         if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
342                                 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
343                         }
344                 }
345
346                 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
347
348                 $item['location'] = $activity['location'];
349
350                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
351                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
352                 }
353
354                 $item['app'] = $activity['generator'];
355
356                 return $item;
357         }
358
359         /**
360          * Creates an item post
361          *
362          * @param array $activity Activity data
363          * @param array $item     item array
364          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
365          * @throws \ImagickException
366          */
367         private static function postItem($activity, $item)
368         {
369                 /// @todo What to do with $activity['context']?
370                 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
371                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
372                         return;
373                 }
374
375                 $item['network'] = Protocol::ACTIVITYPUB;
376                 $item['private'] = !in_array(0, $activity['receiver']);
377                 $item['author-link'] = $activity['author'];
378                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
379                 $item['owner-link'] = $activity['actor'];
380                 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
381
382                 $isForum = false;
383
384                 if (!empty($activity['thread-completion'])) {
385                         // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
386                         $item['causer-link'] = $item['owner-link'];
387                         $item['causer-id'] = $item['owner-id'];
388
389                         Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
390                         $item['owner-link'] = $item['author-link'];
391                         $item['owner-id'] = $item['author-id'];
392                 } else {
393                         $actor = APContact::getByURL($item['owner-link'], false);
394                         $isForum = ($actor['type'] == 'Group');
395                 }
396
397                 $item['uri'] = $activity['id'];
398
399                 $item['created'] = DateTimeFormat::utc($activity['published']);
400                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
401                 $item['guid'] = $activity['diaspora:guid'];
402
403                 $item = self::processContent($activity, $item);
404                 if (empty($item)) {
405                         return;
406                 }
407
408                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
409
410                 $item = self::constructAttachList($activity['attachments'], $item, !empty($activity['source']));
411
412                 $stored = false;
413
414                 foreach ($activity['receiver'] as $receiver) {
415                         $item['uid'] = $receiver;
416
417                         if ($isForum) {
418                                 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
419                         } else {
420                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
421                         }
422
423                         if (($receiver != 0) && empty($item['contact-id'])) {
424                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
425                         }
426
427                         if (!empty($activity['directmessage'])) {
428                                 self::postMail($activity, $item);
429                                 continue;
430                         }
431
432                         if (PConfig::get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
433                                 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
434
435                                 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
436                                         $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
437                                 }
438
439                                 if ($skip) {
440                                         Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
441                                         continue;
442                                 }
443
444                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
445                         }
446
447                         if ($activity['object_type'] == 'as:Event') {
448                                 self::createEvent($activity, $item);
449                         }
450
451                         $item_id = Item::insert($item);
452                         if ($item_id) {
453                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
454                         } else {
455                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
456                         }
457
458                         if ($item['uid'] == 0) {
459                                 $stored = $item_id;
460                         }
461                 }
462
463                 // Store send a follow request for every reshare - but only when the item had been stored
464                 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
465                         $author = APContact::getByURL($item['owner-link'], false);
466                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
467                         if ($author['type'] != 'Group') {
468                                 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
469                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
470                         }
471                 }
472         }
473
474         /**
475          * Creates an mail post
476          *
477          * @param array $activity Activity data
478          * @param array $item     item array
479          * @return int|bool New mail table row id or false on error
480          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
481          */
482         private static function postMail($activity, $item)
483         {
484                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
485                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
486                         return false;
487                 }
488
489                 Logger::info('Direct Message', $item);
490
491                 $msg = [];
492                 $msg['uid'] = $item['uid'];
493
494                 $msg['contact-id'] = $item['contact-id'];
495
496                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
497                 $msg['from-name'] = $contact['name'];
498                 $msg['from-url'] = $contact['url'];
499                 $msg['from-photo'] = $contact['photo'];
500
501                 $msg['uri'] = $item['uri'];
502                 $msg['created'] = $item['created'];
503
504                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
505                 if (DBA::isResult($parent)) {
506                         $msg['parent-uri'] = $parent['parent-uri'];
507                         $msg['title'] = $parent['title'];
508                 } else {
509                         $msg['parent-uri'] = $item['thr-parent'];
510
511                         if (!empty($item['title'])) {
512                                 $msg['title'] = $item['title'];
513                         } elseif (!empty($item['content-warning'])) {
514                                 $msg['title'] = $item['content-warning'];
515                         } else {
516                                 // Trying to generate a title out of the body
517                                 $title = $item['body'];
518
519                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
520                                         $title = $matches[3];
521                                 }
522
523                                 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
524
525                                 if (strlen($title) > 20) {
526                                         $title = substr($title, 0, 20) . '...';
527                                 }
528
529                                 $msg['title'] = $title;
530                         }
531                 }
532                 $msg['body'] = $item['body'];
533
534                 return Mail::insert($msg);
535         }
536
537         /**
538          * Fetches missing posts
539          *
540          * @param string $url message URL
541          * @param array $child activity array with the child of this message
542          * @return boolean success
543          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
544          */
545         public static function fetchMissingActivity($url, $child = [])
546         {
547                 if (!empty($child['receiver'])) {
548                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
549                 } else {
550                         $uid = 0;
551                 }
552
553                 $object = ActivityPub::fetchContent($url, $uid);
554                 if (empty($object)) {
555                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
556                         return false;
557                 }
558
559                 if (empty($object['id'])) {
560                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
561                         return false;
562                 }
563
564                 if (!empty($child['author'])) {
565                         $actor = $child['author'];
566                 } elseif (!empty($object['actor'])) {
567                         $actor = $object['actor'];
568                 } elseif (!empty($object['attributedTo'])) {
569                         $actor = $object['attributedTo'];
570                 } else {
571                         // Shouldn't happen
572                         $actor = '';
573                 }
574
575                 if (!empty($object['published'])) {
576                         $published = $object['published'];
577                 } elseif (!empty($child['published'])) {
578                         $published = $child['published'];
579                 } else {
580                         $published = DateTimeFormat::utcNow();
581                 }
582
583                 $activity = [];
584                 $activity['@context'] = $object['@context'];
585                 unset($object['@context']);
586                 $activity['id'] = $object['id'];
587                 $activity['to'] = $object['to'] ?? [];
588                 $activity['cc'] = $object['cc'] ?? [];
589                 $activity['actor'] = $actor;
590                 $activity['object'] = $object;
591                 $activity['published'] = $published;
592                 $activity['type'] = 'Create';
593
594                 $ldactivity = JsonLD::compact($activity);
595
596                 $ldactivity['thread-completion'] = true;
597
598                 ActivityPub\Receiver::processActivity($ldactivity);
599                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
600
601                 return true;
602         }
603
604         /**
605          * perform a "follow" request
606          *
607          * @param array $activity
608          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
609          * @throws \ImagickException
610          */
611         public static function followUser($activity)
612         {
613                 $uid = User::getIdForURL($activity['object_id']);
614                 if (empty($uid)) {
615                         return;
616                 }
617
618                 $owner = User::getOwnerDataById($uid);
619
620                 $cid = Contact::getIdForURL($activity['actor'], $uid);
621                 if (!empty($cid)) {
622                         self::switchContact($cid);
623                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
624                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
625                 } else {
626                         $contact = [];
627                 }
628
629                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
630                         'author-link' => $activity['actor']];
631
632                 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
633
634                 // Ensure that the contact has got the right network type
635                 self::switchContact($item['author-id']);
636
637                 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
638                 if ($result === true) {
639                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
640                 }
641
642                 $cid = Contact::getIdForURL($activity['actor'], $uid);
643                 if (empty($cid)) {
644                         return;
645                 }
646
647                 if (empty($contact)) {
648                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
649                 }
650
651                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
652         }
653
654         /**
655          * Update the given profile
656          *
657          * @param array $activity
658          * @throws \Exception
659          */
660         public static function updatePerson($activity)
661         {
662                 if (empty($activity['object_id'])) {
663                         return;
664                 }
665
666                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
667                 Contact::updateFromProbeByURL($activity['object_id'], true);
668         }
669
670         /**
671          * Delete the given profile
672          *
673          * @param array $activity
674          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675          */
676         public static function deletePerson($activity)
677         {
678                 if (empty($activity['object_id']) || empty($activity['actor'])) {
679                         Logger::log('Empty object id or actor.', Logger::DEBUG);
680                         return;
681                 }
682
683                 if ($activity['object_id'] != $activity['actor']) {
684                         Logger::log('Object id does not match actor.', Logger::DEBUG);
685                         return;
686                 }
687
688                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
689                 while ($contact = DBA::fetch($contacts)) {
690                         Contact::remove($contact['id']);
691                 }
692                 DBA::close($contacts);
693
694                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
695         }
696
697         /**
698          * Accept a follow request
699          *
700          * @param array $activity
701          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
702          * @throws \ImagickException
703          */
704         public static function acceptFollowUser($activity)
705         {
706                 $uid = User::getIdForURL($activity['object_actor']);
707                 if (empty($uid)) {
708                         return;
709                 }
710
711                 $cid = Contact::getIdForURL($activity['actor'], $uid);
712                 if (empty($cid)) {
713                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
714                         return;
715                 }
716
717                 self::switchContact($cid);
718
719                 $fields = ['pending' => false];
720
721                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
722                 if ($contact['rel'] == Contact::FOLLOWER) {
723                         $fields['rel'] = Contact::FRIEND;
724                 }
725
726                 $condition = ['id' => $cid];
727                 DBA::update('contact', $fields, $condition);
728                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
729         }
730
731         /**
732          * Reject a follow request
733          *
734          * @param array $activity
735          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
736          * @throws \ImagickException
737          */
738         public static function rejectFollowUser($activity)
739         {
740                 $uid = User::getIdForURL($activity['object_actor']);
741                 if (empty($uid)) {
742                         return;
743                 }
744
745                 $cid = Contact::getIdForURL($activity['actor'], $uid);
746                 if (empty($cid)) {
747                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
748                         return;
749                 }
750
751                 self::switchContact($cid);
752
753                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
754                         Contact::remove($cid);
755                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
756                 } else {
757                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
758                 }
759         }
760
761         /**
762          * Undo activity like "like" or "dislike"
763          *
764          * @param array $activity
765          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766          * @throws \ImagickException
767          */
768         public static function undoActivity($activity)
769         {
770                 if (empty($activity['object_id'])) {
771                         return;
772                 }
773
774                 if (empty($activity['object_actor'])) {
775                         return;
776                 }
777
778                 $author_id = Contact::getIdForURL($activity['object_actor']);
779                 if (empty($author_id)) {
780                         return;
781                 }
782
783                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
784         }
785
786         /**
787          * Activity to remove a follower
788          *
789          * @param array $activity
790          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
791          * @throws \ImagickException
792          */
793         public static function undoFollowUser($activity)
794         {
795                 $uid = User::getIdForURL($activity['object_object']);
796                 if (empty($uid)) {
797                         return;
798                 }
799
800                 $owner = User::getOwnerDataById($uid);
801
802                 $cid = Contact::getIdForURL($activity['actor'], $uid);
803                 if (empty($cid)) {
804                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
805                         return;
806                 }
807
808                 self::switchContact($cid);
809
810                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
811                 if (!DBA::isResult($contact)) {
812                         return;
813                 }
814
815                 Contact::removeFollower($owner, $contact);
816                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
817         }
818
819         /**
820          * Switches a contact to AP if needed
821          *
822          * @param integer $cid Contact ID
823          * @throws \Exception
824          */
825         private static function switchContact($cid)
826         {
827                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
828                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
829                         return;
830                 }
831
832                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
833                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
834         }
835
836         /**
837          * Collects implicit mentions like:
838          * - the author of the parent item
839          * - all the mentioned conversants in the parent item
840          *
841          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
842          * @return array
843          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
844          */
845         private static function getImplicitMentionList(array $parent)
846         {
847                 if (Config::get('system', 'disable_implicit_mentions')) {
848                         return [];
849                 }
850
851                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
852
853                 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
854
855                 $implicit_mentions = [];
856                 if (empty($parent_author)) {
857                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
858                 } else {
859                         $implicit_mentions[] = $parent_author['url'];
860                         $implicit_mentions[] = $parent_author['nurl'];
861                         $implicit_mentions[] = $parent_author['alias'];
862                 }
863
864                 if (!empty($parent['alias'])) {
865                         $implicit_mentions[] = $parent['alias'];
866                 }
867
868                 foreach ($parent_terms as $term) {
869                         $contact = Contact::getDetailsByURL($term['url'], 0);
870                         if (!empty($contact)) {
871                                 $implicit_mentions[] = $contact['url'];
872                                 $implicit_mentions[] = $contact['nurl'];
873                                 $implicit_mentions[] = $contact['alias'];
874                         }
875                 }
876
877                 return $implicit_mentions;
878         }
879
880         /**
881          * Strips from the body prepended implicit mentions
882          *
883          * @param string $body
884          * @param array $potential_mentions
885          * @return string
886          */
887         private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
888         {
889                 if (Config::get('system', 'disable_implicit_mentions')) {
890                         return $body;
891                 }
892
893                 $kept_mentions = [];
894
895                 // Extract one prepended mention at a time from the body
896                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
897                         if (!in_array($matches[2], $potential_mentions)) {
898                                 $kept_mentions[] = $matches[1];
899                         }
900
901                         $body = $matches[3];
902                 }
903
904                 // Re-appending the kept mentions to the body after extraction
905                 $kept_mentions[] = $body;
906
907                 return implode('', $kept_mentions);
908         }
909
910         private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
911         {
912                 if (Config::get('system', 'disable_implicit_mentions')) {
913                         return $activity_tags;
914                 }
915
916                 foreach ($activity_tags as $index => $tag) {
917                         if (in_array($tag['href'], $potential_mentions)) {
918                                 $activity_tags[$index]['name'] = preg_replace(
919                                         '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
920                                         Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
921                                         $activity_tags[$index]['name'],
922                                         1
923                                 );
924                         }
925                 }
926
927                 return $activity_tags;
928         }
929 }