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