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