]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Preparation for "Featured" collection added
[friendica.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Exception;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Event;
37 use Friendica\Model\GServer;
38 use Friendica\Model\Item;
39 use Friendica\Model\ItemURI;
40 use Friendica\Model\Mail;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Model\Post;
44 use Friendica\Network\HTTPException\InternalServerErrorException;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Protocol\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\JsonLD;
50 use Friendica\Util\Strings;
51
52 /**
53  * ActivityPub Processor Protocol class
54  */
55 class Processor
56 {
57         /**
58          * Extracts the tag character (#, @, !) from mention links
59          *
60          * @param string $body
61          * @return string
62          */
63         protected static function normalizeMentionLinks(string $body): string
64         {
65                 return preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
66         }
67
68         /**
69          * Convert the language array into a language JSON
70          *
71          * @param array $languages
72          * @return string language JSON
73          */
74         private static function processLanguages(array $languages)
75         {
76                 $codes = array_keys($languages);
77                 $lang = [];
78                 foreach ($codes as $code) {
79                         $lang[$code] = 1;
80                 }
81
82                 if (empty($lang)) {
83                         return '';
84                 }
85
86                 return json_encode($lang);
87         }
88         /**
89          * Replaces emojis in the body
90          *
91          * @param array $emojis
92          * @param string $body
93          *
94          * @return string with replaced emojis
95          */
96         private static function replaceEmojis(int $uri_id, $body, array $emojis)
97         {
98                 $body = strtr($body,
99                         array_combine(
100                                 array_column($emojis, 'name'),
101                                 array_map(function ($emoji) {
102                                         return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
103                                 }, $emojis)
104                         )
105                 );
106
107                 // We store the emoji here to be able to avoid storing it in the media
108                 foreach ($emojis as $emoji) {
109                         Post\Link::getByLink($uri_id, $emoji['href']);
110                 }
111                 return $body;
112         }
113
114         /**
115          * Store attached media files in the post-media table
116          *
117          * @param int $uriid
118          * @param array $attachment
119          * @return void
120          */
121         private static function storeAttachmentAsMedia(int $uriid, array $attachment)
122         {
123                 if (empty($attachment['url'])) {
124                         return;
125                 }
126
127                 $data = ['uri-id' => $uriid];
128                 $data['type'] = Post\Media::UNKNOWN;
129                 $data['url'] = $attachment['url'];
130                 $data['mimetype'] = $attachment['mediaType'] ?? null;
131                 $data['height'] = $attachment['height'] ?? null;
132                 $data['width'] = $attachment['width'] ?? null;
133                 $data['size'] = $attachment['size'] ?? null;
134                 $data['preview'] = $attachment['image'] ?? null;
135                 $data['description'] = $attachment['name'] ?? null;
136
137                 Post\Media::insert($data);
138         }
139
140         /**
141          * Stire attachment data
142          *
143          * @param array   $activity
144          * @param array   $item
145          */
146         private static function storeAttachments($activity, $item)
147         {
148                 if (empty($activity['attachments'])) {
149                         return;
150                 }
151
152                 foreach ($activity['attachments'] as $attach) {
153                         self::storeAttachmentAsMedia($item['uri-id'], $attach);
154                 }
155         }
156
157         /**
158          * Updates a message
159          *
160          * @param array $activity Activity array
161          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
162          */
163         public static function updateItem($activity)
164         {
165                 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type'], ['uri' => $activity['id']]);
166                 if (!DBA::isResult($item)) {
167                         Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
168                         $item = self::createItem($activity);
169                         if (empty($item)) {
170                                 return;
171                         }
172
173                         self::postItem($activity, $item);
174                         return;
175                 }
176
177                 $item['changed'] = DateTimeFormat::utcNow();
178                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
179
180                 $item = self::processContent($activity, $item);
181
182                 self::storeAttachments($activity, $item);
183
184                 if (empty($item)) {
185                         return;
186                 }
187
188                 Item::update($item, ['uri' => $activity['id']]);
189
190                 if ($activity['object_type'] == 'as:Event') {
191                         $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
192                         while ($post = DBA::fetch($posts)) {
193                                 self::updateEvent($post['event-id'], $activity);
194                         }
195                 }
196         }
197
198         /**
199          * Update an existing event
200          *
201          * @param int $event_id
202          * @param array $activity
203          */
204         private static function updateEvent(int $event_id, array $activity)
205         {
206                 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
207
208                 $event['edited']   = DateTimeFormat::utc($activity['updated']);
209                 $event['summary']  = HTML::toBBCode($activity['name']);
210                 $event['desc']     = HTML::toBBCode($activity['content']);
211                 $event['start']    = $activity['start-time'];
212                 $event['finish']   = $activity['end-time'];
213                 $event['nofinish'] = empty($event['finish']);
214                 $event['location'] = $activity['location'];
215
216                 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
217                 Event::store($event);
218         }
219
220         /**
221          * Prepares data for a message
222          *
223          * @param array $activity Activity array
224          * @return array Internal item
225          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
226          * @throws \ImagickException
227          */
228         public static function createItem($activity)
229         {
230                 $item = [];
231                 $item['verb'] = Activity::POST;
232                 $item['thr-parent'] = $activity['reply-to-id'];
233
234                 if ($activity['reply-to-id'] == $activity['id']) {
235                         $item['gravity'] = GRAVITY_PARENT;
236                         $item['object-type'] = Activity\ObjectType::NOTE;
237                 } else {
238                         $item['gravity'] = GRAVITY_COMMENT;
239                         $item['object-type'] = Activity\ObjectType::COMMENT;
240                 }
241
242                 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
243                         Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
244                         self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
245                 }
246
247                 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
248
249                 /// @todo What to do with $activity['context']?
250                 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
251                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
252                         return [];
253                 }
254
255                 $item['network'] = Protocol::ACTIVITYPUB;
256                 $item['author-link'] = $activity['author'];
257                 $item['author-id'] = Contact::getIdForURL($activity['author']);
258                 $item['owner-link'] = $activity['actor'];
259                 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
260
261                 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
262                         $item['private'] = Item::UNLISTED;
263                 } elseif (in_array(0, $activity['receiver'])) {
264                         $item['private'] = Item::PUBLIC;
265                 } else {
266                         $item['private'] = Item::PRIVATE;
267                 }
268
269                 if (!empty($activity['raw'])) {
270                         $item['source'] = $activity['raw'];
271                         $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
272                         $item['conversation-href'] = $activity['context'] ?? '';
273                         $item['conversation-uri'] = $activity['conversation'] ?? '';
274
275                         if (isset($activity['push'])) {
276                                 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
277                         }
278                 }
279
280                 if (!empty($activity['from-relay'])) {
281                         $item['direction'] = Conversation::RELAY;
282                 }
283
284                 if ($activity['object_type'] == 'as:Article') {
285                         $item['post-type'] = Item::PT_ARTICLE;
286                 } elseif ($activity['object_type'] == 'as:Audio') {
287                         $item['post-type'] = Item::PT_AUDIO;
288                 } elseif ($activity['object_type'] == 'as:Document') {
289                         $item['post-type'] = Item::PT_DOCUMENT;
290                 } elseif ($activity['object_type'] == 'as:Event') {
291                         $item['post-type'] = Item::PT_EVENT;
292                 } elseif ($activity['object_type'] == 'as:Image') {
293                         $item['post-type'] = Item::PT_IMAGE;
294                 } elseif ($activity['object_type'] == 'as:Page') {
295                         $item['post-type'] = Item::PT_PAGE;
296                 } elseif ($activity['object_type'] == 'as:Question') {
297                         $item['post-type'] = Item::PT_POLL;
298                 } elseif ($activity['object_type'] == 'as:Video') {
299                         $item['post-type'] = Item::PT_VIDEO;
300                 } else {
301                         $item['post-type'] = Item::PT_NOTE;
302                 }
303
304                 $item['isForum'] = false;
305
306                 if (!empty($activity['thread-completion'])) {
307                         if ($activity['thread-completion'] != $item['owner-id']) {
308                                 $actor = Contact::getById($activity['thread-completion'], ['url']);
309                                 $item['causer-link'] = $actor['url'];
310                                 $item['causer-id'] = $activity['thread-completion'];
311                                 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
312                         } else {
313                                 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
314                                 $item['causer-link'] = $item['owner-link'];
315                                 $item['causer-id']   = $item['owner-id'];
316                                 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
317                         }
318
319                         $item['owner-link'] = $item['author-link'];
320                         $item['owner-id'] = $item['author-id'];
321                 } else {
322                         $actor = APContact::getByURL($item['owner-link'], false);
323                         $item['isForum'] = ($actor['type'] == 'Group');
324                 }
325
326                 $item['uri'] = $activity['id'];
327
328                 if (empty($activity['published']) || empty($activity['updated'])) {
329                         DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
330                 }
331
332                 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
333                 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
334                 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
335                 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
336
337                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
338                 if (empty($item['uri-id'])) {
339                         Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
340                         return [];
341                 }
342
343                 $item = self::processContent($activity, $item);
344                 if (empty($item)) {
345                         Logger::info('Message was not processed');
346                         return [];
347                 }
348
349                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
350
351                 self::storeAttachments($activity, $item);
352
353                 // We received the post via AP, so we set the protocol of the server to AP
354                 $contact = Contact::getById($item['author-id'], ['gsid']);
355                 if (!empty($contact['gsid'])) {
356                         GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
357                 }
358
359                 if ($item['author-id'] != $item['owner-id']) {
360                         $contact = Contact::getById($item['owner-id'], ['gsid']);
361                         if (!empty($contact['gsid'])) {
362                                 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
363                         }
364                 }
365
366                 return $item;
367         }
368
369         /**
370          * Delete items
371          *
372          * @param array $activity
373          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
374          * @throws \ImagickException
375          */
376         public static function deleteItem($activity)
377         {
378                 $owner = Contact::getIdForURL($activity['actor']);
379
380                 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner'  => $owner]);
381                 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
382         }
383
384         /**
385          * Prepare the item array for an activity
386          *
387          * @param array $activity Activity array
388          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389          * @throws \ImagickException
390          */
391         public static function addTag($activity)
392         {
393                 if (empty($activity['object_content']) || empty($activity['object_id'])) {
394                         return;
395                 }
396
397                 foreach ($activity['receiver'] as $receiver) {
398                         $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
399                         if (!DBA::isResult($item)) {
400                                 // We don't fetch missing content for this purpose
401                                 continue;
402                         }
403
404                         if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
405                                 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
406                                 continue;
407                         }
408
409                         Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
410                         Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
411                 }
412         }
413
414         /**
415          * Prepare the item array for an activity
416          *
417          * @param array  $activity Activity array
418          * @param string $verb     Activity verb
419          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420          * @throws \ImagickException
421          */
422         public static function createActivity($activity, $verb)
423         {
424                 $item = self::createItem($activity);
425                 if (empty($item)) {
426                         return;
427                 }
428
429                 $item['verb'] = $verb;
430                 $item['thr-parent'] = $activity['object_id'];
431                 $item['gravity'] = GRAVITY_ACTIVITY;
432                 unset($item['post-type']);
433                 $item['object-type'] = Activity\ObjectType::NOTE;
434
435                 if (!empty($activity['content'])) {
436                         $item['body'] = HTML::toBBCode($activity['content']);
437                 }
438
439                 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
440
441                 self::postItem($activity, $item);
442         }
443
444         /**
445          * Fetch the Uri-Id of a post for the "featured" collection
446          *
447          * @param array $activity 
448          * @return null|int 
449          */
450         private static function getUriIdForFeaturedCollection(array $activity)
451         {
452                 $actor = APContact::getByURL($activity['actor']);
453                 if (empty($actor)) {
454                         return null;
455                 }
456
457                 // Refetch the account when the "featured" collection is missing.
458                 // This can be removed in a future version (end of 2022 should be good).
459                 if (empty($actor['featured'])) {
460                         $actor = APContact::getByURL($activity['actor'], true);
461                         if (empty($actor)) {
462                                 return null;
463                         }
464                 }
465
466                 if ($activity['target_id'] != $actor['featured']) {
467                         return null;
468                 }
469
470                 $id = Contact::getIdForURL($activity['actor']);
471                 if (empty($id)) {
472                         return null;
473                 }
474
475                 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id'], 'author-id' => $id]);
476                 if (!empty($parent['uri-id'])) {
477                         return $parent['uri-id'];
478                 }
479
480                 return null;
481         }
482
483         /**
484          * Add a post to the "Featured" collection
485          *
486          * @param array $activity 
487          */
488         public static function addToFeaturedCollection(array $activity)
489         {
490                 $uriid = self::getUriIdForFeaturedCollection($activity);
491                 if (empty($uriid)) {
492                         return;
493                 }
494
495                 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
496
497                 // @todo Add functionality
498         }
499
500         /**
501          * Remove a post to the "Featured" collection
502          *
503          * @param array $activity 
504          */
505         public static function removeFromFeaturedCollection(array $activity)
506         {
507                 $uriid = self::getUriIdForFeaturedCollection($activity);
508                 if (empty($uriid)) {
509                         return;
510                 }
511
512                 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
513
514                 // @todo Add functionality
515         }
516
517         /**
518          * Create an event
519          *
520          * @param array $activity Activity array
521          * @param array $item
522          *
523          * @return int event id
524          * @throws \Exception
525          */
526         public static function createEvent($activity, $item)
527         {
528                 $event['summary']   = HTML::toBBCode($activity['name'] ?: $activity['summary']);
529                 $event['desc']      = HTML::toBBCode($activity['content']);
530                 $event['start']     = $activity['start-time'];
531                 $event['finish']    = $activity['end-time'];
532                 $event['nofinish']  = empty($event['finish']);
533                 $event['location']  = $activity['location'];
534                 $event['cid']       = $item['contact-id'];
535                 $event['uid']       = $item['uid'];
536                 $event['uri']       = $item['uri'];
537                 $event['edited']    = $item['edited'];
538                 $event['private']   = $item['private'];
539                 $event['guid']      = $item['guid'];
540                 $event['plink']     = $item['plink'];
541                 $event['network']   = $item['network'];
542                 $event['protocol']  = $item['protocol'];
543                 $event['direction'] = $item['direction'];
544                 $event['source']    = $item['source'];
545
546                 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
547                 if (DBA::isResult($ev)) {
548                         $event['id'] = $ev['id'];
549                 }
550
551                 $event_id = Event::store($event);
552
553                 Logger::info('Event was stored', ['id' => $event_id]);
554
555                 return $event_id;
556         }
557
558         /**
559          * Process the content
560          *
561          * @param array $activity Activity array
562          * @param array $item
563          * @return array|bool Returns the item array or false if there was an unexpected occurrence
564          * @throws \Exception
565          */
566         private static function processContent($activity, $item)
567         {
568                 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
569                         $item['title'] = Markdown::toBBCode($activity['name']);
570                         $content = Markdown::toBBCode($activity['content']);
571                 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
572                         $item['title'] = $activity['name'];
573                         $content = $activity['content'];
574                 } else {
575                         // By default assume "text/html"
576                         $item['title'] = HTML::toBBCode($activity['name']);
577                         $content = HTML::toBBCode($activity['content']);
578                 }
579
580                 if (!empty($activity['languages'])) {
581                         $item['language'] = self::processLanguages($activity['languages']);
582                 }
583
584                 if (!empty($activity['emojis'])) {
585                         $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
586                 }
587
588                 $content = self::addMentionLinks($content, $activity['tags']);
589
590                 if (!empty($activity['source'])) {
591                         $item['body'] = $activity['source'];
592                         $item['raw-body'] = $content;
593                         $item['body'] = Item::improveSharedDataInBody($item);
594                 } else {
595                         if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
596                                 $item_private = !in_array(0, $activity['item_receiver']);
597                                 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
598                                 if (!DBA::isResult($parent)) {
599                                         Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
600                                         return false;
601                                 }
602                                 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
603                                         Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
604                                         return false;
605                                 }
606
607                                 $content = self::removeImplicitMentionsFromBody($content, $parent);
608                         }
609                         $item['content-warning'] = HTML::toBBCode($activity['summary']);
610                         $item['raw-body'] = $item['body'] = $content;
611                 }
612
613                 self::storeFromBody($item);
614                 self::storeTags($item['uri-id'], $activity['tags']);
615
616                 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
617
618                 $item['location'] = $activity['location'];
619
620                 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
621                         $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
622                 }
623
624                 $item['app'] = $activity['generator'];
625
626                 return $item;
627         }
628
629         /**
630          * Store hashtags and mentions
631          *
632          * @param array $item
633          */
634         private static function storeFromBody(array $item)
635         {
636                 // Make sure to delete all existing tags (can happen when called via the update functionality)
637                 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
638
639                 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
640         }
641
642         /**
643          * Generate a GUID out of an URL of an ActivityPub post.
644          *
645          * @param string $url message URL
646          * @return string with GUID
647          */
648         private static function getGUIDByURL(string $url)
649         {
650                 $parsed = parse_url($url);
651
652                 $host_hash = hash('crc32', $parsed['host']);
653
654                 unset($parsed["scheme"]);
655                 unset($parsed["host"]);
656
657                 $path = implode("/", $parsed);
658
659                 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
660         }
661
662         /**
663          * Checks if an incoming message is wanted
664          *
665          * @param array $activity
666          * @param array $item
667          * @return boolean Is the message wanted?
668          */
669         private static function isSolicitedMessage(array $activity, array $item)
670         {
671                 // The checks are split to improve the support when searching why a message was accepted.
672                 if (count($activity['receiver']) != 1) {
673                         // The message has more than one receiver, so it is wanted.
674                         Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
675                         return true;
676                 }
677
678                 if ($item['private'] == Item::PRIVATE) {
679                         // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
680                         Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
681                         return true;
682                 }
683
684                 if (!empty($activity['from-relay'])) {
685                         // We check relay posts at another place. When it arrived here, the message is already checked.
686                         Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
687                         return true;
688                 }
689
690                 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
691                         // Manual completions and completions caused by reshares are allowed without any further checks.
692                         Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
693                         return true;
694                 }
695
696                 if ($item['gravity'] != GRAVITY_PARENT) {
697                         // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
698                         // This can possibly be improved in the future.
699                         Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
700                         return true;
701                 }
702
703                 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
704                 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
705                         Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
706                         return true;
707                 } else {
708                         return false;
709                 }
710         }
711
712         /**
713          * Creates an item post
714          *
715          * @param array $activity Activity data
716          * @param array $item     item array
717          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
718          * @throws \ImagickException
719          */
720         public static function postItem(array $activity, array $item)
721         {
722                 if (empty($item)) {
723                         return;
724                 }
725
726                 $stored = false;
727                 ksort($activity['receiver']);
728
729                 if (!self::isSolicitedMessage($activity, $item)) {
730                         DBA::delete('item-uri', ['id' => $item['uri-id']]);
731                         return;
732                 }
733
734                 foreach ($activity['receiver'] as $receiver) {
735                         if ($receiver == -1) {
736                                 continue;
737                         }
738
739                         $item['uid'] = $receiver;
740
741                         $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
742                         switch($type) {
743                                 case Receiver::TARGET_TO:
744                                         $item['post-reason'] = Item::PR_TO;
745                                         break;
746                                 case Receiver::TARGET_CC:
747                                         $item['post-reason'] = Item::PR_CC;
748                                         break;
749                                 case Receiver::TARGET_BTO:
750                                         $item['post-reason'] = Item::PR_BTO;
751                                         break;
752                                 case Receiver::TARGET_BCC:
753                                         $item['post-reason'] = Item::PR_BCC;
754                                         break;
755                                 case Receiver::TARGET_FOLLOWER:
756                                         $item['post-reason'] = Item::PR_FOLLOWER;
757                                         break;
758                                 case Receiver::TARGET_ANSWER:
759                                         $item['post-reason'] = Item::PR_COMMENT;
760                                         break;
761                                 case Receiver::TARGET_GLOBAL:
762                                         $item['post-reason'] = Item::PR_GLOBAL;
763                                         break;
764                                 default:
765                                         $item['post-reason'] = Item::PR_NONE;
766                         }
767
768                         if (!empty($activity['from-relay'])) {
769                                 $item['post-reason'] = Item::PR_RELAY;
770                         } elseif (!empty($activity['thread-completion'])) {
771                                 $item['post-reason'] = Item::PR_FETCHED;
772                         }
773
774                         if ($item['isForum'] ?? false) {
775                                 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
776                         } else {
777                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
778                         }
779
780                         if (($receiver != 0) && empty($item['contact-id'])) {
781                                 $item['contact-id'] = Contact::getIdForURL($activity['author']);
782                         }
783
784                         if (!empty($activity['directmessage'])) {
785                                 self::postMail($activity, $item);
786                                 continue;
787                         }
788
789                         if (!($item['isForum'] ?? false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !Contact::isSharingByURL($activity['author'], $receiver)) {
790                                 if ($item['post-reason'] == Item::PR_BCC) {
791                                         Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id']]);
792                                         continue;
793                                 }
794
795                                 if (
796                                         !empty($activity['thread-children-type'])
797                                         && in_array($activity['thread-children-type'], Receiver::ACTIVITY_TYPES)
798                                         && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE
799                                 ) {
800                                         Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
801                                                 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
802                                         continue;
803                                 }
804                         }
805
806                         $is_forum = false;
807
808                         if ($receiver != 0) {
809                                 $user = User::getById($receiver, ['account-type']);
810                                 if (!empty($user['account-type'])) {
811                                         $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
812                                 }
813                         }
814
815                         if (!$is_forum && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
816                                 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
817
818                                 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
819                                         $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
820                                 }
821
822                                 if ($skip) {
823                                         Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
824                                         continue;
825                                 }
826
827                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
828                         }
829
830                         if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
831                                 $event_id = self::createEvent($activity, $item);
832
833                                 $item = Event::getItemArrayForImportedId($event_id, $item);
834                         }
835
836                         $item_id = Item::insert($item);
837                         if ($item_id) {
838                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
839                         } else {
840                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
841                         }
842
843                         if ($item['uid'] == 0) {
844                                 $stored = $item_id;
845                         }
846                 }
847
848                 // Store send a follow request for every reshare - but only when the item had been stored
849                 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
850                         $author = APContact::getByURL($item['owner-link'], false);
851                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
852                         if ($author['type'] != 'Group') {
853                                 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
854                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
855                         }
856                 }
857         }
858
859         /**
860          * Store tags and mentions into the tag table
861          *
862          * @param integer $uriid
863          * @param array $tags
864          */
865         private static function storeTags(int $uriid, array $tags = null)
866         {
867                 foreach ($tags as $tag) {
868                         if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
869                                 continue;
870                         }
871
872                         $hash = substr($tag['name'], 0, 1);
873
874                         if ($tag['type'] == 'Mention') {
875                                 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
876                                         Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
877                                         Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
878                                         $tag['name'] = substr($tag['name'], 1);
879                                 }
880                                 $type = Tag::IMPLICIT_MENTION;
881
882                                 if (!empty($tag['href'])) {
883                                         $apcontact = APContact::getByURL($tag['href']);
884                                         if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
885                                                 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
886                                         }
887                                 }
888                         } elseif ($tag['type'] == 'Hashtag') {
889                                 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
890                                         $tag['name'] = substr($tag['name'], 1);
891                                 }
892                                 $type = Tag::HASHTAG;
893                         }
894
895                         if (empty($tag['name'])) {
896                                 continue;
897                         }
898
899                         Tag::store($uriid, $type, $tag['name'], $tag['href']);
900                 }
901         }
902
903         public static function storeReceivers(int $uriid, array $receivers)
904         {
905                 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
906                         if (!empty($receivers[$element])) {
907                                 foreach ($receivers[$element] as $receiver) {
908                                         if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
909                                                 $name = Receiver::PUBLIC_COLLECTION;
910                                         } else {
911                                                 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
912                                         }
913                                         Tag::store($uriid, $type, $name, $receiver);
914                                 }
915                         }
916                 }
917         }
918
919         /**
920          * Creates an mail post
921          *
922          * @param array $activity Activity data
923          * @param array $item     item array
924          * @return int|bool New mail table row id or false on error
925          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
926          */
927         private static function postMail($activity, $item)
928         {
929                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
930                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
931                         return false;
932                 }
933
934                 Logger::info('Direct Message', $item);
935
936                 $msg = [];
937                 $msg['uid'] = $item['uid'];
938
939                 $msg['contact-id'] = $item['contact-id'];
940
941                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
942                 $msg['from-name'] = $contact['name'];
943                 $msg['from-url'] = $contact['url'];
944                 $msg['from-photo'] = $contact['photo'];
945
946                 $msg['uri'] = $item['uri'];
947                 $msg['created'] = $item['created'];
948
949                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
950                 if (DBA::isResult($parent)) {
951                         $msg['parent-uri'] = $parent['parent-uri'];
952                         $msg['title'] = $parent['title'];
953                 } else {
954                         $msg['parent-uri'] = $item['thr-parent'];
955
956                         if (!empty($item['title'])) {
957                                 $msg['title'] = $item['title'];
958                         } elseif (!empty($item['content-warning'])) {
959                                 $msg['title'] = $item['content-warning'];
960                         } else {
961                                 // Trying to generate a title out of the body
962                                 $title = $item['body'];
963
964                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
965                                         $title = $matches[3];
966                                 }
967
968                                 $title = trim(BBCode::toPlaintext($title));
969
970                                 if (strlen($title) > 20) {
971                                         $title = substr($title, 0, 20) . '...';
972                                 }
973
974                                 $msg['title'] = $title;
975                         }
976                 }
977                 $msg['body'] = $item['body'];
978
979                 return Mail::insert($msg);
980         }
981
982         /**
983          * Fetches missing posts
984          *
985          * @param string $url         message URL
986          * @param array  $child       activity array with the child of this message
987          * @param string $relay_actor Relay actor
988          * @param int    $completion  Completion mode, see Receiver::COMPLETION_*
989          * @return string fetched message URL
990          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
991          */
992         public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL)
993         {
994                 if (!empty($child['receiver'])) {
995                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
996                 } else {
997                         $uid = 0;
998                 }
999
1000                 $object = ActivityPub::fetchContent($url, $uid);
1001                 if (empty($object)) {
1002                         Logger::notice('Activity was not fetchable, aborting.', ['url' => $url]);
1003                         return '';
1004                 }
1005
1006                 if (empty($object['id'])) {
1007                         Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1008                         return '';
1009                 }
1010
1011                 if (!empty($object['actor'])) {
1012                         $object_actor = $object['actor'];
1013                 } elseif (!empty($object['attributedTo'])) {
1014                         $object_actor = $object['attributedTo'];
1015                         if (is_array($object_actor)) {
1016                                 $compacted = JsonLD::compact($object);
1017                                 $object_actor = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1018                         }
1019                 } else {
1020                         // Shouldn't happen
1021                         $object_actor = '';
1022                 }
1023
1024                 $signer = [$object_actor];
1025
1026                 if (!empty($child['author'])) {
1027                         $actor = $child['author'];
1028                         $signer[] = $actor;
1029                 } else {
1030                         $actor = $object_actor;
1031                 }
1032
1033                 if (!empty($object['published'])) {
1034                         $published = $object['published'];
1035                 } elseif (!empty($child['published'])) {
1036                         $published = $child['published'];
1037                 } else {
1038                         $published = DateTimeFormat::utcNow();
1039                 }
1040
1041                 $activity = [];
1042                 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1043                 unset($object['@context']);
1044                 $activity['id'] = $object['id'];
1045                 $activity['to'] = $object['to'] ?? [];
1046                 $activity['cc'] = $object['cc'] ?? [];
1047                 $activity['actor'] = $actor;
1048                 $activity['object'] = $object;
1049                 $activity['published'] = $published;
1050                 $activity['type'] = 'Create';
1051
1052                 $ldactivity = JsonLD::compact($activity);
1053
1054                 if (!empty($relay_actor)) {
1055                         $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1056                         $ldactivity['completion-mode']   = Receiver::COMPLETION_RELAY;
1057                 } elseif (!empty($child['thread-completion'])) {
1058                         $ldactivity['thread-completion'] = $child['thread-completion'];
1059                         $ldactivity['completion-mode']   = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1060                 } else {
1061                         $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1062                         $ldactivity['completion-mode']   = $completion;
1063                 }
1064
1065                 if (!empty($child['type'])) {
1066                         $ldactivity['thread-children-type'] = $child['type'];
1067                 }
1068
1069                 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1070                         return '';
1071                 }
1072
1073                 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
1074
1075                 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
1076
1077                 return $activity['id'];
1078         }
1079
1080         /**
1081          * Test if incoming relay messages should be accepted
1082          *
1083          * @param array $activity activity array
1084          * @param string $id      object ID
1085          * @return boolean true if message is accepted
1086          */
1087         private static function acceptIncomingMessage(array $activity, string $id)
1088         {
1089                 if (empty($activity['as:object'])) {
1090                         Logger::info('No object field in activity - accepted', ['id' => $id]);
1091                         return true;
1092                 }
1093
1094                 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1095                 $uriid = ItemURI::getIdByURI($replyto);
1096                 if (Post::exists(['uri-id' => $uriid])) {
1097                         Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1098                         return true;
1099                 }
1100
1101                 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1102                 $authorid = Contact::getIdForURL($attributed_to);
1103
1104                 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value'));
1105
1106                 $messageTags = [];
1107                 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1108                 if (!empty($tags)) {
1109                         foreach ($tags as $tag) {
1110                                 if ($tag['type'] != 'Hashtag') {
1111                                         continue;
1112                                 }
1113                                 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1114                         }
1115                 }
1116
1117                 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1118         }
1119
1120         /**
1121          * perform a "follow" request
1122          *
1123          * @param array $activity
1124          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1125          * @throws \ImagickException
1126          */
1127         public static function followUser($activity)
1128         {
1129                 $uid = User::getIdForURL($activity['object_id']);
1130                 if (empty($uid)) {
1131                         return;
1132                 }
1133
1134                 $owner = User::getOwnerDataById($uid);
1135                 if (empty($owner)) {
1136                         return;
1137                 }
1138
1139                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1140                 if (!empty($cid)) {
1141                         self::switchContact($cid);
1142                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1143                 }
1144
1145                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
1146                         'author-link' => $activity['actor']];
1147
1148                 // Ensure that the contact has got the right network type
1149                 self::switchContact($item['author-id']);
1150
1151                 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1152                 if ($result === true) {
1153                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1154                 }
1155
1156                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1157                 if (empty($cid)) {
1158                         return;
1159                 }
1160
1161                 if (empty($contact)) {
1162                         Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1163                 }
1164
1165                 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1166         }
1167
1168         /**
1169          * Update the given profile
1170          *
1171          * @param array $activity
1172          * @throws \Exception
1173          */
1174         public static function updatePerson($activity)
1175         {
1176                 if (empty($activity['object_id'])) {
1177                         return;
1178                 }
1179
1180                 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1181                 Contact::updateFromProbeByURL($activity['object_id']);
1182         }
1183
1184         /**
1185          * Delete the given profile
1186          *
1187          * @param array $activity
1188          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1189          */
1190         public static function deletePerson($activity)
1191         {
1192                 if (empty($activity['object_id']) || empty($activity['actor'])) {
1193                         Logger::info('Empty object id or actor.');
1194                         return;
1195                 }
1196
1197                 if ($activity['object_id'] != $activity['actor']) {
1198                         Logger::info('Object id does not match actor.');
1199                         return;
1200                 }
1201
1202                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1203                 while ($contact = DBA::fetch($contacts)) {
1204                         Contact::remove($contact['id']);
1205                 }
1206                 DBA::close($contacts);
1207
1208                 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1209         }
1210
1211         /**
1212          * Accept a follow request
1213          *
1214          * @param array $activity
1215          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1216          * @throws \ImagickException
1217          */
1218         public static function acceptFollowUser($activity)
1219         {
1220                 $uid = User::getIdForURL($activity['object_actor']);
1221                 if (empty($uid)) {
1222                         return;
1223                 }
1224
1225                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1226                 if (empty($cid)) {
1227                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1228                         return;
1229                 }
1230
1231                 self::switchContact($cid);
1232
1233                 $fields = ['pending' => false];
1234
1235                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1236                 if ($contact['rel'] == Contact::FOLLOWER) {
1237                         $fields['rel'] = Contact::FRIEND;
1238                 }
1239
1240                 $condition = ['id' => $cid];
1241                 Contact::update($fields, $condition);
1242                 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1243         }
1244
1245         /**
1246          * Reject a follow request
1247          *
1248          * @param array $activity
1249          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250          * @throws \ImagickException
1251          */
1252         public static function rejectFollowUser($activity)
1253         {
1254                 $uid = User::getIdForURL($activity['object_actor']);
1255                 if (empty($uid)) {
1256                         return;
1257                 }
1258
1259                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1260                 if (empty($cid)) {
1261                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1262                         return;
1263                 }
1264
1265                 self::switchContact($cid);
1266
1267                 $contact = Contact::getById($cid, ['rel']);
1268                 if ($contact['rel'] == Contact::SHARING) {
1269                         Contact::remove($cid);
1270                         Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1271                 } elseif ($contact['rel'] == Contact::FRIEND) {
1272                         Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1273                 } else {
1274                         Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1275                 }
1276         }
1277
1278         /**
1279          * Undo activity like "like" or "dislike"
1280          *
1281          * @param array $activity
1282          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1283          * @throws \ImagickException
1284          */
1285         public static function undoActivity($activity)
1286         {
1287                 if (empty($activity['object_id'])) {
1288                         return;
1289                 }
1290
1291                 if (empty($activity['object_actor'])) {
1292                         return;
1293                 }
1294
1295                 $author_id = Contact::getIdForURL($activity['object_actor']);
1296                 if (empty($author_id)) {
1297                         return;
1298                 }
1299
1300                 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1301         }
1302
1303         /**
1304          * Activity to remove a follower
1305          *
1306          * @param array $activity
1307          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1308          * @throws \ImagickException
1309          */
1310         public static function undoFollowUser($activity)
1311         {
1312                 $uid = User::getIdForURL($activity['object_object']);
1313                 if (empty($uid)) {
1314                         return;
1315                 }
1316
1317                 $owner = User::getOwnerDataById($uid);
1318                 if (empty($owner)) {
1319                         return;
1320                 }
1321
1322                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1323                 if (empty($cid)) {
1324                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1325                         return;
1326                 }
1327
1328                 self::switchContact($cid);
1329
1330                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1331                 if (!DBA::isResult($contact)) {
1332                         return;
1333                 }
1334
1335                 Contact::removeFollower($contact);
1336                 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1337         }
1338
1339         /**
1340          * Switches a contact to AP if needed
1341          *
1342          * @param integer $cid Contact ID
1343          * @throws \Exception
1344          */
1345         private static function switchContact($cid)
1346         {
1347                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1348                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1349                         return;
1350                 }
1351
1352                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1353                 Contact::updateFromProbe($cid);
1354         }
1355
1356         /**
1357          * Collects implicit mentions like:
1358          * - the author of the parent item
1359          * - all the mentioned conversants in the parent item
1360          *
1361          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1362          * @return array
1363          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1364          */
1365         private static function getImplicitMentionList(array $parent)
1366         {
1367                 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1368
1369                 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1370
1371                 $implicit_mentions = [];
1372                 if (empty($parent_author['url'])) {
1373                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1374                 } else {
1375                         $implicit_mentions[] = $parent_author['url'];
1376                         $implicit_mentions[] = $parent_author['nurl'];
1377                         $implicit_mentions[] = $parent_author['alias'];
1378                 }
1379
1380                 if (!empty($parent['alias'])) {
1381                         $implicit_mentions[] = $parent['alias'];
1382                 }
1383
1384                 foreach ($parent_terms as $term) {
1385                         $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1386                         if (!empty($contact['url'])) {
1387                                 $implicit_mentions[] = $contact['url'];
1388                                 $implicit_mentions[] = $contact['nurl'];
1389                                 $implicit_mentions[] = $contact['alias'];
1390                         }
1391                 }
1392
1393                 return $implicit_mentions;
1394         }
1395
1396         /**
1397          * Strips from the body prepended implicit mentions
1398          *
1399          * @param string $body
1400          * @param array $parent
1401          * @return string
1402          */
1403         private static function removeImplicitMentionsFromBody(string $body, array $parent)
1404         {
1405                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1406                         return $body;
1407                 }
1408
1409                 $potential_mentions = self::getImplicitMentionList($parent);
1410
1411                 $kept_mentions = [];
1412
1413                 // Extract one prepended mention at a time from the body
1414                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1415                         if (!in_array($matches[2], $potential_mentions)) {
1416                                 $kept_mentions[] = $matches[1];
1417                         }
1418
1419                         $body = $matches[3];
1420                 }
1421
1422                 // Re-appending the kept mentions to the body after extraction
1423                 $kept_mentions[] = $body;
1424
1425                 return implode('', $kept_mentions);
1426         }
1427
1428         /**
1429          * Adds links to string mentions
1430          *
1431          * @param string $body
1432          * @param array  $tags
1433          * @return string
1434          */
1435         protected static function addMentionLinks(string $body, array $tags): string
1436         {
1437                 // This prevents links to be added again to Pleroma-style mention links
1438                 $body = self::normalizeMentionLinks($body);
1439
1440                 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1441                         foreach ($tags as $tag) {
1442                                 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1443                                         continue;
1444                                 }
1445
1446                                 $hash = substr($tag['name'], 0, 1);
1447                                 $name = substr($tag['name'], 1);
1448                                 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1449                                         $hash = '';
1450                                         $name = $tag['name'];
1451                                 }
1452
1453                                 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);
1454                         }
1455
1456                         return $body;
1457                 });
1458
1459                 return $body;
1460         }
1461 }