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