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