]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
7d9d6626ce8d918132d945f0b2e24b2c363fdc17
[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['object'] = $item['thr-parent'];
558                 }
559
560                 $owner = User::getOwnerDataById($item['uid']);
561
562                 if (!$object_mode) {
563                         return LDSignature::sign($data, $owner);
564                 } else {
565                         return $data;
566                 }
567
568                 /// @todo Create "conversation" entry
569         }
570
571         /**
572          * Creates an object array for a given item id
573          *
574          * @param integer $item_id
575          *
576          * @return array with the object data
577          */
578         public static function createObjectFromItemID($item_id)
579         {
580                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
581
582                 if (!DBA::isResult($item)) {
583                         return false;
584                 }
585
586                 $data = ['@context' => ActivityPub::CONTEXT];
587                 $data = array_merge($data, self::createNote($item));
588
589                 return $data;
590         }
591
592         /**
593          * Returns a tag array for a given item array
594          *
595          * @param array $item
596          *
597          * @return array of tags
598          */
599         private static function createTagList($item)
600         {
601                 $tags = [];
602
603                 $terms = Term::tagArrayFromItemId($item['id']);
604                 foreach ($terms as $term) {
605                         if ($term['type'] == TERM_HASHTAG) {
606                                 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
607                         } elseif ($term['type'] == TERM_MENTION) {
608                                 $contact = Contact::getDetailsByURL($term['url']);
609                                 if (!empty($contact['addr'])) {
610                                         $mention = '@' . $contact['addr'];
611                                 } else {
612                                         $mention = '@' . $term['url'];
613                                 }
614
615                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
616                         }
617                 }
618                 return $tags;
619         }
620
621         /**
622          * Adds attachment data to the JSON document
623          *
624          * @param array $item Data of the item that is to be posted
625          * @param text $type Object type
626          *
627          * @return array with attachment data
628          */
629         private static function createAttachmentList($item, $type)
630         {
631                 $attachments = [];
632
633                 $arr = explode('[/attach],', $item['attach']);
634                 if (count($arr)) {
635                         foreach ($arr as $r) {
636                                 $matches = false;
637                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
638                                 if ($cnt) {
639                                         $attributes = ['type' => 'Document',
640                                                         'mediaType' => $matches[3],
641                                                         'url' => $matches[1],
642                                                         'name' => null];
643
644                                         if (trim($matches[4]) != '') {
645                                                 $attributes['name'] = trim($matches[4]);
646                                         }
647
648                                         $attachments[] = $attributes;
649                                 }
650                         }
651                 }
652
653                 if ($type != 'Note') {
654                         return $attachments;
655                 }
656
657                 // Simplify image codes
658                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
659
660                 // Grab all pictures and create attachments out of them
661                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
662                         foreach ($pictures[1] as $picture) {
663                                 $imgdata = Image::getInfoFromURL($picture);
664                                 if ($imgdata) {
665                                         $attachments[] = ['type' => 'Document',
666                                                 'mediaType' => $imgdata['mime'],
667                                                 'url' => $picture,
668                                                 'name' => null];
669                                 }
670                         }
671                 }
672
673                 return $attachments;
674         }
675
676         /**
677          * Remove image elements and replaces them with links to the image
678          *
679          * @param string $body
680          *
681          * @return string with replaced elements
682          */
683         private static function removePictures($body)
684         {
685                 // Simplify image codes
686                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
687
688                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
689                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
690
691                 return $body;
692         }
693
694         /**
695          * Fetches the "context" value for a givem item array from the "conversation" table
696          *
697          * @param array $item
698          *
699          * @return string with context url
700          */
701         private static function fetchContextURLForItem($item)
702         {
703                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
704                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
705                         $context_uri = $conversation['conversation-href'];
706                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
707                         $context_uri = $conversation['conversation-uri'];
708                 } else {
709                         $context_uri = $item['parent-uri'] . '#context';
710                 }
711                 return $context_uri;
712         }
713
714         /**
715          * Returns if the post contains sensitive content ("nsfw")
716          *
717          * @param integer $item_id
718          *
719          * @return boolean
720          */
721         private static function isSensitive($item_id)
722         {
723                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
724                 return DBA::exists('term', $condition);
725         }
726
727         /**
728          * Creates a note/article object array
729          *
730          * @param array $item
731          *
732          * @return array with the object data
733          */
734         public static function createNote($item)
735         {
736                 if (!empty($item['title'])) {
737                         $type = 'Article';
738                 } else {
739                         $type = 'Note';
740                 }
741
742                 if ($item['deleted']) {
743                         $type = 'Tombstone';
744                 }
745
746                 $data = [];
747                 $data['id'] = $item['uri'];
748                 $data['type'] = $type;
749
750                 if ($item['deleted']) {
751                         return $data;
752                 }
753
754                 $data['summary'] = null; // Ignore by now
755
756                 if ($item['uri'] != $item['thr-parent']) {
757                         $data['inReplyTo'] = $item['thr-parent'];
758                 } else {
759                         $data['inReplyTo'] = null;
760                 }
761
762                 $data['diaspora:guid'] = $item['guid'];
763                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
764
765                 if ($item['created'] != $item['edited']) {
766                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
767                 }
768
769                 $data['url'] = $item['plink'];
770                 $data['attributedTo'] = $item['author-link'];
771                 $data['actor'] = $item['author-link'];
772                 $data['sensitive'] = self::isSensitive($item['id']);
773                 $data['context'] = self::fetchContextURLForItem($item);
774
775                 if (!empty($item['title'])) {
776                         $data['name'] = BBCode::convert($item['title'], false, 7);
777                 }
778
779                 $body = $item['body'];
780
781                 if ($type == 'Note') {
782                         $body = self::removePictures($body);
783                 }
784
785                 $data['content'] = BBCode::convert($body, false, 7);
786                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
787
788                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
789                         $data['diaspora:comment'] = $item['signed_text'];
790                 }
791
792                 $data['attachment'] = self::createAttachmentList($item, $type);
793                 $data['tag'] = self::createTagList($item);
794                 $data = array_merge($data, self::createPermissionBlockForItem($item));
795
796                 return $data;
797         }
798
799         /**
800          * Transmits a profile deletion to a given inbox
801          *
802          * @param integer $uid User ID
803          * @param string $inbox Target inbox
804          */
805         public static function sendProfileDeletion($uid, $inbox)
806         {
807                 $owner = User::getOwnerDataById($uid);
808                 $profile = APContact::getByURL($owner['url']);
809
810                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
811                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
812                         'type' => 'Delete',
813                         'actor' => $owner['url'],
814                         'object' => $owner['url'],
815                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
816                         'to' => [ActivityPub::PUBLIC_COLLECTION],
817                         'cc' => []];
818
819                 $signed = LDSignature::sign($data, $owner);
820
821                 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
822                 HTTPSignature::transmit($signed, $inbox, $uid);
823         }
824
825         /**
826          * Transmits a profile change to a given inbox
827          *
828          * @param integer $uid User ID
829          * @param string $inbox Target inbox
830          */
831         public static function sendProfileUpdate($uid, $inbox)
832         {
833                 $owner = User::getOwnerDataById($uid);
834                 $profile = APContact::getByURL($owner['url']);
835
836                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
837                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
838                         'type' => 'Update',
839                         'actor' => $owner['url'],
840                         'object' => self::getProfile($uid),
841                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
842                         'to' => [$profile['followers']],
843                         'cc' => []];
844
845                 $signed = LDSignature::sign($data, $owner);
846
847                 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
848                 HTTPSignature::transmit($signed, $inbox, $uid);
849         }
850
851         /**
852          * Transmits a given activity to a target
853          *
854          * @param array $activity
855          * @param string $target Target profile
856          * @param integer $uid User ID
857          */
858         public static function sendActivity($activity, $target, $uid)
859         {
860                 $profile = APContact::getByURL($target);
861
862                 $owner = User::getOwnerDataById($uid);
863
864                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
865                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
866                         'type' => $activity,
867                         'actor' => $owner['url'],
868                         'object' => $profile['url'],
869                         'to' => $profile['url']];
870
871                 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
872
873                 $signed = LDSignature::sign($data, $owner);
874                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
875         }
876
877         /**
878          * Transmit a message that the contact request had been accepted
879          *
880          * @param string $target Target profile
881          * @param $id
882          * @param integer $uid User ID
883          */
884         public static function sendContactAccept($target, $id, $uid)
885         {
886                 $profile = APContact::getByURL($target);
887
888                 $owner = User::getOwnerDataById($uid);
889                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
890                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
891                         'type' => 'Accept',
892                         'actor' => $owner['url'],
893                         'object' => ['id' => $id, 'type' => 'Follow',
894                                 'actor' => $profile['url'],
895                                 'object' => $owner['url']],
896                         'to' => $profile['url']];
897
898                 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
899
900                 $signed = LDSignature::sign($data, $owner);
901                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
902         }
903
904         /**
905          * Reject a contact request or terminates the contact relation
906          *
907          * @param string $target Target profile
908          * @param $id
909          * @param integer $uid User ID
910          */
911         public static function sendContactReject($target, $id, $uid)
912         {
913                 $profile = APContact::getByURL($target);
914
915                 $owner = User::getOwnerDataById($uid);
916                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
917                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
918                         'type' => 'Reject',
919                         'actor' => $owner['url'],
920                         'object' => ['id' => $id, 'type' => 'Follow',
921                                 'actor' => $profile['url'],
922                                 'object' => $owner['url']],
923                         'to' => $profile['url']];
924
925                 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
926
927                 $signed = LDSignature::sign($data, $owner);
928                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
929         }
930
931         /**
932          * Transmits a message that we don't want to follow this contact anymore
933          *
934          * @param string $target Target profile
935          * @param integer $uid User ID
936          */
937         public static function sendContactUndo($target, $uid)
938         {
939                 $profile = APContact::getByURL($target);
940
941                 $id = System::baseUrl() . '/activity/' . System::createGUID();
942
943                 $owner = User::getOwnerDataById($uid);
944                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
945                         'id' => $id,
946                         'type' => 'Undo',
947                         'actor' => $owner['url'],
948                         'object' => ['id' => $id, 'type' => 'Follow',
949                                 'actor' => $owner['url'],
950                                 'object' => $profile['url']],
951                         'to' => $profile['url']];
952
953                 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
954
955                 $signed = LDSignature::sign($data, $owner);
956                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
957         }
958 }