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