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