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