]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Processor.php
Merge pull request #7174 from MrPetovan/task/dba-quote-identifiers
[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                         }
419
420                         if (empty($item['contact-id'])) {
421                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
422                         }
423
424                         if (($receiver != 0) && empty($item['contact-id'])) {
425                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
426                         }
427
428                         if (!empty($activity['directmessage'])) {
429                                 self::postMail($activity, $item);
430                                 continue;
431                         }
432
433                         if (PConfig::get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
434                                 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
435
436                                 if ($skip && (($activity['type'] == 'as:Announce') || $isForum)) {
437                                         $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
438                                 }
439
440                                 if ($skip) {
441                                         Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
442                                         continue;
443                                 }
444
445                                 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
446                         }
447
448                         if ($activity['object_type'] == 'as:Event') {
449                                 self::createEvent($activity, $item);
450                         }
451
452                         $item_id = Item::insert($item);
453                         if ($item_id) {
454                                 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
455                         } else {
456                                 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
457                         }
458
459                         if ($item['uid'] == 0) {
460                                 $stored = $item_id;
461                         }
462                 }
463
464                 // Store send a follow request for every reshare - but only when the item had been stored
465                 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
466                         $author = APContact::getByURL($item['owner-link'], false);
467                         // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
468                         if ($author['type'] != 'Group') {
469                                 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
470                                 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
471                         }
472                 }
473         }
474
475         /**
476          * Creates an mail post
477          *
478          * @param array $activity Activity data
479          * @param array $item     item array
480          * @return int|bool New mail table row id or false on error
481          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
482          */
483         private static function postMail($activity, $item)
484         {
485                 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
486                         Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
487                         return false;
488                 }
489
490                 Logger::info('Direct Message', $item);
491
492                 $msg = [];
493                 $msg['uid'] = $item['uid'];
494
495                 $msg['contact-id'] = $item['contact-id'];
496
497                 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
498                 $msg['from-name'] = $contact['name'];
499                 $msg['from-url'] = $contact['url'];
500                 $msg['from-photo'] = $contact['photo'];
501
502                 $msg['uri'] = $item['uri'];
503                 $msg['created'] = $item['created'];
504
505                 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
506                 if (DBA::isResult($parent)) {
507                         $msg['parent-uri'] = $parent['parent-uri'];
508                         $msg['title'] = $parent['title'];
509                 } else {
510                         $msg['parent-uri'] = $item['thr-parent'];
511
512                         if (!empty($item['title'])) {
513                                 $msg['title'] = $item['title'];
514                         } elseif (!empty($item['content-warning'])) {
515                                 $msg['title'] = $item['content-warning'];
516                         } else {
517                                 // Trying to generate a title out of the body
518                                 $title = $item['body'];
519
520                                 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
521                                         $title = $matches[3];
522                                 }
523
524                                 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
525
526                                 if (strlen($title) > 20) {
527                                         $title = substr($title, 0, 20) . '...';
528                                 }
529
530                                 $msg['title'] = $title;
531                         }
532                 }
533                 $msg['body'] = $item['body'];
534
535                 return Mail::insert($msg);
536         }
537
538         /**
539          * Fetches missing posts
540          *
541          * @param string $url message URL
542          * @param array $child activity array with the child of this message
543          * @return boolean success
544          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
545          */
546         public static function fetchMissingActivity($url, $child = [])
547         {
548                 if (!empty($child['receiver'])) {
549                         $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
550                 } else {
551                         $uid = 0;
552                 }
553
554                 $object = ActivityPub::fetchContent($url, $uid);
555                 if (empty($object)) {
556                         Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
557                         return false;
558                 }
559
560                 if (empty($object['id'])) {
561                         Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
562                         return false;
563                 }
564
565                 if (!empty($child['author'])) {
566                         $actor = $child['author'];
567                 } elseif (!empty($object['actor'])) {
568                         $actor = $object['actor'];
569                 } elseif (!empty($object['attributedTo'])) {
570                         $actor = $object['attributedTo'];
571                 } else {
572                         // Shouldn't happen
573                         $actor = '';
574                 }
575
576                 if (!empty($object['published'])) {
577                         $published = $object['published'];
578                 } elseif (!empty($child['published'])) {
579                         $published = $child['published'];
580                 } else {
581                         $published = DateTimeFormat::utcNow();
582                 }
583
584                 $activity = [];
585                 $activity['@context'] = $object['@context'];
586                 unset($object['@context']);
587                 $activity['id'] = $object['id'];
588                 $activity['to'] = defaults($object, 'to', []);
589                 $activity['cc'] = defaults($object, 'cc', []);
590                 $activity['actor'] = $actor;
591                 $activity['object'] = $object;
592                 $activity['published'] = $published;
593                 $activity['type'] = 'Create';
594
595                 $ldactivity = JsonLD::compact($activity);
596
597                 $ldactivity['thread-completion'] = true;
598
599                 ActivityPub\Receiver::processActivity($ldactivity);
600                 Logger::log('Activity ' . $url . ' had been fetched and processed.');
601
602                 return true;
603         }
604
605         /**
606          * perform a "follow" request
607          *
608          * @param array $activity
609          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
610          * @throws \ImagickException
611          */
612         public static function followUser($activity)
613         {
614                 $uid = User::getIdForURL($activity['object_id']);
615                 if (empty($uid)) {
616                         return;
617                 }
618
619                 $owner = User::getOwnerDataById($uid);
620
621                 $cid = Contact::getIdForURL($activity['actor'], $uid);
622                 if (!empty($cid)) {
623                         self::switchContact($cid);
624                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
625                         $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
626                 } else {
627                         $contact = [];
628                 }
629
630                 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
631                         'author-link' => $activity['actor']];
632
633                 $note = Strings::escapeTags(trim(defaults($activity, 'content', '')));
634
635                 // Ensure that the contact has got the right network type
636                 self::switchContact($item['author-id']);
637
638                 $result = Contact::addRelationship($owner, $contact, $item, false, $note);
639                 if ($result === true) {
640                         ActivityPub\Transmitter::sendContactAccept($item['author-link'], $item['author-id'], $owner['uid']);
641                 }
642
643                 $cid = Contact::getIdForURL($activity['actor'], $uid);
644                 if (empty($cid)) {
645                         return;
646                 }
647
648                 if (empty($contact)) {
649                         DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
650                 }
651
652                 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
653         }
654
655         /**
656          * Update the given profile
657          *
658          * @param array $activity
659          * @throws \Exception
660          */
661         public static function updatePerson($activity)
662         {
663                 if (empty($activity['object_id'])) {
664                         return;
665                 }
666
667                 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
668                 Contact::updateFromProbeByURL($activity['object_id'], true);
669         }
670
671         /**
672          * Delete the given profile
673          *
674          * @param array $activity
675          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
676          */
677         public static function deletePerson($activity)
678         {
679                 if (empty($activity['object_id']) || empty($activity['actor'])) {
680                         Logger::log('Empty object id or actor.', Logger::DEBUG);
681                         return;
682                 }
683
684                 if ($activity['object_id'] != $activity['actor']) {
685                         Logger::log('Object id does not match actor.', Logger::DEBUG);
686                         return;
687                 }
688
689                 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
690                 while ($contact = DBA::fetch($contacts)) {
691                         Contact::remove($contact['id']);
692                 }
693                 DBA::close($contacts);
694
695                 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
696         }
697
698         /**
699          * Accept a follow request
700          *
701          * @param array $activity
702          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
703          * @throws \ImagickException
704          */
705         public static function acceptFollowUser($activity)
706         {
707                 $uid = User::getIdForURL($activity['object_actor']);
708                 if (empty($uid)) {
709                         return;
710                 }
711
712                 $cid = Contact::getIdForURL($activity['actor'], $uid);
713                 if (empty($cid)) {
714                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
715                         return;
716                 }
717
718                 self::switchContact($cid);
719
720                 $fields = ['pending' => false];
721
722                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
723                 if ($contact['rel'] == Contact::FOLLOWER) {
724                         $fields['rel'] = Contact::FRIEND;
725                 }
726
727                 $condition = ['id' => $cid];
728                 DBA::update('contact', $fields, $condition);
729                 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
730         }
731
732         /**
733          * Reject a follow request
734          *
735          * @param array $activity
736          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
737          * @throws \ImagickException
738          */
739         public static function rejectFollowUser($activity)
740         {
741                 $uid = User::getIdForURL($activity['object_actor']);
742                 if (empty($uid)) {
743                         return;
744                 }
745
746                 $cid = Contact::getIdForURL($activity['actor'], $uid);
747                 if (empty($cid)) {
748                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
749                         return;
750                 }
751
752                 self::switchContact($cid);
753
754                 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
755                         Contact::remove($cid);
756                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
757                 } else {
758                         Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
759                 }
760         }
761
762         /**
763          * Undo activity like "like" or "dislike"
764          *
765          * @param array $activity
766          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
767          * @throws \ImagickException
768          */
769         public static function undoActivity($activity)
770         {
771                 if (empty($activity['object_id'])) {
772                         return;
773                 }
774
775                 if (empty($activity['object_actor'])) {
776                         return;
777                 }
778
779                 $author_id = Contact::getIdForURL($activity['object_actor']);
780                 if (empty($author_id)) {
781                         return;
782                 }
783
784                 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
785         }
786
787         /**
788          * Activity to remove a follower
789          *
790          * @param array $activity
791          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
792          * @throws \ImagickException
793          */
794         public static function undoFollowUser($activity)
795         {
796                 $uid = User::getIdForURL($activity['object_object']);
797                 if (empty($uid)) {
798                         return;
799                 }
800
801                 $owner = User::getOwnerDataById($uid);
802
803                 $cid = Contact::getIdForURL($activity['actor'], $uid);
804                 if (empty($cid)) {
805                         Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
806                         return;
807                 }
808
809                 self::switchContact($cid);
810
811                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
812                 if (!DBA::isResult($contact)) {
813                         return;
814                 }
815
816                 Contact::removeFollower($owner, $contact);
817                 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
818         }
819
820         /**
821          * Switches a contact to AP if needed
822          *
823          * @param integer $cid Contact ID
824          * @throws \Exception
825          */
826         private static function switchContact($cid)
827         {
828                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
829                 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
830                         return;
831                 }
832
833                 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
834                 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
835         }
836
837         /**
838          * Collects implicit mentions like:
839          * - the author of the parent item
840          * - all the mentioned conversants in the parent item
841          *
842          * @param array $parent Item array with at least ['id', 'author-link', 'alias']
843          * @return array
844          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
845          */
846         private static function getImplicitMentionList(array $parent)
847         {
848                 if (Config::get('system', 'disable_implicit_mentions')) {
849                         return [];
850                 }
851
852                 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
853
854                 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
855
856                 $implicit_mentions = [];
857                 if (empty($parent_author)) {
858                         Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
859                 } else {
860                         $implicit_mentions[] = $parent_author['url'];
861                         $implicit_mentions[] = $parent_author['nurl'];
862                         $implicit_mentions[] = $parent_author['alias'];
863                 }
864
865                 if (!empty($parent['alias'])) {
866                         $implicit_mentions[] = $parent['alias'];
867                 }
868
869                 foreach ($parent_terms as $term) {
870                         $contact = Contact::getDetailsByURL($term['url'], 0);
871                         if (!empty($contact)) {
872                                 $implicit_mentions[] = $contact['url'];
873                                 $implicit_mentions[] = $contact['nurl'];
874                                 $implicit_mentions[] = $contact['alias'];
875                         }
876                 }
877
878                 return $implicit_mentions;
879         }
880
881         /**
882          * Strips from the body prepended implicit mentions
883          *
884          * @param string $body
885          * @param array $potential_mentions
886          * @return string
887          */
888         private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
889         {
890                 if (Config::get('system', 'disable_implicit_mentions')) {
891                         return $body;
892                 }
893
894                 $kept_mentions = [];
895
896                 // Extract one prepended mention at a time from the body
897                 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
898                         if (!in_array($matches[2], $potential_mentions) ) {
899                                 $kept_mentions[] = $matches[1];
900                         }
901
902                         $body = $matches[3];
903                 }
904
905                 // Re-appending the kept mentions to the body after extraction
906                 $kept_mentions[] = $body;
907
908                 return implode('', $kept_mentions);
909         }
910
911         private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
912         {
913                 if (Config::get('system', 'disable_implicit_mentions')) {
914                         return $activity_tags;
915                 }
916
917                 foreach ($activity_tags as $index => $tag) {
918                         if (in_array($tag['href'], $potential_mentions)) {
919                                 $activity_tags[$index]['name'] = preg_replace(
920                                         '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
921                                         Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
922                                         $activity_tags[$index]['name'],
923                                         1
924                                 );
925                         }
926                 }
927
928                 return $activity_tags;
929         }
930 }