]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Store implicit mentions
[friendica.git] / src / Protocol / ActivityPub / Processor.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\APContact;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Conversation;
33 use Friendica\Model\Event;
34 use Friendica\Model\Item;
35 use Friendica\Model\ItemURI;
36 use Friendica\Model\Mail;
37 use Friendica\Model\Tag;
38 use Friendica\Model\Term;
39 use Friendica\Model\User;
40 use Friendica\Protocol\Activity;
41 use Friendica\Protocol\ActivityPub;
42 use Friendica\Util\DateTimeFormat;
43 use Friendica\Util\JsonLD;
44 use Friendica\Util\Strings;
45
46 /**
47  * ActivityPub Processor Protocol class
48  */
49 class Processor
50 {
51         /**
52          * Converts mentions from Pleroma into the Friendica format
53          *
54          * @param string $body
55          *
56          * @return string converted body
57          */
58         private static function convertMentions($body)
59         {
60                 $URLSearchString = "^\[\]";
61                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
62
63                 return $body;
64         }
65
66         /**
67          * Replaces emojis in the body
68          *
69          * @param array $emojis
70          * @param string $body
71          *
72          * @return string with replaced emojis
73          */
74         private static function replaceEmojis($body, array $emojis)
75         {
76                 foreach ($emojis as $emoji) {
77                         $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
78                         $body = str_replace($emoji['name'], $replace, $body);
79                 }
80                 return $body;
81         }
82
83         /**
84          * Constructs a string with tags for a given tag array
85          *
86          * @param array   $tags
87          * @param boolean $sensitive
88          * @return string with tags
89          */
90         private static function constructTagString(array $tags = null, $sensitive = false)
91         {
92                 if (empty($tags)) {
93                         return '';
94                 }
95
96                 $tag_text = '';
97                 foreach ($tags as $tag) {
98                         if (in_array($tag['type'] ?? '', ['Mention', 'Hashtag'])) {
99                                 if (!empty($tag_text)) {
100                                         $tag_text .= ',';
101                                 }
102
103                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
104                         }
105                 }
106
107                 /// @todo add nsfw for $sensitive
108
109                 return $tag_text;
110         }
111
112         /**
113          * Add attachment data to the item array
114          *
115          * @param array   $activity
116          * @param array   $item
117          *
118          * @return array array
119          */
120         private static function constructAttachList($activity, $item)
121         {
122                 if (empty($activity['attachments'])) {
123                         return $item;
124                 }
125
126                 foreach ($activity['attachments'] as $attach) {
127                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
128                         if ($filetype == 'image') {
129                                 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
130                                         continue;
131                                 }
132
133                                 if (empty($attach['name'])) {
134                                         $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
135                                 } else {
136                                         $item['body'] .= "\n[img=" . $attach['url'] . ']' . $attach['name'] . '[/img]';
137                                 }
138                         } elseif ($filetype == 'audio') {
139                                 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
140                                         continue;
141                                 }
142
143                                 $item['body'] .= "\n[audio]" . $attach['url'] . '[/audio]';
144                         } elseif ($filetype == 'video') {
145                                 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
146                                         continue;
147                                 }
148
149                                 $item['body'] .= "\n[video]" . $attach['url'] . '[/video]';
150                         } else {
151                                 if (!empty($item["attach"])) {
152                                         $item["attach"] .= ',';
153                                 } else {
154                                         $item["attach"] = '';
155                                 }
156                                 if (!isset($attach['length'])) {
157                                         $attach['length'] = "0";
158                                 }
159                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.($attach['name'] ?? '') .'"[/attach]';
160                         }
161                 }
162
163                 return $item;
164         }
165
166         /**
167          * Updates a message
168          *
169          * @param array $activity Activity array
170          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
171          */
172         public static function updateItem($activity)
173         {
174                 $item = Item::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
175                 if (!DBA::isResult($item)) {
176                         Logger::warning('Unknown item', ['uri' => $activity['id']]);
177                         return;
178                 }
179
180                 $item['changed'] = DateTimeFormat::utcNow();
181                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
182
183                 $item = self::processContent($activity, $item);
184                 if (empty($item)) {
185                         return;
186                 }
187
188                 Item::update($item, ['uri' => $activity['id']]);
189         }
190
191         /**
192          * Prepares data for a message
193          *
194          * @param array $activity Activity array
195          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196          * @throws \ImagickException
197          */
198         public static function createItem($activity)
199         {
200                 $item = [];
201                 $item['verb'] = Activity::POST;
202                 $item['thr-parent'] = $activity['reply-to-id'];
203
204                 if ($activity['reply-to-id'] == $activity['id']) {
205                         $item['gravity'] = GRAVITY_PARENT;
206                         $item['object-type'] = Activity\ObjectType::NOTE;
207                 } else {
208                         $item['gravity'] = GRAVITY_COMMENT;
209                         $item['object-type'] = Activity\ObjectType::COMMENT;
210
211                         // Ensure that the comment reaches all receivers of the referring post
212                         $activity['receiver'] = self::addReceivers($activity);
213                 }
214
215                 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
216                         Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
217                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
218                 }
219
220                 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
221
222                 self::postItem($activity, $item);
223         }
224
225         /**
226          * Delete items
227          *
228          * @param array $activity
229          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230          * @throws \ImagickException
231          */
232         public static function deleteItem($activity)
233         {
234                 $owner = Contact::getIdForURL($activity['actor']);
235
236                 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
237                 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
238         }
239
240         /**
241          * Prepare the item array for an activity
242          *
243          * @param array $activity Activity array
244          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
245          * @throws \ImagickException
246          */
247         public static function addTag($activity)
248         {
249                 if (empty($activity['object_content']) || empty($activity['object_id'])) {
250                         return;
251                 }
252
253                 foreach ($activity['receiver'] as $receiver) {
254                         $item = Item::selectFirst(['id', 'uri-id', 'tag', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
255                         if (!DBA::isResult($item)) {
256                                 // We don't fetch missing content for this purpose
257                                 continue;
258                         }
259
260                         if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
261                                 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
262                                 continue;
263                         }
264
265                         Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
266
267                         // To-Do:
268                         // - Check if "blocktag" is set
269                         // - Check if actor is a contact
270
271                         if (!stristr($item['tag'], trim($activity['object_content']))) {
272                                 $tag = $item['tag'] . (strlen($item['tag']) ? ',' : '') . '#[url=' . $activity['object_id'] . ']'. $activity['object_content'] . '[/url]';
273                                 Item::update(['tag' => $tag], ['id' => $item['id']]);
274                                 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
275                         }
276                 }
277         }
278
279         /**
280          * Add users to the receiver list of the given public activity.
281          * This is used to ensure that the activity will be stored in every thread.
282          *
283          * @param array $activity Activity array
284          * @return array Modified receiver list
285          */
286         private static function addReceivers(array $activity)
287         {
288                 if (!in_array(0, $activity['receiver'])) {
289                         // Private activities will not be modified
290                         return $activity['receiver'];
291                 }
292
293                 // Add all owners of the referring item to the receivers
294                 $original = $receivers = $activity['receiver'];
295                 $items = Item::select(['uid'], ['uri' => $activity['object_id']]);
296                 while ($item = DBA::fetch($items)) {
297                         $receivers['uid:' . $item['uid']] = $item['uid'];
298                 }
299                 DBA::close($items);
300
301                 if (count($original) != count($receivers)) {
302                         Logger::info('Improved data', ['id' => $activity['id'], 'object' => $activity['object_id'], 'original' => $original, 'improved' => $receivers]);
303                 }
304
305                 return $receivers;
306         }
307
308         /**
309          * Prepare the item array for an activity
310          *
311          * @param array  $activity Activity array
312          * @param string $verb     Activity verb
313          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
314          * @throws \ImagickException
315          */
316         public static function createActivity($activity, $verb)
317         {
318                 $item = [];
319                 $item['verb'] = $verb;
320                 $item['thr-parent'] = $activity['object_id'];
321                 $item['gravity'] = GRAVITY_ACTIVITY;
322                 $item['object-type'] = Activity\ObjectType::NOTE;
323
324                 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
325
326                 $activity['receiver'] = self::addReceivers($activity);
327
328                 self::postItem($activity, $item);
329         }
330
331         /**
332          * Create an event
333          *
334          * @param array $activity Activity array
335          * @param array $item
336          * @throws \Exception
337          */
338         public static function createEvent($activity, $item)
339         {
340                 $event['summary']  = HTML::toBBCode($activity['name']);
341                 $event['desc']     = HTML::toBBCode($activity['content']);
342                 $event['start']    = $activity['start-time'];
343                 $event['finish']   = $activity['end-time'];
344                 $event['nofinish'] = empty($event['finish']);
345                 $event['location'] = $activity['location'];
346                 $event['adjust']   = true;
347                 $event['cid']      = $item['contact-id'];
348                 $event['uid']      = $item['uid'];
349                 $event['uri']      = $item['uri'];
350                 $event['edited']   = $item['edited'];
351                 $event['private']  = $item['private'];
352                 $event['guid']     = $item['guid'];
353                 $event['plink']    = $item['plink'];
354
355                 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
356                 $ev = DBA::selectFirst('event', ['id'], $condition);
357                 if (DBA::isResult($ev)) {
358                         $event['id'] = $ev['id'];
359                 }
360
361                 $event_id = Event::store($event);
362                 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
363         }
364
365         /**
366          * Process the content
367          *
368          * @param array $activity Activity array
369          * @param array $item
370          * @return array|bool Returns the item array or false if there was an unexpected occurrence
371          * @throws \Exception
372          */
373         private static function processContent($activity, $item)
374         {
375                 $item['title'] = HTML::toBBCode($activity['name']);
376
377                 if (!empty($activity['source'])) {
378                         $item['body'] = $activity['source'];
379                 } else {
380                         $content = HTML::toBBCode($activity['content']);
381
382                         if (!empty($activity['emojis'])) {
383                                 $content = self::replaceEmojis($content, $activity['emojis']);
384                         }
385
386                         $content = self::convertMentions($content);
387
388                         if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
389                                 $item_private = !in_array(0, $activity['item_receiver']);
390                                 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
391                                 if (!DBA::isResult($parent)) {
392                                         Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
393                                         return false;
394                                 }
395                                 if ($item_private && ($parent['private'] == Item::PRIVATE)) {
396                                         Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
397                                         return false;
398                                 }
399
400                                 $potential_implicit_mentions = self::getImplicitMentionList($parent);
401                                 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
402                                 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
403                         }
404                         $item['content-warning'] = HTML::toBBCode($activity['summary']);
405                         $item['body'] = $content;
406                 }
407
408                 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
409
410                 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
411                 self::storeTags($item['uri-id'], $activity['tags']);
412
413                 $item['location'] = $activity['location'];
414
415                 if (!empty($item['latitude']) && !empty($item['longitude'])) {
416                         $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
417                 }
418
419                 $item['app'] = $activity['generator'];
420
421                 return $item;
422         }
423
424         /**
425          * Generate a GUID out of an URL
426          *
427          * @param string $url message URL
428          * @return string with GUID
429          */
430         private static function getGUIDByURL(string $url)
431         {
432                 $parsed = parse_url($url);
433
434                 $host_hash = hash('crc32', $parsed['host']);
435
436                 unset($parsed["scheme"]);
437                 unset($parsed["host"]);
438
439                 $path = implode("/", $parsed);
440
441                 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
442         }
443
444         /**
445          * Creates an item post
446          *
447          * @param array $activity Activity data
448          * @param array $item     item array
449          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
450          * @throws \ImagickException
451          */
452         private static function postItem($activity, $item)
453         {
454                 /// @todo What to do with $activity['context']?
455                 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
456                         Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
457                         return;
458                 }
459
460                 $item['network'] = Protocol::ACTIVITYPUB;
461                 $item['author-link'] = $activity['author'];
462                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
463                 $item['owner-link'] = $activity['actor'];
464                 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
465
466                 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
467                         $item['private'] = Item::UNLISTED;
468                 } elseif (in_array(0, $activity['receiver'])) {
469                         $item['private'] = Item::PUBLIC;
470                 } else {
471                         $item['private'] = Item::PRIVATE;
472                 }
473
474                 if (!empty($activity['raw'])) {
475                         $item['source'] = $activity['raw'];
476                         $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
477                         $item['conversation-href'] = $activity['context'] ?? '';
478                         $item['conversation-uri'] = $activity['conversation'] ?? '';
479
480                         if (isset($activity['push'])) {
481                                 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
482                         }
483                 }
484
485                 $isForum = false;
486
487                 if (!empty($activity['thread-completion'])) {
488                         // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
489                         $item['causer-link'] = $item['owner-link'];
490                         $item['causer-id'] = $item['owner-id'];
491
492                         Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
493                         $item['owner-link'] = $item['author-link'];
494                         $item['owner-id'] = $item['author-id'];
495                 } else {
496                         $actor = APContact::getByURL($item['owner-link'], false);
497                         $isForum = ($actor['type'] == 'Group');
498                 }
499
500                 $item['uri'] = $activity['id'];
501
502                 $item['created'] = DateTimeFormat::utc($activity['published']);
503                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
504                 $item['guid'] = $activity['diaspora:guid'] ?: $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
505
506                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
507
508                 $item = self::processContent($activity, $item);
509                 if (empty($item)) {
510                         return;
511                 }
512
513                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
514
515                 $item = self::constructAttachList($activity, $item);
516
517                 $stored = false;
518
519                 foreach ($activity['receiver'] as $receiver) {
520                         if ($receiver == -1) {
521                                 continue;
522                         }
523
524                         $item['uid'] = $receiver;
525
526                         if ($isForum) {
527                                 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
528                         } else {
529                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
530                         }
531
532                         if (($receiver != 0) && empty($item['contact-id'])) {
533                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
534                         }
535
536                         if (!empty($activity['directmessage'])) {
537                                 self::postMail($activity, $item);
538                                 continue;
539                         }
540
541                         if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
542                                 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
543
544                                 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
545                                         $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
546                                 }
547
548                                 if ($skip) {
549                                         Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
550                                         continue;
551                                 }
552
553                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
554                         }
555
556                         if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
557                                 self::createEvent($activity, $item);
558                         }
559
560                         $item_id = Item::insert($item);
561                         if ($item_id) {
562                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
563                         } else {
564                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
565                         }
566
567                         if ($item['uid'] == 0) {
568                                 $stored = $item_id;
569                         }
570                 }
571
572                 // Store send a follow request for every reshare - but only when the item had been stored
573                 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
574                         $author = APContact::getByURL($item['owner-link'], false);
575                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
576                         if ($author['type'] != 'Group') {
577                                 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
578                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
579                         }
580                 }
581         }
582
583         /**
584          * Store tags and mentions into the tag table
585          *
586          * @param integer $uriid
587          * @param array $tags
588          */
589         private static function storeTags(int $uriid, array $tags = null)
590         {
591                 // Make sure to delete all existing tags (can happen when called via the update functionality)
592                 DBA::delete('post-tag', ['uri-id' => $uriid]);
593
594                 foreach ($tags as $tag) {
595                         if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
596                                 continue;
597                         }
598
599                         $hash = substr($tag['name'], 0, 1);
600
601                         if ($tag['type'] == 'Mention') {
602                                 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
603                                         Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
604                                         Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
605                                         $tag['name'] = substr($tag['name'], 1);
606                                 }
607                                 $type = Tag::IMPLICIT_MENTION;
608
609                                 if (!empty($tag['href'])) {
610                                         $apcontact = APContact::getByURL($tag['href']);
611                                         if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
612                                                 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
613                                         }
614                                 }
615                         } elseif ($tag['type'] == 'Hashtag') {
616                                 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
617                                         $tag['name'] = substr($tag['name'], 1);
618                                 }
619                                 $type = Tag::HASHTAG;
620                         }
621
622                         if (empty($tag['name'])) {
623                                 continue;
624                         }
625                         
626                         Tag::store($uriid, $type, $tag['name'], $tag['href']);
627                 }
628         }
629
630         /**
631          * Creates an mail post
632          *
633          * @param array $activity Activity data
634          * @param array $item     item array
635          * @return int|bool New mail table row id or false on error
636          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637          */
638         private static function postMail($activity, $item)
639         {
640                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
641                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
642                         return false;
643                 }
644
645                 Logger::info('Direct Message', $item);
646
647                 $msg = [];
648                 $msg['uid'] = $item['uid'];
649
650                 $msg['contact-id'] = $item['contact-id'];
651
652                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
653                 $msg['from-name'] = $contact['name'];
654                 $msg['from-url'] = $contact['url'];
655                 $msg['from-photo'] = $contact['photo'];
656
657                 $msg['uri'] = $item['uri'];
658                 $msg['created'] = $item['created'];
659
660                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
661                 if (DBA::isResult($parent)) {
662                         $msg['parent-uri'] = $parent['parent-uri'];
663                         $msg['title'] = $parent['title'];
664                 } else {
665                         $msg['parent-uri'] = $item['thr-parent'];
666
667                         if (!empty($item['title'])) {
668                                 $msg['title'] = $item['title'];
669                         } elseif (!empty($item['content-warning'])) {
670                                 $msg['title'] = $item['content-warning'];
671                         } else {
672                                 // Trying to generate a title out of the body
673                                 $title = $item['body'];
674
675                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
676                                         $title = $matches[3];
677                                 }
678
679                                 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
680
681                                 if (strlen($title) > 20) {
682                                         $title = substr($title, 0, 20) . '...';
683                                 }
684
685                                 $msg['title'] = $title;
686                         }
687                 }
688                 $msg['body'] = $item['body'];
689
690                 return Mail::insert($msg);
691         }
692
693         /**
694          * Fetches missing posts
695          *
696          * @param string $url message URL
697          * @param array $child activity array with the child of this message
698          * @return string fetched message URL
699          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
700          */
701         public static function fetchMissingActivity($url, $child = [])
702         {
703                 if (!empty($child['receiver'])) {
704                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
705                 } else {
706                         $uid = 0;
707                 }
708
709                 $object = ActivityPub::fetchContent($url, $uid);
710                 if (empty($object)) {
711                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
712                         return '';
713                 }
714
715                 if (empty($object['id'])) {
716                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
717                         return '';
718                 }
719
720                 if (!empty($child['author'])) {
721                         $actor = $child['author'];
722                 } elseif (!empty($object['actor'])) {
723                         $actor = $object['actor'];
724                 } elseif (!empty($object['attributedTo'])) {
725                         $actor = $object['attributedTo'];
726                 } else {
727                         // Shouldn't happen
728                         $actor = '';
729                 }
730
731                 if (!empty($object['published'])) {
732                         $published = $object['published'];
733                 } elseif (!empty($child['published'])) {
734                         $published = $child['published'];
735                 } else {
736                         $published = DateTimeFormat::utcNow();
737                 }
738
739                 $activity = [];
740                 $activity['@context'] = $object['@context'];
741                 unset($object['@context']);
742                 $activity['id'] = $object['id'];
743                 $activity['to'] = $object['to'] ?? [];
744                 $activity['cc'] = $object['cc'] ?? [];
745                 $activity['actor'] = $actor;
746                 $activity['object'] = $object;
747                 $activity['published'] = $published;
748                 $activity['type'] = 'Create';
749
750                 $ldactivity = JsonLD::compact($activity);
751
752                 $ldactivity['thread-completion'] = true;
753
754                 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity));
755
756                 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
757
758                 return $activity['id'];
759         }
760
761         /**
762          * perform a "follow" request
763          *
764          * @param array $activity
765          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766          * @throws \ImagickException
767          */
768         public static function followUser($activity)
769         {
770                 $uid = User::getIdForURL($activity['object_id']);
771                 if (empty($uid)) {
772                         return;
773                 }
774
775                 $owner = User::getOwnerDataById($uid);
776
777                 $cid = Contact::getIdForURL($activity['actor'], $uid);
778                 if (!empty($cid)) {
779                         self::switchContact($cid);
780                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
781                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
782                 } else {
783                         $contact = [];
784                 }
785
786                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
787                         'author-link' => $activity['actor']];
788
789                 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
790
791                 // Ensure that the contact has got the right network type
792                 self::switchContact($item['author-id']);
793
794                 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
795                 if ($result === true) {
796                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
797                 }
798
799                 $cid = Contact::getIdForURL($activity['actor'], $uid);
800                 if (empty($cid)) {
801                         return;
802                 }
803
804                 if (empty($contact)) {
805                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
806                 }
807
808                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
809         }
810
811         /**
812          * Update the given profile
813          *
814          * @param array $activity
815          * @throws \Exception
816          */
817         public static function updatePerson($activity)
818         {
819                 if (empty($activity['object_id'])) {
820                         return;
821                 }
822
823                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
824                 Contact::updateFromProbeByURL($activity['object_id'], true);
825         }
826
827         /**
828          * Delete the given profile
829          *
830          * @param array $activity
831          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
832          */
833         public static function deletePerson($activity)
834         {
835                 if (empty($activity['object_id']) || empty($activity['actor'])) {
836                         Logger::log('Empty object id or actor.', Logger::DEBUG);
837                         return;
838                 }
839
840                 if ($activity['object_id'] != $activity['actor']) {
841                         Logger::log('Object id does not match actor.', Logger::DEBUG);
842                         return;
843                 }
844
845                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
846                 while ($contact = DBA::fetch($contacts)) {
847                         Contact::remove($contact['id']);
848                 }
849                 DBA::close($contacts);
850
851                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
852         }
853
854         /**
855          * Accept a follow request
856          *
857          * @param array $activity
858          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
859          * @throws \ImagickException
860          */
861         public static function acceptFollowUser($activity)
862         {
863                 $uid = User::getIdForURL($activity['object_actor']);
864                 if (empty($uid)) {
865                         return;
866                 }
867
868                 $cid = Contact::getIdForURL($activity['actor'], $uid);
869                 if (empty($cid)) {
870                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
871                         return;
872                 }
873
874                 self::switchContact($cid);
875
876                 $fields = ['pending' => false];
877
878                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
879                 if ($contact['rel'] == Contact::FOLLOWER) {
880                         $fields['rel'] = Contact::FRIEND;
881                 }
882
883                 $condition = ['id' => $cid];
884                 DBA::update('contact', $fields, $condition);
885                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
886         }
887
888         /**
889          * Reject a follow request
890          *
891          * @param array $activity
892          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893          * @throws \ImagickException
894          */
895         public static function rejectFollowUser($activity)
896         {
897                 $uid = User::getIdForURL($activity['object_actor']);
898                 if (empty($uid)) {
899                         return;
900                 }
901
902                 $cid = Contact::getIdForURL($activity['actor'], $uid);
903                 if (empty($cid)) {
904                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
905                         return;
906                 }
907
908                 self::switchContact($cid);
909
910                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
911                         Contact::remove($cid);
912                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
913                 } else {
914                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
915                 }
916         }
917
918         /**
919          * Undo activity like "like" or "dislike"
920          *
921          * @param array $activity
922          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
923          * @throws \ImagickException
924          */
925         public static function undoActivity($activity)
926         {
927                 if (empty($activity['object_id'])) {
928                         return;
929                 }
930
931                 if (empty($activity['object_actor'])) {
932                         return;
933                 }
934
935                 $author_id = Contact::getIdForURL($activity['object_actor']);
936                 if (empty($author_id)) {
937                         return;
938                 }
939
940                 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
941         }
942
943         /**
944          * Activity to remove a follower
945          *
946          * @param array $activity
947          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948          * @throws \ImagickException
949          */
950         public static function undoFollowUser($activity)
951         {
952                 $uid = User::getIdForURL($activity['object_object']);
953                 if (empty($uid)) {
954                         return;
955                 }
956
957                 $owner = User::getOwnerDataById($uid);
958
959                 $cid = Contact::getIdForURL($activity['actor'], $uid);
960                 if (empty($cid)) {
961                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
962                         return;
963                 }
964
965                 self::switchContact($cid);
966
967                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
968                 if (!DBA::isResult($contact)) {
969                         return;
970                 }
971
972                 Contact::removeFollower($owner, $contact);
973                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
974         }
975
976         /**
977          * Switches a contact to AP if needed
978          *
979          * @param integer $cid Contact ID
980          * @throws \Exception
981          */
982         private static function switchContact($cid)
983         {
984                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
985                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
986                         return;
987                 }
988
989                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
990                 Contact::updateFromProbe($cid);
991         }
992
993         /**
994          * Collects implicit mentions like:
995          * - the author of the parent item
996          * - all the mentioned conversants in the parent item
997          *
998          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
999          * @return array
1000          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1001          */
1002         private static function getImplicitMentionList(array $parent)
1003         {
1004                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1005                         return [];
1006                 }
1007
1008                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
1009
1010                 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
1011
1012                 $implicit_mentions = [];
1013                 if (empty($parent_author)) {
1014                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
1015                 } else {
1016                         $implicit_mentions[] = $parent_author['url'];
1017                         $implicit_mentions[] = $parent_author['nurl'];
1018                         $implicit_mentions[] = $parent_author['alias'];
1019                 }
1020
1021                 if (!empty($parent['alias'])) {
1022                         $implicit_mentions[] = $parent['alias'];
1023                 }
1024
1025                 foreach ($parent_terms as $term) {
1026                         $contact = Contact::getDetailsByURL($term['url'], 0);
1027                         if (!empty($contact)) {
1028                                 $implicit_mentions[] = $contact['url'];
1029                                 $implicit_mentions[] = $contact['nurl'];
1030                                 $implicit_mentions[] = $contact['alias'];
1031                         }
1032                 }
1033
1034                 return $implicit_mentions;
1035         }
1036
1037         /**
1038          * Strips from the body prepended implicit mentions
1039          *
1040          * @param string $body
1041          * @param array $potential_mentions
1042          * @return string
1043          */
1044         private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
1045         {
1046                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1047                         return $body;
1048                 }
1049
1050                 $kept_mentions = [];
1051
1052                 // Extract one prepended mention at a time from the body
1053                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1054                         if (!in_array($matches[2], $potential_mentions)) {
1055                                 $kept_mentions[] = $matches[1];
1056                         }
1057
1058                         $body = $matches[3];
1059                 }
1060
1061                 // Re-appending the kept mentions to the body after extraction
1062                 $kept_mentions[] = $body;
1063
1064                 return implode('', $kept_mentions);
1065         }
1066
1067         private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
1068         {
1069                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1070                         return $activity_tags;
1071                 }
1072
1073                 foreach ($activity_tags as $index => $tag) {
1074                         if (in_array($tag['href'], $potential_mentions)) {
1075                                 $activity_tags[$index]['name'] = preg_replace(
1076                                         '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
1077                                         Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
1078                                         $activity_tags[$index]['name'],
1079                                         1
1080                                 );
1081                         }
1082                 }
1083
1084                 return $activity_tags;
1085         }
1086 }