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