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