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