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