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