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