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