]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
05d0c458679b2550764469fd21bf3f807a75791e
[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                 // Will be activated in a later step
311                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
312
313                 // For now only send to these contacts:
314                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
315
316                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
317
318                 $actor_profile = APContact::getByURL($item['author-link']);
319
320                 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
321
322                 if (!$item['private']) {
323                         $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
324
325                         $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
326                         if (!empty($actor_profile['followers'])) {
327                                 $data['cc'][] = $actor_profile['followers'];
328                         }
329
330                         foreach ($terms as $term) {
331                                 $profile = APContact::getByURL($term['url'], false);
332                                 if (!empty($profile)) {
333                                         $data['to'][] = $profile['url'];
334                                 }
335                         }
336                 } else {
337                         $receiver_list = Item::enumeratePermissions($item);
338
339                         $mentioned = [];
340
341                         foreach ($terms as $term) {
342                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
343                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
344                                         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
345                                         if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
346                                                 $data['to'][] = $profile['url'];
347                                         }
348                                 }
349                         }
350
351                         foreach ($receiver_list as $receiver) {
352                                 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => $networks]);
353                                 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
354                                         // BCC is currently deactivated, due to Pleroma and Mastodon not reacting like expected
355                                         // $data['bcc'][] = $profile['url'];
356                                         $data['cc'][] = $profile['url'];
357                                 }
358                         }
359                 }
360
361                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
362                 while ($parent = Item::fetch($parents)) {
363                         // Don't include data from future posts
364                         if ($parent['id'] >= $last_id) {
365                                 continue;
366                         }
367
368                         $profile = APContact::getByURL($parent['author-link'], false);
369                         if (!empty($profile)) {
370                                 if ($parent['uri'] == $item['thr-parent']) {
371                                         $data['to'][] = $profile['url'];
372                                 } else {
373                                         $data['cc'][] = $profile['url'];
374                                 }
375                         }
376
377                         if ($item['gravity'] != GRAVITY_PARENT) {
378                                 continue;
379                         }
380
381                         $profile = APContact::getByURL($parent['owner-link'], false);
382                         if (!empty($profile)) {
383                                 $data['cc'][] = $profile['url'];
384                         }
385                 }
386                 DBA::close($parents);
387
388                 $data['to'] = array_unique($data['to']);
389                 $data['cc'] = array_unique($data['cc']);
390                 $data['bcc'] = array_unique($data['bcc']);
391
392                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
393                         unset($data['to'][$key]);
394                 }
395
396                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
397                         unset($data['cc'][$key]);
398                 }
399
400                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
401                         unset($data['bcc'][$key]);
402                 }
403
404                 foreach ($data['to'] as $to) {
405                         if (($key = array_search($to, $data['cc'])) !== false) {
406                                 unset($data['cc'][$key]);
407                         }
408
409                         if (($key = array_search($to, $data['bcc'])) !== false) {
410                                 unset($data['bcc'][$key]);
411                         }
412                 }
413
414                 foreach ($data['cc'] as $cc) {
415                         if (($key = array_search($cc, $data['bcc'])) !== false) {
416                                 unset($data['bcc'][$key]);
417                         }
418                 }
419
420                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
421
422                 if (!$blindcopy) {
423                         unset($receivers['bcc']);
424                 }
425
426                 return $receivers;
427         }
428
429         /**
430          * Fetches a list of inboxes of followers of a given user
431          *
432          * @param integer $uid User ID
433          * @param boolean $personal fetch personal inboxes
434          *
435          * @return array of follower inboxes
436          */
437         public static function fetchTargetInboxesforUser($uid, $personal = false)
438         {
439                 $inboxes = [];
440
441                 // Will be activated in a later step
442                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
443
444                 // For now only send to these contacts:
445                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
446
447                 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
448
449                 if (!empty($uid)) {
450                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
451                 }
452
453                 $contacts = DBA::select('contact', ['url'], $condition);
454                 while ($contact = DBA::fetch($contacts)) {
455                         if (Network::isUrlBlocked($contact['url'])) {
456                                 continue;
457                         }
458
459                         $profile = APContact::getByURL($contact['url'], false);
460                         if (!empty($profile)) {
461                                 if (empty($profile['sharedinbox']) || $personal) {
462                                         $target = $profile['inbox'];
463                                 } else {
464                                         $target = $profile['sharedinbox'];
465                                 }
466                                 $inboxes[$target] = $target;
467                         }
468                 }
469                 DBA::close($contacts);
470
471                 return $inboxes;
472         }
473
474         /**
475          * Fetches an array of inboxes for the given item and user
476          *
477          * @param array $item
478          * @param integer $uid User ID
479          * @param boolean $personal fetch personal inboxes
480          * @param integer $last_id Last item id for adding receivers
481          *
482          * @return array with inboxes
483          */
484         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
485         {
486                 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
487                 if (empty($permissions)) {
488                         return [];
489                 }
490
491                 $inboxes = [];
492
493                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
494                         $item_profile = APContact::getByURL($item['author-link'], false);
495                 } else {
496                         $item_profile = APContact::getByURL($item['owner-link'], false);
497                 }
498
499                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
500                         if (empty($permissions[$element])) {
501                                 continue;
502                         }
503
504                         $blindcopy = in_array($element, ['bto', 'bcc']);
505
506                         foreach ($permissions[$element] as $receiver) {
507                                 if (Network::isUrlBlocked($receiver)) {
508                                         continue;
509                                 }
510
511                                 if ($receiver == $item_profile['followers']) {
512                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
513                                 } else {
514                                         $profile = APContact::getByURL($receiver, false);
515                                         if (!empty($profile)) {
516                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
517                                                         $target = $profile['inbox'];
518                                                 } else {
519                                                         $target = $profile['sharedinbox'];
520                                                 }
521                                                 $inboxes[$target] = $target;
522                                         }
523                                 }
524                         }
525                 }
526
527                 return $inboxes;
528         }
529
530         /**
531          * Returns the activity type of a given item
532          *
533          * @param array $item
534          *
535          * @return string with activity type
536          */
537         private static function getTypeOfItem($item)
538         {
539                 if (!empty(Diaspora::isReshare($item['body'], false))) {
540                         $type = 'Announce';
541                 } elseif ($item['verb'] == ACTIVITY_POST) {
542                         if ($item['created'] == $item['edited']) {
543                                 $type = 'Create';
544                         } else {
545                                 $type = 'Update';
546                         }
547                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
548                         $type = 'Like';
549                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
550                         $type = 'Dislike';
551                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
552                         $type = 'Accept';
553                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
554                         $type = 'Reject';
555                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
556                         $type = 'TentativeAccept';
557                 } else {
558                         $type = '';
559                 }
560
561                 return $type;
562         }
563
564         /**
565          * Creates the activity or fetches it from the cache
566          *
567          * @param integer $item_id
568          * @param boolean $force   Force new cache entry
569          *
570          * @return array with the activity
571          */
572         public static function createCachedActivityFromItem($item_id, $force = false)
573         {
574                 $cachekey = 'APDelivery:createActivity:' . $item_id;
575
576                 if (!$force) {
577                         $data = Cache::get($cachekey);
578                         if (!is_null($data)) {
579                                 return $data;
580                         }
581                 }
582
583                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
584
585                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
586                 return $data;
587         }
588
589         /**
590          * Creates an activity array for a given item id
591          *
592          * @param integer $item_id
593          * @param boolean $object_mode Is the activity item is used inside another object?
594          *
595          * @return array of activity
596          */
597         public static function createActivityFromItem($item_id, $object_mode = false)
598         {
599                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
600
601                 if (!DBA::isResult($item)) {
602                         return false;
603                 }
604
605                 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
606                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
607                 if (DBA::isResult($conversation)) {
608                         $data = json_decode($conversation['source']);
609                         if (!empty($data)) {
610                                 return $data;
611                         }
612                 }
613
614                 $type = self::getTypeOfItem($item);
615
616                 if (!$object_mode) {
617                         $data = ['@context' => ActivityPub::CONTEXT];
618
619                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
620                                 $type = 'Undo';
621                         } elseif ($item['deleted']) {
622                                 $type = 'Delete';
623                         }
624                 } else {
625                         $data = [];
626                 }
627
628                 $data['id'] = $item['uri'] . '#' . $type;
629                 $data['type'] = $type;
630                 $data['actor'] = $item['owner-link'];
631
632                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
633
634                 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
635
636                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
637
638                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
639                         $data['object'] = self::createNote($item);
640                 } elseif ($data['type'] == 'Announce') {
641                         $data['object'] = self::createAnnounce($item);
642                 } elseif ($data['type'] == 'Undo') {
643                         $data['object'] = self::createActivityFromItem($item_id, true);
644                 } else {
645                         $data['diaspora:guid'] = $item['guid'];
646                         if (!empty($item['signed_text'])) {
647                                 $data['diaspora:like'] = $item['signed_text'];
648                         }
649                         $data['object'] = $item['thr-parent'];
650                 }
651
652                 if (!empty($item['contact-uid'])) {
653                         $uid = $item['contact-uid'];
654                 } else {
655                         $uid = $item['uid'];
656                 }
657
658                 $owner = User::getOwnerDataById($uid);
659
660                 if (!$object_mode && !empty($owner)) {
661                         return LDSignature::sign($data, $owner);
662                 } else {
663                         return $data;
664                 }
665
666                 /// @todo Create "conversation" entry
667         }
668
669         /**
670          * Creates an object array for a given item id
671          *
672          * @param integer $item_id
673          *
674          * @return array with the object data
675          */
676         public static function createObjectFromItemID($item_id)
677         {
678                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
679
680                 if (!DBA::isResult($item)) {
681                         return false;
682                 }
683
684                 $data = ['@context' => ActivityPub::CONTEXT];
685                 $data = array_merge($data, self::createNote($item));
686
687                 return $data;
688         }
689
690         /**
691          * Creates a location entry for a given item array
692          *
693          * @param array $item
694          *
695          * @return array with location array
696          */
697         private static function createLocation($item)
698         {
699                 $location = ['type' => 'Place'];
700
701                 if (!empty($item['location'])) {
702                         $location['name'] = $item['location'];
703                 }
704
705                 $coord = [];
706
707                 if (empty($item['coord'])) {
708                         $coord = Map::getCoordinates($item['location']);
709                 } else {
710                         $coords = explode(' ', $item['coord']);
711                         if (count($coords) == 2) {
712                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
713                         }
714                 }
715
716                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
717                         $location['latitude'] = $coord['lat'];
718                         $location['longitude'] = $coord['lon'];
719                 }
720
721                 return $location;
722         }
723
724         /**
725          * Returns a tag array for a given item array
726          *
727          * @param array $item
728          *
729          * @return array of tags
730          */
731         private static function createTagList($item)
732         {
733                 $tags = [];
734
735                 $terms = Term::tagArrayFromItemId($item['id']);
736                 foreach ($terms as $term) {
737                         if ($term['type'] == TERM_HASHTAG) {
738                                 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
739                         } elseif ($term['type'] == TERM_MENTION) {
740                                 $contact = Contact::getDetailsByURL($term['url']);
741                                 if (!empty($contact['addr'])) {
742                                         $mention = '@' . $contact['addr'];
743                                 } else {
744                                         $mention = '@' . $term['url'];
745                                 }
746
747                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
748                         }
749                 }
750                 return $tags;
751         }
752
753         /**
754          * Adds attachment data to the JSON document
755          *
756          * @param array $item Data of the item that is to be posted
757          * @param text $type Object type
758          *
759          * @return array with attachment data
760          */
761         private static function createAttachmentList($item, $type)
762         {
763                 $attachments = [];
764
765                 $arr = explode('[/attach],', $item['attach']);
766                 if (count($arr)) {
767                         foreach ($arr as $r) {
768                                 $matches = false;
769                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
770                                 if ($cnt) {
771                                         $attributes = ['type' => 'Document',
772                                                         'mediaType' => $matches[3],
773                                                         'url' => $matches[1],
774                                                         'name' => null];
775
776                                         if (trim($matches[4]) != '') {
777                                                 $attributes['name'] = trim($matches[4]);
778                                         }
779
780                                         $attachments[] = $attributes;
781                                 }
782                         }
783                 }
784
785                 if ($type != 'Note') {
786                         return $attachments;
787                 }
788
789                 // Simplify image codes
790                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
791
792                 // Grab all pictures and create attachments out of them
793                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
794                         foreach ($pictures[1] as $picture) {
795                                 $imgdata = Image::getInfoFromURL($picture);
796                                 if ($imgdata) {
797                                         $attachments[] = ['type' => 'Document',
798                                                 'mediaType' => $imgdata['mime'],
799                                                 'url' => $picture,
800                                                 'name' => null];
801                                 }
802                         }
803                 }
804
805                 return $attachments;
806         }
807
808         /**
809          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
810          *
811          * @param array $match Matching values for the callback
812          * @return string Replaced mention
813          */
814         private static function mentionCallback($match)
815         {
816                 if (empty($match[1])) {
817                         return;
818                 }
819
820                 $data = Contact::getDetailsByURL($match[1]);
821                 if (empty($data) || empty($data['nick'])) {
822                         return;
823                 }
824
825                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
826         }
827
828         /**
829          * Remove image elements and replaces them with links to the image
830          *
831          * @param string $body
832          *
833          * @return string with replaced elements
834          */
835         private static function removePictures($body)
836         {
837                 // Simplify image codes
838                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
839
840                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
841                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
842
843                 return $body;
844         }
845
846         /**
847          * Fetches the "context" value for a givem item array from the "conversation" table
848          *
849          * @param array $item
850          *
851          * @return string with context url
852          */
853         private static function fetchContextURLForItem($item)
854         {
855                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
856                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
857                         $context_uri = $conversation['conversation-href'];
858                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
859                         $context_uri = $conversation['conversation-uri'];
860                 } else {
861                         $context_uri = $item['parent-uri'] . '#context';
862                 }
863                 return $context_uri;
864         }
865
866         /**
867          * Returns if the post contains sensitive content ("nsfw")
868          *
869          * @param integer $item_id
870          *
871          * @return boolean
872          */
873         private static function isSensitive($item_id)
874         {
875                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
876                 return DBA::exists('term', $condition);
877         }
878
879         /**
880          * Creates event data
881          *
882          * @param array $item
883          *
884          * @return array with the event data
885          */
886         public static function createEvent($item)
887         {
888                 $event = [];
889                 $event['name'] = $item['event-summary'];
890                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
891                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
892
893                 if (!$item['event-nofinish']) {
894                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
895                 }
896
897                 if (!empty($item['event-location'])) {
898                         $item['location'] = $item['event-location'];
899                         $event['location'] = self::createLocation($item);
900                 }
901
902                 return $event;
903         }
904
905         /**
906          * Creates a note/article object array
907          *
908          * @param array $item
909          *
910          * @return array with the object data
911          */
912         public static function createNote($item)
913         {
914                 if ($item['event-type'] == 'event') {
915                         $type = 'Event';
916                 } elseif (!empty($item['title'])) {
917                         $type = 'Article';
918                 } else {
919                         $type = 'Note';
920                 }
921
922                 if ($item['deleted']) {
923                         $type = 'Tombstone';
924                 }
925
926                 $data = [];
927                 $data['id'] = $item['uri'];
928                 $data['type'] = $type;
929
930                 if ($item['deleted']) {
931                         return $data;
932                 }
933
934                 $data['summary'] = null; // Ignore by now
935
936                 if ($item['uri'] != $item['thr-parent']) {
937                         $data['inReplyTo'] = $item['thr-parent'];
938                 } else {
939                         $data['inReplyTo'] = null;
940                 }
941
942                 $data['diaspora:guid'] = $item['guid'];
943                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
944
945                 if ($item['created'] != $item['edited']) {
946                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
947                 }
948
949                 $data['url'] = $item['plink'];
950                 $data['attributedTo'] = $item['author-link'];
951                 $data['sensitive'] = self::isSensitive($item['id']);
952                 $data['context'] = self::fetchContextURLForItem($item);
953
954                 if (!empty($item['title'])) {
955                         $data['name'] = BBCode::toPlaintext($item['title'], false);
956                 }
957
958                 $body = $item['body'];
959
960                 if ($type == 'Note') {
961                         $body = self::removePictures($body);
962                 }
963
964                 if ($type == 'Event') {
965                         $data = array_merge($data, self::createEvent($item));
966                 } else {
967                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
968                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
969
970                         $data['content'] = BBCode::convert($body, false, 7);
971                 }
972
973                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
974
975                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
976                         $data['diaspora:comment'] = $item['signed_text'];
977                 }
978
979                 $data['attachment'] = self::createAttachmentList($item, $type);
980                 $data['tag'] = self::createTagList($item);
981
982                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
983                         $data['location'] = self::createLocation($item);
984                 }
985
986                 if (!empty($item['app'])) {
987                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
988                 }
989
990                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
991
992                 return $data;
993         }
994
995         /**
996          * Creates an announce object entry
997          *
998          * @param array $item
999          *
1000          * @return string with announced object url
1001          */
1002         public static function createAnnounce($item)
1003         {
1004                 $announce = api_share_as_retweet($item);
1005                 if (empty($announce['plink'])) {
1006                         return self::createNote($item);
1007                 }
1008
1009                 return $announce['plink'];
1010         }
1011
1012         /**
1013          * Creates an activity id for a given contact id
1014          *
1015          * @param integer $cid Contact ID of target
1016          *
1017          * @return bool|string activity id
1018          */
1019         public static function activityIDFromContact($cid)
1020         {
1021                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1022                 if (!DBA::isResult($contact)) {
1023                         return false;
1024                 }
1025
1026                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1027                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1028                 return System::baseUrl() . '/activity/' . $uuid;
1029         }
1030
1031         /**
1032          * Transmits a contact suggestion to a given inbox
1033          *
1034          * @param integer $uid User ID
1035          * @param string $inbox Target inbox
1036          * @param integer $suggestion_id Suggestion ID
1037          *
1038          * @return boolean was the transmission successful?
1039          */
1040         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1041         {
1042                 $owner = User::getOwnerDataById($uid);
1043
1044                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1045
1046                 $data = ['@context' => ActivityPub::CONTEXT,
1047                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1048                         'type' => 'Announce',
1049                         'actor' => $owner['url'],
1050                         'object' => $suggestion['url'],
1051                         'content' => $suggestion['note'],
1052                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1053                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1054                         'cc' => []];
1055
1056                 $signed = LDSignature::sign($data, $owner);
1057
1058                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1059                 return HTTPSignature::transmit($signed, $inbox, $uid);
1060         }
1061
1062         /**
1063          * Transmits a profile relocation to a given inbox
1064          *
1065          * @param integer $uid User ID
1066          * @param string $inbox Target inbox
1067          *
1068          * @return boolean was the transmission successful?
1069          */
1070         public static function sendProfileRelocation($uid, $inbox)
1071         {
1072                 $owner = User::getOwnerDataById($uid);
1073
1074                 $data = ['@context' => ActivityPub::CONTEXT,
1075                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1076                         'type' => 'dfrn:relocate',
1077                         'actor' => $owner['url'],
1078                         'object' => $owner['url'],
1079                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1080                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1081                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1082                         'cc' => []];
1083
1084                 $signed = LDSignature::sign($data, $owner);
1085
1086                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1087                 return HTTPSignature::transmit($signed, $inbox, $uid);
1088         }
1089
1090         /**
1091          * Transmits a profile deletion to a given inbox
1092          *
1093          * @param integer $uid User ID
1094          * @param string $inbox Target inbox
1095          *
1096          * @return boolean was the transmission successful?
1097          */
1098         public static function sendProfileDeletion($uid, $inbox)
1099         {
1100                 $owner = User::getOwnerDataById($uid);
1101
1102                 $data = ['@context' => ActivityPub::CONTEXT,
1103                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1104                         'type' => 'Delete',
1105                         'actor' => $owner['url'],
1106                         'object' => $owner['url'],
1107                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1108                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1109                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1110                         'cc' => []];
1111
1112                 $signed = LDSignature::sign($data, $owner);
1113
1114                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1115                 return HTTPSignature::transmit($signed, $inbox, $uid);
1116         }
1117
1118         /**
1119          * Transmits a profile change to a given inbox
1120          *
1121          * @param integer $uid User ID
1122          * @param string $inbox Target inbox
1123          *
1124          * @return boolean was the transmission successful?
1125          */
1126         public static function sendProfileUpdate($uid, $inbox)
1127         {
1128                 $owner = User::getOwnerDataById($uid);
1129                 $profile = APContact::getByURL($owner['url']);
1130
1131                 $data = ['@context' => ActivityPub::CONTEXT,
1132                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1133                         'type' => 'Update',
1134                         'actor' => $owner['url'],
1135                         'object' => self::getProfile($uid),
1136                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1137                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1138                         'to' => [$profile['followers']],
1139                         'cc' => []];
1140
1141                 $signed = LDSignature::sign($data, $owner);
1142
1143                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1144                 return HTTPSignature::transmit($signed, $inbox, $uid);
1145         }
1146
1147         /**
1148          * Transmits a given activity to a target
1149          *
1150          * @param array $activity
1151          * @param string $target Target profile
1152          * @param integer $uid User ID
1153          * @param string $id activity id
1154          */
1155         public static function sendActivity($activity, $target, $uid, $id = '')
1156         {
1157                 $profile = APContact::getByURL($target);
1158
1159                 $owner = User::getOwnerDataById($uid);
1160
1161                 if (empty($id)) {
1162                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1163                 }
1164
1165                 $data = ['@context' => ActivityPub::CONTEXT,
1166                         'id' => $id,
1167                         'type' => $activity,
1168                         'actor' => $owner['url'],
1169                         'object' => $profile['url'],
1170                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1171                         'to' => [$profile['url']]];
1172
1173                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1174
1175                 $signed = LDSignature::sign($data, $owner);
1176                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1177         }
1178
1179         /**
1180          * Transmit a message that the contact request had been accepted
1181          *
1182          * @param string $target Target profile
1183          * @param $id
1184          * @param integer $uid User ID
1185          */
1186         public static function sendContactAccept($target, $id, $uid)
1187         {
1188                 $profile = APContact::getByURL($target);
1189
1190                 $owner = User::getOwnerDataById($uid);
1191                 $data = ['@context' => ActivityPub::CONTEXT,
1192                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1193                         'type' => 'Accept',
1194                         'actor' => $owner['url'],
1195                         'object' => ['id' => $id, 'type' => 'Follow',
1196                                 'actor' => $profile['url'],
1197                                 'object' => $owner['url']],
1198                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1199                         'to' => [$profile['url']]];
1200
1201                 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1202
1203                 $signed = LDSignature::sign($data, $owner);
1204                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1205         }
1206
1207         /**
1208          * Reject a contact request or terminates the contact relation
1209          *
1210          * @param string $target Target profile
1211          * @param $id
1212          * @param integer $uid User ID
1213          */
1214         public static function sendContactReject($target, $id, $uid)
1215         {
1216                 $profile = APContact::getByURL($target);
1217
1218                 $owner = User::getOwnerDataById($uid);
1219                 $data = ['@context' => ActivityPub::CONTEXT,
1220                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1221                         'type' => 'Reject',
1222                         'actor' => $owner['url'],
1223                         'object' => ['id' => $id, 'type' => 'Follow',
1224                                 'actor' => $profile['url'],
1225                                 'object' => $owner['url']],
1226                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1227                         'to' => [$profile['url']]];
1228
1229                 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1230
1231                 $signed = LDSignature::sign($data, $owner);
1232                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1233         }
1234
1235         /**
1236          * Transmits a message that we don't want to follow this contact anymore
1237          *
1238          * @param string $target Target profile
1239          * @param integer $cid Contact ID of target
1240          * @param integer $uid User ID
1241          */
1242         public static function sendContactUndo($target, $cid, $uid)
1243         {
1244                 $profile = APContact::getByURL($target);
1245
1246                 $object_id = self::activityIDFromContact($cid);
1247                 if (empty($object_id)) {
1248                         return;
1249                 }
1250
1251                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1252
1253                 $owner = User::getOwnerDataById($uid);
1254                 $data = ['@context' => ActivityPub::CONTEXT,
1255                         'id' => $id,
1256                         'type' => 'Undo',
1257                         'actor' => $owner['url'],
1258                         'object' => ['id' => $object_id, 'type' => 'Follow',
1259                                 'actor' => $owner['url'],
1260                                 'object' => $profile['url']],
1261                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1262                         'to' => [$profile['url']]];
1263
1264                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1265
1266                 $signed = LDSignature::sign($data, $owner);
1267                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1268         }
1269 }