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