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