]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
91042c06bb963554a4b517a0fd115f20d6dc9af8
[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                 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
985                         $data['id'] = $item['uri'];
986                 } else {
987                         $data['id'] = $item['uri'] . '/' . $type;
988                 }
989
990                 $data['type'] = $type;
991
992                 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
993                         $data['actor'] = $item['author-link'];
994                 } else {
995                         $data['actor'] = $item['owner-link'];
996                 }
997
998                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
999
1000                 $data['instrument'] = self::getService();
1001
1002                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1003
1004                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1005                         $data['object'] = $object ?? self::createNote($item);
1006                 } elseif ($data['type'] == 'Add') {
1007                         $data = self::createAddTag($item, $data);
1008                 } elseif ($data['type'] == 'Announce') {
1009                         if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1010                                 $data['object'] = $item['thr-parent'];
1011                         } else {
1012                                 $data = self::createAnnounce($item, $data);
1013                         }
1014                 } elseif ($data['type'] == 'Follow') {
1015                         $data['object'] = $item['parent-uri'];
1016                 } elseif ($data['type'] == 'Undo') {
1017                         $data['object'] = self::createActivityFromItem($item_id, true);
1018                 } else {
1019                         $data['diaspora:guid'] = $item['guid'];
1020                         if (!empty($item['signed_text'])) {
1021                                 $data['diaspora:like'] = $item['signed_text'];
1022                         }
1023                         $data['object'] = $item['thr-parent'];
1024                 }
1025
1026                 if (!empty($item['contact-uid'])) {
1027                         $uid = $item['contact-uid'];
1028                 } else {
1029                         $uid = $item['uid'];
1030                 }
1031
1032                 $owner = User::getOwnerDataById($uid);
1033
1034                 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1035
1036                 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1037                 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1038                         return LDSignature::sign($data, $owner);
1039                 } else {
1040                         return $data;
1041                 }
1042
1043                 /// @todo Create "conversation" entry
1044         }
1045
1046         /**
1047          * Creates a location entry for a given item array
1048          *
1049          * @param array $item
1050          *
1051          * @return array with location array
1052          */
1053         private static function createLocation($item)
1054         {
1055                 $location = ['type' => 'Place'];
1056
1057                 if (!empty($item['location'])) {
1058                         $location['name'] = $item['location'];
1059                 }
1060
1061                 $coord = [];
1062
1063                 if (empty($item['coord'])) {
1064                         $coord = Map::getCoordinates($item['location']);
1065                 } else {
1066                         $coords = explode(' ', $item['coord']);
1067                         if (count($coords) == 2) {
1068                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1069                         }
1070                 }
1071
1072                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1073                         $location['latitude'] = $coord['lat'];
1074                         $location['longitude'] = $coord['lon'];
1075                 }
1076
1077                 return $location;
1078         }
1079
1080         /**
1081          * Returns a tag array for a given item array
1082          *
1083          * @param array $item
1084          *
1085          * @return array of tags
1086          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1087          */
1088         private static function createTagList($item)
1089         {
1090                 $tags = [];
1091
1092                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1093                 foreach ($terms as $term) {
1094                         if ($term['type'] == Tag::HASHTAG) {
1095                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1096                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1097                         } else {
1098                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1099                                 if (empty($contact)) {
1100                                         continue;
1101                                 }
1102                                 if (!empty($contact['addr'])) {
1103                                         $mention = '@' . $contact['addr'];
1104                                 } else {
1105                                         $mention = '@' . $term['url'];
1106                                 }
1107
1108                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1109                         }
1110                 }
1111
1112                 $announce = self::getAnnounceArray($item);
1113                 // Mention the original author upon commented reshares
1114                 if (!empty($announce['comment'])) {
1115                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1116                 }
1117
1118                 return $tags;
1119         }
1120
1121         /**
1122          * Adds attachment data to the JSON document
1123          *
1124          * @param array  $item Data of the item that is to be posted
1125          * @param string $type Object type
1126          *
1127          * @return array with attachment data
1128          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1129          */
1130         private static function createAttachmentList($item, $type)
1131         {
1132                 $attachments = [];
1133
1134                 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1135                 // It will be reactivated, once this cleared.
1136                 /*
1137                 $attach_data = BBCode::getAttachmentData($item['body']);
1138                 if (!empty($attach_data['url'])) {
1139                         $attachment = ['type' => 'Page',
1140                                 'mediaType' => 'text/html',
1141                                 'url' => $attach_data['url']];
1142
1143                         if (!empty($attach_data['title'])) {
1144                                 $attachment['name'] = $attach_data['title'];
1145                         }
1146
1147                         if (!empty($attach_data['description'])) {
1148                                 $attachment['summary'] = $attach_data['description'];
1149                         }
1150
1151                         if (!empty($attach_data['image'])) {
1152                                 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1153                                 if ($imgdata) {
1154                                         $attachment['icon'] = ['type' => 'Image',
1155                                                 'mediaType' => $imgdata['mime'],
1156                                                 'width' => $imgdata[0],
1157                                                 'height' => $imgdata[1],
1158                                                 'url' => $attach_data['image']];
1159                                 }
1160                         }
1161
1162                         $attachments[] = $attachment;
1163                 }
1164                 */
1165                 $arr = explode('[/attach],', $item['attach']);
1166                 if (count($arr)) {
1167                         foreach ($arr as $r) {
1168                                 $matches = false;
1169                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1170                                 if ($cnt) {
1171                                         $attributes = ['type' => 'Document',
1172                                                         'mediaType' => $matches[3],
1173                                                         'url' => $matches[1],
1174                                                         'name' => null];
1175
1176                                         if (trim($matches[4]) != '') {
1177                                                 $attributes['name'] = trim($matches[4]);
1178                                         }
1179
1180                                         $attachments[] = $attributes;
1181                                 }
1182                         }
1183                 }
1184
1185                 if ($type != 'Note') {
1186                         return $attachments;
1187                 }
1188
1189                 // Simplify image codes
1190                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1191
1192                 // Grab all pictures without alternative descriptions and create attachments out of them
1193                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1194                         foreach ($pictures[1] as $picture) {
1195                                 $imgdata = Images::getInfoFromURLCached($picture);
1196                                 if ($imgdata) {
1197                                         $attachments[] = ['type' => 'Document',
1198                                                 'mediaType' => $imgdata['mime'],
1199                                                 'url' => $picture,
1200                                                 'name' => null];
1201                                 }
1202                         }
1203                 }
1204
1205                 // Grab all pictures with alternative description and create attachments out of them
1206                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1207                         foreach ($pictures as $picture) {
1208                                 $imgdata = Images::getInfoFromURLCached($picture[1]);
1209                                 if ($imgdata) {
1210                                         $attachments[] = ['type' => 'Document',
1211                                                 'mediaType' => $imgdata['mime'],
1212                                                 'url' => $picture[1],
1213                                                 'name' => $picture[2]];
1214                                 }
1215                         }
1216                 }
1217
1218                 return $attachments;
1219         }
1220
1221         /**
1222          * Callback function to replace a Friendica style mention in a mention that is used on AP
1223          *
1224          * @param array $match Matching values for the callback
1225          * @return string Replaced mention
1226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1227          */
1228         private static function mentionCallback($match)
1229         {
1230                 if (empty($match[1])) {
1231                         return '';
1232                 }
1233
1234                 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1235                 if (empty($data['nick'])) {
1236                         return $match[0];
1237                 }
1238
1239                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1240         }
1241
1242         /**
1243          * Remove image elements since they are added as attachment
1244          *
1245          * @param string $body
1246          *
1247          * @return string with removed images
1248          */
1249         private static function removePictures($body)
1250         {
1251                 // Simplify image codes
1252                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1253                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1254
1255                 // Now remove local links
1256                 $body = preg_replace_callback(
1257                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1258                         function ($match) {
1259                                 // We remove the link when it is a link to a local photo page
1260                                 if (Photo::isLocalPage($match[1])) {
1261                                         return '';
1262                                 }
1263                                 // otherwise we just return the link
1264                                 return '[url]' . $match[1] . '[/url]';
1265                         },
1266                         $body
1267                 );
1268
1269                 // Remove all pictures
1270                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1271
1272                 return $body;
1273         }
1274
1275         /**
1276          * Fetches the "context" value for a givem item array from the "conversation" table
1277          *
1278          * @param array $item
1279          *
1280          * @return string with context url
1281          * @throws \Exception
1282          */
1283         private static function fetchContextURLForItem($item)
1284         {
1285                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1286                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1287                         $context_uri = $conversation['conversation-href'];
1288                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1289                         $context_uri = $conversation['conversation-uri'];
1290                 } else {
1291                         $context_uri = $item['parent-uri'] . '#context';
1292                 }
1293                 return $context_uri;
1294         }
1295
1296         /**
1297          * Returns if the post contains sensitive content ("nsfw")
1298          *
1299          * @param integer $uri_id
1300          *
1301          * @return boolean
1302          * @throws \Exception
1303          */
1304         private static function isSensitive($uri_id)
1305         {
1306                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1307         }
1308
1309         /**
1310          * Creates event data
1311          *
1312          * @param array $item
1313          *
1314          * @return array with the event data
1315          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1316          */
1317         public static function createEvent($item)
1318         {
1319                 $event = [];
1320                 $event['name'] = $item['event-summary'];
1321                 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1322                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1323
1324                 if (!$item['event-nofinish']) {
1325                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1326                 }
1327
1328                 if (!empty($item['event-location'])) {
1329                         $item['location'] = $item['event-location'];
1330                         $event['location'] = self::createLocation($item);
1331                 }
1332
1333                 return $event;
1334         }
1335
1336         /**
1337          * Creates a note/article object array
1338          *
1339          * @param array $item
1340          *
1341          * @return array with the object data
1342          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1343          * @throws \ImagickException
1344          */
1345         public static function createNote($item)
1346         {
1347                 if (empty($item)) {
1348                         return [];
1349                 }
1350
1351                 if ($item['event-type'] == 'event') {
1352                         $type = 'Event';
1353                 } elseif (!empty($item['title'])) {
1354                         $type = 'Article';
1355                 } else {
1356                         $type = 'Note';
1357                 }
1358
1359                 if ($item['deleted']) {
1360                         $type = 'Tombstone';
1361                 }
1362
1363                 $data = [];
1364                 $data['id'] = $item['uri'];
1365                 $data['type'] = $type;
1366
1367                 if ($item['deleted']) {
1368                         return $data;
1369                 }
1370
1371                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1372
1373                 if ($item['uri'] != $item['thr-parent']) {
1374                         $data['inReplyTo'] = $item['thr-parent'];
1375                 } else {
1376                         $data['inReplyTo'] = null;
1377                 }
1378
1379                 $data['diaspora:guid'] = $item['guid'];
1380                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1381
1382                 if ($item['created'] != $item['edited']) {
1383                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1384                 }
1385
1386                 $data['url'] = $item['plink'];
1387                 $data['attributedTo'] = $item['author-link'];
1388                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1389                 $data['context'] = self::fetchContextURLForItem($item);
1390
1391                 if (!empty($item['title'])) {
1392                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1393                 }
1394
1395                 $permission_block = self::createPermissionBlockForItem($item, false);
1396
1397                 $body = $item['body'];
1398
1399                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1400                         $body = self::prependMentions($body, $item['uri-id']);
1401                 }
1402
1403                 if ($type == 'Note') {
1404                         $body = self::removePictures($body);
1405                 } elseif (($type == 'Article') && empty($data['summary'])) {
1406                         $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1407                 }
1408
1409                 if ($type == 'Event') {
1410                         $data = array_merge($data, self::createEvent($item));
1411                 } else {
1412                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1413                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1414
1415                         $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1416                 }
1417
1418                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1419                 // Mastodon has got problems with - for example - embedded pictures.
1420                 // The contentMap does contain the unmodified HTML.
1421                 $language = self::getLanguage($item);
1422                 if (!empty($language)) {
1423                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1424                         $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1425                         $richbody = BBCode::removeAttachment($richbody);
1426
1427                         $data['contentMap'][$language] = BBCode::convert($richbody, false);
1428                 }
1429
1430                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1431
1432                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1433                         $data['diaspora:comment'] = $item['signed_text'];
1434                 }
1435
1436                 $data['attachment'] = self::createAttachmentList($item, $type);
1437                 $data['tag'] = self::createTagList($item);
1438
1439                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1440                         $data['location'] = self::createLocation($item);
1441                 }
1442
1443                 if (!empty($item['app'])) {
1444                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1445                 }
1446
1447                 $data = array_merge($data, $permission_block);
1448
1449                 return $data;
1450         }
1451
1452         /**
1453          * Fetches the language from the post, the user or the system.
1454          *
1455          * @param array $item
1456          *
1457          * @return string language string
1458          */
1459         private static function getLanguage(array $item)
1460         {
1461                 // Try to fetch the language from the post itself
1462                 if (!empty($item['language'])) {
1463                         $languages = array_keys(json_decode($item['language'], true));
1464                         if (!empty($languages[0])) {
1465                                 return $languages[0];
1466                         }
1467                 }
1468
1469                 // Otherwise use the user's language
1470                 if (!empty($item['uid'])) {
1471                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1472                         if (!empty($user['language'])) {
1473                                 return $user['language'];
1474                         }
1475                 }
1476
1477                 // And finally just use the system language
1478                 return DI::config()->get('system', 'language');
1479         }
1480
1481         /**
1482          * Creates an an "add tag" entry
1483          *
1484          * @param array $item
1485          * @param array $data activity data
1486          *
1487          * @return array with activity data for adding tags
1488          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1489          * @throws \ImagickException
1490          */
1491         private static function createAddTag($item, $data)
1492         {
1493                 $object = XML::parseString($item['object']);
1494                 $target = XML::parseString($item["target"]);
1495
1496                 $data['diaspora:guid'] = $item['guid'];
1497                 $data['actor'] = $item['author-link'];
1498                 $data['target'] = (string)$target->id;
1499                 $data['summary'] = BBCode::toPlaintext($item['body']);
1500                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1501
1502                 return $data;
1503         }
1504
1505         /**
1506          * Creates an announce object entry
1507          *
1508          * @param array $item
1509          * @param array $data activity data
1510          *
1511          * @return array with activity data
1512          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1513          * @throws \ImagickException
1514          */
1515         private static function createAnnounce($item, $data)
1516         {
1517                 $orig_body = $item['body'];
1518                 $announce = self::getAnnounceArray($item);
1519                 if (empty($announce)) {
1520                         $data['type'] = 'Create';
1521                         $data['object'] = self::createNote($item);
1522                         return $data;
1523                 }
1524
1525                 if (empty($announce['comment'])) {
1526                         // Pure announce, without a quote
1527                         $data['type'] = 'Announce';
1528                         $data['object'] = $announce['object']['uri'];
1529                         return $data;
1530                 }
1531
1532                 // Quote
1533                 $data['type'] = 'Create';
1534                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1535                 $data['object'] = self::createNote($item);
1536
1537                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1538                 $data['object']['attachment'][] = self::createNote($announce['object']);
1539
1540                 $data['object']['source']['content'] = $orig_body;
1541                 return $data;
1542         }
1543
1544         /**
1545          * Return announce related data if the item is an annunce
1546          *
1547          * @param array $item
1548          *
1549          * @return array
1550          */
1551         public static function getAnnounceArray($item)
1552         {
1553                 $reshared = Item::getShareArray($item);
1554                 if (empty($reshared['guid'])) {
1555                         return [];
1556                 }
1557
1558                 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1559                 if (!DBA::isResult($reshared_item)) {
1560                         return [];
1561                 }
1562
1563                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1564                         return [];
1565                 }
1566
1567                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1568                 if (empty($profile)) {
1569                         return [];
1570                 }
1571
1572                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1573         }
1574
1575         /**
1576          * Checks if the provided item array is an announce
1577          *
1578          * @param array $item
1579          *
1580          * @return boolean
1581          */
1582         public static function isAnnounce($item)
1583         {
1584                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1585                         return true;
1586                 }
1587
1588                 $announce = self::getAnnounceArray($item);
1589                 if (empty($announce)) {
1590                         return false;
1591                 }
1592
1593                 return empty($announce['comment']);
1594         }
1595
1596         /**
1597          * Creates an activity id for a given contact id
1598          *
1599          * @param integer $cid Contact ID of target
1600          *
1601          * @return bool|string activity id
1602          */
1603         public static function activityIDFromContact($cid)
1604         {
1605                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1606                 if (!DBA::isResult($contact)) {
1607                         return false;
1608                 }
1609
1610                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1611                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1612                 return DI::baseUrl() . '/activity/' . $uuid;
1613         }
1614
1615         /**
1616          * Transmits a contact suggestion to a given inbox
1617          *
1618          * @param integer $uid           User ID
1619          * @param string  $inbox         Target inbox
1620          * @param integer $suggestion_id Suggestion ID
1621          *
1622          * @return boolean was the transmission successful?
1623          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1624          */
1625         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1626         {
1627                 $owner = User::getOwnerDataById($uid);
1628
1629                 $suggestion = DI::fsuggest()->getById($suggestion_id);
1630
1631                 $data = ['@context' => ActivityPub::CONTEXT,
1632                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1633                         'type' => 'Announce',
1634                         'actor' => $owner['url'],
1635                         'object' => $suggestion->url,
1636                         'content' => $suggestion->note,
1637                         'instrument' => self::getService(),
1638                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1639                         'cc' => []];
1640
1641                 $signed = LDSignature::sign($data, $owner);
1642
1643                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1644                 return HTTPSignature::transmit($signed, $inbox, $uid);
1645         }
1646
1647         /**
1648          * Transmits a profile relocation to a given inbox
1649          *
1650          * @param integer $uid   User ID
1651          * @param string  $inbox Target inbox
1652          *
1653          * @return boolean was the transmission successful?
1654          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1655          */
1656         public static function sendProfileRelocation($uid, $inbox)
1657         {
1658                 $owner = User::getOwnerDataById($uid);
1659
1660                 $data = ['@context' => ActivityPub::CONTEXT,
1661                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1662                         'type' => 'dfrn:relocate',
1663                         'actor' => $owner['url'],
1664                         'object' => $owner['url'],
1665                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1666                         'instrument' => self::getService(),
1667                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1668                         'cc' => []];
1669
1670                 $signed = LDSignature::sign($data, $owner);
1671
1672                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1673                 return HTTPSignature::transmit($signed, $inbox, $uid);
1674         }
1675
1676         /**
1677          * Transmits a profile deletion to a given inbox
1678          *
1679          * @param integer $uid   User ID
1680          * @param string  $inbox Target inbox
1681          *
1682          * @return boolean was the transmission successful?
1683          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1684          */
1685         public static function sendProfileDeletion($uid, $inbox)
1686         {
1687                 $owner = User::getOwnerDataById($uid);
1688
1689                 if (empty($owner)) {
1690                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1691                         return false;
1692                 }
1693
1694                 if (empty($owner['uprvkey'])) {
1695                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1696                         return false;
1697                 }
1698
1699                 $data = ['@context' => ActivityPub::CONTEXT,
1700                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1701                         'type' => 'Delete',
1702                         'actor' => $owner['url'],
1703                         'object' => $owner['url'],
1704                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1705                         'instrument' => self::getService(),
1706                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1707                         'cc' => []];
1708
1709                 $signed = LDSignature::sign($data, $owner);
1710
1711                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1712                 return HTTPSignature::transmit($signed, $inbox, $uid);
1713         }
1714
1715         /**
1716          * Transmits a profile change to a given inbox
1717          *
1718          * @param integer $uid   User ID
1719          * @param string  $inbox Target inbox
1720          *
1721          * @return boolean was the transmission successful?
1722          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1723          * @throws \ImagickException
1724          */
1725         public static function sendProfileUpdate($uid, $inbox)
1726         {
1727                 $owner = User::getOwnerDataById($uid);
1728                 $profile = APContact::getByURL($owner['url']);
1729
1730                 $data = ['@context' => ActivityPub::CONTEXT,
1731                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1732                         'type' => 'Update',
1733                         'actor' => $owner['url'],
1734                         'object' => self::getProfile($uid),
1735                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1736                         'instrument' => self::getService(),
1737                         'to' => [$profile['followers']],
1738                         'cc' => []];
1739
1740                 $signed = LDSignature::sign($data, $owner);
1741
1742                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1743                 return HTTPSignature::transmit($signed, $inbox, $uid);
1744         }
1745
1746         /**
1747          * Transmits a given activity to a target
1748          *
1749          * @param string  $activity Type name
1750          * @param string  $target   Target profile
1751          * @param integer $uid      User ID
1752          * @return bool
1753          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1754          * @throws \ImagickException
1755          * @throws \Exception
1756          */
1757         public static function sendActivity($activity, $target, $uid, $id = '')
1758         {
1759                 $profile = APContact::getByURL($target);
1760                 if (empty($profile['inbox'])) {
1761                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1762                         return;
1763                 }
1764
1765                 $owner = User::getOwnerDataById($uid);
1766
1767                 if (empty($id)) {
1768                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
1769                 }
1770
1771                 $data = ['@context' => ActivityPub::CONTEXT,
1772                         'id' => $id,
1773                         'type' => $activity,
1774                         'actor' => $owner['url'],
1775                         'object' => $profile['url'],
1776                         'instrument' => self::getService(),
1777                         'to' => [$profile['url']]];
1778
1779                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1780
1781                 $signed = LDSignature::sign($data, $owner);
1782                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1783         }
1784
1785         /**
1786          * Transmits a "follow object" activity to a target
1787          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1788          *
1789          * @param string  $object Object URL
1790          * @param string  $target Target profile
1791          * @param integer $uid    User ID
1792          * @return bool
1793          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1794          * @throws \ImagickException
1795          * @throws \Exception
1796          */
1797         public static function sendFollowObject($object, $target, $uid = 0)
1798         {
1799                 $profile = APContact::getByURL($target);
1800                 if (empty($profile['inbox'])) {
1801                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1802                         return;
1803                 }
1804
1805                 if (empty($uid)) {
1806                         // Fetch the list of administrators
1807                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1808
1809                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1810                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1811                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1812                         $uid = $first_user['uid'];
1813                 }
1814
1815                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1816                         'author-id' => Contact::getPublicIdByUserId($uid)];
1817                 if (Item::exists($condition)) {
1818                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1819                         return false;
1820                 }
1821
1822                 $owner = User::getOwnerDataById($uid);
1823
1824                 $data = ['@context' => ActivityPub::CONTEXT,
1825                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1826                         'type' => 'Follow',
1827                         'actor' => $owner['url'],
1828                         'object' => $object,
1829                         'instrument' => self::getService(),
1830                         'to' => [$profile['url']]];
1831
1832                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1833
1834                 $signed = LDSignature::sign($data, $owner);
1835                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1836         }
1837
1838         /**
1839          * Transmit a message that the contact request had been accepted
1840          *
1841          * @param string  $target Target profile
1842          * @param         $id
1843          * @param integer $uid    User ID
1844          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1845          * @throws \ImagickException
1846          */
1847         public static function sendContactAccept($target, $id, $uid)
1848         {
1849                 $profile = APContact::getByURL($target);
1850                 if (empty($profile['inbox'])) {
1851                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1852                         return;
1853                 }
1854
1855                 $owner = User::getOwnerDataById($uid);
1856                 $data = ['@context' => ActivityPub::CONTEXT,
1857                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1858                         'type' => 'Accept',
1859                         'actor' => $owner['url'],
1860                         'object' => [
1861                                 'id' => (string)$id,
1862                                 'type' => 'Follow',
1863                                 'actor' => $profile['url'],
1864                                 'object' => $owner['url']
1865                         ],
1866                         'instrument' => self::getService(),
1867                         'to' => [$profile['url']]];
1868
1869                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1870
1871                 $signed = LDSignature::sign($data, $owner);
1872                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1873         }
1874
1875         /**
1876          * Reject a contact request or terminates the contact relation
1877          *
1878          * @param string  $target Target profile
1879          * @param         $id
1880          * @param integer $uid    User ID
1881          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1882          * @throws \ImagickException
1883          */
1884         public static function sendContactReject($target, $id, $uid)
1885         {
1886                 $profile = APContact::getByURL($target);
1887                 if (empty($profile['inbox'])) {
1888                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1889                         return;
1890                 }
1891
1892                 $owner = User::getOwnerDataById($uid);
1893                 $data = ['@context' => ActivityPub::CONTEXT,
1894                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1895                         'type' => 'Reject',
1896                         'actor' => $owner['url'],
1897                         'object' => [
1898                                 'id' => (string)$id,
1899                                 'type' => 'Follow',
1900                                 'actor' => $profile['url'],
1901                                 'object' => $owner['url']
1902                         ],
1903                         'instrument' => self::getService(),
1904                         'to' => [$profile['url']]];
1905
1906                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1907
1908                 $signed = LDSignature::sign($data, $owner);
1909                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1910         }
1911
1912         /**
1913          * Transmits a message that we don't want to follow this contact anymore
1914          *
1915          * @param string  $target Target profile
1916          * @param integer $uid    User ID
1917          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918          * @throws \ImagickException
1919          * @throws \Exception
1920          */
1921         public static function sendContactUndo($target, $cid, $uid)
1922         {
1923                 $profile = APContact::getByURL($target);
1924                 if (empty($profile['inbox'])) {
1925                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1926                         return;
1927                 }
1928
1929                 $object_id = self::activityIDFromContact($cid);
1930                 if (empty($object_id)) {
1931                         return;
1932                 }
1933
1934                 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1935
1936                 $owner = User::getOwnerDataById($uid);
1937                 $data = ['@context' => ActivityPub::CONTEXT,
1938                         'id' => $id,
1939                         'type' => 'Undo',
1940                         'actor' => $owner['url'],
1941                         'object' => ['id' => $object_id, 'type' => 'Follow',
1942                                 'actor' => $owner['url'],
1943                                 'object' => $profile['url']],
1944                         'instrument' => self::getService(),
1945                         'to' => [$profile['url']]];
1946
1947                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1948
1949                 $signed = LDSignature::sign($data, $owner);
1950                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1951         }
1952
1953         private static function prependMentions($body, int $uriid)
1954         {
1955                 $mentions = [];
1956
1957                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
1958                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
1959                         if (!empty($profile['addr'])
1960                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1961                                 && !strstr($body, $profile['addr'])
1962                                 && !strstr($body, $tag['url'])
1963                         ) {
1964                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
1965                         }
1966                 }
1967
1968                 $mentions[] = $body;
1969
1970                 return implode(' ', $mentions);
1971         }
1972 }