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