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