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