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