]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Merge pull request #8909 from MrPetovan/task/ex_auth
[friendica.git] / src / Protocol / ActivityPub / Transmitter.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\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Profile;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Images;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\XML;
52
53 require_once 'include/api.php';
54 require_once 'mod/share.php';
55
56 /**
57  * ActivityPub Transmitter Protocol class
58  *
59  * To-Do:
60  * @todo Undo Announce
61  */
62 class Transmitter
63 {
64         /**
65          * Collects a list of contacts of the given owner
66          *
67          * @param array     $owner  Owner array
68          * @param int|array $rel    The relevant value(s) contact.rel should match
69          * @param string    $module The name of the relevant AP endpoint module (followers|following)
70          * @param integer   $page   Page number
71          *
72          * @return array of owners
73          * @throws \Exception
74          */
75         public static function getContacts($owner, $rel, $module, $page = null)
76         {
77                 $parameters = [
78                         'rel' => $rel,
79                         'uid' => $owner['uid'],
80                         'self' => false,
81                         'deleted' => false,
82                         'hidden' => false,
83                         'archive' => false,
84                         'pending' => false
85                 ];
86                 $condition = DBA::buildCondition($parameters);
87
88                 $sql = "SELECT COUNT(*) as `count`
89                         FROM `contact`
90                         JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
91                         " . $condition;
92
93                 $contacts = DBA::fetchFirst($sql, ...$parameters);
94
95                 $modulePath = '/' . $module . '/';
96
97                 $data = ['@context' => ActivityPub::CONTEXT];
98                 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
99                 $data['type'] = 'OrderedCollection';
100                 $data['totalItems'] = $contacts['count'];
101
102                 // When we hide our friends we will only show the pure number but don't allow more.
103                 $profile = Profile::getByUID($owner['uid']);
104                 if (!empty($profile['hide-friends'])) {
105                         return $data;
106                 }
107
108                 if (empty($page)) {
109                         $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
110                 } else {
111                         $data['type'] = 'OrderedCollectionPage';
112                         $list = [];
113
114                         $sql = "SELECT `contact`.`url`
115                                 FROM `contact`
116                                 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
117                                 " . $condition . "
118                                 LIMIT ?, ?";
119
120                         $parameters[] = ($page - 1) * 100;
121                         $parameters[] = 100;
122
123                         $contacts = DBA::p($sql, ...$parameters);
124                         while ($contact = DBA::fetch($contacts)) {
125                                 $list[] = $contact['url'];
126                         }
127                         DBA::close($contacts);
128
129                         if (!empty($list)) {
130                                 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
131                         }
132
133                         $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
134
135                         $data['orderedItems'] = $list;
136                 }
137
138                 return $data;
139         }
140
141         /**
142          * Public posts for the given owner
143          *
144          * @param array   $owner Owner array
145          * @param integer $page  Page numbe
146          *
147          * @return array of posts
148          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
149          * @throws \ImagickException
150          */
151         public static function getOutbox($owner, $page = null)
152         {
153                 $public_contact = Contact::getIdForURL($owner['url']);
154
155                 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
156                         'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
157                         'deleted' => false, 'visible' => true, 'moderated' => false];
158                 $count = DBA::count('item', $condition);
159
160                 $data = ['@context' => ActivityPub::CONTEXT];
161                 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
162                 $data['type'] = 'OrderedCollection';
163                 $data['totalItems'] = $count;
164
165                 if (empty($page)) {
166                         $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
167                 } else {
168                         $data['type'] = 'OrderedCollectionPage';
169                         $list = [];
170
171                         $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
172
173                         $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
174                         while ($item = Item::fetch($items)) {
175                                 $activity = self::createActivityFromItem($item['id'], true);
176                                 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
177
178                                 // Only list "Create" activity objects here, no reshares
179                                 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
180                                         $list[] = $activity['object'];
181                                 }
182                         }
183
184                         if (!empty($list)) {
185                                 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
186                         }
187
188                         $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
189
190                         $data['orderedItems'] = $list;
191                 }
192
193                 return $data;
194         }
195
196         /**
197          * Return the service array containing information the used software and it's url
198          *
199          * @return array with service data
200          */
201         private static function getService()
202         {
203                 return ['type' => 'Service',
204                         'name' =>  FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
205                         'url' => DI::baseUrl()->get()];
206         }
207
208         /**
209          * Return the ActivityPub profile of the given user
210          *
211          * @param integer $uid User ID
212          * @return array with profile data
213          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
214          */
215         public static function getProfile($uid)
216         {
217                 if ($uid != 0) {
218                         $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
219                                 'account_removed' => false, 'verified' => true];
220                         $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
221                         $user = DBA::selectFirst('user', $fields, $condition);
222                         if (!DBA::isResult($user)) {
223                                 return [];
224                         }
225
226                         $fields = ['locality', 'region', 'country-name'];
227                         $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
228                         if (!DBA::isResult($profile)) {
229                                 return [];
230                         }
231
232                         $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
233                         $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
234                         if (!DBA::isResult($contact)) {
235                                 return [];
236                         }
237                 } else {
238                         $contact = User::getSystemAccount();
239                         $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
240                                 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
241                         $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
242                 }
243
244                 $data = ['@context' => ActivityPub::CONTEXT];
245                 $data['id'] = $contact['url'];
246
247                 if (!empty($user['guid'])) {
248                         $data['diaspora:guid'] = $user['guid'];
249                 }
250
251                 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
252                 
253                 if ($uid != 0) {
254                         $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
255                         $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
256                         $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
257                         $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
258                 } else {
259                         $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
260                 }
261
262                 $data['preferredUsername'] = $user['nickname'];
263                 $data['name'] = $contact['name'];
264
265                 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
266                         $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
267                                 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
268                 }
269
270                 if (!empty($contact['about'])) {
271                         $data['summary'] = BBCode::convert($contact['about'], false);
272                 }
273
274                 $data['url'] = $contact['url'];
275                 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
276                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
277                         'owner' => $contact['url'],
278                         'publicKeyPem' => $user['pubkey']];
279                 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
280                 $data['icon'] = ['type' => 'Image',
281                         'url' => $contact['photo']];
282
283                 $data['generator'] = self::getService();
284
285                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
286                 return $data;
287         }
288
289         /**
290          * @param string $username
291          * @return array
292          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
293          */
294         public static function getDeletedUser($username)
295         {
296                 return [
297                         '@context' => ActivityPub::CONTEXT,
298                         'id' => DI::baseUrl() . '/profile/' . $username,
299                         'type' => 'Tombstone',
300                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
301                         'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
302                         'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
303                 ];
304         }
305
306         /**
307          * Returns an array with permissions of a given item array
308          *
309          * @param array $item
310          *
311          * @return array with permissions
312          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
313          * @throws \ImagickException
314          */
315         private static function fetchPermissionBlockFromConversation($item)
316         {
317                 if (empty($item['thr-parent'])) {
318                         return [];
319                 }
320
321                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
322                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
323                 if (!DBA::isResult($conversation)) {
324                         return [];
325                 }
326
327                 $activity = json_decode($conversation['source'], true);
328
329                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
330                 $profile = APContact::getByURL($actor);
331
332                 $item_profile = APContact::getByURL($item['author-link']);
333                 $exclude[] = $item['author-link'];
334
335                 if ($item['gravity'] == GRAVITY_PARENT) {
336                         $exclude[] = $item['owner-link'];
337                 }
338
339                 $permissions['to'][] = $actor;
340
341                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
342                         if (empty($activity[$element])) {
343                                 continue;
344                         }
345                         if (is_string($activity[$element])) {
346                                 $activity[$element] = [$activity[$element]];
347                         }
348
349                         foreach ($activity[$element] as $receiver) {
350                                 if (empty($receiver)) {
351                                         continue;
352                                 }
353
354                                 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
355                                         $permissions[$element][] = $item_profile['followers'];
356                                 } elseif (!in_array($receiver, $exclude)) {
357                                         $permissions[$element][] = $receiver;
358                                 }
359                         }
360                 }
361                 return $permissions;
362         }
363
364         /**
365          * Creates an array of permissions from an item thread
366          *
367          * @param array   $item       Item array
368          * @param boolean $blindcopy  addressing via "bcc" or "cc"?
369          * @param integer $last_id    Last item id for adding receivers
370          * @param boolean $forum_mode "true" means that we are sending content to a forum
371          *
372          * @return array with permission data
373          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
374          * @throws \ImagickException
375          */
376         private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
377         {
378                 if ($last_id == 0) {
379                         $last_id = $item['id'];
380                 }
381
382                 $always_bcc = false;
383                 $isforum = false;
384
385                 // Check if we should always deliver our stuff via BCC
386                 if (!empty($item['uid'])) {
387                         $profile = User::getOwnerDataById($item['uid']);
388                         if (!empty($profile)) {
389                                 $always_bcc = $profile['hide-friends'];
390                                 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
391                         }
392                 }
393
394                 if (DI::config()->get('system', 'ap_always_bcc')) {
395                         $always_bcc = true;
396                 }
397
398                 if ((self::isAnnounce($item) && !$isforum) || DI::config()->get('debug', 'total_ap_delivery')) {
399                         // Will be activated in a later step
400                         $networks = Protocol::FEDERATED;
401                 } else {
402                         // For now only send to these contacts:
403                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
404                 }
405
406                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
407
408                 if ($item['gravity'] == GRAVITY_PARENT) {
409                         $actor_profile = APContact::getByURL($item['owner-link']);
410                 } else {
411                         $actor_profile = APContact::getByURL($item['author-link']);
412                 }
413
414                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
415
416                 if ($item['private'] != Item::PRIVATE) {
417                         // Directly mention the original author upon a quoted reshare.
418                         // Else just ensure that the original author receives the reshare.
419                         $announce = self::getAnnounceArray($item);
420                         if (!empty($announce['comment'])) {
421                                 $data['to'][] = $announce['actor']['url'];
422                         } elseif (!empty($announce)) {
423                                 $data['cc'][] = $announce['actor']['url'];
424                         }
425
426                         $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
427
428                         // Check if the item is completely public or unlisted
429                         if ($item['private'] == Item::PUBLIC) {
430                                 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
431                         } else {
432                                 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
433                         }
434
435                         foreach ($terms as $term) {
436                                 $profile = APContact::getByURL($term['url'], false);
437                                 if (!empty($profile)) {
438                                         $data['to'][] = $profile['url'];
439                                 }
440                         }
441                 } else {
442                         $receiver_list = Item::enumeratePermissions($item, true);
443
444                         foreach ($terms as $term) {
445                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
446                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
447                                         $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
448                                         if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
449                                                 continue;
450                                         }
451
452                                         if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
453                                                 continue;
454                                         }
455
456                                         if (!empty($profile = APContact::getByURL($contact['url'], false))) {
457                                                 $data['to'][] = $profile['url'];
458                                         }
459                                 }
460                         }
461
462                         foreach ($receiver_list as $receiver) {
463                                 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
464                                 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
465                                         continue;
466                                 }
467
468                                 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
469                                         continue;
470                                 }
471
472                                 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
473                                         if ($contact['hidden'] || $always_bcc) {
474                                                 $data['bcc'][] = $profile['url'];
475                                         } else {
476                                                 $data['cc'][] = $profile['url'];
477                                         }
478                                 }
479                         }
480                 }
481
482                 if (!empty($item['parent'])) {
483                         $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
484                         while ($parent = Item::fetch($parents)) {
485                                 if ($parent['gravity'] == GRAVITY_PARENT) {
486                                         $profile = APContact::getByURL($parent['owner-link'], false);
487                                         if (!empty($profile)) {
488                                                 if ($item['gravity'] != GRAVITY_PARENT) {
489                                                         // Comments to forums are directed to the forum
490                                                         // But comments to forums aren't directed to the followers collection
491                                                         // This rule is only valid when the actor isn't the forum.
492                                                         // The forum needs to transmit their content to their followers.
493                                                         if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
494                                                                 $data['to'][] = $profile['url'];
495                                                         } else {
496                                                                 $data['cc'][] = $profile['url'];
497                                                                 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
498                                                                         $data['cc'][] = $actor_profile['followers'];
499                                                                 }
500                                                         }
501                                                 } else {
502                                                         // Public thread parent post always are directed to the followers
503                                                         if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
504                                                                 $data['cc'][] = $actor_profile['followers'];
505                                                         }
506                                                 }
507                                         }
508                                 }
509
510                                 // Don't include data from future posts
511                                 if ($parent['id'] >= $last_id) {
512                                         continue;
513                                 }
514
515                                 $profile = APContact::getByURL($parent['author-link'], false);
516                                 if (!empty($profile)) {
517                                         if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
518                                                 $data['to'][] = $profile['url'];
519                                         } else {
520                                                 $data['cc'][] = $profile['url'];
521                                         }
522                                 }
523                         }
524                         DBA::close($parents);
525                 }
526
527                 $data['to'] = array_unique($data['to']);
528                 $data['cc'] = array_unique($data['cc']);
529                 $data['bcc'] = array_unique($data['bcc']);
530
531                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
532                         unset($data['to'][$key]);
533                 }
534
535                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
536                         unset($data['cc'][$key]);
537                 }
538
539                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
540                         unset($data['bcc'][$key]);
541                 }
542
543                 foreach ($data['to'] as $to) {
544                         if (($key = array_search($to, $data['cc'])) !== false) {
545                                 unset($data['cc'][$key]);
546                         }
547
548                         if (($key = array_search($to, $data['bcc'])) !== false) {
549                                 unset($data['bcc'][$key]);
550                         }
551                 }
552
553                 foreach ($data['cc'] as $cc) {
554                         if (($key = array_search($cc, $data['bcc'])) !== false) {
555                                 unset($data['bcc'][$key]);
556                         }
557                 }
558
559                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
560
561                 if (!$blindcopy) {
562                         unset($receivers['bcc']);
563                 }
564
565                 return $receivers;
566         }
567
568         /**
569          * Check if an inbox is archived
570          *
571          * @param string $url Inbox url
572          *
573          * @return boolean "true" if inbox is archived
574          */
575         private static function archivedInbox($url)
576         {
577                 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
578         }
579
580         /**
581          * Fetches a list of inboxes of followers of a given user
582          *
583          * @param integer $uid      User ID
584          * @param boolean $personal fetch personal inboxes
585          *
586          * @return array of follower inboxes
587          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
588          * @throws \ImagickException
589          */
590         public static function fetchTargetInboxesforUser($uid, $personal = false)
591         {
592                 $inboxes = [];
593
594                 $isforum = false;
595
596                 if (!empty($item['uid'])) {
597                         $profile = User::getOwnerDataById($item['uid']);
598                         if (!empty($profile)) {
599                                 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
600                         }
601                 }
602
603                 if (DI::config()->get('debug', 'total_ap_delivery')) {
604                         // Will be activated in a later step
605                         $networks = Protocol::FEDERATED;
606                 } else {
607                         // For now only send to these contacts:
608                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
609                 }
610
611                 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
612
613                 if (!empty($uid)) {
614                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
615                 }
616
617                 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
618                 while ($contact = DBA::fetch($contacts)) {
619                         if (Contact::isLocal($contact['url'])) {
620                                 continue;
621                         }
622
623                         if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
624                                 continue;
625                         }
626
627                         if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
628                                 continue;
629                         }
630
631                         if (Network::isUrlBlocked($contact['url'])) {
632                                 continue;
633                         }
634
635                         $profile = APContact::getByURL($contact['url'], false);
636                         if (!empty($profile)) {
637                                 if (empty($profile['sharedinbox']) || $personal) {
638                                         $target = $profile['inbox'];
639                                 } else {
640                                         $target = $profile['sharedinbox'];
641                                 }
642                                 if (!self::archivedInbox($target)) {
643                                         $inboxes[$target] = $target;
644                                 }
645                         }
646                 }
647                 DBA::close($contacts);
648
649                 return $inboxes;
650         }
651
652         /**
653          * Fetches an array of inboxes for the given item and user
654          *
655          * @param array   $item       Item array
656          * @param integer $uid        User ID
657          * @param boolean $personal   fetch personal inboxes
658          * @param integer $last_id    Last item id for adding receivers
659          * @param boolean $forum_mode "true" means that we are sending content to a forum
660          * @return array with inboxes
661          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662          * @throws \ImagickException
663          */
664         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
665         {
666                 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
667                 if (empty($permissions)) {
668                         return [];
669                 }
670
671                 $inboxes = [];
672
673                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
674                         $item_profile = APContact::getByURL($item['author-link'], false);
675                 } else {
676                         $item_profile = APContact::getByURL($item['owner-link'], false);
677                 }
678
679                 if (empty($item_profile)) {
680                         return [];
681                 }
682
683                 $profile_uid = User::getIdForURL($item_profile['url']);
684
685                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
686                         if (empty($permissions[$element])) {
687                                 continue;
688                         }
689
690                         $blindcopy = in_array($element, ['bto', 'bcc']);
691
692                         foreach ($permissions[$element] as $receiver) {
693                                 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
694                                         continue;
695                                 }
696
697                                 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
698                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
699                                 } else {
700                                         if (Contact::isLocal($receiver)) {
701                                                 continue;
702                                         }
703
704                                         $profile = APContact::getByURL($receiver, false);
705                                         if (!empty($profile)) {
706                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
707                                                         $target = $profile['inbox'];
708                                                 } else {
709                                                         $target = $profile['sharedinbox'];
710                                                 }
711                                                 if (!self::archivedInbox($target)) {
712                                                         $inboxes[$target] = $target;
713                                                 }
714                                         }
715                                 }
716                         }
717                 }
718
719                 return $inboxes;
720         }
721
722         /**
723          * Creates an array in the structure of the item table for a given mail id
724          *
725          * @param integer $mail_id
726          *
727          * @return array
728          * @throws \Exception
729          */
730         public static function ItemArrayFromMail($mail_id)
731         {
732                 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
733                 if (!DBA::isResult($mail)) {
734                         return [];
735                 }
736
737                 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
738
739                 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
740
741                 // Making the post more compatible for Mastodon by:
742                 // - Making it a note and not an article (no title)
743                 // - Moving the title into the "summary" field that is used as a "content warning"
744                 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
745                 $mail['title'] = '';
746
747                 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
748                 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
749                 $mail['allow_gid'] = '';
750                 $mail['deny_cid'] = '';
751                 $mail['deny_gid'] = '';
752                 $mail['private'] = true;
753                 $mail['deleted'] = false;
754                 $mail['edited'] = $mail['created'];
755                 $mail['plink'] = $mail['uri'];
756                 $mail['thr-parent'] = $reply['uri'];
757                 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
758
759                 $mail['event-type'] = '';
760                 $mail['attach'] = '';
761
762                 $mail['parent'] = 0;
763
764                 return $mail;
765         }
766
767         /**
768          * Creates an activity array for a given mail id
769          *
770          * @param integer $mail_id
771          * @param boolean $object_mode Is the activity item is used inside another object?
772          *
773          * @return array of activity
774          * @throws \Exception
775          */
776         public static function createActivityFromMail($mail_id, $object_mode = false)
777         {
778                 $mail = self::ItemArrayFromMail($mail_id);
779                 $object = self::createNote($mail);
780
781                 if (!$object_mode) {
782                         $data = ['@context' => ActivityPub::CONTEXT];
783                 } else {
784                         $data = [];
785                 }
786
787                 $data['id'] = $mail['uri'] . '/Create';
788                 $data['type'] = 'Create';
789                 $data['actor'] = $mail['author-link'];
790                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
791                 $data['instrument'] = self::getService();
792                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
793
794                 if (empty($data['to']) && !empty($data['cc'])) {
795                         $data['to'] = $data['cc'];
796                 }
797
798                 if (empty($data['to']) && !empty($data['bcc'])) {
799                         $data['to'] = $data['bcc'];
800                 }
801
802                 unset($data['cc']);
803                 unset($data['bcc']);
804
805                 $object['to'] = $data['to'];
806                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
807
808                 unset($object['cc']);
809                 unset($object['bcc']);
810
811                 $data['directMessage'] = true;
812
813                 $data['object'] = $object;
814
815                 $owner = User::getOwnerDataById($mail['uid']);
816
817                 if (!$object_mode && !empty($owner)) {
818                         return LDSignature::sign($data, $owner);
819                 } else {
820                         return $data;
821                 }
822         }
823
824         /**
825          * Returns the activity type of a given item
826          *
827          * @param array $item
828          *
829          * @return string with activity type
830          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
831          * @throws \ImagickException
832          */
833         private static function getTypeOfItem($item)
834         {
835                 $reshared = false;
836
837                 // Only check for a reshare, if it is a real reshare and no quoted reshare
838                 if (strpos($item['body'], "[share") === 0) {
839                         $announce = self::getAnnounceArray($item);
840                         $reshared = !empty($announce);
841                 }
842
843                 if ($reshared) {
844                         $type = 'Announce';
845                 } elseif ($item['verb'] == Activity::POST) {
846                         if ($item['created'] == $item['edited']) {
847                                 $type = 'Create';
848                         } else {
849                                 $type = 'Update';
850                         }
851                 } elseif ($item['verb'] == Activity::LIKE) {
852                         $type = 'Like';
853                 } elseif ($item['verb'] == Activity::DISLIKE) {
854                         $type = 'Dislike';
855                 } elseif ($item['verb'] == Activity::ATTEND) {
856                         $type = 'Accept';
857                 } elseif ($item['verb'] == Activity::ATTENDNO) {
858                         $type = 'Reject';
859                 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
860                         $type = 'TentativeAccept';
861                 } elseif ($item['verb'] == Activity::FOLLOW) {
862                         $type = 'Follow';
863                 } elseif ($item['verb'] == Activity::TAG) {
864                         $type = 'Add';
865                 } elseif ($item['verb'] == Activity::ANNOUNCE) {
866                         $type = 'Announce';
867                 } else {
868                         $type = '';
869                 }
870
871                 return $type;
872         }
873
874         /**
875          * Creates the activity or fetches it from the cache
876          *
877          * @param integer $item_id
878          * @param boolean $force Force new cache entry
879          *
880          * @return array with the activity
881          * @throws \Exception
882          */
883         public static function createCachedActivityFromItem($item_id, $force = false)
884         {
885                 $cachekey = 'APDelivery:createActivity:' . $item_id;
886
887                 if (!$force) {
888                         $data = DI::cache()->get($cachekey);
889                         if (!is_null($data)) {
890                                 return $data;
891                         }
892                 }
893
894                 $data = self::createActivityFromItem($item_id);
895
896                 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
897                 return $data;
898         }
899
900         /**
901          * Creates an activity array for a given item id
902          *
903          * @param integer $item_id
904          * @param boolean $object_mode Is the activity item is used inside another object?
905          *
906          * @return array of activity
907          * @throws \Exception
908          */
909         public static function createActivityFromItem($item_id, $object_mode = false)
910         {
911                 Logger::info('Fetching activity', ['item' => $item_id]);
912                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
913                 if (!DBA::isResult($item)) {
914                         return false;
915                 }
916
917                 /// @todo This code should be removed by the end of the year 2020
918                 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
919                         $owner = User::getOwnerDataById($item['uid']);
920                         if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
921                                 $type = 'Announce';
922
923                                 // Disguise forum posts as reshares. Will later be converted to a real announce
924                                 $item['body'] = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
925                                         $item['plink'], $item['created'], $item['guid']) . $item['body'] . '[/share]';
926                         }
927                 }
928
929                 /*
930                 /// @todo This code should be activated by the end of the year 2020             
931                 // See also "tagDeliver";
932                 // In case of a forum post ensure to return the original post if author and forum are on the same machine
933                 if (!empty($item['forum_mode'])) {
934                         $author = Contact::getById($item['author-id'], ['nurl']);
935                         if (!empty($author['nurl'])) {
936                                 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
937                                 if (!empty($self['uid'])) {
938                                         $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
939                                 }
940                         }
941                 }
942                 */
943
944                 if (empty($type)) {
945                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
946                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
947                         if (DBA::isResult($conversation)) {
948                                 $data = json_decode($conversation['source'], true);
949                                 if (!empty($data['type'])) {
950                                         if (in_array($data['type'], ['Create', 'Update'])) {
951                                                 if ($object_mode) {
952                                                         unset($data['@context']);
953                                                         unset($data['signature']);
954                                                 }
955                                                 Logger::info('Return stored conversation', ['item' => $item_id]);
956                                                 return $data;
957                                         } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
958                                                 if (!empty($data['@context'])) {
959                                                         $context = $data['@context'];
960                                                         unset($data['@context']);
961                                                 }
962                                                 unset($data['actor']);
963                                                 $object = $data;
964                                         }
965                                 }
966                         }
967
968                         $type = self::getTypeOfItem($item);
969                 }
970
971                 if (!$object_mode) {
972                         $data = ['@context' => $context ?? ActivityPub::CONTEXT];
973
974                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
975                                 $type = 'Undo';
976                         } elseif ($item['deleted']) {
977                                 $type = 'Delete';
978                         }
979                 } else {
980                         $data = [];
981                 }
982
983                 $data['id'] = $item['uri'] . '/' . $type;
984                 $data['type'] = $type;
985
986                 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
987                         $data['actor'] = $item['author-link'];
988                 } else {
989                         $data['actor'] = $item['owner-link'];
990                 }
991
992                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
993
994                 $data['instrument'] = self::getService();
995
996                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
997
998                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
999                         $data['object'] = $object ?? self::createNote($item);
1000                 } elseif ($data['type'] == 'Add') {
1001                         $data = self::createAddTag($item, $data);
1002                 } elseif ($data['type'] == 'Announce') {
1003                         if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1004                                 $data['object'] = $item['thr-parent'];
1005                         } else {
1006                                 $data = self::createAnnounce($item, $data);
1007                         }
1008                 } elseif ($data['type'] == 'Follow') {
1009                         $data['object'] = $item['parent-uri'];
1010                 } elseif ($data['type'] == 'Undo') {
1011                         $data['object'] = self::createActivityFromItem($item_id, true);
1012                 } else {
1013                         $data['diaspora:guid'] = $item['guid'];
1014                         if (!empty($item['signed_text'])) {
1015                                 $data['diaspora:like'] = $item['signed_text'];
1016                         }
1017                         $data['object'] = $item['thr-parent'];
1018                 }
1019
1020                 if (!empty($item['contact-uid'])) {
1021                         $uid = $item['contact-uid'];
1022                 } else {
1023                         $uid = $item['uid'];
1024                 }
1025
1026                 $owner = User::getOwnerDataById($uid);
1027
1028                 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1029
1030                 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1031                 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1032                         return LDSignature::sign($data, $owner);
1033                 } else {
1034                         return $data;
1035                 }
1036
1037                 /// @todo Create "conversation" entry
1038         }
1039
1040         /**
1041          * Creates a location entry for a given item array
1042          *
1043          * @param array $item
1044          *
1045          * @return array with location array
1046          */
1047         private static function createLocation($item)
1048         {
1049                 $location = ['type' => 'Place'];
1050
1051                 if (!empty($item['location'])) {
1052                         $location['name'] = $item['location'];
1053                 }
1054
1055                 $coord = [];
1056
1057                 if (empty($item['coord'])) {
1058                         $coord = Map::getCoordinates($item['location']);
1059                 } else {
1060                         $coords = explode(' ', $item['coord']);
1061                         if (count($coords) == 2) {
1062                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1063                         }
1064                 }
1065
1066                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1067                         $location['latitude'] = $coord['lat'];
1068                         $location['longitude'] = $coord['lon'];
1069                 }
1070
1071                 return $location;
1072         }
1073
1074         /**
1075          * Returns a tag array for a given item array
1076          *
1077          * @param array $item
1078          *
1079          * @return array of tags
1080          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1081          */
1082         private static function createTagList($item)
1083         {
1084                 $tags = [];
1085
1086                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1087                 foreach ($terms as $term) {
1088                         if ($term['type'] == Tag::HASHTAG) {
1089                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1090                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1091                         } else {
1092                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1093                                 if (empty($contact)) {
1094                                         continue;
1095                                 }
1096                                 if (!empty($contact['addr'])) {
1097                                         $mention = '@' . $contact['addr'];
1098                                 } else {
1099                                         $mention = '@' . $term['url'];
1100                                 }
1101
1102                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1103                         }
1104                 }
1105
1106                 $announce = self::getAnnounceArray($item);
1107                 // Mention the original author upon commented reshares
1108                 if (!empty($announce['comment'])) {
1109                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1110                 }
1111
1112                 return $tags;
1113         }
1114
1115         /**
1116          * Adds attachment data to the JSON document
1117          *
1118          * @param array  $item Data of the item that is to be posted
1119          * @param string $type Object type
1120          *
1121          * @return array with attachment data
1122          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1123          */
1124         private static function createAttachmentList($item, $type)
1125         {
1126                 $attachments = [];
1127
1128                 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1129                 // It will be reactivated, once this cleared.
1130                 /*
1131                 $attach_data = BBCode::getAttachmentData($item['body']);
1132                 if (!empty($attach_data['url'])) {
1133                         $attachment = ['type' => 'Page',
1134                                 'mediaType' => 'text/html',
1135                                 'url' => $attach_data['url']];
1136
1137                         if (!empty($attach_data['title'])) {
1138                                 $attachment['name'] = $attach_data['title'];
1139                         }
1140
1141                         if (!empty($attach_data['description'])) {
1142                                 $attachment['summary'] = $attach_data['description'];
1143                         }
1144
1145                         if (!empty($attach_data['image'])) {
1146                                 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1147                                 if ($imgdata) {
1148                                         $attachment['icon'] = ['type' => 'Image',
1149                                                 'mediaType' => $imgdata['mime'],
1150                                                 'width' => $imgdata[0],
1151                                                 'height' => $imgdata[1],
1152                                                 'url' => $attach_data['image']];
1153                                 }
1154                         }
1155
1156                         $attachments[] = $attachment;
1157                 }
1158                 */
1159                 $arr = explode('[/attach],', $item['attach']);
1160                 if (count($arr)) {
1161                         foreach ($arr as $r) {
1162                                 $matches = false;
1163                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1164                                 if ($cnt) {
1165                                         $attributes = ['type' => 'Document',
1166                                                         'mediaType' => $matches[3],
1167                                                         'url' => $matches[1],
1168                                                         'name' => null];
1169
1170                                         if (trim($matches[4]) != '') {
1171                                                 $attributes['name'] = trim($matches[4]);
1172                                         }
1173
1174                                         $attachments[] = $attributes;
1175                                 }
1176                         }
1177                 }
1178
1179                 if ($type != 'Note') {
1180                         return $attachments;
1181                 }
1182
1183                 // Simplify image codes
1184                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1185
1186                 // Grab all pictures without alternative descriptions and create attachments out of them
1187                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1188                         foreach ($pictures[1] as $picture) {
1189                                 $imgdata = Images::getInfoFromURLCached($picture);
1190                                 if ($imgdata) {
1191                                         $attachments[] = ['type' => 'Document',
1192                                                 'mediaType' => $imgdata['mime'],
1193                                                 'url' => $picture,
1194                                                 'name' => null];
1195                                 }
1196                         }
1197                 }
1198
1199                 // Grab all pictures with alternative description and create attachments out of them
1200                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1201                         foreach ($pictures as $picture) {
1202                                 $imgdata = Images::getInfoFromURLCached($picture[1]);
1203                                 if ($imgdata) {
1204                                         $attachments[] = ['type' => 'Document',
1205                                                 'mediaType' => $imgdata['mime'],
1206                                                 'url' => $picture[1],
1207                                                 'name' => $picture[2]];
1208                                 }
1209                         }
1210                 }
1211
1212                 return $attachments;
1213         }
1214
1215         /**
1216          * Callback function to replace a Friendica style mention in a mention that is used on AP
1217          *
1218          * @param array $match Matching values for the callback
1219          * @return string Replaced mention
1220          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1221          */
1222         private static function mentionCallback($match)
1223         {
1224                 if (empty($match[1])) {
1225                         return '';
1226                 }
1227
1228                 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1229                 if (empty($data['nick'])) {
1230                         return $match[0];
1231                 }
1232
1233                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1234         }
1235
1236         /**
1237          * Remove image elements since they are added as attachment
1238          *
1239          * @param string $body
1240          *
1241          * @return string with removed images
1242          */
1243         private static function removePictures($body)
1244         {
1245                 // Simplify image codes
1246                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1247                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1248
1249                 // Now remove local links
1250                 $body = preg_replace_callback(
1251                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1252                         function ($match) {
1253                                 // We remove the link when it is a link to a local photo page
1254                                 if (Photo::isLocalPage($match[1])) {
1255                                         return '';
1256                                 }
1257                                 // otherwise we just return the link
1258                                 return '[url]' . $match[1] . '[/url]';
1259                         },
1260                         $body
1261                 );
1262
1263                 // Remove all pictures
1264                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1265
1266                 return $body;
1267         }
1268
1269         /**
1270          * Fetches the "context" value for a givem item array from the "conversation" table
1271          *
1272          * @param array $item
1273          *
1274          * @return string with context url
1275          * @throws \Exception
1276          */
1277         private static function fetchContextURLForItem($item)
1278         {
1279                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1280                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1281                         $context_uri = $conversation['conversation-href'];
1282                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1283                         $context_uri = $conversation['conversation-uri'];
1284                 } else {
1285                         $context_uri = $item['parent-uri'] . '#context';
1286                 }
1287                 return $context_uri;
1288         }
1289
1290         /**
1291          * Returns if the post contains sensitive content ("nsfw")
1292          *
1293          * @param integer $uri_id
1294          *
1295          * @return boolean
1296          * @throws \Exception
1297          */
1298         private static function isSensitive($uri_id)
1299         {
1300                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1301         }
1302
1303         /**
1304          * Creates event data
1305          *
1306          * @param array $item
1307          *
1308          * @return array with the event data
1309          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1310          */
1311         public static function createEvent($item)
1312         {
1313                 $event = [];
1314                 $event['name'] = $item['event-summary'];
1315                 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1316                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1317
1318                 if (!$item['event-nofinish']) {
1319                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1320                 }
1321
1322                 if (!empty($item['event-location'])) {
1323                         $item['location'] = $item['event-location'];
1324                         $event['location'] = self::createLocation($item);
1325                 }
1326
1327                 return $event;
1328         }
1329
1330         /**
1331          * Creates a note/article object array
1332          *
1333          * @param array $item
1334          *
1335          * @return array with the object data
1336          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1337          * @throws \ImagickException
1338          */
1339         public static function createNote($item)
1340         {
1341                 if (empty($item)) {
1342                         return [];
1343                 }
1344
1345                 if ($item['event-type'] == 'event') {
1346                         $type = 'Event';
1347                 } elseif (!empty($item['title'])) {
1348                         $type = 'Article';
1349                 } else {
1350                         $type = 'Note';
1351                 }
1352
1353                 if ($item['deleted']) {
1354                         $type = 'Tombstone';
1355                 }
1356
1357                 $data = [];
1358                 $data['id'] = $item['uri'];
1359                 $data['type'] = $type;
1360
1361                 if ($item['deleted']) {
1362                         return $data;
1363                 }
1364
1365                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1366
1367                 if ($item['uri'] != $item['thr-parent']) {
1368                         $data['inReplyTo'] = $item['thr-parent'];
1369                 } else {
1370                         $data['inReplyTo'] = null;
1371                 }
1372
1373                 $data['diaspora:guid'] = $item['guid'];
1374                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1375
1376                 if ($item['created'] != $item['edited']) {
1377                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1378                 }
1379
1380                 $data['url'] = $item['plink'];
1381                 $data['attributedTo'] = $item['author-link'];
1382                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1383                 $data['context'] = self::fetchContextURLForItem($item);
1384
1385                 if (!empty($item['title'])) {
1386                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1387                 }
1388
1389                 $permission_block = self::createPermissionBlockForItem($item, false);
1390
1391                 $body = $item['body'];
1392
1393                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1394                         $body = self::prependMentions($body, $item['uri-id']);
1395                 }
1396
1397                 if ($type == 'Note') {
1398                         $body = self::removePictures($body);
1399                 } elseif (($type == 'Article') && empty($data['summary'])) {
1400                         $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1401                 }
1402
1403                 if ($type == 'Event') {
1404                         $data = array_merge($data, self::createEvent($item));
1405                 } else {
1406                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1407                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1408
1409                         $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1410                 }
1411
1412                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1413                 // Mastodon has got problems with - for example - embedded pictures.
1414                 // The contentMap does contain the unmodified HTML.
1415                 $language = self::getLanguage($item);
1416                 if (!empty($language)) {
1417                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1418                         $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1419                         $richbody = BBCode::removeAttachment($richbody);
1420
1421                         $data['contentMap'][$language] = BBCode::convert($richbody, false);
1422                 }
1423
1424                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1425
1426                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1427                         $data['diaspora:comment'] = $item['signed_text'];
1428                 }
1429
1430                 $data['attachment'] = self::createAttachmentList($item, $type);
1431                 $data['tag'] = self::createTagList($item);
1432
1433                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1434                         $data['location'] = self::createLocation($item);
1435                 }
1436
1437                 if (!empty($item['app'])) {
1438                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1439                 }
1440
1441                 $data = array_merge($data, $permission_block);
1442
1443                 return $data;
1444         }
1445
1446         /**
1447          * Fetches the language from the post, the user or the system.
1448          *
1449          * @param array $item
1450          *
1451          * @return string language string
1452          */
1453         private static function getLanguage(array $item)
1454         {
1455                 // Try to fetch the language from the post itself
1456                 if (!empty($item['language'])) {
1457                         $languages = array_keys(json_decode($item['language'], true));
1458                         if (!empty($languages[0])) {
1459                                 return $languages[0];
1460                         }
1461                 }
1462
1463                 // Otherwise use the user's language
1464                 if (!empty($item['uid'])) {
1465                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1466                         if (!empty($user['language'])) {
1467                                 return $user['language'];
1468                         }
1469                 }
1470
1471                 // And finally just use the system language
1472                 return DI::config()->get('system', 'language');
1473         }
1474
1475         /**
1476          * Creates an an "add tag" entry
1477          *
1478          * @param array $item
1479          * @param array $data activity data
1480          *
1481          * @return array with activity data for adding tags
1482          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1483          * @throws \ImagickException
1484          */
1485         private static function createAddTag($item, $data)
1486         {
1487                 $object = XML::parseString($item['object']);
1488                 $target = XML::parseString($item["target"]);
1489
1490                 $data['diaspora:guid'] = $item['guid'];
1491                 $data['actor'] = $item['author-link'];
1492                 $data['target'] = (string)$target->id;
1493                 $data['summary'] = BBCode::toPlaintext($item['body']);
1494                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1495
1496                 return $data;
1497         }
1498
1499         /**
1500          * Creates an announce object entry
1501          *
1502          * @param array $item
1503          * @param array $data activity data
1504          *
1505          * @return array with activity data
1506          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1507          * @throws \ImagickException
1508          */
1509         private static function createAnnounce($item, $data)
1510         {
1511                 $orig_body = $item['body'];
1512                 $announce = self::getAnnounceArray($item);
1513                 if (empty($announce)) {
1514                         $data['type'] = 'Create';
1515                         $data['object'] = self::createNote($item);
1516                         return $data;
1517                 }
1518
1519                 if (empty($announce['comment'])) {
1520                         // Pure announce, without a quote
1521                         $data['type'] = 'Announce';
1522                         $data['object'] = $announce['object']['uri'];
1523                         return $data;
1524                 }
1525
1526                 // Quote
1527                 $data['type'] = 'Create';
1528                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1529                 $data['object'] = self::createNote($item);
1530
1531                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1532                 $data['object']['attachment'][] = self::createNote($announce['object']);
1533
1534                 $data['object']['source']['content'] = $orig_body;
1535                 return $data;
1536         }
1537
1538         /**
1539          * Return announce related data if the item is an annunce
1540          *
1541          * @param array $item
1542          *
1543          * @return array
1544          */
1545         public static function getAnnounceArray($item)
1546         {
1547                 $reshared = Item::getShareArray($item);
1548                 if (empty($reshared['guid'])) {
1549                         return [];
1550                 }
1551
1552                 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1553                 if (!DBA::isResult($reshared_item)) {
1554                         return [];
1555                 }
1556
1557                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1558                         return [];
1559                 }
1560
1561                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1562                 if (empty($profile)) {
1563                         return [];
1564                 }
1565
1566                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1567         }
1568
1569         /**
1570          * Checks if the provided item array is an announce
1571          *
1572          * @param array $item
1573          *
1574          * @return boolean
1575          */
1576         public static function isAnnounce($item)
1577         {
1578                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1579                         return true;
1580                 }
1581
1582                 $announce = self::getAnnounceArray($item);
1583                 if (empty($announce)) {
1584                         return false;
1585                 }
1586
1587                 return empty($announce['comment']);
1588         }
1589
1590         /**
1591          * Creates an activity id for a given contact id
1592          *
1593          * @param integer $cid Contact ID of target
1594          *
1595          * @return bool|string activity id
1596          */
1597         public static function activityIDFromContact($cid)
1598         {
1599                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1600                 if (!DBA::isResult($contact)) {
1601                         return false;
1602                 }
1603
1604                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1605                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1606                 return DI::baseUrl() . '/activity/' . $uuid;
1607         }
1608
1609         /**
1610          * Transmits a contact suggestion to a given inbox
1611          *
1612          * @param integer $uid           User ID
1613          * @param string  $inbox         Target inbox
1614          * @param integer $suggestion_id Suggestion ID
1615          *
1616          * @return boolean was the transmission successful?
1617          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1618          */
1619         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1620         {
1621                 $owner = User::getOwnerDataById($uid);
1622
1623                 $suggestion = DI::fsuggest()->getById($suggestion_id);
1624
1625                 $data = ['@context' => ActivityPub::CONTEXT,
1626                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1627                         'type' => 'Announce',
1628                         'actor' => $owner['url'],
1629                         'object' => $suggestion->url,
1630                         'content' => $suggestion->note,
1631                         'instrument' => self::getService(),
1632                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1633                         'cc' => []];
1634
1635                 $signed = LDSignature::sign($data, $owner);
1636
1637                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1638                 return HTTPSignature::transmit($signed, $inbox, $uid);
1639         }
1640
1641         /**
1642          * Transmits a profile relocation to a given inbox
1643          *
1644          * @param integer $uid   User ID
1645          * @param string  $inbox Target inbox
1646          *
1647          * @return boolean was the transmission successful?
1648          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1649          */
1650         public static function sendProfileRelocation($uid, $inbox)
1651         {
1652                 $owner = User::getOwnerDataById($uid);
1653
1654                 $data = ['@context' => ActivityPub::CONTEXT,
1655                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1656                         'type' => 'dfrn:relocate',
1657                         'actor' => $owner['url'],
1658                         'object' => $owner['url'],
1659                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1660                         'instrument' => self::getService(),
1661                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1662                         'cc' => []];
1663
1664                 $signed = LDSignature::sign($data, $owner);
1665
1666                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1667                 return HTTPSignature::transmit($signed, $inbox, $uid);
1668         }
1669
1670         /**
1671          * Transmits a profile deletion to a given inbox
1672          *
1673          * @param integer $uid   User ID
1674          * @param string  $inbox Target inbox
1675          *
1676          * @return boolean was the transmission successful?
1677          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1678          */
1679         public static function sendProfileDeletion($uid, $inbox)
1680         {
1681                 $owner = User::getOwnerDataById($uid);
1682
1683                 if (empty($owner)) {
1684                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1685                         return false;
1686                 }
1687
1688                 if (empty($owner['uprvkey'])) {
1689                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1690                         return false;
1691                 }
1692
1693                 $data = ['@context' => ActivityPub::CONTEXT,
1694                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1695                         'type' => 'Delete',
1696                         'actor' => $owner['url'],
1697                         'object' => $owner['url'],
1698                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1699                         'instrument' => self::getService(),
1700                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1701                         'cc' => []];
1702
1703                 $signed = LDSignature::sign($data, $owner);
1704
1705                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1706                 return HTTPSignature::transmit($signed, $inbox, $uid);
1707         }
1708
1709         /**
1710          * Transmits a profile change to a given inbox
1711          *
1712          * @param integer $uid   User ID
1713          * @param string  $inbox Target inbox
1714          *
1715          * @return boolean was the transmission successful?
1716          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1717          * @throws \ImagickException
1718          */
1719         public static function sendProfileUpdate($uid, $inbox)
1720         {
1721                 $owner = User::getOwnerDataById($uid);
1722                 $profile = APContact::getByURL($owner['url']);
1723
1724                 $data = ['@context' => ActivityPub::CONTEXT,
1725                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1726                         'type' => 'Update',
1727                         'actor' => $owner['url'],
1728                         'object' => self::getProfile($uid),
1729                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1730                         'instrument' => self::getService(),
1731                         'to' => [$profile['followers']],
1732                         'cc' => []];
1733
1734                 $signed = LDSignature::sign($data, $owner);
1735
1736                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1737                 return HTTPSignature::transmit($signed, $inbox, $uid);
1738         }
1739
1740         /**
1741          * Transmits a given activity to a target
1742          *
1743          * @param string  $activity Type name
1744          * @param string  $target   Target profile
1745          * @param integer $uid      User ID
1746          * @return bool
1747          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1748          * @throws \ImagickException
1749          * @throws \Exception
1750          */
1751         public static function sendActivity($activity, $target, $uid, $id = '')
1752         {
1753                 $profile = APContact::getByURL($target);
1754                 if (empty($profile['inbox'])) {
1755                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1756                         return;
1757                 }
1758
1759                 $owner = User::getOwnerDataById($uid);
1760
1761                 if (empty($id)) {
1762                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
1763                 }
1764
1765                 $data = ['@context' => ActivityPub::CONTEXT,
1766                         'id' => $id,
1767                         'type' => $activity,
1768                         'actor' => $owner['url'],
1769                         'object' => $profile['url'],
1770                         'instrument' => self::getService(),
1771                         'to' => [$profile['url']]];
1772
1773                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1774
1775                 $signed = LDSignature::sign($data, $owner);
1776                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1777         }
1778
1779         /**
1780          * Transmits a "follow object" activity to a target
1781          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1782          *
1783          * @param string  $object Object URL
1784          * @param string  $target Target profile
1785          * @param integer $uid    User ID
1786          * @return bool
1787          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1788          * @throws \ImagickException
1789          * @throws \Exception
1790          */
1791         public static function sendFollowObject($object, $target, $uid = 0)
1792         {
1793                 $profile = APContact::getByURL($target);
1794                 if (empty($profile['inbox'])) {
1795                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1796                         return;
1797                 }
1798
1799                 if (empty($uid)) {
1800                         // Fetch the list of administrators
1801                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1802
1803                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1804                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1805                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1806                         $uid = $first_user['uid'];
1807                 }
1808
1809                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1810                         'author-id' => Contact::getPublicIdByUserId($uid)];
1811                 if (Item::exists($condition)) {
1812                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1813                         return false;
1814                 }
1815
1816                 $owner = User::getOwnerDataById($uid);
1817
1818                 $data = ['@context' => ActivityPub::CONTEXT,
1819                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1820                         'type' => 'Follow',
1821                         'actor' => $owner['url'],
1822                         'object' => $object,
1823                         'instrument' => self::getService(),
1824                         'to' => [$profile['url']]];
1825
1826                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1827
1828                 $signed = LDSignature::sign($data, $owner);
1829                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1830         }
1831
1832         /**
1833          * Transmit a message that the contact request had been accepted
1834          *
1835          * @param string  $target Target profile
1836          * @param         $id
1837          * @param integer $uid    User ID
1838          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1839          * @throws \ImagickException
1840          */
1841         public static function sendContactAccept($target, $id, $uid)
1842         {
1843                 $profile = APContact::getByURL($target);
1844                 if (empty($profile['inbox'])) {
1845                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1846                         return;
1847                 }
1848
1849                 $owner = User::getOwnerDataById($uid);
1850                 $data = ['@context' => ActivityPub::CONTEXT,
1851                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1852                         'type' => 'Accept',
1853                         'actor' => $owner['url'],
1854                         'object' => [
1855                                 'id' => (string)$id,
1856                                 'type' => 'Follow',
1857                                 'actor' => $profile['url'],
1858                                 'object' => $owner['url']
1859                         ],
1860                         'instrument' => self::getService(),
1861                         'to' => [$profile['url']]];
1862
1863                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1864
1865                 $signed = LDSignature::sign($data, $owner);
1866                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1867         }
1868
1869         /**
1870          * Reject a contact request or terminates the contact relation
1871          *
1872          * @param string  $target Target profile
1873          * @param         $id
1874          * @param integer $uid    User ID
1875          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1876          * @throws \ImagickException
1877          */
1878         public static function sendContactReject($target, $id, $uid)
1879         {
1880                 $profile = APContact::getByURL($target);
1881                 if (empty($profile['inbox'])) {
1882                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1883                         return;
1884                 }
1885
1886                 $owner = User::getOwnerDataById($uid);
1887                 $data = ['@context' => ActivityPub::CONTEXT,
1888                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1889                         'type' => 'Reject',
1890                         'actor' => $owner['url'],
1891                         'object' => [
1892                                 'id' => (string)$id,
1893                                 'type' => 'Follow',
1894                                 'actor' => $profile['url'],
1895                                 'object' => $owner['url']
1896                         ],
1897                         'instrument' => self::getService(),
1898                         'to' => [$profile['url']]];
1899
1900                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1901
1902                 $signed = LDSignature::sign($data, $owner);
1903                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1904         }
1905
1906         /**
1907          * Transmits a message that we don't want to follow this contact anymore
1908          *
1909          * @param string  $target Target profile
1910          * @param integer $uid    User ID
1911          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1912          * @throws \ImagickException
1913          * @throws \Exception
1914          */
1915         public static function sendContactUndo($target, $cid, $uid)
1916         {
1917                 $profile = APContact::getByURL($target);
1918                 if (empty($profile['inbox'])) {
1919                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1920                         return;
1921                 }
1922
1923                 $object_id = self::activityIDFromContact($cid);
1924                 if (empty($object_id)) {
1925                         return;
1926                 }
1927
1928                 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1929
1930                 $owner = User::getOwnerDataById($uid);
1931                 $data = ['@context' => ActivityPub::CONTEXT,
1932                         'id' => $id,
1933                         'type' => 'Undo',
1934                         'actor' => $owner['url'],
1935                         'object' => ['id' => $object_id, 'type' => 'Follow',
1936                                 'actor' => $owner['url'],
1937                                 'object' => $profile['url']],
1938                         'instrument' => self::getService(),
1939                         'to' => [$profile['url']]];
1940
1941                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1942
1943                 $signed = LDSignature::sign($data, $owner);
1944                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1945         }
1946
1947         private static function prependMentions($body, int $uriid)
1948         {
1949                 $mentions = [];
1950
1951                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
1952                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
1953                         if (!empty($profile['addr'])
1954                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1955                                 && !strstr($body, $profile['addr'])
1956                                 && !strstr($body, $tag['url'])
1957                         ) {
1958                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
1959                         }
1960                 }
1961
1962                 $mentions[] = $body;
1963
1964                 return implode(' ', $mentions);
1965         }
1966 }