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