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