]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Missing arrrrr!
[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          * @param array   $implicit_mentions List of profile URLs to skip
68          * @return string with tags
69          */
70         private static function constructTagString(array $tags, $sensitive)
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'] = $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 (($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          * @param string $verb     Activity verb
207          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208          * @throws \ImagickException
209          */
210         public static function createActivity($activity, $verb)
211         {
212                 $item = [];
213                 $item['verb'] = $verb;
214                 $item['thr-parent'] = $activity['object_id'];
215                 $item['gravity'] = GRAVITY_ACTIVITY;
216                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
217
218                 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
219
220                 self::postItem($activity, $item);
221         }
222
223         /**
224          * Create an event
225          *
226          * @param array $activity Activity array
227          * @param array $item
228          * @throws \Exception
229          */
230         public static function createEvent($activity, $item)
231         {
232                 $event['summary']  = HTML::toBBCode($activity['name']);
233                 $event['desc']     = HTML::toBBCode($activity['content']);
234                 $event['start']    = $activity['start-time'];
235                 $event['finish']   = $activity['end-time'];
236                 $event['nofinish'] = empty($event['finish']);
237                 $event['location'] = $activity['location'];
238                 $event['adjust']   = true;
239                 $event['cid']      = $item['contact-id'];
240                 $event['uid']      = $item['uid'];
241                 $event['uri']      = $item['uri'];
242                 $event['edited']   = $item['edited'];
243                 $event['private']  = $item['private'];
244                 $event['guid']     = $item['guid'];
245                 $event['plink']    = $item['plink'];
246
247                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
248                 $ev = DBA::selectFirst('event', ['id'], $condition);
249                 if (DBA::isResult($ev)) {
250                         $event['id'] = $ev['id'];
251                 }
252
253                 $event_id = Event::store($event);
254                 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
255         }
256
257         /**
258          * Process the content
259          *
260          * @param array $activity Activity array
261          * @param array $item
262          * @return array|bool Returns the item array or false if there was an unexpected occurrence
263          * @throws \Exception
264          */
265         private static function processContent($activity, $item)
266         {
267                 $item['title'] = HTML::toBBCode($activity['name']);
268
269                 if (!empty($activity['source'])) {
270                         $item['body'] = $activity['source'];
271                 } else {
272                         $content = HTML::toBBCode($activity['content']);
273
274                         if (!empty($activity['emojis'])) {
275                                 $content = self::replaceEmojis($content, $activity['emojis']);
276                         }
277
278                         $content = self::convertMentions($content);
279
280                         if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
281                                 $item_private = !in_array(0, $activity['item_receiver']);
282                                 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
283                                 if (!DBA::isResult($parent)) {
284                                         Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
285                                         return false;
286                                 }
287                                 if ($item_private && !$parent['private']) {
288                                         Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
289                                         return false;
290                                 }
291
292                                 $potential_implicit_mentions = self::getImplicitMentionList($parent);
293                                 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
294                                 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
295                         }
296                         $item['content-warning'] = HTML::toBBCode($activity['summary']);
297                         $item['body'] = $content;
298
299                         if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
300                                 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
301                         }
302                 }
303
304                 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
305
306                 $item['location'] = $activity['location'];
307
308                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
309                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
310                 }
311
312                 $item['app'] = $activity['generator'];
313
314                 return $item;
315         }
316
317         /**
318          * Creates an item post
319          *
320          * @param array $activity Activity data
321          * @param array $item     item array
322          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
323          * @throws \ImagickException
324          */
325         private static function postItem($activity, $item)
326         {
327                 /// @todo What to do with $activity['context']?
328                 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
329                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
330                         return;
331                 }
332
333                 $item['network'] = Protocol::ACTIVITYPUB;
334                 $item['private'] = !in_array(0, $activity['receiver']);
335                 $item['author-link'] = $activity['author'];
336                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
337
338                 if (empty($activity['thread-completion'])) {
339                         $item['owner-link'] = $activity['actor'];
340                         $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
341                 } else {
342                         Logger::info('Ignoring actor because of thread completion.');
343                         $item['owner-link'] = $item['author-link'];
344                         $item['owner-id'] = $item['author-id'];
345                 }
346
347                 $item['uri'] = $activity['id'];
348
349                 $item['created'] = $activity['published'];
350                 $item['edited'] = $activity['updated'];
351                 $item['guid'] = $activity['diaspora:guid'];
352
353                 $item = self::processContent($activity, $item);
354                 if (empty($item)) {
355                         return;
356                 }
357
358                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
359
360                 $item = self::constructAttachList($activity['attachments'], $item, !empty($activity['source']));
361
362                 $stored = false;
363
364                 foreach ($activity['receiver'] as $receiver) {
365                         $item['uid'] = $receiver;
366                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
367
368                         if (($receiver != 0) && empty($item['contact-id'])) {
369                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
370                         }
371
372                         if (!empty($activity['directmessage'])) {
373                                 self::postMail($activity, $item);
374                                 continue;
375                         }
376
377                         if ($activity['object_type'] == 'as:Event') {
378                                 self::createEvent($activity, $item);
379                         }
380
381                         $item_id = Item::insert($item);
382                         if ($item_id) {
383                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
384                         } else {
385                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
386                         }
387
388                         if ($item['uid'] == 0) {
389                                 $stored = $item_id;
390                         }
391                 }
392
393                 // Store send a follow request for every reshare - but only when the item had been stored
394                 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
395                         $author = APContact::getByURL($item['owner-link'], false);
396                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
397                         if ($author['type'] != 'Group') {
398                                 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
399                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
400                         }
401                 }
402         }
403
404         /**
405          * Creates an mail post
406          *
407          * @param array $activity Activity data
408          * @param array $item     item array
409          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
410          * @throws \ImagickException
411          */
412         private static function postMail($activity, $item)
413         {
414                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
415                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
416                         return false;
417                 }
418
419                 Logger::info('Direct Message', $item);
420
421                 $msg = [];
422                 $msg['uid'] = $item['uid'];
423
424                 $msg['contact-id'] = $item['contact-id'];
425
426                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
427                 $msg['from-name'] = $contact['name'];
428                 $msg['from-url'] = $contact['url'];
429                 $msg['from-photo'] = $contact['photo'];
430
431                 $msg['uri'] = $item['uri'];
432                 $msg['created'] = $item['created'];
433
434                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
435                 if (DBA::isResult($parent)) {
436                         $msg['parent-uri'] = $parent['parent-uri'];
437                         $msg['title'] = $parent['title'];
438                 } else {
439                         $msg['parent-uri'] = $item['thr-parent'];
440
441                         if (!empty($item['title'])) {
442                                 $msg['title'] = $item['title'];
443                         } elseif (!empty($item['content-warning'])) {
444                                 $msg['title'] = $item['content-warning'];
445                         } else {
446                                 // Trying to generate a title out of the body
447                                 $title = $item['body'];
448
449                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
450                                         $title = $matches[3];
451                                 }
452
453                                 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
454
455                                 if (strlen($title) > 20) {
456                                         $title = substr($title, 0, 20) . '...';
457                                 }
458
459                                 $msg['title'] = $title;
460                         }
461                 }
462                 $msg['body'] = $item['body'];
463
464                 Mail::insert($msg);
465         }
466
467         /**
468          * Fetches missing posts
469          *
470          * @param $url
471          * @param $child
472          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
473          */
474         private static function fetchMissingActivity($url, $child)
475         {
476                 if (Config::get('system', 'ostatus_full_threads')) {
477                         return;
478                 }
479
480                 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
481
482                 $object = ActivityPub::fetchContent($url, $uid);
483                 if (empty($object)) {
484                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
485                         return;
486                 }
487
488                 if (empty($object['id'])) {
489                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
490                         return;
491                 }
492
493                 $activity = [];
494                 $activity['@context'] = $object['@context'];
495                 unset($object['@context']);
496                 $activity['id'] = $object['id'];
497                 $activity['to'] = defaults($object, 'to', []);
498                 $activity['cc'] = defaults($object, 'cc', []);
499                 $activity['actor'] = $child['author'];
500                 $activity['object'] = $object;
501                 $activity['published'] = defaults($object, 'published', $child['published']);
502                 $activity['type'] = 'Create';
503
504                 $ldactivity = JsonLD::compact($activity);
505
506                 $ldactivity['thread-completion'] = true;
507
508                 ActivityPub\Receiver::processActivity($ldactivity);
509                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
510         }
511
512         /**
513          * perform a "follow" request
514          *
515          * @param array $activity
516          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517          * @throws \ImagickException
518          */
519         public static function followUser($activity)
520         {
521                 $uid = User::getIdForURL($activity['object_id']);
522                 if (empty($uid)) {
523                         return;
524                 }
525
526                 $owner = User::getOwnerDataById($uid);
527
528                 $cid = Contact::getIdForURL($activity['actor'], $uid);
529                 if (!empty($cid)) {
530                         self::switchContact($cid);
531                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
532                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
533                 } else {
534                         $contact = false;
535                 }
536
537                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
538                         'author-link' => $activity['actor']];
539
540                 $note = Strings::escapeTags(trim(defaults($activity, 'content', '')));
541
542                 // Ensure that the contact has got the right network type
543                 self::switchContact($item['author-id']);
544
545                 Contact::addRelationship($owner, $contact, $item, '', false, $note);
546                 $cid = Contact::getIdForURL($activity['actor'], $uid);
547                 if (empty($cid)) {
548                         return;
549                 }
550
551                 if (empty($contact)) {
552                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
553                 }
554
555                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
556         }
557
558         /**
559          * Update the given profile
560          *
561          * @param array $activity
562          * @throws \Exception
563          */
564         public static function updatePerson($activity)
565         {
566                 if (empty($activity['object_id'])) {
567                         return;
568                 }
569
570                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
571                 APContact::getByURL($activity['object_id'], true);
572         }
573
574         /**
575          * Delete the given profile
576          *
577          * @param array $activity
578          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
579          */
580         public static function deletePerson($activity)
581         {
582                 if (empty($activity['object_id']) || empty($activity['actor'])) {
583                         Logger::log('Empty object id or actor.', Logger::DEBUG);
584                         return;
585                 }
586
587                 if ($activity['object_id'] != $activity['actor']) {
588                         Logger::log('Object id does not match actor.', Logger::DEBUG);
589                         return;
590                 }
591
592                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
593                 while ($contact = DBA::fetch($contacts)) {
594                         Contact::remove($contact['id']);
595                 }
596                 DBA::close($contacts);
597
598                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
599         }
600
601         /**
602          * Accept a follow request
603          *
604          * @param array $activity
605          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606          * @throws \ImagickException
607          */
608         public static function acceptFollowUser($activity)
609         {
610                 $uid = User::getIdForURL($activity['object_actor']);
611                 if (empty($uid)) {
612                         return;
613                 }
614
615                 $cid = Contact::getIdForURL($activity['actor'], $uid);
616                 if (empty($cid)) {
617                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
618                         return;
619                 }
620
621                 self::switchContact($cid);
622
623                 $fields = ['pending' => false];
624
625                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
626                 if ($contact['rel'] == Contact::FOLLOWER) {
627                         $fields['rel'] = Contact::FRIEND;
628                 }
629
630                 $condition = ['id' => $cid];
631                 DBA::update('contact', $fields, $condition);
632                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
633         }
634
635         /**
636          * Reject a follow request
637          *
638          * @param array $activity
639          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
640          * @throws \ImagickException
641          */
642         public static function rejectFollowUser($activity)
643         {
644                 $uid = User::getIdForURL($activity['object_actor']);
645                 if (empty($uid)) {
646                         return;
647                 }
648
649                 $cid = Contact::getIdForURL($activity['actor'], $uid);
650                 if (empty($cid)) {
651                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
652                         return;
653                 }
654
655                 self::switchContact($cid);
656
657                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
658                         Contact::remove($cid);
659                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
660                 } else {
661                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
662                 }
663         }
664
665         /**
666          * Undo activity like "like" or "dislike"
667          *
668          * @param array $activity
669          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670          * @throws \ImagickException
671          */
672         public static function undoActivity($activity)
673         {
674                 if (empty($activity['object_id'])) {
675                         return;
676                 }
677
678                 if (empty($activity['object_actor'])) {
679                         return;
680                 }
681
682                 $author_id = Contact::getIdForURL($activity['object_actor']);
683                 if (empty($author_id)) {
684                         return;
685                 }
686
687                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
688         }
689
690         /**
691          * Activity to remove a follower
692          *
693          * @param array $activity
694          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
695          * @throws \ImagickException
696          */
697         public static function undoFollowUser($activity)
698         {
699                 $uid = User::getIdForURL($activity['object_object']);
700                 if (empty($uid)) {
701                         return;
702                 }
703
704                 $owner = User::getOwnerDataById($uid);
705
706                 $cid = Contact::getIdForURL($activity['actor'], $uid);
707                 if (empty($cid)) {
708                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
709                         return;
710                 }
711
712                 self::switchContact($cid);
713
714                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
715                 if (!DBA::isResult($contact)) {
716                         return;
717                 }
718
719                 Contact::removeFollower($owner, $contact);
720                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
721         }
722
723         /**
724          * Switches a contact to AP if needed
725          *
726          * @param integer $cid Contact ID
727          * @throws \Exception
728          */
729         private static function switchContact($cid)
730         {
731                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
732                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
733                         return;
734                 }
735
736                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
737                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
738         }
739
740         /**
741          * Collects implicit mentions like:
742          * - the author of the parent item
743          * - all the mentioned conversants in the parent item
744          *
745          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
746          * @return array
747          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
748          */
749         private static function getImplicitMentionList(array $parent)
750         {
751                 if (Config::get('system', 'disable_implicit_mentions')) {
752                         return [];
753                 }
754
755                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
756
757                 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
758
759                 $implicit_mentions = [];
760                 if (empty($parent_author)) {
761                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
762                 } else {
763                         $implicit_mentions[] = $parent_author['url'];
764                         $implicit_mentions[] = $parent_author['nurl'];
765                         $implicit_mentions[] = $parent_author['alias'];
766                 }
767
768                 if (!empty($parent['alias'])) {
769                         $implicit_mentions[] = $parent['alias'];
770                 }
771
772                 foreach ($parent_terms as $term) {
773                         $contact = Contact::getDetailsByURL($term['url'], 0);
774                         if (!empty($contact)) {
775                                 $implicit_mentions[] = $contact['url'];
776                                 $implicit_mentions[] = $contact['nurl'];
777                                 $implicit_mentions[] = $contact['alias'];
778                         }
779                 }
780
781                 return $implicit_mentions;
782         }
783
784         /**
785          * Strips from the body prepended implicit mentions
786          *
787          * @param string $body
788          * @param array $potential_mentions
789          * @return string
790          */
791         private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
792         {
793                 if (Config::get('system', 'disable_implicit_mentions')) {
794                         return $body;
795                 }
796
797                 $kept_mentions = [];
798
799                 // Extract one prepended mention at a time from the body
800                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
801                         if (!in_array($matches[2], $potential_mentions) ) {
802                                 $kept_mentions[] = $matches[1];
803                         }
804
805                         $body = $matches[3];
806                 }
807
808                 // Re-appending the kept mentions to the body after extraction
809                 $kept_mentions[] = $body;
810
811                 return implode('', $kept_mentions);
812         }
813
814         private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
815         {
816                 if (Config::get('system', 'disable_implicit_mentions')) {
817                         return $activity_tags;
818                 }
819
820                 foreach ($activity_tags as $index => $tag) {
821                         if (in_array($tag['href'], $potential_mentions)) {
822                                 $activity_tags[$index]['name'] = preg_replace(
823                                         '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
824                                         Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
825                                         $activity_tags[$index]['name'],
826                                         1
827                                 );
828                         }
829                 }
830
831                 return $activity_tags;
832         }
833 }