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