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