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