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