]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
5d3094339cbf99f7afb863773de944ef9703d187
[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                 $object['to'] = $object['cc'];
703                 unset($object['cc']);
704
705                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => 'test']];
706
707                 if (!$object_mode) {
708                         $data = ['@context' => ActivityPub::CONTEXT];
709                 } else {
710                         $data = [];
711                 }
712
713                 $data['id'] = $mail['uri'] . '#Create';
714                 $data['type'] = 'Create';
715                 $data['actor'] = $mail['author-link'];
716                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
717                 $data['instrument'] = self::getService();
718                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
719
720                 if (empty($data['to']) && !empty($data['cc'])) {
721                         $data['to'] = $data['cc'];
722                 }
723
724                 if (empty($data['to']) && !empty($data['bcc'])) {
725                         $data['to'] = $data['bcc'];
726                 }
727
728                 unset($data['cc']);
729                 unset($data['bcc']);
730
731                 $object['to'] = $data['to'];
732                 unset($object['cc']);
733                 unset($object['bcc']);
734
735                 $data['directMessage'] = true;
736
737                 $data['object'] = $object;
738
739                 $owner = User::getOwnerDataById($mail['uid']);
740
741                 if (!$object_mode && !empty($owner)) {
742                         return LDSignature::sign($data, $owner);
743                 } else {
744                         return $data;
745                 }
746         }
747
748         /**
749          * Returns the activity type of a given item
750          *
751          * @param array $item
752          *
753          * @return string with activity type
754          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
755          * @throws \ImagickException
756          */
757         private static function getTypeOfItem($item)
758         {
759                 $reshared = false;
760
761                 // Only check for a reshare, if it is a real reshare and no quoted reshare
762                 if (strpos($item['body'], "[share") === 0) {
763                         $announce = api_share_as_retweet($item);
764                         $reshared = !empty($announce['plink']);
765                 }
766
767                 if ($reshared) {
768                         $type = 'Announce';
769                 } elseif ($item['verb'] == Activity::POST) {
770                         if ($item['created'] == $item['edited']) {
771                                 $type = 'Create';
772                         } else {
773                                 $type = 'Update';
774                         }
775                 } elseif ($item['verb'] == Activity::LIKE) {
776                         $type = 'Like';
777                 } elseif ($item['verb'] == Activity::DISLIKE) {
778                         $type = 'Dislike';
779                 } elseif ($item['verb'] == Activity::ATTEND) {
780                         $type = 'Accept';
781                 } elseif ($item['verb'] == Activity::ATTENDNO) {
782                         $type = 'Reject';
783                 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
784                         $type = 'TentativeAccept';
785                 } elseif ($item['verb'] == Activity::FOLLOW) {
786                         $type = 'Follow';
787                 } elseif ($item['verb'] == Activity::TAG) {
788                         $type = 'Add';
789                 } else {
790                         $type = '';
791                 }
792
793                 return $type;
794         }
795
796         /**
797          * Creates the activity or fetches it from the cache
798          *
799          * @param integer $item_id
800          * @param boolean $force Force new cache entry
801          *
802          * @return array with the activity
803          * @throws \Exception
804          */
805         public static function createCachedActivityFromItem($item_id, $force = false)
806         {
807                 $cachekey = 'APDelivery:createActivity:' . $item_id;
808
809                 if (!$force) {
810                         $data = Cache::get($cachekey);
811                         if (!is_null($data)) {
812                                 return $data;
813                         }
814                 }
815
816                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
817
818                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
819                 return $data;
820         }
821
822         /**
823          * Creates an activity array for a given item id
824          *
825          * @param integer $item_id
826          * @param boolean $object_mode Is the activity item is used inside another object?
827          *
828          * @return array of activity
829          * @throws \Exception
830          */
831         public static function createActivityFromItem($item_id, $object_mode = false)
832         {
833                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
834
835                 if (!DBA::isResult($item)) {
836                         return false;
837                 }
838
839                 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
840                         $owner = User::getOwnerDataById($item['uid']);
841                         if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
842                                 $type = 'Announce';
843
844                                 // Disguise forum posts as reshares. Will later be converted to a real announce
845                                 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
846                                         $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
847                         }
848                 }
849
850                 if (empty($type)) {
851                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
852                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
853                         if (DBA::isResult($conversation)) {
854                                 $data = json_decode($conversation['source'], true);
855                                 if (!empty($data)) {
856                                         return $data;
857                                 }
858                         }
859
860                         $type = self::getTypeOfItem($item);
861                 }
862
863                 if (!$object_mode) {
864                         $data = ['@context' => ActivityPub::CONTEXT];
865
866                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
867                                 $type = 'Undo';
868                         } elseif ($item['deleted']) {
869                                 $type = 'Delete';
870                         }
871                 } else {
872                         $data = [];
873                 }
874
875                 $data['id'] = $item['uri'] . '#' . $type;
876                 $data['type'] = $type;
877
878                 if (Item::isForumPost($item) && ($type != 'Announce')) {
879                         $data['actor'] = $item['author-link'];
880                 } else {
881                         $data['actor'] = $item['owner-link'];
882                 }
883
884                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
885
886                 $data['instrument'] = self::getService();
887
888                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
889
890                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
891                         $data['object'] = self::createNote($item);
892                 } elseif ($data['type'] == 'Add') {
893                         $data = self::createAddTag($item, $data);
894                 } elseif ($data['type'] == 'Announce') {
895                         $data = self::createAnnounce($item, $data);
896                 } elseif ($data['type'] == 'Follow') {
897                         $data['object'] = $item['parent-uri'];
898                 } elseif ($data['type'] == 'Undo') {
899                         $data['object'] = self::createActivityFromItem($item_id, true);
900                 } else {
901                         $data['diaspora:guid'] = $item['guid'];
902                         if (!empty($item['signed_text'])) {
903                                 $data['diaspora:like'] = $item['signed_text'];
904                         }
905                         $data['object'] = $item['thr-parent'];
906                 }
907
908                 if (!empty($item['contact-uid'])) {
909                         $uid = $item['contact-uid'];
910                 } else {
911                         $uid = $item['uid'];
912                 }
913
914                 $owner = User::getOwnerDataById($uid);
915
916                 if (!$object_mode && !empty($owner)) {
917                         return LDSignature::sign($data, $owner);
918                 } else {
919                         return $data;
920                 }
921
922                 /// @todo Create "conversation" entry
923         }
924
925         /**
926          * Creates an object array for a given item id
927          *
928          * @param integer $item_id
929          *
930          * @return array with the object data
931          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932          * @throws \ImagickException
933          */
934         public static function createObjectFromItemID($item_id)
935         {
936                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
937
938                 if (!DBA::isResult($item)) {
939                         return false;
940                 }
941
942                 $data = ['@context' => ActivityPub::CONTEXT];
943                 $data = array_merge($data, self::createNote($item));
944
945                 return $data;
946         }
947
948         /**
949          * Creates a location entry for a given item array
950          *
951          * @param array $item
952          *
953          * @return array with location array
954          */
955         private static function createLocation($item)
956         {
957                 $location = ['type' => 'Place'];
958
959                 if (!empty($item['location'])) {
960                         $location['name'] = $item['location'];
961                 }
962
963                 $coord = [];
964
965                 if (empty($item['coord'])) {
966                         $coord = Map::getCoordinates($item['location']);
967                 } else {
968                         $coords = explode(' ', $item['coord']);
969                         if (count($coords) == 2) {
970                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
971                         }
972                 }
973
974                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
975                         $location['latitude'] = $coord['lat'];
976                         $location['longitude'] = $coord['lon'];
977                 }
978
979                 return $location;
980         }
981
982         /**
983          * Returns a tag array for a given item array
984          *
985          * @param array $item
986          *
987          * @return array of tags
988          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989          */
990         private static function createTagList($item)
991         {
992                 $tags = [];
993
994                 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
995                 foreach ($terms as $term) {
996                         if ($term['type'] == Term::HASHTAG) {
997                                 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
998                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
999                         } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
1000                                 $contact = Contact::getDetailsByURL($term['url']);
1001                                 if (!empty($contact['addr'])) {
1002                                         $mention = '@' . $contact['addr'];
1003                                 } else {
1004                                         $mention = '@' . $term['url'];
1005                                 }
1006
1007                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1008                         }
1009                 }
1010                 return $tags;
1011         }
1012
1013         /**
1014          * Adds attachment data to the JSON document
1015          *
1016          * @param array  $item Data of the item that is to be posted
1017          * @param string $type Object type
1018          *
1019          * @return array with attachment data
1020          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1021          */
1022         private static function createAttachmentList($item, $type)
1023         {
1024                 $attachments = [];
1025
1026                 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1027                 // It will be reactivated, once this cleared.
1028                 /*
1029                 $attach_data = BBCode::getAttachmentData($item['body']);
1030                 if (!empty($attach_data['url'])) {
1031                         $attachment = ['type' => 'Page',
1032                                 'mediaType' => 'text/html',
1033                                 'url' => $attach_data['url']];
1034
1035                         if (!empty($attach_data['title'])) {
1036                                 $attachment['name'] = $attach_data['title'];
1037                         }
1038
1039                         if (!empty($attach_data['description'])) {
1040                                 $attachment['summary'] = $attach_data['description'];
1041                         }
1042
1043                         if (!empty($attach_data['image'])) {
1044                                 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1045                                 if ($imgdata) {
1046                                         $attachment['icon'] = ['type' => 'Image',
1047                                                 'mediaType' => $imgdata['mime'],
1048                                                 'width' => $imgdata[0],
1049                                                 'height' => $imgdata[1],
1050                                                 'url' => $attach_data['image']];
1051                                 }
1052                         }
1053
1054                         $attachments[] = $attachment;
1055                 }
1056                 */
1057                 $arr = explode('[/attach],', $item['attach']);
1058                 if (count($arr)) {
1059                         foreach ($arr as $r) {
1060                                 $matches = false;
1061                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1062                                 if ($cnt) {
1063                                         $attributes = ['type' => 'Document',
1064                                                         'mediaType' => $matches[3],
1065                                                         'url' => $matches[1],
1066                                                         'name' => null];
1067
1068                                         if (trim($matches[4]) != '') {
1069                                                 $attributes['name'] = trim($matches[4]);
1070                                         }
1071
1072                                         $attachments[] = $attributes;
1073                                 }
1074                         }
1075                 }
1076
1077                 if ($type != 'Note') {
1078                         return $attachments;
1079                 }
1080
1081                 // Simplify image codes
1082                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1083
1084                 // Grab all pictures without alternative descriptions and create attachments out of them
1085                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1086                         foreach ($pictures[1] as $picture) {
1087                                 $imgdata = Images::getInfoFromURLCached($picture);
1088                                 if ($imgdata) {
1089                                         $attachments[] = ['type' => 'Document',
1090                                                 'mediaType' => $imgdata['mime'],
1091                                                 'url' => $picture,
1092                                                 'name' => null];
1093                                 }
1094                         }
1095                 }
1096
1097                 // Grab all pictures with alternative description and create attachments out of them
1098                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1099                         foreach ($pictures as $picture) {
1100                                 $imgdata = Images::getInfoFromURLCached($picture[1]);
1101                                 if ($imgdata) {
1102                                         $attachments[] = ['type' => 'Document',
1103                                                 'mediaType' => $imgdata['mime'],
1104                                                 'url' => $picture[1],
1105                                                 'name' => $picture[2]];
1106                                 }
1107                         }
1108                 }
1109
1110                 return $attachments;
1111         }
1112
1113         /**
1114          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1115          *
1116          * @param array $match Matching values for the callback
1117          * @return string Replaced mention
1118          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1119          */
1120         private static function mentionCallback($match)
1121         {
1122                 if (empty($match[1])) {
1123                         return '';
1124                 }
1125
1126                 $data = Contact::getDetailsByURL($match[1]);
1127                 if (empty($data['nick'])) {
1128                         return $match[0];
1129                 }
1130
1131                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1132         }
1133
1134         /**
1135          * Remove image elements since they are added as attachment
1136          *
1137          * @param string $body
1138          *
1139          * @return string with removed images
1140          */
1141         private static function removePictures($body)
1142         {
1143                 // Simplify image codes
1144                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1145                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1146
1147                 // Now remove local links
1148                 $body = preg_replace_callback(
1149                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1150                         function ($match) {
1151                                 // We remove the link when it is a link to a local photo page
1152                                 if (Photo::isLocalPage($match[1])) {
1153                                         return '';
1154                                 }
1155                                 // otherwise we just return the link
1156                                 return '[url]' . $match[1] . '[/url]';
1157                         },
1158                         $body
1159                 );
1160
1161                 // Remove all pictures
1162                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1163
1164                 return $body;
1165         }
1166
1167         /**
1168          * Fetches the "context" value for a givem item array from the "conversation" table
1169          *
1170          * @param array $item
1171          *
1172          * @return string with context url
1173          * @throws \Exception
1174          */
1175         private static function fetchContextURLForItem($item)
1176         {
1177                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1178                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1179                         $context_uri = $conversation['conversation-href'];
1180                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1181                         $context_uri = $conversation['conversation-uri'];
1182                 } else {
1183                         $context_uri = $item['parent-uri'] . '#context';
1184                 }
1185                 return $context_uri;
1186         }
1187
1188         /**
1189          * Returns if the post contains sensitive content ("nsfw")
1190          *
1191          * @param integer $item_id
1192          *
1193          * @return boolean
1194          * @throws \Exception
1195          */
1196         private static function isSensitive($item_id)
1197         {
1198                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1199                 return DBA::exists('term', $condition);
1200         }
1201
1202         /**
1203          * Creates event data
1204          *
1205          * @param array $item
1206          *
1207          * @return array with the event data
1208          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1209          */
1210         public static function createEvent($item)
1211         {
1212                 $event = [];
1213                 $event['name'] = $item['event-summary'];
1214                 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1215                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1216
1217                 if (!$item['event-nofinish']) {
1218                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1219                 }
1220
1221                 if (!empty($item['event-location'])) {
1222                         $item['location'] = $item['event-location'];
1223                         $event['location'] = self::createLocation($item);
1224                 }
1225
1226                 return $event;
1227         }
1228
1229         /**
1230          * Creates a note/article object array
1231          *
1232          * @param array $item
1233          *
1234          * @return array with the object data
1235          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1236          * @throws \ImagickException
1237          */
1238         public static function createNote($item)
1239         {
1240                 if (empty($item)) {
1241                         return [];
1242                 }
1243
1244                 if ($item['event-type'] == 'event') {
1245                         $type = 'Event';
1246                 } elseif (!empty($item['title'])) {
1247                         $type = 'Article';
1248                 } else {
1249                         $type = 'Note';
1250                 }
1251
1252                 if ($item['deleted']) {
1253                         $type = 'Tombstone';
1254                 }
1255
1256                 $data = [];
1257                 $data['id'] = $item['uri'];
1258                 $data['type'] = $type;
1259
1260                 if ($item['deleted']) {
1261                         return $data;
1262                 }
1263
1264                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1265
1266                 if ($item['uri'] != $item['thr-parent']) {
1267                         $data['inReplyTo'] = $item['thr-parent'];
1268                 } else {
1269                         $data['inReplyTo'] = null;
1270                 }
1271
1272                 $data['diaspora:guid'] = $item['guid'];
1273                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1274
1275                 if ($item['created'] != $item['edited']) {
1276                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1277                 }
1278
1279                 $data['url'] = $item['plink'];
1280                 $data['attributedTo'] = $item['author-link'];
1281                 $data['sensitive'] = self::isSensitive($item['id']);
1282                 $data['context'] = self::fetchContextURLForItem($item);
1283
1284                 if (!empty($item['title'])) {
1285                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1286                 }
1287
1288                 $permission_block = self::createPermissionBlockForItem($item, false);
1289
1290                 $body = $item['body'];
1291
1292                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1293                         $body = self::prependMentions($body, $permission_block);
1294                 }
1295
1296                 if ($type == 'Note') {
1297                         $body = self::removePictures($body);
1298                 } elseif (($type == 'Article') && empty($data['summary'])) {
1299                         $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1300                 }
1301
1302                 if ($type == 'Event') {
1303                         $data = array_merge($data, self::createEvent($item));
1304                 } else {
1305                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1306                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1307
1308                         $data['content'] = BBCode::convert($body, false, 9);
1309                 }
1310
1311                 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1312                 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1313                 $richbody = BBCode::removeAttachment($richbody);
1314
1315                 $data['contentMap']['text/html'] = BBCode::convert($richbody, false);
1316                 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1317
1318                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1319
1320                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1321                         $data['diaspora:comment'] = $item['signed_text'];
1322                 }
1323
1324                 $data['attachment'] = self::createAttachmentList($item, $type);
1325                 $data['tag'] = self::createTagList($item);
1326
1327                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1328                         $data['location'] = self::createLocation($item);
1329                 }
1330
1331                 if (!empty($item['app'])) {
1332                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1333                 }
1334
1335                 $data = array_merge($data, $permission_block);
1336
1337                 return $data;
1338         }
1339
1340         /**
1341          * Creates an an "add tag" entry
1342          *
1343          * @param array $item
1344          * @param array $data activity data
1345          *
1346          * @return array with activity data for adding tags
1347          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1348          * @throws \ImagickException
1349          */
1350         private static function createAddTag($item, $data)
1351         {
1352                 $object = XML::parseString($item['object'], false);
1353                 $target = XML::parseString($item["target"], false);
1354
1355                 $data['diaspora:guid'] = $item['guid'];
1356                 $data['actor'] = $item['author-link'];
1357                 $data['target'] = (string)$target->id;
1358                 $data['summary'] = BBCode::toPlaintext($item['body']);
1359                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1360
1361                 return $data;
1362         }
1363
1364         /**
1365          * Creates an announce object entry
1366          *
1367          * @param array $item
1368          * @param array $data activity data
1369          *
1370          * @return array with activity data
1371          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1372          * @throws \ImagickException
1373          */
1374         private static function createAnnounce($item, $data)
1375         {
1376                 $orig_body = $item['body'];
1377                 $announce = api_share_as_retweet($item);
1378                 if (empty($announce['plink'])) {
1379                         $data['type'] = 'Create';
1380                         $data['object'] = self::createNote($item);
1381                         return $data;
1382                 }
1383
1384                 // Fetch the original id of the object
1385                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1386                 if (!empty($activity)) {
1387                         $ldactivity = JsonLD::compact($activity);
1388                         $id = JsonLD::fetchElement($ldactivity, '@id');
1389                         $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1390                         if (!empty($id)) {
1391                                 if (empty($announce['share-pre-body'])) {
1392                                         // Pure announce, without a quote
1393                                         $data['type'] = 'Announce';
1394                                         $data['object'] = $id;
1395                                         return $data;
1396                                 }
1397
1398                                 // Quote
1399                                 $data['type'] = 'Create';
1400                                 $item['body'] = trim($announce['share-pre-body']) . "\n" . $id;
1401                                 $data['object'] = self::createNote($item);
1402
1403                                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1404                                 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1405
1406                                 $data['object']['source']['content'] = $orig_body;
1407                                 return $data;
1408                         }
1409                 }
1410
1411                 $item['body'] = $orig_body;
1412                 $data['type'] = 'Create';
1413                 $data['object'] = self::createNote($item);
1414                 return $data;
1415         }
1416
1417         /**
1418          * Creates an activity id for a given contact id
1419          *
1420          * @param integer $cid Contact ID of target
1421          *
1422          * @return bool|string activity id
1423          */
1424         public static function activityIDFromContact($cid)
1425         {
1426                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1427                 if (!DBA::isResult($contact)) {
1428                         return false;
1429                 }
1430
1431                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1432                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1433                 return System::baseUrl() . '/activity/' . $uuid;
1434         }
1435
1436         /**
1437          * Transmits a contact suggestion to a given inbox
1438          *
1439          * @param integer $uid           User ID
1440          * @param string  $inbox         Target inbox
1441          * @param integer $suggestion_id Suggestion ID
1442          *
1443          * @return boolean was the transmission successful?
1444          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1445          */
1446         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1447         {
1448                 $owner = User::getOwnerDataById($uid);
1449
1450                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1451
1452                 $data = ['@context' => ActivityPub::CONTEXT,
1453                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1454                         'type' => 'Announce',
1455                         'actor' => $owner['url'],
1456                         'object' => $suggestion['url'],
1457                         'content' => $suggestion['note'],
1458                         'instrument' => self::getService(),
1459                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1460                         'cc' => []];
1461
1462                 $signed = LDSignature::sign($data, $owner);
1463
1464                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1465                 return HTTPSignature::transmit($signed, $inbox, $uid);
1466         }
1467
1468         /**
1469          * Transmits a profile relocation to a given inbox
1470          *
1471          * @param integer $uid   User ID
1472          * @param string  $inbox Target inbox
1473          *
1474          * @return boolean was the transmission successful?
1475          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1476          */
1477         public static function sendProfileRelocation($uid, $inbox)
1478         {
1479                 $owner = User::getOwnerDataById($uid);
1480
1481                 $data = ['@context' => ActivityPub::CONTEXT,
1482                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1483                         'type' => 'dfrn:relocate',
1484                         'actor' => $owner['url'],
1485                         'object' => $owner['url'],
1486                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1487                         'instrument' => self::getService(),
1488                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1489                         'cc' => []];
1490
1491                 $signed = LDSignature::sign($data, $owner);
1492
1493                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1494                 return HTTPSignature::transmit($signed, $inbox, $uid);
1495         }
1496
1497         /**
1498          * Transmits a profile deletion to a given inbox
1499          *
1500          * @param integer $uid   User ID
1501          * @param string  $inbox Target inbox
1502          *
1503          * @return boolean was the transmission successful?
1504          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1505          */
1506         public static function sendProfileDeletion($uid, $inbox)
1507         {
1508                 $owner = User::getOwnerDataById($uid);
1509
1510                 if (empty($owner)) {
1511                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1512                         return false;
1513                 }
1514
1515                 if (empty($owner['uprvkey'])) {
1516                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1517                         return false;
1518                 }
1519
1520                 $data = ['@context' => ActivityPub::CONTEXT,
1521                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1522                         'type' => 'Delete',
1523                         'actor' => $owner['url'],
1524                         'object' => $owner['url'],
1525                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1526                         'instrument' => self::getService(),
1527                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1528                         'cc' => []];
1529
1530                 $signed = LDSignature::sign($data, $owner);
1531
1532                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1533                 return HTTPSignature::transmit($signed, $inbox, $uid);
1534         }
1535
1536         /**
1537          * Transmits a profile change to a given inbox
1538          *
1539          * @param integer $uid   User ID
1540          * @param string  $inbox Target inbox
1541          *
1542          * @return boolean was the transmission successful?
1543          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1544          * @throws \ImagickException
1545          */
1546         public static function sendProfileUpdate($uid, $inbox)
1547         {
1548                 $owner = User::getOwnerDataById($uid);
1549                 $profile = APContact::getByURL($owner['url']);
1550
1551                 $data = ['@context' => ActivityPub::CONTEXT,
1552                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1553                         'type' => 'Update',
1554                         'actor' => $owner['url'],
1555                         'object' => self::getProfile($uid),
1556                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1557                         'instrument' => self::getService(),
1558                         'to' => [$profile['followers']],
1559                         'cc' => []];
1560
1561                 $signed = LDSignature::sign($data, $owner);
1562
1563                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1564                 return HTTPSignature::transmit($signed, $inbox, $uid);
1565         }
1566
1567         /**
1568          * Transmits a given activity to a target
1569          *
1570          * @param string  $activity Type name
1571          * @param string  $target   Target profile
1572          * @param integer $uid      User ID
1573          * @return bool
1574          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1575          * @throws \ImagickException
1576          * @throws \Exception
1577          */
1578         public static function sendActivity($activity, $target, $uid, $id = '')
1579         {
1580                 $profile = APContact::getByURL($target);
1581                 if (empty($profile['inbox'])) {
1582                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1583                         return;
1584                 }
1585
1586                 $owner = User::getOwnerDataById($uid);
1587
1588                 if (empty($id)) {
1589                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1590                 }
1591
1592                 $data = ['@context' => ActivityPub::CONTEXT,
1593                         'id' => $id,
1594                         'type' => $activity,
1595                         'actor' => $owner['url'],
1596                         'object' => $profile['url'],
1597                         'instrument' => self::getService(),
1598                         'to' => [$profile['url']]];
1599
1600                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1601
1602                 $signed = LDSignature::sign($data, $owner);
1603                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1604         }
1605
1606         /**
1607          * Transmits a "follow object" activity to a target
1608          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1609          *
1610          * @param string  $object Object URL
1611          * @param string  $target Target profile
1612          * @param integer $uid    User ID
1613          * @return bool
1614          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1615          * @throws \ImagickException
1616          * @throws \Exception
1617          */
1618         public static function sendFollowObject($object, $target, $uid = 0)
1619         {
1620                 $profile = APContact::getByURL($target);
1621                 if (empty($profile['inbox'])) {
1622                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1623                         return;
1624                 }
1625
1626                 if (empty($uid)) {
1627                         // Fetch the list of administrators
1628                         $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1629
1630                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1631                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1632                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1633                         $uid = $first_user['uid'];
1634                 }
1635
1636                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1637                         'author-id' => Contact::getPublicIdByUserId($uid)];
1638                 if (Item::exists($condition)) {
1639                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1640                         return false;
1641                 }
1642
1643                 $owner = User::getOwnerDataById($uid);
1644
1645                 $data = ['@context' => ActivityPub::CONTEXT,
1646                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1647                         'type' => 'Follow',
1648                         'actor' => $owner['url'],
1649                         'object' => $object,
1650                         'instrument' => self::getService(),
1651                         'to' => [$profile['url']]];
1652
1653                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1654
1655                 $signed = LDSignature::sign($data, $owner);
1656                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1657         }
1658
1659         /**
1660          * Transmit a message that the contact request had been accepted
1661          *
1662          * @param string  $target Target profile
1663          * @param         $id
1664          * @param integer $uid    User ID
1665          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1666          * @throws \ImagickException
1667          */
1668         public static function sendContactAccept($target, $id, $uid)
1669         {
1670                 $profile = APContact::getByURL($target);
1671                 if (empty($profile['inbox'])) {
1672                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1673                         return;
1674                 }
1675
1676                 $owner = User::getOwnerDataById($uid);
1677                 $data = ['@context' => ActivityPub::CONTEXT,
1678                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1679                         'type' => 'Accept',
1680                         'actor' => $owner['url'],
1681                         'object' => [
1682                                 'id' => (string)$id,
1683                                 'type' => 'Follow',
1684                                 'actor' => $profile['url'],
1685                                 'object' => $owner['url']
1686                         ],
1687                         'instrument' => self::getService(),
1688                         'to' => [$profile['url']]];
1689
1690                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1691
1692                 $signed = LDSignature::sign($data, $owner);
1693                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1694         }
1695
1696         /**
1697          * Reject a contact request or terminates the contact relation
1698          *
1699          * @param string  $target Target profile
1700          * @param         $id
1701          * @param integer $uid    User ID
1702          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1703          * @throws \ImagickException
1704          */
1705         public static function sendContactReject($target, $id, $uid)
1706         {
1707                 $profile = APContact::getByURL($target);
1708                 if (empty($profile['inbox'])) {
1709                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1710                         return;
1711                 }
1712
1713                 $owner = User::getOwnerDataById($uid);
1714                 $data = ['@context' => ActivityPub::CONTEXT,
1715                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1716                         'type' => 'Reject',
1717                         'actor' => $owner['url'],
1718                         'object' => [
1719                                 'id' => (string)$id,
1720                                 'type' => 'Follow',
1721                                 'actor' => $profile['url'],
1722                                 'object' => $owner['url']
1723                         ],
1724                         'instrument' => self::getService(),
1725                         'to' => [$profile['url']]];
1726
1727                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1728
1729                 $signed = LDSignature::sign($data, $owner);
1730                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1731         }
1732
1733         /**
1734          * Transmits a message that we don't want to follow this contact anymore
1735          *
1736          * @param string  $target Target profile
1737          * @param integer $uid    User ID
1738          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1739          * @throws \ImagickException
1740          * @throws \Exception
1741          */
1742         public static function sendContactUndo($target, $cid, $uid)
1743         {
1744                 $profile = APContact::getByURL($target);
1745                 if (empty($profile['inbox'])) {
1746                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1747                         return;
1748                 }
1749
1750                 $object_id = self::activityIDFromContact($cid);
1751                 if (empty($object_id)) {
1752                         return;
1753                 }
1754
1755                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1756
1757                 $owner = User::getOwnerDataById($uid);
1758                 $data = ['@context' => ActivityPub::CONTEXT,
1759                         'id' => $id,
1760                         'type' => 'Undo',
1761                         'actor' => $owner['url'],
1762                         'object' => ['id' => $object_id, 'type' => 'Follow',
1763                                 'actor' => $owner['url'],
1764                                 'object' => $profile['url']],
1765                         'instrument' => self::getService(),
1766                         'to' => [$profile['url']]];
1767
1768                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1769
1770                 $signed = LDSignature::sign($data, $owner);
1771                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1772         }
1773
1774         private static function prependMentions($body, array $permission_block)
1775         {
1776                 if (Config::get('system', 'disable_implicit_mentions')) {
1777                         return $body;
1778                 }
1779
1780                 $mentions = [];
1781
1782                 foreach ($permission_block['to'] as $profile_url) {
1783                         $profile = Contact::getDetailsByURL($profile_url);
1784                         if (!empty($profile['addr'])
1785                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1786                                 && !strstr($body, $profile['addr'])
1787                                 && !strstr($body, $profile_url)
1788                         ) {
1789                                 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1790                         }
1791                 }
1792
1793                 $mentions[] = $body;
1794
1795                 return implode(' ', $mentions);
1796         }
1797 }