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