]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Store the conversation data as well
[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                 if (!empty($activity['raw']) && isset($activity['protocol'])) {
452                         $item['source'] = $activity['raw'];
453                         $item['protocol'] = $activity['protocol'];
454                         $item['conversation-href'] = $activity['context'] ?? '';
455                         $item['conversation-uri'] = $activity['conversation'] ?? '';
456                 }
457
458                 $isForum = false;
459
460                 if (!empty($activity['thread-completion'])) {
461                         // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
462                         $item['causer-link'] = $item['owner-link'];
463                         $item['causer-id'] = $item['owner-id'];
464
465                         Logger::info('Ignoring actor because of thread completion.', ['actor' => $item['owner-link']]);
466                         $item['owner-link'] = $item['author-link'];
467                         $item['owner-id'] = $item['author-id'];
468                 } else {
469                         $actor = APContact::getByURL($item['owner-link'], false);
470                         $isForum = ($actor['type'] == 'Group');
471                 }
472
473                 $item['uri'] = $activity['id'];
474
475                 $item['created'] = DateTimeFormat::utc($activity['published']);
476                 $item['edited'] = DateTimeFormat::utc($activity['updated']);
477                 $item['guid'] = $activity['diaspora:guid'] ?: self::getGUIDByURL($item['uri']);
478
479                 $item = self::processContent($activity, $item);
480                 if (empty($item)) {
481                         return;
482                 }
483
484                 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
485
486                 $item = self::constructAttachList($activity, $item);
487
488                 $stored = false;
489
490                 foreach ($activity['receiver'] as $receiver) {
491                         $item['uid'] = $receiver;
492
493                         if ($isForum) {
494                                 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver, true);
495                         } else {
496                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
497                         }
498
499                         if (($receiver != 0) && empty($item['contact-id'])) {
500                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
501                         }
502
503                         if (!empty($activity['directmessage'])) {
504                                 self::postMail($activity, $item);
505                                 continue;
506                         }
507
508                         if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
509                                 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
510
511                                 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
512                                         $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
513                                 }
514
515                                 if ($skip) {
516                                         Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
517                                         continue;
518                                 }
519
520                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
521                         }
522
523                         if ($activity['object_type'] == 'as:Event') {
524                                 self::createEvent($activity, $item);
525                         }
526
527                         $item_id = Item::insert($item);
528                         if ($item_id) {
529                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
530                         } else {
531                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
532                         }
533
534                         if ($item['uid'] == 0) {
535                                 $stored = $item_id;
536                         }
537                 }
538
539                 // Store send a follow request for every reshare - but only when the item had been stored
540                 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
541                         $author = APContact::getByURL($item['owner-link'], false);
542                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
543                         if ($author['type'] != 'Group') {
544                                 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
545                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
546                         }
547                 }
548         }
549
550         /**
551          * Creates an mail post
552          *
553          * @param array $activity Activity data
554          * @param array $item     item array
555          * @return int|bool New mail table row id or false on error
556          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
557          */
558         private static function postMail($activity, $item)
559         {
560                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
561                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
562                         return false;
563                 }
564
565                 Logger::info('Direct Message', $item);
566
567                 $msg = [];
568                 $msg['uid'] = $item['uid'];
569
570                 $msg['contact-id'] = $item['contact-id'];
571
572                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
573                 $msg['from-name'] = $contact['name'];
574                 $msg['from-url'] = $contact['url'];
575                 $msg['from-photo'] = $contact['photo'];
576
577                 $msg['uri'] = $item['uri'];
578                 $msg['created'] = $item['created'];
579
580                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
581                 if (DBA::isResult($parent)) {
582                         $msg['parent-uri'] = $parent['parent-uri'];
583                         $msg['title'] = $parent['title'];
584                 } else {
585                         $msg['parent-uri'] = $item['thr-parent'];
586
587                         if (!empty($item['title'])) {
588                                 $msg['title'] = $item['title'];
589                         } elseif (!empty($item['content-warning'])) {
590                                 $msg['title'] = $item['content-warning'];
591                         } else {
592                                 // Trying to generate a title out of the body
593                                 $title = $item['body'];
594
595                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
596                                         $title = $matches[3];
597                                 }
598
599                                 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
600
601                                 if (strlen($title) > 20) {
602                                         $title = substr($title, 0, 20) . '...';
603                                 }
604
605                                 $msg['title'] = $title;
606                         }
607                 }
608                 $msg['body'] = $item['body'];
609
610                 return Mail::insert($msg);
611         }
612
613         /**
614          * Fetches missing posts
615          *
616          * @param string $url message URL
617          * @param array $child activity array with the child of this message
618          * @return string fetched message URL
619          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
620          */
621         public static function fetchMissingActivity($url, $child = [])
622         {
623                 if (!empty($child['receiver'])) {
624                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
625                 } else {
626                         $uid = 0;
627                 }
628
629                 $object = ActivityPub::fetchContent($url, $uid);
630                 if (empty($object)) {
631                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
632                         return '';
633                 }
634
635                 if (empty($object['id'])) {
636                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
637                         return '';
638                 }
639
640                 if (!empty($child['author'])) {
641                         $actor = $child['author'];
642                 } elseif (!empty($object['actor'])) {
643                         $actor = $object['actor'];
644                 } elseif (!empty($object['attributedTo'])) {
645                         $actor = $object['attributedTo'];
646                 } else {
647                         // Shouldn't happen
648                         $actor = '';
649                 }
650
651                 if (!empty($object['published'])) {
652                         $published = $object['published'];
653                 } elseif (!empty($child['published'])) {
654                         $published = $child['published'];
655                 } else {
656                         $published = DateTimeFormat::utcNow();
657                 }
658
659                 $activity = [];
660                 $activity['@context'] = $object['@context'];
661                 unset($object['@context']);
662                 $activity['id'] = $object['id'];
663                 $activity['to'] = $object['to'] ?? [];
664                 $activity['cc'] = $object['cc'] ?? [];
665                 $activity['actor'] = $actor;
666                 $activity['object'] = $object;
667                 $activity['published'] = $published;
668                 $activity['type'] = 'Create';
669
670                 $ldactivity = JsonLD::compact($activity);
671
672                 $ldactivity['thread-completion'] = true;
673
674                 ActivityPub\Receiver::processActivity($ldactivity);
675                 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
676
677                 return $activity['id'];
678         }
679
680         /**
681          * perform a "follow" request
682          *
683          * @param array $activity
684          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
685          * @throws \ImagickException
686          */
687         public static function followUser($activity)
688         {
689                 $uid = User::getIdForURL($activity['object_id']);
690                 if (empty($uid)) {
691                         return;
692                 }
693
694                 $owner = User::getOwnerDataById($uid);
695
696                 $cid = Contact::getIdForURL($activity['actor'], $uid);
697                 if (!empty($cid)) {
698                         self::switchContact($cid);
699                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
700                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
701                 } else {
702                         $contact = [];
703                 }
704
705                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
706                         'author-link' => $activity['actor']];
707
708                 $note = Strings::escapeTags(trim($activity['content'] ?? ''));
709
710                 // Ensure that the contact has got the right network type
711                 self::switchContact($item['author-id']);
712
713                 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
714                 if ($result === true) {
715                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
716                 }
717
718                 $cid = Contact::getIdForURL($activity['actor'], $uid);
719                 if (empty($cid)) {
720                         return;
721                 }
722
723                 if (empty($contact)) {
724                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
725                 }
726
727                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
728         }
729
730         /**
731          * Update the given profile
732          *
733          * @param array $activity
734          * @throws \Exception
735          */
736         public static function updatePerson($activity)
737         {
738                 if (empty($activity['object_id'])) {
739                         return;
740                 }
741
742                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
743                 Contact::updateFromProbeByURL($activity['object_id'], true);
744         }
745
746         /**
747          * Delete the given profile
748          *
749          * @param array $activity
750          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
751          */
752         public static function deletePerson($activity)
753         {
754                 if (empty($activity['object_id']) || empty($activity['actor'])) {
755                         Logger::log('Empty object id or actor.', Logger::DEBUG);
756                         return;
757                 }
758
759                 if ($activity['object_id'] != $activity['actor']) {
760                         Logger::log('Object id does not match actor.', Logger::DEBUG);
761                         return;
762                 }
763
764                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
765                 while ($contact = DBA::fetch($contacts)) {
766                         Contact::remove($contact['id']);
767                 }
768                 DBA::close($contacts);
769
770                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
771         }
772
773         /**
774          * Accept a follow request
775          *
776          * @param array $activity
777          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
778          * @throws \ImagickException
779          */
780         public static function acceptFollowUser($activity)
781         {
782                 $uid = User::getIdForURL($activity['object_actor']);
783                 if (empty($uid)) {
784                         return;
785                 }
786
787                 $cid = Contact::getIdForURL($activity['actor'], $uid);
788                 if (empty($cid)) {
789                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
790                         return;
791                 }
792
793                 self::switchContact($cid);
794
795                 $fields = ['pending' => false];
796
797                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
798                 if ($contact['rel'] == Contact::FOLLOWER) {
799                         $fields['rel'] = Contact::FRIEND;
800                 }
801
802                 $condition = ['id' => $cid];
803                 DBA::update('contact', $fields, $condition);
804                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
805         }
806
807         /**
808          * Reject a follow request
809          *
810          * @param array $activity
811          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812          * @throws \ImagickException
813          */
814         public static function rejectFollowUser($activity)
815         {
816                 $uid = User::getIdForURL($activity['object_actor']);
817                 if (empty($uid)) {
818                         return;
819                 }
820
821                 $cid = Contact::getIdForURL($activity['actor'], $uid);
822                 if (empty($cid)) {
823                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
824                         return;
825                 }
826
827                 self::switchContact($cid);
828
829                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
830                         Contact::remove($cid);
831                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
832                 } else {
833                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
834                 }
835         }
836
837         /**
838          * Undo activity like "like" or "dislike"
839          *
840          * @param array $activity
841          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
842          * @throws \ImagickException
843          */
844         public static function undoActivity($activity)
845         {
846                 if (empty($activity['object_id'])) {
847                         return;
848                 }
849
850                 if (empty($activity['object_actor'])) {
851                         return;
852                 }
853
854                 $author_id = Contact::getIdForURL($activity['object_actor']);
855                 if (empty($author_id)) {
856                         return;
857                 }
858
859                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
860         }
861
862         /**
863          * Activity to remove a follower
864          *
865          * @param array $activity
866          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
867          * @throws \ImagickException
868          */
869         public static function undoFollowUser($activity)
870         {
871                 $uid = User::getIdForURL($activity['object_object']);
872                 if (empty($uid)) {
873                         return;
874                 }
875
876                 $owner = User::getOwnerDataById($uid);
877
878                 $cid = Contact::getIdForURL($activity['actor'], $uid);
879                 if (empty($cid)) {
880                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
881                         return;
882                 }
883
884                 self::switchContact($cid);
885
886                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
887                 if (!DBA::isResult($contact)) {
888                         return;
889                 }
890
891                 Contact::removeFollower($owner, $contact);
892                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
893         }
894
895         /**
896          * Switches a contact to AP if needed
897          *
898          * @param integer $cid Contact ID
899          * @throws \Exception
900          */
901         private static function switchContact($cid)
902         {
903                 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
904                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
905                         return;
906                 }
907
908                 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
909                 Contact::updateFromProbe($cid);
910         }
911
912         /**
913          * Collects implicit mentions like:
914          * - the author of the parent item
915          * - all the mentioned conversants in the parent item
916          *
917          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
918          * @return array
919          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
920          */
921         private static function getImplicitMentionList(array $parent)
922         {
923                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
924                         return [];
925                 }
926
927                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
928
929                 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
930
931                 $implicit_mentions = [];
932                 if (empty($parent_author)) {
933                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
934                 } else {
935                         $implicit_mentions[] = $parent_author['url'];
936                         $implicit_mentions[] = $parent_author['nurl'];
937                         $implicit_mentions[] = $parent_author['alias'];
938                 }
939
940                 if (!empty($parent['alias'])) {
941                         $implicit_mentions[] = $parent['alias'];
942                 }
943
944                 foreach ($parent_terms as $term) {
945                         $contact = Contact::getDetailsByURL($term['url'], 0);
946                         if (!empty($contact)) {
947                                 $implicit_mentions[] = $contact['url'];
948                                 $implicit_mentions[] = $contact['nurl'];
949                                 $implicit_mentions[] = $contact['alias'];
950                         }
951                 }
952
953                 return $implicit_mentions;
954         }
955
956         /**
957          * Strips from the body prepended implicit mentions
958          *
959          * @param string $body
960          * @param array $potential_mentions
961          * @return string
962          */
963         private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
964         {
965                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
966                         return $body;
967                 }
968
969                 $kept_mentions = [];
970
971                 // Extract one prepended mention at a time from the body
972                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
973                         if (!in_array($matches[2], $potential_mentions)) {
974                                 $kept_mentions[] = $matches[1];
975                         }
976
977                         $body = $matches[3];
978                 }
979
980                 // Re-appending the kept mentions to the body after extraction
981                 $kept_mentions[] = $body;
982
983                 return implode('', $kept_mentions);
984         }
985
986         private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
987         {
988                 if (DI::config()->get('system', 'disable_implicit_mentions')) {
989                         return $activity_tags;
990                 }
991
992                 foreach ($activity_tags as $index => $tag) {
993                         if (in_array($tag['href'], $potential_mentions)) {
994                                 $activity_tags[$index]['name'] = preg_replace(
995                                         '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
996                                         Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
997                                         $activity_tags[$index]['name'],
998                                         1
999                                 );
1000                         }
1001                 }
1002
1003                 return $activity_tags;
1004         }
1005 }