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