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