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