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