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