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