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