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