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