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