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