]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Merge pull request #9314 from annando/suggestions
[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                 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
810                 $authorid = Contact::getIdForURL($attributed_to);
811
812                 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value'));
813
814                 $messageTags = [];
815                 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
816                 if (!empty($tags)) {
817                         foreach ($tags as $tag) {
818                                 if ($tag['type'] != 'Hashtag') {
819                                         continue;
820                                 }
821                                 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
822                         }
823                 }
824
825                 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
826         }
827
828         /**
829          * perform a "follow" request
830          *
831          * @param array $activity
832          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833          * @throws \ImagickException
834          */
835         public static function followUser($activity)
836         {
837                 $uid = User::getIdForURL($activity['object_id']);
838                 if (empty($uid)) {
839                         return;
840                 }
841
842                 $owner = User::getOwnerDataById($uid);
843                 if (empty($owner)) {
844                         return;
845                 }
846
847                 $cid = Contact::getIdForURL($activity['actor'], $uid);
848                 if (!empty($cid)) {
849                         self::switchContact($cid);
850                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
851                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
852                 } else {
853                         $contact = [];
854                 }
855
856                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
857                         'author-link' => $activity['actor']];
858
859                 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
860
861                 // Ensure that the contact has got the right network type
862                 self::switchContact($item['author-id']);
863
864                 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
865                 if ($result === true) {
866                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
867                 }
868
869                 $cid = Contact::getIdForURL($activity['actor'], $uid);
870                 if (empty($cid)) {
871                         return;
872                 }
873
874                 if (empty($contact)) {
875                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
876                 }
877
878                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
879         }
880
881         /**
882          * Update the given profile
883          *
884          * @param array $activity
885          * @throws \Exception
886          */
887         public static function updatePerson($activity)
888         {
889                 if (empty($activity['object_id'])) {
890                         return;
891                 }
892
893                 Logger::info('Updating profile', ['object' => $activity['object_id']]);
894                 Contact::updateFromProbeByURL($activity['object_id']);
895         }
896
897         /**
898          * Delete the given profile
899          *
900          * @param array $activity
901          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
902          */
903         public static function deletePerson($activity)
904         {
905                 if (empty($activity['object_id']) || empty($activity['actor'])) {
906                         Logger::info('Empty object id or actor.');
907                         return;
908                 }
909
910                 if ($activity['object_id'] != $activity['actor']) {
911                         Logger::info('Object id does not match actor.');
912                         return;
913                 }
914
915                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
916                 while ($contact = DBA::fetch($contacts)) {
917                         Contact::remove($contact['id']);
918                 }
919                 DBA::close($contacts);
920
921                 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
922         }
923
924         /**
925          * Accept a follow request
926          *
927          * @param array $activity
928          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
929          * @throws \ImagickException
930          */
931         public static function acceptFollowUser($activity)
932         {
933                 $uid = User::getIdForURL($activity['object_actor']);
934                 if (empty($uid)) {
935                         return;
936                 }
937
938                 $cid = Contact::getIdForURL($activity['actor'], $uid);
939                 if (empty($cid)) {
940                         Logger::info('No contact found', ['actor' => $activity['actor']]);
941                         return;
942                 }
943
944                 self::switchContact($cid);
945
946                 $fields = ['pending' => false];
947
948                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
949                 if ($contact['rel'] == Contact::FOLLOWER) {
950                         $fields['rel'] = Contact::FRIEND;
951                 }
952
953                 $condition = ['id' => $cid];
954                 DBA::update('contact', $fields, $condition);
955                 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
956         }
957
958         /**
959          * Reject a follow request
960          *
961          * @param array $activity
962          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
963          * @throws \ImagickException
964          */
965         public static function rejectFollowUser($activity)
966         {
967                 $uid = User::getIdForURL($activity['object_actor']);
968                 if (empty($uid)) {
969                         return;
970                 }
971
972                 $cid = Contact::getIdForURL($activity['actor'], $uid);
973                 if (empty($cid)) {
974                         Logger::info('No contact found', ['actor' => $activity['actor']]);
975                         return;
976                 }
977
978                 self::switchContact($cid);
979
980                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
981                         Contact::remove($cid);
982                         Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
983                 } else {
984                         Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
985                 }
986         }
987
988         /**
989          * Undo activity like "like" or "dislike"
990          *
991          * @param array $activity
992          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993          * @throws \ImagickException
994          */
995         public static function undoActivity($activity)
996         {
997                 if (empty($activity['object_id'])) {
998                         return;
999                 }
1000
1001                 if (empty($activity['object_actor'])) {
1002                         return;
1003                 }
1004
1005                 $author_id = Contact::getIdForURL($activity['object_actor']);
1006                 if (empty($author_id)) {
1007                         return;
1008                 }
1009
1010                 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1011         }
1012
1013         /**
1014          * Activity to remove a follower
1015          *
1016          * @param array $activity
1017          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018          * @throws \ImagickException
1019          */
1020         public static function undoFollowUser($activity)
1021         {
1022                 $uid = User::getIdForURL($activity['object_object']);
1023                 if (empty($uid)) {
1024                         return;
1025                 }
1026
1027                 $owner = User::getOwnerDataById($uid);
1028                 if (empty($owner)) {
1029                         return;
1030                 }
1031
1032                 $cid = Contact::getIdForURL($activity['actor'], $uid);
1033                 if (empty($cid)) {
1034                         Logger::info('No contact found', ['actor' => $activity['actor']]);
1035                         return;
1036                 }
1037
1038                 self::switchContact($cid);
1039
1040                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1041                 if (!DBA::isResult($contact)) {
1042                         return;
1043                 }
1044
1045                 Contact::removeFollower($owner, $contact);
1046                 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1047         }
1048
1049         /**
1050          * Switches a contact to AP if needed
1051          *
1052          * @param integer $cid Contact ID
1053          * @throws \Exception
1054          */
1055         private static function switchContact($cid)
1056         {
1057                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1058                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1059                         return;
1060                 }
1061
1062                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1063                 Contact::updateFromProbe($cid);
1064         }
1065
1066         /**
1067          * Collects implicit mentions like:
1068          * - the author of the parent item
1069          * - all the mentioned conversants in the parent item
1070          *
1071          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1072          * @return array
1073          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1074          */
1075         private static function getImplicitMentionList(array $parent)
1076         {
1077                 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1078
1079                 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1080
1081                 $implicit_mentions = [];
1082                 if (empty($parent_author['url'])) {
1083                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
1084                 } else {
1085                         $implicit_mentions[] = $parent_author['url'];
1086                         $implicit_mentions[] = $parent_author['nurl'];
1087                         $implicit_mentions[] = $parent_author['alias'];
1088                 }
1089
1090                 if (!empty($parent['alias'])) {
1091                         $implicit_mentions[] = $parent['alias'];
1092                 }
1093
1094                 foreach ($parent_terms as $term) {
1095                         $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1096                         if (!empty($contact['url'])) {
1097                                 $implicit_mentions[] = $contact['url'];
1098                                 $implicit_mentions[] = $contact['nurl'];
1099                                 $implicit_mentions[] = $contact['alias'];
1100                         }
1101                 }
1102
1103                 return $implicit_mentions;
1104         }
1105
1106         /**
1107          * Strips from the body prepended implicit mentions
1108          *
1109          * @param string $body
1110          * @param array $parent
1111          * @return string
1112          */
1113         private static function removeImplicitMentionsFromBody(string $body, array $parent)
1114         {
1115                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1116                         return $body;
1117                 }
1118
1119                 $potential_mentions = self::getImplicitMentionList($parent);
1120
1121                 $kept_mentions = [];
1122
1123                 // Extract one prepended mention at a time from the body
1124                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1125                         if (!in_array($matches[2], $potential_mentions)) {
1126                                 $kept_mentions[] = $matches[1];
1127                         }
1128
1129                         $body = $matches[3];
1130                 }
1131
1132                 // Re-appending the kept mentions to the body after extraction
1133                 $kept_mentions[] = $body;
1134
1135                 return implode('', $kept_mentions);
1136         }
1137 }