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