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