We only need to fetch the content once
[friendica.git/.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                         $reshared = !empty($announce['plink']);
557                 }
558
559                 if ($reshared) {
560                         $type = 'Announce';
561                 } elseif ($item['verb'] == ACTIVITY_POST) {
562                         if ($item['created'] == $item['edited']) {
563                                 $type = 'Create';
564                         } else {
565                                 $type = 'Update';
566                         }
567                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
568                         $type = 'Like';
569                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
570                         $type = 'Dislike';
571                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
572                         $type = 'Accept';
573                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
574                         $type = 'Reject';
575                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
576                         $type = 'TentativeAccept';
577                 } else {
578                         $type = '';
579                 }
580
581                 return $type;
582         }
583
584         /**
585          * Creates the activity or fetches it from the cache
586          *
587          * @param integer $item_id
588          * @param boolean $force   Force new cache entry
589          *
590          * @return array with the activity
591          */
592         public static function createCachedActivityFromItem($item_id, $force = false)
593         {
594                 $cachekey = 'APDelivery:createActivity:' . $item_id;
595
596                 if (!$force) {
597                         $data = Cache::get($cachekey);
598                         if (!is_null($data)) {
599                                 return $data;
600                         }
601                 }
602
603                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
604
605                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
606                 return $data;
607         }
608
609         /**
610          * Creates an activity array for a given item id
611          *
612          * @param integer $item_id
613          * @param boolean $object_mode Is the activity item is used inside another object?
614          *
615          * @return array of activity
616          */
617         public static function createActivityFromItem($item_id, $object_mode = false)
618         {
619                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
620
621                 if (!DBA::isResult($item)) {
622                         return false;
623                 }
624
625                 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
626                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
627                 if (DBA::isResult($conversation)) {
628                         $data = json_decode($conversation['source']);
629                         if (!empty($data)) {
630                                 return $data;
631                         }
632                 }
633
634                 $type = self::getTypeOfItem($item);
635
636                 if (!$object_mode) {
637                         $data = ['@context' => ActivityPub::CONTEXT];
638
639                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
640                                 $type = 'Undo';
641                         } elseif ($item['deleted']) {
642                                 $type = 'Delete';
643                         }
644                 } else {
645                         $data = [];
646                 }
647
648                 $data['id'] = $item['uri'] . '#' . $type;
649                 $data['type'] = $type;
650                 $data['actor'] = $item['owner-link'];
651
652                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
653
654                 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
655
656                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
657
658                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
659                         $data['object'] = self::createNote($item);
660                 } elseif ($data['type'] == 'Announce') {
661                         $data['object'] = self::createAnnounce($item);
662                 } elseif ($data['type'] == 'Undo') {
663                         $data['object'] = self::createActivityFromItem($item_id, true);
664                 } else {
665                         $data['diaspora:guid'] = $item['guid'];
666                         if (!empty($item['signed_text'])) {
667                                 $data['diaspora:like'] = $item['signed_text'];
668                         }
669                         $data['object'] = $item['thr-parent'];
670                 }
671
672                 if (!empty($item['contact-uid'])) {
673                         $uid = $item['contact-uid'];
674                 } else {
675                         $uid = $item['uid'];
676                 }
677
678                 $owner = User::getOwnerDataById($uid);
679
680                 if (!$object_mode && !empty($owner)) {
681                         return LDSignature::sign($data, $owner);
682                 } else {
683                         return $data;
684                 }
685
686                 /// @todo Create "conversation" entry
687         }
688
689         /**
690          * Creates an object array for a given item id
691          *
692          * @param integer $item_id
693          *
694          * @return array with the object data
695          */
696         public static function createObjectFromItemID($item_id)
697         {
698                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
699
700                 if (!DBA::isResult($item)) {
701                         return false;
702                 }
703
704                 $data = ['@context' => ActivityPub::CONTEXT];
705                 $data = array_merge($data, self::createNote($item));
706
707                 return $data;
708         }
709
710         /**
711          * Creates a location entry for a given item array
712          *
713          * @param array $item
714          *
715          * @return array with location array
716          */
717         private static function createLocation($item)
718         {
719                 $location = ['type' => 'Place'];
720
721                 if (!empty($item['location'])) {
722                         $location['name'] = $item['location'];
723                 }
724
725                 $coord = [];
726
727                 if (empty($item['coord'])) {
728                         $coord = Map::getCoordinates($item['location']);
729                 } else {
730                         $coords = explode(' ', $item['coord']);
731                         if (count($coords) == 2) {
732                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
733                         }
734                 }
735
736                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
737                         $location['latitude'] = $coord['lat'];
738                         $location['longitude'] = $coord['lon'];
739                 }
740
741                 return $location;
742         }
743
744         /**
745          * Returns a tag array for a given item array
746          *
747          * @param array $item
748          *
749          * @return array of tags
750          */
751         private static function createTagList($item)
752         {
753                 $tags = [];
754
755                 $terms = Term::tagArrayFromItemId($item['id']);
756                 foreach ($terms as $term) {
757                         if ($term['type'] == TERM_HASHTAG) {
758                                 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
759                         } elseif ($term['type'] == TERM_MENTION) {
760                                 $contact = Contact::getDetailsByURL($term['url']);
761                                 if (!empty($contact['addr'])) {
762                                         $mention = '@' . $contact['addr'];
763                                 } else {
764                                         $mention = '@' . $term['url'];
765                                 }
766
767                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
768                         }
769                 }
770                 return $tags;
771         }
772
773         /**
774          * Adds attachment data to the JSON document
775          *
776          * @param array $item Data of the item that is to be posted
777          * @param text $type Object type
778          *
779          * @return array with attachment data
780          */
781         private static function createAttachmentList($item, $type)
782         {
783                 $attachments = [];
784
785                 $arr = explode('[/attach],', $item['attach']);
786                 if (count($arr)) {
787                         foreach ($arr as $r) {
788                                 $matches = false;
789                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
790                                 if ($cnt) {
791                                         $attributes = ['type' => 'Document',
792                                                         'mediaType' => $matches[3],
793                                                         'url' => $matches[1],
794                                                         'name' => null];
795
796                                         if (trim($matches[4]) != '') {
797                                                 $attributes['name'] = trim($matches[4]);
798                                         }
799
800                                         $attachments[] = $attributes;
801                                 }
802                         }
803                 }
804
805                 if ($type != 'Note') {
806                         return $attachments;
807                 }
808
809                 // Simplify image codes
810                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
811
812                 // Grab all pictures and create attachments out of them
813                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
814                         foreach ($pictures[1] as $picture) {
815                                 $imgdata = Image::getInfoFromURL($picture);
816                                 if ($imgdata) {
817                                         $attachments[] = ['type' => 'Document',
818                                                 'mediaType' => $imgdata['mime'],
819                                                 'url' => $picture,
820                                                 'name' => null];
821                                 }
822                         }
823                 }
824
825                 return $attachments;
826         }
827
828         /**
829          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
830          *
831          * @param array $match Matching values for the callback
832          * @return string Replaced mention
833          */
834         private static function mentionCallback($match)
835         {
836                 if (empty($match[1])) {
837                         return;
838                 }
839
840                 $data = Contact::getDetailsByURL($match[1]);
841                 if (empty($data) || empty($data['nick'])) {
842                         return;
843                 }
844
845                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
846         }
847
848         /**
849          * Remove image elements and replaces them with links to the image
850          *
851          * @param string $body
852          *
853          * @return string with replaced elements
854          */
855         private static function removePictures($body)
856         {
857                 // Simplify image codes
858                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
859
860                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
861                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
862
863                 return $body;
864         }
865
866         /**
867          * Fetches the "context" value for a givem item array from the "conversation" table
868          *
869          * @param array $item
870          *
871          * @return string with context url
872          */
873         private static function fetchContextURLForItem($item)
874         {
875                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
876                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
877                         $context_uri = $conversation['conversation-href'];
878                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
879                         $context_uri = $conversation['conversation-uri'];
880                 } else {
881                         $context_uri = $item['parent-uri'] . '#context';
882                 }
883                 return $context_uri;
884         }
885
886         /**
887          * Returns if the post contains sensitive content ("nsfw")
888          *
889          * @param integer $item_id
890          *
891          * @return boolean
892          */
893         private static function isSensitive($item_id)
894         {
895                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
896                 return DBA::exists('term', $condition);
897         }
898
899         /**
900          * Creates event data
901          *
902          * @param array $item
903          *
904          * @return array with the event data
905          */
906         public static function createEvent($item)
907         {
908                 $event = [];
909                 $event['name'] = $item['event-summary'];
910                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
911                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
912
913                 if (!$item['event-nofinish']) {
914                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
915                 }
916
917                 if (!empty($item['event-location'])) {
918                         $item['location'] = $item['event-location'];
919                         $event['location'] = self::createLocation($item);
920                 }
921
922                 return $event;
923         }
924
925         /**
926          * Creates a note/article object array
927          *
928          * @param array $item
929          *
930          * @return array with the object data
931          */
932         public static function createNote($item)
933         {
934                 if ($item['event-type'] == 'event') {
935                         $type = 'Event';
936                 } elseif (!empty($item['title'])) {
937                         $type = 'Article';
938                 } else {
939                         $type = 'Note';
940                 }
941
942                 if ($item['deleted']) {
943                         $type = 'Tombstone';
944                 }
945
946                 $data = [];
947                 $data['id'] = $item['uri'];
948                 $data['type'] = $type;
949
950                 if ($item['deleted']) {
951                         return $data;
952                 }
953
954                 $data['summary'] = null; // Ignore by now
955
956                 if ($item['uri'] != $item['thr-parent']) {
957                         $data['inReplyTo'] = $item['thr-parent'];
958                 } else {
959                         $data['inReplyTo'] = null;
960                 }
961
962                 $data['diaspora:guid'] = $item['guid'];
963                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
964
965                 if ($item['created'] != $item['edited']) {
966                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
967                 }
968
969                 $data['url'] = $item['plink'];
970                 $data['attributedTo'] = $item['author-link'];
971                 $data['sensitive'] = self::isSensitive($item['id']);
972                 $data['context'] = self::fetchContextURLForItem($item);
973
974                 if (!empty($item['title'])) {
975                         $data['name'] = BBCode::toPlaintext($item['title'], false);
976                 }
977
978                 $body = $item['body'];
979
980                 if ($type == 'Note') {
981                         $body = self::removePictures($body);
982                 }
983
984                 if ($type == 'Event') {
985                         $data = array_merge($data, self::createEvent($item));
986                 } else {
987                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
988                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
989
990                         $data['content'] = BBCode::convert($body, false, 7);
991                 }
992
993                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
994
995                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
996                         $data['diaspora:comment'] = $item['signed_text'];
997                 }
998
999                 $data['attachment'] = self::createAttachmentList($item, $type);
1000                 $data['tag'] = self::createTagList($item);
1001
1002                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1003                         $data['location'] = self::createLocation($item);
1004                 }
1005
1006                 if (!empty($item['app'])) {
1007                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1008                 }
1009
1010                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1011
1012                 return $data;
1013         }
1014
1015         /**
1016          * Creates an announce object entry
1017          *
1018          * @param array $item
1019          *
1020          * @return string with announced object url
1021          */
1022         public static function createAnnounce($item)
1023         {
1024                 $announce = api_share_as_retweet($item);
1025                 if (empty($announce['plink'])) {
1026                         return self::createNote($item);
1027                 }
1028
1029                 // Fetch the original id of the object
1030                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1031                 if (!empty($activity)) {
1032                         $ldactivity = JsonLD::compact($activity);
1033                         $id = JsonLD::fetchElement($ldactivity, '@id');
1034                         if (!empty($id)) {
1035                                 return $id;
1036                         }
1037                 }
1038
1039                 return self::createNote($item);
1040         }
1041
1042         /**
1043          * Creates an activity id for a given contact id
1044          *
1045          * @param integer $cid Contact ID of target
1046          *
1047          * @return bool|string activity id
1048          */
1049         public static function activityIDFromContact($cid)
1050         {
1051                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1052                 if (!DBA::isResult($contact)) {
1053                         return false;
1054                 }
1055
1056                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1057                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1058                 return System::baseUrl() . '/activity/' . $uuid;
1059         }
1060
1061         /**
1062          * Transmits a contact suggestion to a given inbox
1063          *
1064          * @param integer $uid User ID
1065          * @param string $inbox Target inbox
1066          * @param integer $suggestion_id Suggestion ID
1067          *
1068          * @return boolean was the transmission successful?
1069          */
1070         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1071         {
1072                 $owner = User::getOwnerDataById($uid);
1073
1074                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1075
1076                 $data = ['@context' => ActivityPub::CONTEXT,
1077                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1078                         'type' => 'Announce',
1079                         'actor' => $owner['url'],
1080                         'object' => $suggestion['url'],
1081                         'content' => $suggestion['note'],
1082                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1083                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1084                         'cc' => []];
1085
1086                 $signed = LDSignature::sign($data, $owner);
1087
1088                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1089                 return HTTPSignature::transmit($signed, $inbox, $uid);
1090         }
1091
1092         /**
1093          * Transmits a profile relocation to a given inbox
1094          *
1095          * @param integer $uid User ID
1096          * @param string $inbox Target inbox
1097          *
1098          * @return boolean was the transmission successful?
1099          */
1100         public static function sendProfileRelocation($uid, $inbox)
1101         {
1102                 $owner = User::getOwnerDataById($uid);
1103
1104                 $data = ['@context' => ActivityPub::CONTEXT,
1105                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1106                         'type' => 'dfrn:relocate',
1107                         'actor' => $owner['url'],
1108                         'object' => $owner['url'],
1109                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1110                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1111                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1112                         'cc' => []];
1113
1114                 $signed = LDSignature::sign($data, $owner);
1115
1116                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1117                 return HTTPSignature::transmit($signed, $inbox, $uid);
1118         }
1119
1120         /**
1121          * Transmits a profile deletion to a given inbox
1122          *
1123          * @param integer $uid User ID
1124          * @param string $inbox Target inbox
1125          *
1126          * @return boolean was the transmission successful?
1127          */
1128         public static function sendProfileDeletion($uid, $inbox)
1129         {
1130                 $owner = User::getOwnerDataById($uid);
1131
1132                 $data = ['@context' => ActivityPub::CONTEXT,
1133                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1134                         'type' => 'Delete',
1135                         'actor' => $owner['url'],
1136                         'object' => $owner['url'],
1137                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1138                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1139                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1140                         'cc' => []];
1141
1142                 $signed = LDSignature::sign($data, $owner);
1143
1144                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1145                 return HTTPSignature::transmit($signed, $inbox, $uid);
1146         }
1147
1148         /**
1149          * Transmits a profile change to a given inbox
1150          *
1151          * @param integer $uid User ID
1152          * @param string $inbox Target inbox
1153          *
1154          * @return boolean was the transmission successful?
1155          */
1156         public static function sendProfileUpdate($uid, $inbox)
1157         {
1158                 $owner = User::getOwnerDataById($uid);
1159                 $profile = APContact::getByURL($owner['url']);
1160
1161                 $data = ['@context' => ActivityPub::CONTEXT,
1162                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1163                         'type' => 'Update',
1164                         'actor' => $owner['url'],
1165                         'object' => self::getProfile($uid),
1166                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1167                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1168                         'to' => [$profile['followers']],
1169                         'cc' => []];
1170
1171                 $signed = LDSignature::sign($data, $owner);
1172
1173                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1174                 return HTTPSignature::transmit($signed, $inbox, $uid);
1175         }
1176
1177         /**
1178          * Transmits a given activity to a target
1179          *
1180          * @param array $activity
1181          * @param string $target Target profile
1182          * @param integer $uid User ID
1183          * @param string $id activity id
1184          */
1185         public static function sendActivity($activity, $target, $uid, $id = '')
1186         {
1187                 $profile = APContact::getByURL($target);
1188
1189                 $owner = User::getOwnerDataById($uid);
1190
1191                 if (empty($id)) {
1192                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1193                 }
1194
1195                 $data = ['@context' => ActivityPub::CONTEXT,
1196                         'id' => $id,
1197                         'type' => $activity,
1198                         'actor' => $owner['url'],
1199                         'object' => $profile['url'],
1200                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1201                         'to' => [$profile['url']]];
1202
1203                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1204
1205                 $signed = LDSignature::sign($data, $owner);
1206                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1207         }
1208
1209         /**
1210          * Transmit a message that the contact request had been accepted
1211          *
1212          * @param string $target Target profile
1213          * @param $id
1214          * @param integer $uid User ID
1215          */
1216         public static function sendContactAccept($target, $id, $uid)
1217         {
1218                 $profile = APContact::getByURL($target);
1219
1220                 $owner = User::getOwnerDataById($uid);
1221                 $data = ['@context' => ActivityPub::CONTEXT,
1222                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1223                         'type' => 'Accept',
1224                         'actor' => $owner['url'],
1225                         'object' => ['id' => $id, 'type' => 'Follow',
1226                                 'actor' => $profile['url'],
1227                                 'object' => $owner['url']],
1228                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1229                         'to' => [$profile['url']]];
1230
1231                 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1232
1233                 $signed = LDSignature::sign($data, $owner);
1234                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1235         }
1236
1237         /**
1238          * Reject a contact request or terminates the contact relation
1239          *
1240          * @param string $target Target profile
1241          * @param $id
1242          * @param integer $uid User ID
1243          */
1244         public static function sendContactReject($target, $id, $uid)
1245         {
1246                 $profile = APContact::getByURL($target);
1247
1248                 $owner = User::getOwnerDataById($uid);
1249                 $data = ['@context' => ActivityPub::CONTEXT,
1250                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1251                         'type' => 'Reject',
1252                         'actor' => $owner['url'],
1253                         'object' => ['id' => $id, 'type' => 'Follow',
1254                                 'actor' => $profile['url'],
1255                                 'object' => $owner['url']],
1256                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1257                         'to' => [$profile['url']]];
1258
1259                 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1260
1261                 $signed = LDSignature::sign($data, $owner);
1262                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1263         }
1264
1265         /**
1266          * Transmits a message that we don't want to follow this contact anymore
1267          *
1268          * @param string $target Target profile
1269          * @param integer $cid Contact ID of target
1270          * @param integer $uid User ID
1271          */
1272         public static function sendContactUndo($target, $cid, $uid)
1273         {
1274                 $profile = APContact::getByURL($target);
1275
1276                 $object_id = self::activityIDFromContact($cid);
1277                 if (empty($object_id)) {
1278                         return;
1279                 }
1280
1281                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1282
1283                 $owner = User::getOwnerDataById($uid);
1284                 $data = ['@context' => ActivityPub::CONTEXT,
1285                         'id' => $id,
1286                         'type' => 'Undo',
1287                         'actor' => $owner['url'],
1288                         'object' => ['id' => $object_id, 'type' => 'Follow',
1289                                 'actor' => $owner['url'],
1290                                 'object' => $profile['url']],
1291                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1292                         'to' => [$profile['url']]];
1293
1294                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1295
1296                 $signed = LDSignature::sign($data, $owner);
1297                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1298         }
1299 }