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