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