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