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