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