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