]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Fetch Diaspora posts by url
[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 string $url message URL
538          * @param array $child activity array with the child of this message
539          * @return boolean success
540          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
541          */
542         public static function fetchMissingActivity($url, $child = [])
543         {
544                 if (!empty($child['receiver'])) {
545                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
546                 } else {
547                         $uid = 0;
548                 }
549
550                 $object = ActivityPub::fetchContent($url, $uid);
551                 if (empty($object)) {
552                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
553                         return false;
554                 }
555
556                 if (empty($object['id'])) {
557                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
558                         return false;
559                 }
560
561                 if (!empty($child['author'])) {
562                         $actor = $child['author'];
563                 } elseif (!empty($object['actor'])) {
564                         $actor = $object['actor'];
565                 } elseif (!empty($object['attributedTo'])) {
566                         $actor = $object['attributedTo'];
567                 } else {
568                         // Shouldn't happen
569                         $actor = '';
570                 }
571
572                 if (!empty($object['published'])) {
573                         $published = $object['published'];
574                 } elseif (!empty($child['published'])) {
575                         $published = $child['published'];
576                 } else {
577                         $published = DateTimeFormat::utcNow();
578                 }
579
580                 $activity = [];
581                 $activity['@context'] = $object['@context'];
582                 unset($object['@context']);
583                 $activity['id'] = $object['id'];
584                 $activity['to'] = defaults($object, 'to', []);
585                 $activity['cc'] = defaults($object, 'cc', []);
586                 $activity['actor'] = $actor;
587                 $activity['object'] = $object;
588                 $activity['published'] = $published;
589                 $activity['type'] = 'Create';
590
591                 $ldactivity = JsonLD::compact($activity);
592
593                 $ldactivity['thread-completion'] = true;
594
595                 ActivityPub\Receiver::processActivity($ldactivity);
596                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
597
598                 return true;
599         }
600
601         /**
602          * perform a "follow" request
603          *
604          * @param array $activity
605          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606          * @throws \ImagickException
607          */
608         public static function followUser($activity)
609         {
610                 $uid = User::getIdForURL($activity['object_id']);
611                 if (empty($uid)) {
612                         return;
613                 }
614
615                 $owner = User::getOwnerDataById($uid);
616
617                 $cid = Contact::getIdForURL($activity['actor'], $uid);
618                 if (!empty($cid)) {
619                         self::switchContact($cid);
620                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
621                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
622                 } else {
623                         $contact = [];
624                 }
625
626                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
627                         'author-link' => $activity['actor']];
628
629                 $note = Strings::escapeTags(trim(defaults($activity, 'content', '')));
630
631                 // Ensure that the contact has got the right network type
632                 self::switchContact($item['author-id']);
633
634                 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
635                 if ($result === true) {
636                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
637                 }
638
639                 $cid = Contact::getIdForURL($activity['actor'], $uid);
640                 if (empty($cid)) {
641                         return;
642                 }
643
644                 if (empty($contact)) {
645                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
646                 }
647
648                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
649         }
650
651         /**
652          * Update the given profile
653          *
654          * @param array $activity
655          * @throws \Exception
656          */
657         public static function updatePerson($activity)
658         {
659                 if (empty($activity['object_id'])) {
660                         return;
661                 }
662
663                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
664                 Contact::updateFromProbeByURL($activity['object_id'], true);
665         }
666
667         /**
668          * Delete the given profile
669          *
670          * @param array $activity
671          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
672          */
673         public static function deletePerson($activity)
674         {
675                 if (empty($activity['object_id']) || empty($activity['actor'])) {
676                         Logger::log('Empty object id or actor.', Logger::DEBUG);
677                         return;
678                 }
679
680                 if ($activity['object_id'] != $activity['actor']) {
681                         Logger::log('Object id does not match actor.', Logger::DEBUG);
682                         return;
683                 }
684
685                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
686                 while ($contact = DBA::fetch($contacts)) {
687                         Contact::remove($contact['id']);
688                 }
689                 DBA::close($contacts);
690
691                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
692         }
693
694         /**
695          * Accept a follow request
696          *
697          * @param array $activity
698          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
699          * @throws \ImagickException
700          */
701         public static function acceptFollowUser($activity)
702         {
703                 $uid = User::getIdForURL($activity['object_actor']);
704                 if (empty($uid)) {
705                         return;
706                 }
707
708                 $cid = Contact::getIdForURL($activity['actor'], $uid);
709                 if (empty($cid)) {
710                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
711                         return;
712                 }
713
714                 self::switchContact($cid);
715
716                 $fields = ['pending' => false];
717
718                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
719                 if ($contact['rel'] == Contact::FOLLOWER) {
720                         $fields['rel'] = Contact::FRIEND;
721                 }
722
723                 $condition = ['id' => $cid];
724                 DBA::update('contact', $fields, $condition);
725                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
726         }
727
728         /**
729          * Reject a follow request
730          *
731          * @param array $activity
732          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
733          * @throws \ImagickException
734          */
735         public static function rejectFollowUser($activity)
736         {
737                 $uid = User::getIdForURL($activity['object_actor']);
738                 if (empty($uid)) {
739                         return;
740                 }
741
742                 $cid = Contact::getIdForURL($activity['actor'], $uid);
743                 if (empty($cid)) {
744                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
745                         return;
746                 }
747
748                 self::switchContact($cid);
749
750                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
751                         Contact::remove($cid);
752                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
753                 } else {
754                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
755                 }
756         }
757
758         /**
759          * Undo activity like "like" or "dislike"
760          *
761          * @param array $activity
762          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
763          * @throws \ImagickException
764          */
765         public static function undoActivity($activity)
766         {
767                 if (empty($activity['object_id'])) {
768                         return;
769                 }
770
771                 if (empty($activity['object_actor'])) {
772                         return;
773                 }
774
775                 $author_id = Contact::getIdForURL($activity['object_actor']);
776                 if (empty($author_id)) {
777                         return;
778                 }
779
780                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
781         }
782
783         /**
784          * Activity to remove a follower
785          *
786          * @param array $activity
787          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
788          * @throws \ImagickException
789          */
790         public static function undoFollowUser($activity)
791         {
792                 $uid = User::getIdForURL($activity['object_object']);
793                 if (empty($uid)) {
794                         return;
795                 }
796
797                 $owner = User::getOwnerDataById($uid);
798
799                 $cid = Contact::getIdForURL($activity['actor'], $uid);
800                 if (empty($cid)) {
801                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
802                         return;
803                 }
804
805                 self::switchContact($cid);
806
807                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
808                 if (!DBA::isResult($contact)) {
809                         return;
810                 }
811
812                 Contact::removeFollower($owner, $contact);
813                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
814         }
815
816         /**
817          * Switches a contact to AP if needed
818          *
819          * @param integer $cid Contact ID
820          * @throws \Exception
821          */
822         private static function switchContact($cid)
823         {
824                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
825                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
826                         return;
827                 }
828
829                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
830                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
831         }
832
833         /**
834          * Collects implicit mentions like:
835          * - the author of the parent item
836          * - all the mentioned conversants in the parent item
837          *
838          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
839          * @return array
840          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
841          */
842         private static function getImplicitMentionList(array $parent)
843         {
844                 if (Config::get('system', 'disable_implicit_mentions')) {
845                         return [];
846                 }
847
848                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
849
850                 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
851
852                 $implicit_mentions = [];
853                 if (empty($parent_author)) {
854                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
855                 } else {
856                         $implicit_mentions[] = $parent_author['url'];
857                         $implicit_mentions[] = $parent_author['nurl'];
858                         $implicit_mentions[] = $parent_author['alias'];
859                 }
860
861                 if (!empty($parent['alias'])) {
862                         $implicit_mentions[] = $parent['alias'];
863                 }
864
865                 foreach ($parent_terms as $term) {
866                         $contact = Contact::getDetailsByURL($term['url'], 0);
867                         if (!empty($contact)) {
868                                 $implicit_mentions[] = $contact['url'];
869                                 $implicit_mentions[] = $contact['nurl'];
870                                 $implicit_mentions[] = $contact['alias'];
871                         }
872                 }
873
874                 return $implicit_mentions;
875         }
876
877         /**
878          * Strips from the body prepended implicit mentions
879          *
880          * @param string $body
881          * @param array $potential_mentions
882          * @return string
883          */
884         private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
885         {
886                 if (Config::get('system', 'disable_implicit_mentions')) {
887                         return $body;
888                 }
889
890                 $kept_mentions = [];
891
892                 // Extract one prepended mention at a time from the body
893                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
894                         if (!in_array($matches[2], $potential_mentions) ) {
895                                 $kept_mentions[] = $matches[1];
896                         }
897
898                         $body = $matches[3];
899                 }
900
901                 // Re-appending the kept mentions to the body after extraction
902                 $kept_mentions[] = $body;
903
904                 return implode('', $kept_mentions);
905         }
906
907         private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
908         {
909                 if (Config::get('system', 'disable_implicit_mentions')) {
910                         return $activity_tags;
911                 }
912
913                 foreach ($activity_tags as $index => $tag) {
914                         if (in_array($tag['href'], $potential_mentions)) {
915                                 $activity_tags[$index]['name'] = preg_replace(
916                                         '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
917                                         Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
918                                         $activity_tags[$index]['name'],
919                                         1
920                                 );
921                         }
922                 }
923
924                 return $activity_tags;
925         }
926 }