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