]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Improve SQL-Queries / fixed "fetch_parents" setting
[friendica.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Event;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Post;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Protocol\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\HTTPSignature;
50 use Friendica\Util\JsonLD;
51 use Friendica\Util\Network;
52 use Friendica\Util\Strings;
53 use Friendica\Worker\Delivery;
54
55 /**
56  * ActivityPub Processor Protocol class
57  */
58 class Processor
59 {
60         const CACHEKEY_FETCH_ACTIVITY = 'processor:fetchMissingActivity:';
61         const CACHEKEY_JUST_FETCHED   = 'processor:isJustFetched:';
62
63         /**
64          * Add an object id to the list of processed ids
65          *
66          * @param string $id
67          *
68          * @return void
69          */
70         private static function addActivityId(string $id)
71         {
72                 DBA::delete('processed-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
73                 DBA::insert('processed-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()]);
74         }
75
76         /**
77          * Checks if the given object id has just been processed
78          *
79          * @param string $id
80          *
81          * @return boolean
82          */
83         private static function isProcessed(string $id): bool
84         {
85                 return DBA::exists('processed-activity', ['object-id' => $id]);
86         }
87
88         /**
89          * Extracts the tag character (#, @, !) from mention links
90          *
91          * @param string $body
92          * @return string
93          */
94         protected static function normalizeMentionLinks(string $body): string
95         {
96                 return preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
97         }
98
99         /**
100          * Convert the language array into a language JSON
101          *
102          * @param array $languages
103          * @return string language JSON
104          */
105         private static function processLanguages(array $languages): string
106         {
107                 $codes = array_keys($languages);
108                 $lang = [];
109                 foreach ($codes as $code) {
110                         $lang[$code] = 1;
111                 }
112
113                 if (empty($lang)) {
114                         return '';
115                 }
116
117                 return json_encode($lang);
118         }
119         /**
120          * Replaces emojis in the body
121          *
122          * @param int $uri_id
123          * @param string $body
124          * @param array $emojis
125          *
126          * @return string with replaced emojis
127          */
128         private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
129         {
130                 $body = strtr($body,
131                         array_combine(
132                                 array_column($emojis, 'name'),
133                                 array_map(function ($emoji) {
134                                         return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
135                                 }, $emojis)
136                         )
137                 );
138
139                 // We store the emoji here to be able to avoid storing it in the media
140                 foreach ($emojis as $emoji) {
141                         Post\Link::getByLink($uri_id, $emoji['href']);
142                 }
143                 return $body;
144         }
145
146         /**
147          * Store attached media files in the post-media table
148          *
149          * @param int $uriid
150          * @param array $attachment
151          * @return void
152          */
153         private static function storeAttachmentAsMedia(int $uriid, array $attachment)
154         {
155                 if (empty($attachment['url'])) {
156                         return;
157                 }
158
159                 $data = ['uri-id' => $uriid];
160                 $data['type'] = Post\Media::UNKNOWN;
161                 $data['url'] = $attachment['url'];
162                 $data['mimetype'] = $attachment['mediaType'] ?? null;
163                 $data['height'] = $attachment['height'] ?? null;
164                 $data['width'] = $attachment['width'] ?? null;
165                 $data['size'] = $attachment['size'] ?? null;
166                 $data['preview'] = $attachment['image'] ?? null;
167                 $data['description'] = $attachment['name'] ?? null;
168
169                 Post\Media::insert($data);
170         }
171
172         /**
173          * Stire attachment data
174          *
175          * @param array   $activity
176          * @param array   $item
177          */
178         private static function storeAttachments(array $activity, array $item)
179         {
180                 if (empty($activity['attachments'])) {
181                         return;
182                 }
183
184                 foreach ($activity['attachments'] as $attach) {
185                         self::storeAttachmentAsMedia($item['uri-id'], $attach);
186                 }
187         }
188
189         /**
190          * Store attachment data
191          *
192          * @param array   $activity
193          * @param array   $item
194          */
195         private static function storeQuestion(array $activity, array $item)
196         {
197                 if (empty($activity['question'])) {
198                         return;
199                 }
200                 $question = ['multiple' => $activity['question']['multiple']];
201
202                 if (!empty($activity['question']['voters'])) {
203                         $question['voters'] = $activity['question']['voters'];
204                 }
205
206                 if (!empty($activity['question']['end-time'])) {
207                         $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
208                 }
209
210                 Post\Question::update($item['uri-id'], $question);
211
212                 foreach ($activity['question']['options'] as $key => $option) {
213                         $option = ['name' => $option['name'], 'replies' => $option['replies']];
214                         Post\QuestionOption::update($item['uri-id'], $key, $option);
215                 }
216
217                 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
218         }
219
220         /**
221          * Updates a message
222          *
223          * @param array      $activity   Activity array
224          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225          * @throws \ImagickException
226          */
227         public static function updateItem(array $activity)
228         {
229                 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type', 'private'], ['uri' => $activity['id']]);
230                 if (!DBA::isResult($item)) {
231                         Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
232                         $item = self::createItem($activity, false);
233                         if (empty($item)) {
234                                 Queue::remove($activity);
235                                 return;
236                         }
237
238                         self::postItem($activity, $item);
239                         return;
240                 }
241
242                 $item['changed'] = DateTimeFormat::utcNow();
243                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
244
245                 $item = self::processContent($activity, $item);
246                 if (empty($item)) {
247                         Queue::remove($activity);
248                         return;
249                 }
250
251                 self::storeAttachments($activity, $item);
252                 self::storeQuestion($activity, $item);
253
254                 Post\History::add($item['uri-id'], $item);
255                 Item::update($item, ['uri' => $activity['id']]);
256
257                 Queue::remove($activity);
258
259                 if ($activity['object_type'] == 'as:Event') {
260                         $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
261                         while ($post = DBA::fetch($posts)) {
262                                 self::updateEvent($post['event-id'], $activity);
263                         }
264                 }
265         }
266
267         /**
268          * Update an existing event
269          *
270          * @param int $event_id
271          * @param array $activity
272          */
273         private static function updateEvent(int $event_id, array $activity)
274         {
275                 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
276
277                 $event['edited']   = DateTimeFormat::utc($activity['updated']);
278                 $event['summary']  = HTML::toBBCode($activity['name']);
279                 $event['desc']     = HTML::toBBCode($activity['content']);
280                 if (!empty($activity['start-time'])) {
281                         $event['start']  = DateTimeFormat::utc($activity['start-time']);
282                 }
283                 if (!empty($activity['end-time'])) {
284                         $event['finish'] = DateTimeFormat::utc($activity['end-time']);
285                 }
286                 $event['nofinish'] = empty($event['finish']);
287                 $event['location'] = $activity['location'];
288
289                 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
290                 Event::store($event);
291         }
292
293         /**
294          * Prepares data for a message
295          *
296          * @param array $activity      Activity array
297          * @param bool  $fetch_parents
298          *
299          * @return array Internal item
300          *
301          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302          * @throws \ImagickException
303          */
304         public static function createItem(array $activity, bool $fetch_parents): array
305         {
306                 if (self::isProcessed($activity['id']) && !Post::exists(['uri' => $activity['id']])) {
307                         Logger::info('Id is already processed', ['id' => $activity['id']]);
308                         return [];
309                 }
310
311                 self::addActivityId($activity['id']);
312
313                 $item = [];
314                 $item['verb'] = Activity::POST;
315                 $item['thr-parent'] = $activity['reply-to-id'];
316
317                 if ($activity['reply-to-id'] == $activity['id']) {
318                         $item['gravity'] = GRAVITY_PARENT;
319                         $item['object-type'] = Activity\ObjectType::NOTE;
320                 } else {
321                         $item['gravity'] = GRAVITY_COMMENT;
322                         $item['object-type'] = Activity\ObjectType::COMMENT;
323                 }
324
325                 if (!empty($activity['conversation'])) {
326                         $item['conversation'] = $activity['conversation'];
327                 } elseif (!empty($activity['context'])) {
328                         $item['conversation'] = $activity['context'];
329                 }
330
331                 if (!empty($item['conversation'])) {
332                         $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
333                         if (!empty($conversation)) {
334                                 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
335                                 $item['parent-uri'] = $conversation['uri'];
336                         }
337                 } else {
338                         $conversation = [];
339                 }
340
341                 Logger::debug('Create Item', ['id' => $activity['id'], 'conversation' => $item['conversation'] ?? '']);
342                 if (empty($activity['author']) && empty($activity['actor'])) {
343                         Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
344                         Queue::remove($activity);
345                         return [];
346                 }
347
348                 if (!in_array(0, $activity['receiver']) || !DI::config()->get('system', 'fetch_parents')) {
349                         $fetch_parents = false;
350                 }
351
352                 if ($fetch_parents && empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
353                         $result = self::fetchParent($activity);
354                         if (!empty($result)) {
355                                 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
356                                         $item['thr-parent'] = $result;
357                                 }
358                         } elseif (empty($conversation)) {
359                                 return [];
360                         }
361                 }
362
363                 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
364
365                 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
366                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
367                         if (!$fetch_parents) {
368                                 Queue::remove($activity);
369                         }
370                         return [];
371                 }
372
373                 $item['network'] = Protocol::ACTIVITYPUB;
374                 $item['author-link'] = $activity['author'];
375                 $item['author-id'] = Contact::getIdForURL($activity['author']);
376                 $item['owner-link'] = $activity['actor'];
377                 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
378
379                 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
380                         $item['private'] = Item::UNLISTED;
381                 } elseif (in_array(0, $activity['receiver'])) {
382                         $item['private'] = Item::PUBLIC;
383                 } else {
384                         $item['private'] = Item::PRIVATE;
385                 }
386
387                 if (!empty($activity['raw'])) {
388                         $item['source'] = $activity['raw'];
389                 }
390
391                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
392
393                 if (isset($activity['push'])) {
394                         $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
395                 }
396
397                 if (!empty($activity['from-relay'])) {
398                         $item['direction'] = Conversation::RELAY;
399                 }
400
401                 if ($activity['object_type'] == 'as:Article') {
402                         $item['post-type'] = Item::PT_ARTICLE;
403                 } elseif ($activity['object_type'] == 'as:Audio') {
404                         $item['post-type'] = Item::PT_AUDIO;
405                 } elseif ($activity['object_type'] == 'as:Document') {
406                         $item['post-type'] = Item::PT_DOCUMENT;
407                 } elseif ($activity['object_type'] == 'as:Event') {
408                         $item['post-type'] = Item::PT_EVENT;
409                 } elseif ($activity['object_type'] == 'as:Image') {
410                         $item['post-type'] = Item::PT_IMAGE;
411                 } elseif ($activity['object_type'] == 'as:Page') {
412                         $item['post-type'] = Item::PT_PAGE;
413                 } elseif ($activity['object_type'] == 'as:Question') {
414                         $item['post-type'] = Item::PT_POLL;
415                 } elseif ($activity['object_type'] == 'as:Video') {
416                         $item['post-type'] = Item::PT_VIDEO;
417                 } else {
418                         $item['post-type'] = Item::PT_NOTE;
419                 }
420
421                 $item['isForum'] = false;
422
423                 if (!empty($activity['thread-completion'])) {
424                         if ($activity['thread-completion'] != $item['owner-id']) {
425                                 $actor = Contact::getById($activity['thread-completion'], ['url']);
426                                 $item['causer-link'] = $actor['url'];
427                                 $item['causer-id'] = $activity['thread-completion'];
428                                 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
429                         } else {
430                                 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
431                                 $item['causer-link'] = $item['owner-link'];
432                                 $item['causer-id']   = $item['owner-id'];
433                                 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
434                         }
435
436                         $item['owner-link'] = $item['author-link'];
437                         $item['owner-id'] = $item['author-id'];
438                 } else {
439                         $actor = APContact::getByURL($item['owner-link'], false);
440                         $item['isForum'] = ($actor['type'] == 'Group');
441                 }
442
443                 $item['uri'] = $activity['id'];
444
445                 if (empty($activity['published']) || empty($activity['updated'])) {
446                         DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
447                 }
448
449                 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
450                 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
451                 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
452                 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
453
454                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
455                 if (empty($item['uri-id'])) {
456                         Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
457                         return [];
458                 }
459
460                 $item = self::processContent($activity, $item);
461                 if (empty($item)) {
462                         Logger::info('Message was not processed');
463                         Queue::remove($activity);
464                         return [];
465                 }
466
467                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
468
469                 self::storeAttachments($activity, $item);
470                 self::storeQuestion($activity, $item);
471
472                 // We received the post via AP, so we set the protocol of the server to AP
473                 $contact = Contact::getById($item['author-id'], ['gsid']);
474                 if (!empty($contact['gsid'])) {
475                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
476                 }
477
478                 if ($item['author-id'] != $item['owner-id']) {
479                         $contact = Contact::getById($item['owner-id'], ['gsid']);
480                         if (!empty($contact['gsid'])) {
481                                 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
482                         }
483                 }
484
485                 return $item;
486         }
487
488         /**
489          * Fetch and process parent posts for the given activity
490          *
491          * @param array $activity
492          *
493          * @return string
494          */
495         private static function fetchParent(array $activity): string
496         {
497                 $recursion_depth = $activity['recursion-depth'] ?? 0;
498
499                 if ($recursion_depth < DI::config()->get('system', 'max_recursion_depth')) {
500                         Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
501                         $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
502                         if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
503                                 Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
504                                 if (!empty($activity['entry-id'])) {
505                                         Queue::deleteById($activity['entry-id']);
506                                 }
507                                 return '';
508                         } elseif (!empty($result)) {
509                                 $exists = Post::exists(['uri' => [$result, $activity['reply-to-id']]]);
510                                 if ($exists) {
511                                         Logger::notice('The activity has been fetched and created.', ['parent' => $result]);
512                                         return $result;
513                                 } elseif (DI::config()->get('system', 'fetch_by_worker') || DI::config()->get('system', 'decoupled_receiver')) {
514                                         Logger::notice('The activity has been fetched and will hopefully be created later.', ['parent' => $result]);
515                                 } else {
516                                         Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]);
517                                         if (!empty($activity['entry-id'])) {
518                                                 Queue::deleteById($activity['entry-id']);
519                                         }
520                                 }
521                                 return '';
522                         }
523                         if (empty($result) && !DI::config()->get('system', 'fetch_by_worker')) {
524                                 return '';
525                         }
526                 } elseif (self::isActivityGone($activity['reply-to-id'])) {
527                         Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
528                         if (!empty($activity['entry-id'])) {
529                                 Queue::deleteById($activity['entry-id']);
530                         }
531                         return '';
532                 } else {
533                         Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
534                 }
535
536                 if (Queue::hasWorker($activity['worker-id'] ?? 0)) {
537                         Logger::notice('There is already a worker task to fetch the post.', ['id' => $activity['id'], 'parent' => $activity['reply-to-id']]);
538                         return '';
539                 }
540
541                 if (!Fetch::hasWorker($activity['reply-to-id'])) {
542                         Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
543                         Fetch::add($activity['reply-to-id']);
544                         $activity['recursion-depth'] = 0;
545                         $wid = Worker::add(PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
546                         Fetch::setWorkerId($activity['reply-to-id'], $wid);
547                 } else {
548                         Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
549                 }
550
551                 return '';
552         }
553
554         /**
555          * Check if a given activity is no longer available
556          *
557          * @param string $url
558          *
559          * @return boolean
560          */
561         public static function isActivityGone(string $url): bool
562         {
563                 $curlResult = HTTPSignature::fetchRaw($url, 0);
564
565                 if (Network::isUrlBlocked($url)) {
566                         return true;
567                 }
568
569                 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
570                 if (in_array($curlResult->getReturnCode(), [401, 404])) {
571                         return true;
572                 }
573
574                 if ($curlResult->isSuccess()) {
575                         $object = json_decode($curlResult->getBody(), true);
576                         if (!empty($object)) {
577                                 $activity = JsonLD::compact($object);
578                                 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
579                                         return true;
580                                 }
581                         }
582                 } elseif ($curlResult->getReturnCode() == 0) {
583                         $host = parse_url($url, PHP_URL_HOST);
584                         if (!(filter_var($host, FILTER_VALIDATE_IP) || @dns_get_record($host . '.', DNS_A + DNS_AAAA))) {
585                                 return true;
586                         }
587                 }
588
589                 return false;
590         }
591         /**
592          * Delete items
593          *
594          * @param array $activity
595          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
596          * @throws \ImagickException
597          */
598         public static function deleteItem(array $activity)
599         {
600                 $owner = Contact::getIdForURL($activity['actor']);
601
602                 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner'  => $owner]);
603                 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
604                 Queue::remove($activity);
605         }
606
607         /**
608          * Prepare the item array for an activity
609          *
610          * @param array $activity Activity array
611          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
612          * @throws \ImagickException
613          */
614         public static function addTag(array $activity)
615         {
616                 if (empty($activity['object_content']) || empty($activity['object_id'])) {
617                         return;
618                 }
619
620                 foreach ($activity['receiver'] as $receiver) {
621                         $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
622                         if (!DBA::isResult($item)) {
623                                 // We don't fetch missing content for this purpose
624                                 continue;
625                         }
626
627                         if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
628                                 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
629                                 continue;
630                         }
631
632                         Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
633                         Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
634                 }
635         }
636
637         /**
638          * Prepare the item array for an activity
639          *
640          * @param array      $activity   Activity array
641          * @param string     $verb       Activity verb
642          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
643          * @throws \ImagickException
644          */
645         public static function createActivity(array $activity, string $verb)
646         {
647                 $activity['reply-to-id'] = $activity['object_id'];
648                 $item = self::createItem($activity, false);
649                 if (empty($item)) {
650                         return;
651                 }
652
653                 $item['verb'] = $verb;
654                 $item['thr-parent'] = $activity['object_id'];
655                 $item['gravity'] = GRAVITY_ACTIVITY;
656                 unset($item['post-type']);
657                 $item['object-type'] = Activity\ObjectType::NOTE;
658
659                 if (!empty($activity['content'])) {
660                         $item['body'] = HTML::toBBCode($activity['content']);
661                 }
662
663                 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
664
665                 self::postItem($activity, $item);
666         }
667
668         /**
669          * Fetch the Uri-Id of a post for the "featured" collection
670          *
671          * @param array $activity
672          * @return null|int
673          */
674         private static function getUriIdForFeaturedCollection(array $activity)
675         {
676                 $actor = APContact::getByURL($activity['actor']);
677                 if (empty($actor)) {
678                         return null;
679                 }
680
681                 // Refetch the account when the "featured" collection is missing.
682                 // This can be removed in a future version (end of 2022 should be good).
683                 if (empty($actor['featured'])) {
684                         $actor = APContact::getByURL($activity['actor'], true);
685                         if (empty($actor)) {
686                                 return null;
687                         }
688                 }
689
690                 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
691                 if (empty($parent['uri-id'])) {
692                         if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
693                                 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
694                         }
695                 }
696
697                 if (!empty($parent['uri-id'])) {
698                         return $parent['uri-id'];
699                 }
700
701                 return null;
702         }
703
704         /**
705          * Add a post to the "Featured" collection
706          *
707          * @param array $activity
708          */
709         public static function addToFeaturedCollection(array $activity)
710         {
711                 $uriid = self::getUriIdForFeaturedCollection($activity);
712                 if (empty($uriid)) {
713                         return;
714                 }
715
716                 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
717
718                 Post\Collection::add($uriid, Post\Collection::FEATURED);
719                 Queue::remove($activity);
720         }
721
722         /**
723          * Remove a post to the "Featured" collection
724          *
725          * @param array $activity
726          */
727         public static function removeFromFeaturedCollection(array $activity)
728         {
729                 $uriid = self::getUriIdForFeaturedCollection($activity);
730                 if (empty($uriid)) {
731                         return;
732                 }
733
734                 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
735
736                 Post\Collection::remove($uriid, Post\Collection::FEATURED);
737                 Queue::remove($activity);
738         }
739
740         /**
741          * Create an event
742          *
743          * @param array $activity Activity array
744          * @param array $item
745          *
746          * @return int event id
747          * @throws \Exception
748          */
749         public static function createEvent(array $activity, array $item): int
750         {
751                 $event['summary']   = HTML::toBBCode($activity['name'] ?: $activity['summary']);
752                 $event['desc']      = HTML::toBBCode($activity['content']);
753                 if (!empty($activity['start-time'])) {
754                         $event['start']  = DateTimeFormat::utc($activity['start-time']);
755                 }
756                 if (!empty($activity['end-time'])) {
757                         $event['finish'] = DateTimeFormat::utc($activity['end-time']);
758                 }
759                 $event['nofinish']  = empty($event['finish']);
760                 $event['location']  = $activity['location'];
761                 $event['cid']       = $item['contact-id'];
762                 $event['uid']       = $item['uid'];
763                 $event['uri']       = $item['uri'];
764                 $event['edited']    = $item['edited'];
765                 $event['private']   = $item['private'];
766                 $event['guid']      = $item['guid'];
767                 $event['plink']     = $item['plink'];
768                 $event['network']   = $item['network'];
769                 $event['protocol']  = $item['protocol'];
770                 $event['direction'] = $item['direction'];
771                 $event['source']    = $item['source'];
772
773                 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
774                 if (DBA::isResult($ev)) {
775                         $event['id'] = $ev['id'];
776                 }
777
778                 $event_id = Event::store($event);
779
780                 Logger::info('Event was stored', ['id' => $event_id]);
781
782                 return $event_id;
783         }
784
785         /**
786          * Process the content
787          *
788          * @param array $activity Activity array
789          * @param array $item
790          * @return array|bool Returns the item array or false if there was an unexpected occurrence
791          * @throws \Exception
792          */
793         private static function processContent(array $activity, array $item)
794         {
795                 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
796                         $item['title'] = strip_tags($activity['name']);
797                         $content = Markdown::toBBCode($activity['content']);
798                 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
799                         $item['title'] = $activity['name'];
800                         $content = $activity['content'];
801                 } else {
802                         // By default assume "text/html"
803                         $item['title'] = HTML::toBBCode($activity['name'] ?? '');
804                         $content = HTML::toBBCode($activity['content'] ?? '');
805                 }
806
807                 $item['title'] = trim(BBCode::toPlaintext($item['title']));
808
809                 if (!empty($activity['languages'])) {
810                         $item['language'] = self::processLanguages($activity['languages']);
811                 }
812
813                 if (!empty($activity['emojis'])) {
814                         $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
815                 }
816
817                 $content = self::addMentionLinks($content, $activity['tags']);
818
819                 if (!empty($activity['source'])) {
820                         $item['body'] = $activity['source'];
821                         $item['raw-body'] = $content;
822                         $item['body'] = Item::improveSharedDataInBody($item);
823                 } else {
824                         $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
825                         if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
826                                 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
827                                 if (!DBA::isResult($parent)) {
828                                         Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
829                                         return false;
830                                 }
831                                 if (!empty($activity['type']) && in_array($activity['type'], Receiver::CONTENT_TYPES) && ($item['private'] == Item::PRIVATE) && ($parent['private'] != Item::PRIVATE)) {
832                                         Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
833                                         return false;
834                                 }
835
836                                 $content = self::removeImplicitMentionsFromBody($content, $parent);
837                         }
838                         $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
839                         $item['raw-body'] = $item['body'] = $content;
840                 }
841
842                 self::storeFromBody($item);
843                 self::storeTags($item['uri-id'], $activity['tags']);
844
845                 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
846
847                 $item['location'] = $activity['location'];
848
849                 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
850                         $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
851                 }
852
853                 $item['app'] = $activity['generator'];
854
855                 return $item;
856         }
857
858         /**
859          * Store hashtags and mentions
860          *
861          * @param array $item
862          */
863         private static function storeFromBody(array $item)
864         {
865                 // Make sure to delete all existing tags (can happen when called via the update functionality)
866                 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
867
868                 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
869         }
870
871         /**
872          * Generate a GUID out of an URL of an ActivityPub post.
873          *
874          * @param string $url message URL
875          * @return string with GUID
876          */
877         private static function getGUIDByURL(string $url): string
878         {
879                 $parsed = parse_url($url);
880
881                 $host_hash = hash('crc32', $parsed['host']);
882
883                 unset($parsed["scheme"]);
884                 unset($parsed["host"]);
885
886                 $path = implode("/", $parsed);
887
888                 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
889         }
890
891         /**
892          * Checks if an incoming message is wanted
893          *
894          * @param array $activity
895          * @param array $item
896          * @return boolean Is the message wanted?
897          */
898         private static function isSolicitedMessage(array $activity, array $item): bool
899         {
900                 // The checks are split to improve the support when searching why a message was accepted.
901                 if (count($activity['receiver']) != 1) {
902                         // The message has more than one receiver, so it is wanted.
903                         Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
904                         return true;
905                 }
906
907                 if ($item['private'] == Item::PRIVATE) {
908                         // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
909                         Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
910                         return true;
911                 }
912
913                 if (!empty($activity['from-relay'])) {
914                         // We check relay posts at another place. When it arrived here, the message is already checked.
915                         Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
916                         return true;
917                 }
918
919                 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
920                         // Manual completions and completions caused by reshares are allowed without any further checks.
921                         Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
922                         return true;
923                 }
924
925                 if ($item['gravity'] != GRAVITY_PARENT) {
926                         // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
927                         // This can possibly be improved in the future.
928                         Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
929                         return true;
930                 }
931
932                 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
933                 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
934                         Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
935                         return true;
936                 } else {
937                         return false;
938                 }
939         }
940
941         /**
942          * Creates an item post
943          *
944          * @param array $activity Activity data
945          * @param array $item     item array
946          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
947          * @throws \ImagickException
948          */
949         public static function postItem(array $activity, array $item)
950         {
951                 if (empty($item)) {
952                         return;
953                 }
954
955                 $stored = false;
956                 $success = false;
957                 ksort($activity['receiver']);
958
959                 if (!self::isSolicitedMessage($activity, $item)) {
960                         DBA::delete('item-uri', ['id' => $item['uri-id']]);
961                         if (!empty($activity['entry-id'])) {
962                                 Queue::deleteById($activity['entry-id']);
963                         }
964                         return;
965                 }
966
967                 foreach ($activity['receiver'] as $receiver) {
968                         if ($receiver == -1) {
969                                 continue;
970                         }
971
972                         $item['uid'] = $receiver;
973
974                         $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
975                         switch($type) {
976                                 case Receiver::TARGET_TO:
977                                         $item['post-reason'] = Item::PR_TO;
978                                         break;
979                                 case Receiver::TARGET_CC:
980                                         $item['post-reason'] = Item::PR_CC;
981                                         break;
982                                 case Receiver::TARGET_BTO:
983                                         $item['post-reason'] = Item::PR_BTO;
984                                         break;
985                                 case Receiver::TARGET_BCC:
986                                         $item['post-reason'] = Item::PR_BCC;
987                                         break;
988                                 case Receiver::TARGET_FOLLOWER:
989                                         $item['post-reason'] = Item::PR_FOLLOWER;
990                                         break;
991                                 case Receiver::TARGET_ANSWER:
992                                         $item['post-reason'] = Item::PR_COMMENT;
993                                         break;
994                                 case Receiver::TARGET_GLOBAL:
995                                         $item['post-reason'] = Item::PR_GLOBAL;
996                                         break;
997                                 default:
998                                         $item['post-reason'] = Item::PR_NONE;
999                         }
1000
1001                         $item['post-reason'] = Item::getPostReason($item);
1002
1003                         if (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE])) {
1004                                 if (!empty($activity['from-relay'])) {
1005                                         $item['post-reason'] = Item::PR_RELAY;
1006                                 } elseif (!empty($activity['thread-completion'])) {
1007                                         $item['post-reason'] = Item::PR_FETCHED;
1008                                 } elseif (!empty($activity['push'])) {
1009                                         $item['post-reason'] = Item::PR_PUSHED;
1010                                 }
1011                         }
1012
1013                         if ($item['isForum'] ?? false) {
1014                                 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
1015                         } else {
1016                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
1017                         }
1018
1019                         if (($receiver != 0) && empty($item['contact-id'])) {
1020                                 $item['contact-id'] = Contact::getIdForURL($activity['author']);
1021                         }
1022
1023                         if (!empty($activity['directmessage'])) {
1024                                 self::postMail($activity, $item);
1025                                 continue;
1026                         }
1027
1028                         if (($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !in_array($item['post-reason'], [Item::PR_FOLLOWER, Item::PR_TAG, item::PR_TO, Item::PR_CC])) {
1029                                 if (!($item['isForum'] ?? false)) {
1030                                         if ($item['post-reason'] == Item::PR_BCC) {
1031                                                 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id'], 'url' => $item['uri']]);
1032                                                 continue;
1033                                         }
1034
1035                                         if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE)
1036                                                 && in_array($activity['thread-children-type'] ?? '', Receiver::ACTIVITY_TYPES)) {
1037                                                 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
1038                                                         ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
1039                                                 continue;
1040                                         }
1041                                 }
1042
1043                                 $is_forum = false;
1044                                 $user = User::getById($receiver, ['account-type']);
1045                                 if (!empty($user['account-type'])) {
1046                                         $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
1047                                 }
1048
1049                                 if ((DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE)
1050                                         && ((!$is_forum && !($item['isForum'] ?? false) && ($activity['type'] != 'as:Announce'))
1051                                         || !Contact::isSharingByURL($activity['actor'], $receiver))) {
1052                                         Logger::info('Actor is a non sharer, is no forum or it is no announce', ['uid' => $receiver, 'actor' => $activity['actor'], 'url' => $item['uri'], 'type' => $activity['type']]);
1053                                         continue;
1054                                 }
1055
1056                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
1057                         }
1058
1059                         if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
1060                                 $event_id = self::createEvent($activity, $item);
1061
1062                                 $item = Event::getItemArrayForImportedId($event_id, $item);
1063                         }
1064
1065                         $item_id = Item::insert($item);
1066                         if ($item_id) {
1067                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
1068                                 $success = true;
1069                         } else {
1070                                 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
1071                                 if (($item['uid'] == 0) && (count($activity['receiver']) > 1)) {
1072                                         Logger::info('Public item was aborted. We skip for all users.', ['uri' => $item['uri']]);
1073                                         break;
1074                                 }
1075                         }
1076
1077                         if ($item['uid'] == 0) {
1078                                 $stored = $item_id;
1079                         }
1080                 }
1081
1082                 Queue::remove($activity);
1083
1084                 if ($success && Queue::hasChildren($item['uri']) && Post::exists(['uri' => $item['uri']])) {
1085                         Queue::processReplyByUri($item['uri']);
1086                 }
1087
1088                 // Store send a follow request for every reshare - but only when the item had been stored
1089                 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
1090                         $author = APContact::getByURL($item['owner-link'], false);
1091                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
1092                         if ($author['type'] != 'Group') {
1093                                 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
1094                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1095                         }
1096                 }
1097         }
1098
1099         /**
1100          * Store tags and mentions into the tag table
1101          *
1102          * @param integer $uriid
1103          * @param array $tags
1104          */
1105         private static function storeTags(int $uriid, array $tags = null)
1106         {
1107                 foreach ($tags as $tag) {
1108                         if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1109                                 continue;
1110                         }
1111
1112                         $hash = substr($tag['name'], 0, 1);
1113
1114                         if ($tag['type'] == 'Mention') {
1115                                 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1116                                         Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1117                                         Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1118                                         $tag['name'] = substr($tag['name'], 1);
1119                                 }
1120                                 $type = Tag::IMPLICIT_MENTION;
1121
1122                                 if (!empty($tag['href'])) {
1123                                         $apcontact = APContact::getByURL($tag['href']);
1124                                         if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1125                                                 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1126                                         }
1127                                 }
1128                         } elseif ($tag['type'] == 'Hashtag') {
1129                                 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1130                                         $tag['name'] = substr($tag['name'], 1);
1131                                 }
1132                                 $type = Tag::HASHTAG;
1133                         }
1134
1135                         if (empty($tag['name'])) {
1136                                 continue;
1137                         }
1138
1139                         Tag::store($uriid, $type, $tag['name'], $tag['href']);
1140                 }
1141         }
1142
1143         public static function storeReceivers(int $uriid, array $receivers)
1144         {
1145                 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1146                         if (!empty($receivers[$element])) {
1147                                 foreach ($receivers[$element] as $receiver) {
1148                                         if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1149                                                 $name = Receiver::PUBLIC_COLLECTION;
1150                                         } else {
1151                                                 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
1152                                         }
1153
1154                                         $target = Tag::getTargetType($receiver);
1155                                         Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1156                                         Tag::store($uriid, $type, $name, $receiver, $target);
1157                                 }
1158                         }
1159                 }
1160         }
1161
1162         /**
1163          * Creates an mail post
1164          *
1165          * @param array $activity Activity data
1166          * @param array $item     item array
1167          * @return int|bool New mail table row id or false on error
1168          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1169          */
1170         private static function postMail(array $activity, array $item)
1171         {
1172                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1173                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1174                         return false;
1175                 }
1176
1177                 Logger::info('Direct Message', $item);
1178
1179                 $msg = [];
1180                 $msg['uid'] = $item['uid'];
1181
1182                 $msg['contact-id'] = $item['contact-id'];
1183
1184                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1185                 $msg['from-name'] = $contact['name'];
1186                 $msg['from-url'] = $contact['url'];
1187                 $msg['from-photo'] = $contact['photo'];
1188
1189                 $msg['uri'] = $item['uri'];
1190                 $msg['created'] = $item['created'];
1191
1192                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1193                 if (DBA::isResult($parent)) {
1194                         $msg['parent-uri'] = $parent['parent-uri'];
1195                         $msg['title'] = $parent['title'];
1196                 } else {
1197                         $msg['parent-uri'] = $item['thr-parent'];
1198
1199                         if (!empty($item['title'])) {
1200                                 $msg['title'] = $item['title'];
1201                         } elseif (!empty($item['content-warning'])) {
1202                                 $msg['title'] = $item['content-warning'];
1203                         } else {
1204                                 // Trying to generate a title out of the body
1205                                 $title = $item['body'];
1206
1207                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1208                                         $title = $matches[3];
1209                                 }
1210
1211                                 $title = trim(BBCode::toPlaintext($title));
1212
1213                                 if (strlen($title) > 20) {
1214                                         $title = substr($title, 0, 20) . '...';
1215                                 }
1216
1217                                 $msg['title'] = $title;
1218                         }
1219                 }
1220                 $msg['body'] = $item['body'];
1221
1222                 return Mail::insert($msg);
1223         }
1224
1225         /**
1226          * Fetch featured posts from a contact with the given url
1227          *
1228          * @param string $url
1229          * @return void
1230          */
1231         public static function fetchFeaturedPosts(string $url)
1232         {
1233                 Logger::info('Fetch featured posts', ['contact' => $url]);
1234
1235                 $apcontact = APContact::getByURL($url);
1236                 if (empty($apcontact['featured'])) {
1237                         Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1238                         return;
1239                 }
1240
1241                 $pcid = Contact::getIdForURL($url, 0, false);
1242                 if (empty($pcid)) {
1243                         Logger::info('Contact not found', ['contact' => $url]);
1244                         return;
1245                 }
1246
1247                 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1248                 if (!empty($posts)) {
1249                         $old_featured = array_column($posts, 'uri-id');
1250                 } else {
1251                         $old_featured = [];
1252                 }
1253
1254                 $featured = ActivityPub::fetchItems($apcontact['featured']);
1255                 if (empty($featured)) {
1256                         Logger::info('Contact does not have featured posts', ['contact' => $url]);
1257
1258                         foreach ($old_featured as $uri_id) {
1259                                 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1260                                 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1261                         }
1262                         return;
1263                 }
1264
1265                 $new = 0;
1266                 $old = 0;
1267
1268                 foreach ($featured as $post) {
1269                         if (empty($post['id'])) {
1270                                 continue;
1271                         }
1272                         $id = Item::fetchByLink($post['id']);
1273                         if (!empty($id)) {
1274                                 $item = Post::selectFirst(['uri-id', 'featured'], ['id' => $id]);
1275                                 if (!empty($item['uri-id'])) {
1276                                         if (!$item['featured']) {
1277                                                 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED);
1278                                                 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1279                                                 $new++;
1280                                         } else {
1281                                                 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1282                                                 $old++;
1283                                         }
1284
1285                                         $index = array_search($item['uri-id'], $old_featured);
1286                                         if (!($index === false)) {
1287                                                 unset($old_featured[$index]);
1288                                         }
1289                                 }
1290                         }
1291                 }
1292
1293                 foreach ($old_featured as $uri_id) {
1294                         Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1295                         Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1296                 }
1297
1298                 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1299         }
1300
1301         public static function fetchCachedActivity(string $url, int $uid): array
1302         {
1303                 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . $url;
1304                 $object = DI::cache()->get($cachekey);
1305
1306                 if (!is_null($object)) {
1307                         if (!empty($object)) {
1308                                 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1309                         } else {
1310                                 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1311                         }
1312                         return $object;
1313                 }
1314
1315                 $object = ActivityPub::fetchContent($url, $uid);
1316                 if (empty($object)) {
1317                         Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1318                         // We perform negative caching.
1319                         DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1320                         return [];
1321                 }
1322
1323                 if (empty($object['id'])) {
1324                         Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1325                         return [];
1326                 }
1327                 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1328
1329                 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1330
1331                 return $object;
1332         }
1333
1334         /**
1335          * Fetches missing posts
1336          *
1337          * @param string     $url         message URL
1338          * @param array      $child       activity array with the child of this message
1339          * @param string     $relay_actor Relay actor
1340          * @param int        $completion  Completion mode, see Receiver::COMPLETION_*
1341          * @return string fetched message URL
1342          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1343          * @throws \ImagickException
1344          */
1345         public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
1346         {
1347                 $object = self::fetchCachedActivity($url, 0);
1348                 if (empty($object)) {
1349                         return '';
1350                 }
1351
1352                 $signer = [];
1353
1354                 if (!empty($object['attributedTo'])) {
1355                         $attributed_to = $object['attributedTo'];
1356                         if (is_array($attributed_to)) {
1357                                 $compacted = JsonLD::compact($object);
1358                                 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1359                         }
1360                         $signer[] = $attributed_to;
1361                 }
1362
1363                 if (!empty($object['actor'])) {
1364                         $object_actor = $object['actor'];
1365                 } elseif (!empty($attributed_to)) {
1366                         $object_actor = $attributed_to;
1367                 } else {
1368                         // Shouldn't happen
1369                         $object_actor = '';
1370                 }
1371
1372                 $signer[] = $object_actor;
1373
1374                 if (!empty($child['author'])) {
1375                         $actor = $child['author'];
1376                         $signer[] = $actor;
1377                 } else {
1378                         $actor = $object_actor;
1379                 }
1380
1381                 if (!empty($object['published'])) {
1382                         $published = $object['published'];
1383                 } elseif (!empty($child['published'])) {
1384                         $published = $child['published'];
1385                 } else {
1386                         $published = DateTimeFormat::utcNow();
1387                 }
1388
1389                 $activity = [];
1390                 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1391                 unset($object['@context']);
1392                 $activity['id'] = $object['id'];
1393                 $activity['to'] = $object['to'] ?? [];
1394                 $activity['cc'] = $object['cc'] ?? [];
1395                 $activity['actor'] = $actor;
1396                 $activity['object'] = $object;
1397                 $activity['published'] = $published;
1398                 $activity['type'] = 'Create';
1399
1400                 $ldactivity = JsonLD::compact($activity);
1401
1402                 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 0;
1403
1404                 if (!empty($relay_actor)) {
1405                         $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1406                         $ldactivity['completion-mode']   = Receiver::COMPLETION_RELAY;
1407                 } elseif (!empty($child['thread-completion'])) {
1408                         $ldactivity['thread-completion'] = $child['thread-completion'];
1409                         $ldactivity['completion-mode']   = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1410                 } else {
1411                         $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1412                         $ldactivity['completion-mode']   = $completion;
1413                 }
1414
1415                 if (!empty($child['thread-children-type'])) {
1416                         $ldactivity['thread-children-type'] = $child['thread-children-type'];
1417                 } elseif (!empty($child['type'])) {
1418                         $ldactivity['thread-children-type'] = $child['type'];
1419                 } else {
1420                         $ldactivity['thread-children-type'] = 'as:Create';
1421                 }
1422
1423                 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1424                         return '';
1425                 }
1426
1427                 if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) {
1428                         Logger::notice('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]);
1429                 } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), 0, true, false, $signer, '', $completion)) {
1430                         Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1431                 } else {
1432                         Logger::notice('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1433                 }
1434
1435                 return $activity['id'];
1436         }
1437
1438         /**
1439          * Test if incoming relay messages should be accepted
1440          *
1441          * @param array $activity activity array
1442          * @param string $id      object ID
1443          * @return boolean true if message is accepted
1444          */
1445         private static function acceptIncomingMessage(array $activity, string $id): bool
1446         {
1447                 if (empty($activity['as:object'])) {
1448                         Logger::info('No object field in activity - accepted', ['id' => $id]);
1449                         return true;
1450                 }
1451
1452                 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1453                 $uriid = ItemURI::getIdByURI($replyto ?? '');
1454                 if (Post::exists(['uri-id' => $uriid])) {
1455                         Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1456                         return true;
1457                 }
1458
1459                 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1460                 $authorid = Contact::getIdForURL($attributed_to);
1461
1462                 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1463
1464                 $messageTags = [];
1465                 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1466                 if (!empty($tags)) {
1467                         foreach ($tags as $tag) {
1468                                 if ($tag['type'] != 'Hashtag') {
1469                                         continue;
1470                                 }
1471                                 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1472                         }
1473                 }
1474
1475                 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1476         }
1477
1478         /**
1479          * perform a "follow" request
1480          *
1481          * @param array $activity
1482          * @return void
1483          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1484          * @throws \ImagickException
1485          */
1486         public static function followUser(array $activity)
1487         {
1488                 $uid = User::getIdForURL($activity['object_id']);
1489                 if (empty($uid)) {
1490                         Queue::remove($activity);
1491                         return;
1492                 }
1493
1494                 $owner = User::getOwnerDataById($uid);
1495                 if (empty($owner)) {
1496                         return;
1497                 }
1498
1499                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1500                 if (!empty($cid)) {
1501                         self::switchContact($cid);
1502                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1503                 }
1504
1505                 $item = [
1506                         'author-id' => Contact::getIdForURL($activity['actor']),
1507                         'author-link' => $activity['actor'],
1508                 ];
1509
1510                 // Ensure that the contact has got the right network type
1511                 self::switchContact($item['author-id']);
1512
1513                 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1514                 if ($result === true) {
1515                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1516                 }
1517
1518                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1519                 if (empty($cid)) {
1520                         return;
1521                 }
1522
1523                 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1524                         self::transmitPendingEvents($cid, $owner['uid']);
1525                 }
1526
1527                 if (empty($contact)) {
1528                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1529                 }
1530                 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1531                 Queue::remove($activity);
1532         }
1533
1534         /**
1535          * Transmit pending events to the new follower
1536          *
1537          * @param integer $cid Contact id
1538          * @param integer $uid User id
1539          * @return void
1540          */
1541         private static function transmitPendingEvents(int $cid, int $uid)
1542         {
1543                 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1544                 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1545
1546                 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1547                 while ($event = DBA::fetch($events)) {
1548                         $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1549                         if (empty($post)) {
1550                                 continue;
1551                         }
1552                         if (DI::config()->get('system', 'bulk_delivery')) {
1553                                 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1554                                 Worker::add(PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1555                         } else {
1556                                 Worker::add(PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1557                         }
1558                 }
1559         }
1560
1561         /**
1562          * Update the given profile
1563          *
1564          * @param array $activity
1565          * @throws \Exception
1566          */
1567         public static function updatePerson(array $activity)
1568         {
1569                 if (empty($activity['object_id'])) {
1570                         return;
1571                 }
1572
1573                 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1574                 Contact::updateFromProbeByURL($activity['object_id']);
1575                 Queue::remove($activity);
1576         }
1577
1578         /**
1579          * Delete the given profile
1580          *
1581          * @param array $activity
1582          * @return void
1583          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1584          */
1585         public static function deletePerson(array $activity)
1586         {
1587                 if (empty($activity['object_id']) || empty($activity['actor'])) {
1588                         Logger::info('Empty object id or actor.');
1589                         return;
1590                 }
1591
1592                 if ($activity['object_id'] != $activity['actor']) {
1593                         Logger::info('Object id does not match actor.');
1594                         return;
1595                 }
1596
1597                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1598                 while ($contact = DBA::fetch($contacts)) {
1599                         Contact::remove($contact['id']);
1600                 }
1601                 DBA::close($contacts);
1602
1603                 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1604                 Queue::remove($activity);
1605         }
1606
1607         /**
1608          * Blocks the user by the contact
1609          *
1610          * @param array $activity
1611          * @return void
1612          * @throws \Exception
1613          */
1614         public static function blockAccount(array $activity)
1615         {
1616                 $cid = Contact::getIdForURL($activity['actor']);
1617                 if (empty($cid)) {
1618                         return;
1619                 }
1620
1621                 $uid = User::getIdForURL($activity['object_id']);
1622                 if (empty($uid)) {
1623                         return;
1624                 }
1625
1626                 Contact\User::setIsBlocked($cid, $uid, true);
1627
1628                 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1629                 Queue::remove($activity);
1630         }
1631
1632         /**
1633          * Unblocks the user by the contact
1634          *
1635          * @param array $activity
1636          * @return void
1637          * @throws \Exception
1638          */
1639         public static function unblockAccount(array $activity)
1640         {
1641                 $cid = Contact::getIdForURL($activity['actor']);
1642                 if (empty($cid)) {
1643                         return;
1644                 }
1645
1646                 $uid = User::getIdForURL($activity['object_object']);
1647                 if (empty($uid)) {
1648                         return;
1649                 }
1650
1651                 Contact\User::setIsBlocked($cid, $uid, false);
1652
1653                 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1654                 Queue::remove($activity);
1655         }
1656
1657         /**
1658          * Accept a follow request
1659          *
1660          * @param array $activity
1661          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1662          * @throws \ImagickException
1663          */
1664         public static function acceptFollowUser(array $activity)
1665         {
1666                 $uid = User::getIdForURL($activity['object_actor']);
1667                 if (empty($uid)) {
1668                         return;
1669                 }
1670
1671                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1672                 if (empty($cid)) {
1673                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1674                         return;
1675                 }
1676
1677                 self::switchContact($cid);
1678
1679                 $fields = ['pending' => false];
1680
1681                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1682                 if ($contact['rel'] == Contact::FOLLOWER) {
1683                         $fields['rel'] = Contact::FRIEND;
1684                 }
1685
1686                 $condition = ['id' => $cid];
1687                 Contact::update($fields, $condition);
1688                 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1689                 Queue::remove($activity);
1690         }
1691
1692         /**
1693          * Reject a follow request
1694          *
1695          * @param array $activity
1696          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1697          * @throws \ImagickException
1698          */
1699         public static function rejectFollowUser(array $activity)
1700         {
1701                 $uid = User::getIdForURL($activity['object_actor']);
1702                 if (empty($uid)) {
1703                         return;
1704                 }
1705
1706                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1707                 if (empty($cid)) {
1708                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1709                         return;
1710                 }
1711
1712                 self::switchContact($cid);
1713
1714                 $contact = Contact::getById($cid, ['rel']);
1715                 if ($contact['rel'] == Contact::SHARING) {
1716                         Contact::remove($cid);
1717                         Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1718                 } elseif ($contact['rel'] == Contact::FRIEND) {
1719                         Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1720                 } else {
1721                         Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1722                 }
1723                 Queue::remove($activity);
1724         }
1725
1726         /**
1727          * Undo activity like "like" or "dislike"
1728          *
1729          * @param array $activity
1730          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1731          * @throws \ImagickException
1732          */
1733         public static function undoActivity(array $activity)
1734         {
1735                 if (empty($activity['object_id'])) {
1736                         return;
1737                 }
1738
1739                 if (empty($activity['object_actor'])) {
1740                         return;
1741                 }
1742
1743                 $author_id = Contact::getIdForURL($activity['object_actor']);
1744                 if (empty($author_id)) {
1745                         return;
1746                 }
1747
1748                 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1749                 Queue::remove($activity);
1750         }
1751
1752         /**
1753          * Activity to remove a follower
1754          *
1755          * @param array $activity
1756          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1757          * @throws \ImagickException
1758          */
1759         public static function undoFollowUser(array $activity)
1760         {
1761                 $uid = User::getIdForURL($activity['object_object']);
1762                 if (empty($uid)) {
1763                         return;
1764                 }
1765
1766                 $owner = User::getOwnerDataById($uid);
1767                 if (empty($owner)) {
1768                         return;
1769                 }
1770
1771                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1772                 if (empty($cid)) {
1773                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1774                         return;
1775                 }
1776
1777                 self::switchContact($cid);
1778
1779                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1780                 if (!DBA::isResult($contact)) {
1781                         return;
1782                 }
1783
1784                 Contact::removeFollower($contact);
1785                 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1786                 Queue::remove($activity);
1787         }
1788
1789         /**
1790          * Switches a contact to AP if needed
1791          *
1792          * @param integer $cid Contact ID
1793          * @return void
1794          * @throws \Exception
1795          */
1796         private static function switchContact(int $cid)
1797         {
1798                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1799                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1800                         return;
1801                 }
1802
1803                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1804                 Contact::updateFromProbe($cid);
1805         }
1806
1807         /**
1808          * Collects implicit mentions like:
1809          * - the author of the parent item
1810          * - all the mentioned conversants in the parent item
1811          *
1812          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1813          * @return array
1814          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1815          */
1816         private static function getImplicitMentionList(array $parent): array
1817         {
1818                 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1819
1820                 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1821
1822                 $implicit_mentions = [];
1823                 if (empty($parent_author['url'])) {
1824                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1825                 } else {
1826                         $implicit_mentions[] = $parent_author['url'];
1827                         $implicit_mentions[] = $parent_author['nurl'];
1828                         $implicit_mentions[] = $parent_author['alias'];
1829                 }
1830
1831                 if (!empty($parent['alias'])) {
1832                         $implicit_mentions[] = $parent['alias'];
1833                 }
1834
1835                 foreach ($parent_terms as $term) {
1836                         $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1837                         if (!empty($contact['url'])) {
1838                                 $implicit_mentions[] = $contact['url'];
1839                                 $implicit_mentions[] = $contact['nurl'];
1840                                 $implicit_mentions[] = $contact['alias'];
1841                         }
1842                 }
1843
1844                 return $implicit_mentions;
1845         }
1846
1847         /**
1848          * Strips from the body prepended implicit mentions
1849          *
1850          * @param string $body
1851          * @param array $parent
1852          * @return string
1853          */
1854         private static function removeImplicitMentionsFromBody(string $body, array $parent): string
1855         {
1856                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1857                         return $body;
1858                 }
1859
1860                 $potential_mentions = self::getImplicitMentionList($parent);
1861
1862                 $kept_mentions = [];
1863
1864                 // Extract one prepended mention at a time from the body
1865                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1866                         if (!in_array($matches[2], $potential_mentions)) {
1867                                 $kept_mentions[] = $matches[1];
1868                         }
1869
1870                         $body = $matches[3];
1871                 }
1872
1873                 // Re-appending the kept mentions to the body after extraction
1874                 $kept_mentions[] = $body;
1875
1876                 return implode('', $kept_mentions);
1877         }
1878
1879         /**
1880          * Adds links to string mentions
1881          *
1882          * @param string $body
1883          * @param array  $tags
1884          * @return string
1885          */
1886         protected static function addMentionLinks(string $body, array $tags): string
1887         {
1888                 // This prevents links to be added again to Pleroma-style mention links
1889                 $body = self::normalizeMentionLinks($body);
1890
1891                 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1892                         foreach ($tags as $tag) {
1893                                 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1894                                         continue;
1895                                 }
1896
1897                                 $hash = substr($tag['name'], 0, 1);
1898                                 $name = substr($tag['name'], 1);
1899                                 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1900                                         $hash = '';
1901                                         $name = $tag['name'];
1902                                 }
1903
1904                                 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);
1905                         }
1906
1907                         return $body;
1908                 });
1909
1910                 return $body;
1911         }
1912 }