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