]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
671f4279a2d21a04474830aeb854a4d59fd662ae
[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\Database\DBA;
9 use Friendica\Core\Logger;
10 use Friendica\Core\System;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\APContact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Util\JsonLD;
22 use Friendica\Util\LDSignature;
23 use Friendica\Model\Profile;
24 use Friendica\Core\Config;
25 use Friendica\Object\Image;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Protocol\Diaspora;
28 use Friendica\Core\Cache;
29 use Friendica\Util\Map;
30 use Friendica\Util\Network;
31
32 require_once 'include/api.php';
33
34 /**
35  * @brief ActivityPub Transmitter Protocol class
36  *
37  * To-Do:
38  * - Undo Announce
39  */
40 class Transmitter
41 {
42         /**
43          * collects the lost of followers of the given owner
44          *
45          * @param array $owner Owner array
46          * @param integer $page Page number
47          *
48          * @return array of owners
49          */
50         public static function getFollowers($owner, $page = null)
51         {
52                 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
53                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
54                 $count = DBA::count('contact', $condition);
55
56                 $data = ['@context' => ActivityPub::CONTEXT];
57                 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
58                 $data['type'] = 'OrderedCollection';
59                 $data['totalItems'] = $count;
60
61                 // When we hide our friends we will only show the pure number but don't allow more.
62                 $profile = Profile::getByUID($owner['uid']);
63                 if (!empty($profile['hide-friends'])) {
64                         return $data;
65                 }
66
67                 if (empty($page)) {
68                         $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
69                 } else {
70                         $list = [];
71
72                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
73                         while ($contact = DBA::fetch($contacts)) {
74                                 $list[] = $contact['url'];
75                         }
76
77                         if (!empty($list)) {
78                                 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
79                         }
80
81                         $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
82
83                         $data['orderedItems'] = $list;
84                 }
85
86                 return $data;
87         }
88
89         /**
90          * Create list of following contacts
91          *
92          * @param array $owner Owner array
93          * @param integer $page Page numbe
94          *
95          * @return array of following contacts
96          */
97         public static function getFollowing($owner, $page = null)
98         {
99                 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
100                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
101                 $count = DBA::count('contact', $condition);
102
103                 $data = ['@context' => ActivityPub::CONTEXT];
104                 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
105                 $data['type'] = 'OrderedCollection';
106                 $data['totalItems'] = $count;
107
108                 // When we hide our friends we will only show the pure number but don't allow more.
109                 $profile = Profile::getByUID($owner['uid']);
110                 if (!empty($profile['hide-friends'])) {
111                         return $data;
112                 }
113
114                 if (empty($page)) {
115                         $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
116                 } else {
117                         $list = [];
118
119                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
120                         while ($contact = DBA::fetch($contacts)) {
121                                 $list[] = $contact['url'];
122                         }
123
124                         if (!empty($list)) {
125                                 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
126                         }
127
128                         $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
129
130                         $data['orderedItems'] = $list;
131                 }
132
133                 return $data;
134         }
135
136         /**
137          * Public posts for the given owner
138          *
139          * @param array $owner Owner array
140          * @param integer $page Page numbe
141          *
142          * @return array of posts
143          */
144         public static function getOutbox($owner, $page = null)
145         {
146                 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
147
148                 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
149                         'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
150                         'deleted' => false, 'visible' => true];
151                 $count = DBA::count('item', $condition);
152
153                 $data = ['@context' => ActivityPub::CONTEXT];
154                 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
155                 $data['type'] = 'OrderedCollection';
156                 $data['totalItems'] = $count;
157
158                 if (empty($page)) {
159                         $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
160                 } else {
161                         $list = [];
162
163                         $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
164
165                         $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
166                         while ($item = Item::fetch($items)) {
167                                 $object = self::createObjectFromItemID($item['id']);
168                                 unset($object['@context']);
169                                 $list[] = $object;
170                         }
171
172                         if (!empty($list)) {
173                                 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
174                         }
175
176                         $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
177
178                         $data['orderedItems'] = $list;
179                 }
180
181                 return $data;
182         }
183
184         /**
185          * Return the ActivityPub profile of the given user
186          *
187          * @param integer $uid User ID
188          * @return array with profile data
189          */
190         public static function getProfile($uid)
191         {
192                 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
193                         'account_removed' => false, 'verified' => true];
194                 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
195                 $user = DBA::selectFirst('user', $fields, $condition);
196                 if (!DBA::isResult($user)) {
197                         return [];
198                 }
199
200                 $fields = ['locality', 'region', 'country-name'];
201                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
202                 if (!DBA::isResult($profile)) {
203                         return [];
204                 }
205
206                 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
207                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
208                 if (!DBA::isResult($contact)) {
209                         return [];
210                 }
211
212                 // On old installations and never changed contacts this might not be filled
213                 if (empty($contact['avatar'])) {
214                         $contact['avatar'] = $contact['photo'];
215                 }
216
217                 $data = ['@context' => ActivityPub::CONTEXT];
218                 $data['id'] = $contact['url'];
219                 $data['diaspora:guid'] = $user['guid'];
220                 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
221                 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
222                 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
223                 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
224                 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
225                 $data['preferredUsername'] = $user['nickname'];
226                 $data['name'] = $contact['name'];
227                 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
228                         'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
229                 $data['summary'] = $contact['about'];
230                 $data['url'] = $contact['url'];
231                 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
232                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
233                         'owner' => $contact['url'],
234                         'publicKeyPem' => $user['pubkey']];
235                 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
236                 $data['icon'] = ['type' => 'Image',
237                         'url' => $contact['avatar']];
238
239                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
240                 return $data;
241         }
242
243         /**
244          * Returns an array with permissions of a given item array
245          *
246          * @param array $item
247          *
248          * @return array with permissions
249          */
250         private static function fetchPermissionBlockFromConversation($item)
251         {
252                 if (empty($item['thr-parent'])) {
253                         return [];
254                 }
255
256                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
257                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
258                 if (!DBA::isResult($conversation)) {
259                         return [];
260                 }
261
262                 $activity = json_decode($conversation['source'], true);
263
264                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
265                 $profile = APContact::getByURL($actor);
266
267                 $item_profile = APContact::getByURL($item['author-link']);
268                 $exclude[] = $item['author-link'];
269
270                 if ($item['gravity'] == GRAVITY_PARENT) {
271                         $exclude[] = $item['owner-link'];
272                 }
273
274                 $permissions['to'][] = $actor;
275
276                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
277                         if (empty($activity[$element])) {
278                                 continue;
279                         }
280                         if (is_string($activity[$element])) {
281                                 $activity[$element] = [$activity[$element]];
282                         }
283
284                         foreach ($activity[$element] as $receiver) {
285                                 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
286                                         $permissions[$element][] = $item_profile['followers'];
287                                 } elseif (!in_array($receiver, $exclude)) {
288                                         $permissions[$element][] = $receiver;
289                                 }
290                         }
291                 }
292                 return $permissions;
293         }
294
295         /**
296          * Creates an array of permissions from an item thread
297          *
298          * @param array $item
299          * @param boolean $blindcopy
300          * @param boolean $last_id
301          *
302          * @return array with permission data
303          */
304         private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
305         {
306                 if ($last_id == 0) {
307                         $last_id = $item['id'];
308                 }
309
310                 $always_bcc = false;
311
312                 // Check if we should always deliver our stuff via BCC
313                 if (!empty($item['uid'])) {
314                         $profile = Profile::getByUID($item['uid']);
315                         if (!empty($profile)) {
316                                 $always_bcc = $profile['hide-friends'];
317                         }
318                 }
319
320                 // Will be activated in a later step
321                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
322
323                 // For now only send to these contacts:
324                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
325
326                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
327
328                 $actor_profile = APContact::getByURL($item['author-link']);
329
330                 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
331
332                 if (!$item['private']) {
333                         $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
334
335                         $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
336                         if (!empty($actor_profile['followers'])) {
337                                 $data['cc'][] = $actor_profile['followers'];
338                         }
339
340                         foreach ($terms as $term) {
341                                 $profile = APContact::getByURL($term['url'], false);
342                                 if (!empty($profile)) {
343                                         $data['to'][] = $profile['url'];
344                                 }
345                         }
346                 } else {
347                         $receiver_list = Item::enumeratePermissions($item);
348
349                         $mentioned = [];
350
351                         foreach ($terms as $term) {
352                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
353                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
354                                         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
355                                         if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
356                                                 $data['to'][] = $profile['url'];
357                                         }
358                                 }
359                         }
360
361                         foreach ($receiver_list as $receiver) {
362                                 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
363                                 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
364                                         if ($contact['hidden'] || $always_bcc) {
365                                                 $data['bcc'][] = $profile['url'];
366                                         } else {
367                                                 $data['cc'][] = $profile['url'];
368                                         }
369                                 }
370                         }
371                 }
372
373                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
374                 while ($parent = Item::fetch($parents)) {
375                         // Don't include data from future posts
376                         if ($parent['id'] >= $last_id) {
377                                 continue;
378                         }
379
380                         $profile = APContact::getByURL($parent['author-link'], false);
381                         if (!empty($profile)) {
382                                 if ($parent['uri'] == $item['thr-parent']) {
383                                         $data['to'][] = $profile['url'];
384                                 } else {
385                                         $data['cc'][] = $profile['url'];
386                                 }
387                         }
388
389                         if ($item['gravity'] != GRAVITY_PARENT) {
390                                 continue;
391                         }
392
393                         $profile = APContact::getByURL($parent['owner-link'], false);
394                         if (!empty($profile)) {
395                                 $data['cc'][] = $profile['url'];
396                         }
397                 }
398                 DBA::close($parents);
399
400                 $data['to'] = array_unique($data['to']);
401                 $data['cc'] = array_unique($data['cc']);
402                 $data['bcc'] = array_unique($data['bcc']);
403
404                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
405                         unset($data['to'][$key]);
406                 }
407
408                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
409                         unset($data['cc'][$key]);
410                 }
411
412                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
413                         unset($data['bcc'][$key]);
414                 }
415
416                 foreach ($data['to'] as $to) {
417                         if (($key = array_search($to, $data['cc'])) !== false) {
418                                 unset($data['cc'][$key]);
419                         }
420
421                         if (($key = array_search($to, $data['bcc'])) !== false) {
422                                 unset($data['bcc'][$key]);
423                         }
424                 }
425
426                 foreach ($data['cc'] as $cc) {
427                         if (($key = array_search($cc, $data['bcc'])) !== false) {
428                                 unset($data['bcc'][$key]);
429                         }
430                 }
431
432                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
433
434                 if (!$blindcopy) {
435                         unset($receivers['bcc']);
436                 }
437
438                 return $receivers;
439         }
440
441         /**
442          * Fetches a list of inboxes of followers of a given user
443          *
444          * @param integer $uid User ID
445          * @param boolean $personal fetch personal inboxes
446          *
447          * @return array of follower inboxes
448          */
449         public static function fetchTargetInboxesforUser($uid, $personal = false)
450         {
451                 $inboxes = [];
452
453                 // Will be activated in a later step
454                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
455
456                 // For now only send to these contacts:
457                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
458
459                 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
460
461                 if (!empty($uid)) {
462                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
463                 }
464
465                 $contacts = DBA::select('contact', ['url'], $condition);
466                 while ($contact = DBA::fetch($contacts)) {
467                         if (Network::isUrlBlocked($contact['url'])) {
468                                 continue;
469                         }
470
471                         $profile = APContact::getByURL($contact['url'], false);
472                         if (!empty($profile)) {
473                                 if (empty($profile['sharedinbox']) || $personal) {
474                                         $target = $profile['inbox'];
475                                 } else {
476                                         $target = $profile['sharedinbox'];
477                                 }
478                                 $inboxes[$target] = $target;
479                         }
480                 }
481                 DBA::close($contacts);
482
483                 return $inboxes;
484         }
485
486         /**
487          * Fetches an array of inboxes for the given item and user
488          *
489          * @param array $item
490          * @param integer $uid User ID
491          * @param boolean $personal fetch personal inboxes
492          * @param integer $last_id Last item id for adding receivers
493          *
494          * @return array with inboxes
495          */
496         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
497         {
498                 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
499                 if (empty($permissions)) {
500                         return [];
501                 }
502
503                 $inboxes = [];
504
505                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
506                         $item_profile = APContact::getByURL($item['author-link'], false);
507                 } else {
508                         $item_profile = APContact::getByURL($item['owner-link'], false);
509                 }
510
511                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
512                         if (empty($permissions[$element])) {
513                                 continue;
514                         }
515
516                         $blindcopy = in_array($element, ['bto', 'bcc']);
517
518                         foreach ($permissions[$element] as $receiver) {
519                                 if (Network::isUrlBlocked($receiver)) {
520                                         continue;
521                                 }
522
523                                 if ($receiver == $item_profile['followers']) {
524                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
525                                 } else {
526                                         $profile = APContact::getByURL($receiver, false);
527                                         if (!empty($profile)) {
528                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
529                                                         $target = $profile['inbox'];
530                                                 } else {
531                                                         $target = $profile['sharedinbox'];
532                                                 }
533                                                 $inboxes[$target] = $target;
534                                         }
535                                 }
536                         }
537                 }
538
539                 return $inboxes;
540         }
541
542         /**
543          * Returns the activity type of a given item
544          *
545          * @param array $item
546          *
547          * @return string with activity type
548          */
549         private static function getTypeOfItem($item)
550         {
551                 $reshared = false;
552
553                 // Only check for a reshare, if it is a real reshare and no quoted reshare
554                 if (strpos($item['body'], "[share") === 0) {
555                         $announce = api_share_as_retweet($item);
556                         if (!empty($announce['plink'])) {
557                                 $data = ActivityPub::fetchContent($announce['plink'], $item['uid']);
558                                 $reshared = !empty($data);
559                         }
560                 }
561
562                 if ($reshared) {
563                         $type = 'Announce';
564                 } elseif ($item['verb'] == ACTIVITY_POST) {
565                         if ($item['created'] == $item['edited']) {
566                                 $type = 'Create';
567                         } else {
568                                 $type = 'Update';
569                         }
570                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
571                         $type = 'Like';
572                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
573                         $type = 'Dislike';
574                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
575                         $type = 'Accept';
576                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
577                         $type = 'Reject';
578                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
579                         $type = 'TentativeAccept';
580                 } else {
581                         $type = '';
582                 }
583
584                 return $type;
585         }
586
587         /**
588          * Creates the activity or fetches it from the cache
589          *
590          * @param integer $item_id
591          * @param boolean $force   Force new cache entry
592          *
593          * @return array with the activity
594          */
595         public static function createCachedActivityFromItem($item_id, $force = false)
596         {
597                 $cachekey = 'APDelivery:createActivity:' . $item_id;
598
599                 if (!$force) {
600                         $data = Cache::get($cachekey);
601                         if (!is_null($data)) {
602                                 return $data;
603                         }
604                 }
605
606                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
607
608                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
609                 return $data;
610         }
611
612         /**
613          * Creates an activity array for a given item id
614          *
615          * @param integer $item_id
616          * @param boolean $object_mode Is the activity item is used inside another object?
617          *
618          * @return array of activity
619          */
620         public static function createActivityFromItem($item_id, $object_mode = false)
621         {
622                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
623
624                 if (!DBA::isResult($item)) {
625                         return false;
626                 }
627
628                 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
629                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
630                 if (DBA::isResult($conversation)) {
631                         $data = json_decode($conversation['source']);
632                         if (!empty($data)) {
633                                 return $data;
634                         }
635                 }
636
637                 $type = self::getTypeOfItem($item);
638
639                 if (!$object_mode) {
640                         $data = ['@context' => ActivityPub::CONTEXT];
641
642                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
643                                 $type = 'Undo';
644                         } elseif ($item['deleted']) {
645                                 $type = 'Delete';
646                         }
647                 } else {
648                         $data = [];
649                 }
650
651                 $data['id'] = $item['uri'] . '#' . $type;
652                 $data['type'] = $type;
653                 $data['actor'] = $item['owner-link'];
654
655                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
656
657                 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
658
659                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
660
661                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
662                         $data['object'] = self::createNote($item);
663                 } elseif ($data['type'] == 'Announce') {
664                         $data['object'] = self::createAnnounce($item);
665                 } elseif ($data['type'] == 'Undo') {
666                         $data['object'] = self::createActivityFromItem($item_id, true);
667                 } else {
668                         $data['diaspora:guid'] = $item['guid'];
669                         if (!empty($item['signed_text'])) {
670                                 $data['diaspora:like'] = $item['signed_text'];
671                         }
672                         $data['object'] = $item['thr-parent'];
673                 }
674
675                 if (!empty($item['contact-uid'])) {
676                         $uid = $item['contact-uid'];
677                 } else {
678                         $uid = $item['uid'];
679                 }
680
681                 $owner = User::getOwnerDataById($uid);
682
683                 if (!$object_mode && !empty($owner)) {
684                         return LDSignature::sign($data, $owner);
685                 } else {
686                         return $data;
687                 }
688
689                 /// @todo Create "conversation" entry
690         }
691
692         /**
693          * Creates an object array for a given item id
694          *
695          * @param integer $item_id
696          *
697          * @return array with the object data
698          */
699         public static function createObjectFromItemID($item_id)
700         {
701                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
702
703                 if (!DBA::isResult($item)) {
704                         return false;
705                 }
706
707                 $data = ['@context' => ActivityPub::CONTEXT];
708                 $data = array_merge($data, self::createNote($item));
709
710                 return $data;
711         }
712
713         /**
714          * Creates a location entry for a given item array
715          *
716          * @param array $item
717          *
718          * @return array with location array
719          */
720         private static function createLocation($item)
721         {
722                 $location = ['type' => 'Place'];
723
724                 if (!empty($item['location'])) {
725                         $location['name'] = $item['location'];
726                 }
727
728                 $coord = [];
729
730                 if (empty($item['coord'])) {
731                         $coord = Map::getCoordinates($item['location']);
732                 } else {
733                         $coords = explode(' ', $item['coord']);
734                         if (count($coords) == 2) {
735                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
736                         }
737                 }
738
739                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
740                         $location['latitude'] = $coord['lat'];
741                         $location['longitude'] = $coord['lon'];
742                 }
743
744                 return $location;
745         }
746
747         /**
748          * Returns a tag array for a given item array
749          *
750          * @param array $item
751          *
752          * @return array of tags
753          */
754         private static function createTagList($item)
755         {
756                 $tags = [];
757
758                 $terms = Term::tagArrayFromItemId($item['id']);
759                 foreach ($terms as $term) {
760                         if ($term['type'] == TERM_HASHTAG) {
761                                 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
762                         } elseif ($term['type'] == TERM_MENTION) {
763                                 $contact = Contact::getDetailsByURL($term['url']);
764                                 if (!empty($contact['addr'])) {
765                                         $mention = '@' . $contact['addr'];
766                                 } else {
767                                         $mention = '@' . $term['url'];
768                                 }
769
770                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
771                         }
772                 }
773                 return $tags;
774         }
775
776         /**
777          * Adds attachment data to the JSON document
778          *
779          * @param array $item Data of the item that is to be posted
780          * @param text $type Object type
781          *
782          * @return array with attachment data
783          */
784         private static function createAttachmentList($item, $type)
785         {
786                 $attachments = [];
787
788                 $arr = explode('[/attach],', $item['attach']);
789                 if (count($arr)) {
790                         foreach ($arr as $r) {
791                                 $matches = false;
792                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
793                                 if ($cnt) {
794                                         $attributes = ['type' => 'Document',
795                                                         'mediaType' => $matches[3],
796                                                         'url' => $matches[1],
797                                                         'name' => null];
798
799                                         if (trim($matches[4]) != '') {
800                                                 $attributes['name'] = trim($matches[4]);
801                                         }
802
803                                         $attachments[] = $attributes;
804                                 }
805                         }
806                 }
807
808                 if ($type != 'Note') {
809                         return $attachments;
810                 }
811
812                 // Simplify image codes
813                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
814
815                 // Grab all pictures and create attachments out of them
816                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
817                         foreach ($pictures[1] as $picture) {
818                                 $imgdata = Image::getInfoFromURL($picture);
819                                 if ($imgdata) {
820                                         $attachments[] = ['type' => 'Document',
821                                                 'mediaType' => $imgdata['mime'],
822                                                 'url' => $picture,
823                                                 'name' => null];
824                                 }
825                         }
826                 }
827
828                 return $attachments;
829         }
830
831         /**
832          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
833          *
834          * @param array $match Matching values for the callback
835          * @return string Replaced mention
836          */
837         private static function mentionCallback($match)
838         {
839                 if (empty($match[1])) {
840                         return;
841                 }
842
843                 $data = Contact::getDetailsByURL($match[1]);
844                 if (empty($data) || empty($data['nick'])) {
845                         return;
846                 }
847
848                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
849         }
850
851         /**
852          * Remove image elements and replaces them with links to the image
853          *
854          * @param string $body
855          *
856          * @return string with replaced elements
857          */
858         private static function removePictures($body)
859         {
860                 // Simplify image codes
861                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
862
863                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
864                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
865
866                 return $body;
867         }
868
869         /**
870          * Fetches the "context" value for a givem item array from the "conversation" table
871          *
872          * @param array $item
873          *
874          * @return string with context url
875          */
876         private static function fetchContextURLForItem($item)
877         {
878                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
879                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
880                         $context_uri = $conversation['conversation-href'];
881                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
882                         $context_uri = $conversation['conversation-uri'];
883                 } else {
884                         $context_uri = $item['parent-uri'] . '#context';
885                 }
886                 return $context_uri;
887         }
888
889         /**
890          * Returns if the post contains sensitive content ("nsfw")
891          *
892          * @param integer $item_id
893          *
894          * @return boolean
895          */
896         private static function isSensitive($item_id)
897         {
898                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
899                 return DBA::exists('term', $condition);
900         }
901
902         /**
903          * Creates event data
904          *
905          * @param array $item
906          *
907          * @return array with the event data
908          */
909         public static function createEvent($item)
910         {
911                 $event = [];
912                 $event['name'] = $item['event-summary'];
913                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
914                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
915
916                 if (!$item['event-nofinish']) {
917                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
918                 }
919
920                 if (!empty($item['event-location'])) {
921                         $item['location'] = $item['event-location'];
922                         $event['location'] = self::createLocation($item);
923                 }
924
925                 return $event;
926         }
927
928         /**
929          * Creates a note/article object array
930          *
931          * @param array $item
932          *
933          * @return array with the object data
934          */
935         public static function createNote($item)
936         {
937                 if ($item['event-type'] == 'event') {
938                         $type = 'Event';
939                 } elseif (!empty($item['title'])) {
940                         $type = 'Article';
941                 } else {
942                         $type = 'Note';
943                 }
944
945                 if ($item['deleted']) {
946                         $type = 'Tombstone';
947                 }
948
949                 $data = [];
950                 $data['id'] = $item['uri'];
951                 $data['type'] = $type;
952
953                 if ($item['deleted']) {
954                         return $data;
955                 }
956
957                 $data['summary'] = null; // Ignore by now
958
959                 if ($item['uri'] != $item['thr-parent']) {
960                         $data['inReplyTo'] = $item['thr-parent'];
961                 } else {
962                         $data['inReplyTo'] = null;
963                 }
964
965                 $data['diaspora:guid'] = $item['guid'];
966                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
967
968                 if ($item['created'] != $item['edited']) {
969                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
970                 }
971
972                 $data['url'] = $item['plink'];
973                 $data['attributedTo'] = $item['author-link'];
974                 $data['sensitive'] = self::isSensitive($item['id']);
975                 $data['context'] = self::fetchContextURLForItem($item);
976
977                 if (!empty($item['title'])) {
978                         $data['name'] = BBCode::toPlaintext($item['title'], false);
979                 }
980
981                 $body = $item['body'];
982
983                 if ($type == 'Note') {
984                         $body = self::removePictures($body);
985                 }
986
987                 if ($type == 'Event') {
988                         $data = array_merge($data, self::createEvent($item));
989                 } else {
990                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
991                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
992
993                         $data['content'] = BBCode::convert($body, false, 7);
994                 }
995
996                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
997
998                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
999                         $data['diaspora:comment'] = $item['signed_text'];
1000                 }
1001
1002                 $data['attachment'] = self::createAttachmentList($item, $type);
1003                 $data['tag'] = self::createTagList($item);
1004
1005                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1006                         $data['location'] = self::createLocation($item);
1007                 }
1008
1009                 if (!empty($item['app'])) {
1010                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1011                 }
1012
1013                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1014
1015                 return $data;
1016         }
1017
1018         /**
1019          * Creates an announce object entry
1020          *
1021          * @param array $item
1022          *
1023          * @return string with announced object url
1024          */
1025         public static function createAnnounce($item)
1026         {
1027                 $announce = api_share_as_retweet($item);
1028                 if (empty($announce['plink'])) {
1029                         return self::createNote($item);
1030                 }
1031
1032                 // Fetch the original id of the object
1033                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1034                 if (!empty($activity)) {
1035                         $ldactivity = JsonLD::compact($activity);
1036                         $id = JsonLD::fetchElement($ldactivity, '@id');
1037                         if (!empty($id)) {
1038                                 return $id;
1039                         }
1040                 }
1041
1042                 return self::createNote($item);
1043         }
1044
1045         /**
1046          * Creates an activity id for a given contact id
1047          *
1048          * @param integer $cid Contact ID of target
1049          *
1050          * @return bool|string activity id
1051          */
1052         public static function activityIDFromContact($cid)
1053         {
1054                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1055                 if (!DBA::isResult($contact)) {
1056                         return false;
1057                 }
1058
1059                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1060                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1061                 return System::baseUrl() . '/activity/' . $uuid;
1062         }
1063
1064         /**
1065          * Transmits a contact suggestion to a given inbox
1066          *
1067          * @param integer $uid User ID
1068          * @param string $inbox Target inbox
1069          * @param integer $suggestion_id Suggestion ID
1070          *
1071          * @return boolean was the transmission successful?
1072          */
1073         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1074         {
1075                 $owner = User::getOwnerDataById($uid);
1076
1077                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1078
1079                 $data = ['@context' => ActivityPub::CONTEXT,
1080                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1081                         'type' => 'Announce',
1082                         'actor' => $owner['url'],
1083                         'object' => $suggestion['url'],
1084                         'content' => $suggestion['note'],
1085                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1086                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1087                         'cc' => []];
1088
1089                 $signed = LDSignature::sign($data, $owner);
1090
1091                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1092                 return HTTPSignature::transmit($signed, $inbox, $uid);
1093         }
1094
1095         /**
1096          * Transmits a profile relocation to a given inbox
1097          *
1098          * @param integer $uid User ID
1099          * @param string $inbox Target inbox
1100          *
1101          * @return boolean was the transmission successful?
1102          */
1103         public static function sendProfileRelocation($uid, $inbox)
1104         {
1105                 $owner = User::getOwnerDataById($uid);
1106
1107                 $data = ['@context' => ActivityPub::CONTEXT,
1108                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1109                         'type' => 'dfrn:relocate',
1110                         'actor' => $owner['url'],
1111                         'object' => $owner['url'],
1112                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1113                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1114                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1115                         'cc' => []];
1116
1117                 $signed = LDSignature::sign($data, $owner);
1118
1119                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1120                 return HTTPSignature::transmit($signed, $inbox, $uid);
1121         }
1122
1123         /**
1124          * Transmits a profile deletion to a given inbox
1125          *
1126          * @param integer $uid User ID
1127          * @param string $inbox Target inbox
1128          *
1129          * @return boolean was the transmission successful?
1130          */
1131         public static function sendProfileDeletion($uid, $inbox)
1132         {
1133                 $owner = User::getOwnerDataById($uid);
1134
1135                 $data = ['@context' => ActivityPub::CONTEXT,
1136                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1137                         'type' => 'Delete',
1138                         'actor' => $owner['url'],
1139                         'object' => $owner['url'],
1140                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1141                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1142                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1143                         'cc' => []];
1144
1145                 $signed = LDSignature::sign($data, $owner);
1146
1147                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1148                 return HTTPSignature::transmit($signed, $inbox, $uid);
1149         }
1150
1151         /**
1152          * Transmits a profile change to a given inbox
1153          *
1154          * @param integer $uid User ID
1155          * @param string $inbox Target inbox
1156          *
1157          * @return boolean was the transmission successful?
1158          */
1159         public static function sendProfileUpdate($uid, $inbox)
1160         {
1161                 $owner = User::getOwnerDataById($uid);
1162                 $profile = APContact::getByURL($owner['url']);
1163
1164                 $data = ['@context' => ActivityPub::CONTEXT,
1165                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1166                         'type' => 'Update',
1167                         'actor' => $owner['url'],
1168                         'object' => self::getProfile($uid),
1169                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1170                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1171                         'to' => [$profile['followers']],
1172                         'cc' => []];
1173
1174                 $signed = LDSignature::sign($data, $owner);
1175
1176                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1177                 return HTTPSignature::transmit($signed, $inbox, $uid);
1178         }
1179
1180         /**
1181          * Transmits a given activity to a target
1182          *
1183          * @param array $activity
1184          * @param string $target Target profile
1185          * @param integer $uid User ID
1186          * @param string $id activity id
1187          */
1188         public static function sendActivity($activity, $target, $uid, $id = '')
1189         {
1190                 $profile = APContact::getByURL($target);
1191
1192                 $owner = User::getOwnerDataById($uid);
1193
1194                 if (empty($id)) {
1195                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1196                 }
1197
1198                 $data = ['@context' => ActivityPub::CONTEXT,
1199                         'id' => $id,
1200                         'type' => $activity,
1201                         'actor' => $owner['url'],
1202                         'object' => $profile['url'],
1203                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1204                         'to' => [$profile['url']]];
1205
1206                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1207
1208                 $signed = LDSignature::sign($data, $owner);
1209                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1210         }
1211
1212         /**
1213          * Transmit a message that the contact request had been accepted
1214          *
1215          * @param string $target Target profile
1216          * @param $id
1217          * @param integer $uid User ID
1218          */
1219         public static function sendContactAccept($target, $id, $uid)
1220         {
1221                 $profile = APContact::getByURL($target);
1222
1223                 $owner = User::getOwnerDataById($uid);
1224                 $data = ['@context' => ActivityPub::CONTEXT,
1225                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1226                         'type' => 'Accept',
1227                         'actor' => $owner['url'],
1228                         'object' => ['id' => $id, 'type' => 'Follow',
1229                                 'actor' => $profile['url'],
1230                                 'object' => $owner['url']],
1231                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1232                         'to' => [$profile['url']]];
1233
1234                 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1235
1236                 $signed = LDSignature::sign($data, $owner);
1237                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1238         }
1239
1240         /**
1241          * Reject a contact request or terminates the contact relation
1242          *
1243          * @param string $target Target profile
1244          * @param $id
1245          * @param integer $uid User ID
1246          */
1247         public static function sendContactReject($target, $id, $uid)
1248         {
1249                 $profile = APContact::getByURL($target);
1250
1251                 $owner = User::getOwnerDataById($uid);
1252                 $data = ['@context' => ActivityPub::CONTEXT,
1253                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1254                         'type' => 'Reject',
1255                         'actor' => $owner['url'],
1256                         'object' => ['id' => $id, 'type' => 'Follow',
1257                                 'actor' => $profile['url'],
1258                                 'object' => $owner['url']],
1259                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1260                         'to' => [$profile['url']]];
1261
1262                 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1263
1264                 $signed = LDSignature::sign($data, $owner);
1265                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1266         }
1267
1268         /**
1269          * Transmits a message that we don't want to follow this contact anymore
1270          *
1271          * @param string $target Target profile
1272          * @param integer $cid Contact ID of target
1273          * @param integer $uid User ID
1274          */
1275         public static function sendContactUndo($target, $cid, $uid)
1276         {
1277                 $profile = APContact::getByURL($target);
1278
1279                 $object_id = self::activityIDFromContact($cid);
1280                 if (empty($object_id)) {
1281                         return;
1282                 }
1283
1284                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1285
1286                 $owner = User::getOwnerDataById($uid);
1287                 $data = ['@context' => ActivityPub::CONTEXT,
1288                         'id' => $id,
1289                         'type' => 'Undo',
1290                         'actor' => $owner['url'],
1291                         'object' => ['id' => $object_id, 'type' => 'Follow',
1292                                 'actor' => $owner['url'],
1293                                 'object' => $profile['url']],
1294                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1295                         'to' => [$profile['url']]];
1296
1297                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1298
1299                 $signed = LDSignature::sign($data, $owner);
1300                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1301         }
1302 }