Merge pull request #7161 from nupplaphil/task/mod_toggle_mobile
[friendica.git/.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\Content\Feature;
9 use Friendica\Database\DBA;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
13 use Friendica\Util\HTTPSignature;
14 use Friendica\Core\Protocol;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\Contact;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Item;
19 use Friendica\Model\Term;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\Plaintext;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\LDSignature;
26 use Friendica\Model\Profile;
27 use Friendica\Object\Image;
28 use Friendica\Protocol\ActivityPub;
29 use Friendica\Core\Cache;
30 use Friendica\Util\Map;
31 use Friendica\Util\Network;
32
33 require_once 'include/api.php';
34 require_once 'mod/share.php';
35
36 /**
37  * @brief ActivityPub Transmitter Protocol class
38  *
39  * To-Do:
40  * - Undo Announce
41  */
42 class Transmitter
43 {
44         /**
45          * collects the lost of followers of the given owner
46          *
47          * @param array   $owner Owner array
48          * @param integer $page  Page number
49          *
50          * @return array of owners
51          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
52          */
53         public static function getFollowers($owner, $page = null)
54         {
55                 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
56                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
57                 $count = DBA::count('contact', $condition);
58
59                 $data = ['@context' => ActivityPub::CONTEXT];
60                 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
61                 $data['type'] = 'OrderedCollection';
62                 $data['totalItems'] = $count;
63
64                 // When we hide our friends we will only show the pure number but don't allow more.
65                 $profile = Profile::getByUID($owner['uid']);
66                 if (!empty($profile['hide-friends'])) {
67                         return $data;
68                 }
69
70                 if (empty($page)) {
71                         $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
72                 } else {
73                         $list = [];
74
75                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
76                         while ($contact = DBA::fetch($contacts)) {
77                                 $list[] = $contact['url'];
78                         }
79
80                         if (!empty($list)) {
81                                 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
82                         }
83
84                         $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
85
86                         $data['orderedItems'] = $list;
87                 }
88
89                 return $data;
90         }
91
92         /**
93          * Create list of following contacts
94          *
95          * @param array   $owner Owner array
96          * @param integer $page  Page numbe
97          *
98          * @return array of following contacts
99          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100          */
101         public static function getFollowing($owner, $page = null)
102         {
103                 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
104                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
105                 $count = DBA::count('contact', $condition);
106
107                 $data = ['@context' => ActivityPub::CONTEXT];
108                 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
109                 $data['type'] = 'OrderedCollection';
110                 $data['totalItems'] = $count;
111
112                 // When we hide our friends we will only show the pure number but don't allow more.
113                 $profile = Profile::getByUID($owner['uid']);
114                 if (!empty($profile['hide-friends'])) {
115                         return $data;
116                 }
117
118                 if (empty($page)) {
119                         $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
120                 } else {
121                         $list = [];
122
123                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
124                         while ($contact = DBA::fetch($contacts)) {
125                                 $list[] = $contact['url'];
126                         }
127
128                         if (!empty($list)) {
129                                 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
130                         }
131
132                         $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
133
134                         $data['orderedItems'] = $list;
135                 }
136
137                 return $data;
138         }
139
140         /**
141          * Public posts for the given owner
142          *
143          * @param array   $owner Owner array
144          * @param integer $page  Page numbe
145          *
146          * @return array of posts
147          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
148          * @throws \ImagickException
149          */
150         public static function getOutbox($owner, $page = null)
151         {
152                 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
153
154                 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
155                         'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
156                         'deleted' => false, 'visible' => true, 'moderated' => false];
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 service array containing information the used software and it's url
192          *
193          * @return array with service data
194          */
195         private static function getService()
196         {
197                 return ['type' => 'Service',
198                         'name' =>  FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
199                         'url' => BaseObject::getApp()->getBaseURL()];
200         }
201
202         /**
203          * Return the ActivityPub profile of the given user
204          *
205          * @param integer $uid User ID
206          * @return array with profile data
207          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208          */
209         public static function getProfile($uid)
210         {
211                 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
212                         'account_removed' => false, 'verified' => true];
213                 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
214                 $user = DBA::selectFirst('user', $fields, $condition);
215                 if (!DBA::isResult($user)) {
216                         return [];
217                 }
218
219                 $fields = ['locality', 'region', 'country-name'];
220                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
221                 if (!DBA::isResult($profile)) {
222                         return [];
223                 }
224
225                 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
226                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
227                 if (!DBA::isResult($contact)) {
228                         return [];
229                 }
230
231                 // On old installations and never changed contacts this might not be filled
232                 if (empty($contact['avatar'])) {
233                         $contact['avatar'] = $contact['photo'];
234                 }
235
236                 $data = ['@context' => ActivityPub::CONTEXT];
237                 $data['id'] = $contact['url'];
238                 $data['diaspora:guid'] = $user['guid'];
239                 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
240                 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
241                 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
242                 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
243                 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
244                 $data['preferredUsername'] = $user['nickname'];
245                 $data['name'] = $contact['name'];
246                 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
247                         'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
248                 $data['summary'] = $contact['about'];
249                 $data['url'] = $contact['url'];
250                 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
251                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
252                         'owner' => $contact['url'],
253                         'publicKeyPem' => $user['pubkey']];
254                 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
255                 $data['icon'] = ['type' => 'Image',
256                         'url' => $contact['avatar']];
257
258                 $data['generator'] = self::getService();
259
260                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
261                 return $data;
262         }
263
264         /**
265          * @param string $username
266          * @return array
267          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268          */
269         public static function getDeletedUser($username)
270         {
271                 return [
272                         '@context' => ActivityPub::CONTEXT,
273                         'id' => System::baseUrl() . '/profile/' . $username,
274                         'type' => 'Tombstone',
275                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
276                         'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
277                         'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
278                 ];
279         }
280
281         /**
282          * Returns an array with permissions of a given item array
283          *
284          * @param array $item
285          *
286          * @return array with permissions
287          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288          * @throws \ImagickException
289          */
290         private static function fetchPermissionBlockFromConversation($item)
291         {
292                 if (empty($item['thr-parent'])) {
293                         return [];
294                 }
295
296                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
297                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
298                 if (!DBA::isResult($conversation)) {
299                         return [];
300                 }
301
302                 $activity = json_decode($conversation['source'], true);
303
304                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
305                 $profile = APContact::getByURL($actor);
306
307                 $item_profile = APContact::getByURL($item['author-link']);
308                 $exclude[] = $item['author-link'];
309
310                 if ($item['gravity'] == GRAVITY_PARENT) {
311                         $exclude[] = $item['owner-link'];
312                 }
313
314                 $permissions['to'][] = $actor;
315
316                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
317                         if (empty($activity[$element])) {
318                                 continue;
319                         }
320                         if (is_string($activity[$element])) {
321                                 $activity[$element] = [$activity[$element]];
322                         }
323
324                         foreach ($activity[$element] as $receiver) {
325                                 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
326                                         $permissions[$element][] = $item_profile['followers'];
327                                 } elseif (!in_array($receiver, $exclude)) {
328                                         $permissions[$element][] = $receiver;
329                                 }
330                         }
331                 }
332                 return $permissions;
333         }
334
335         /**
336          * Creates an array of permissions from an item thread
337          *
338          * @param array   $item       Item array
339          * @param boolean $blindcopy  addressing via "bcc" or "cc"?
340          * @param integer $last_id    Last item id for adding receivers
341          * @param boolean $forum_mode "true" means that we are sending content to a forum
342          *
343          * @return array with permission data
344          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
345          * @throws \ImagickException
346          */
347         private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
348         {
349                 if ($last_id == 0) {
350                         $last_id = $item['id'];
351                 }
352
353                 $always_bcc = false;
354
355                 // Check if we should always deliver our stuff via BCC
356                 if (!empty($item['uid'])) {
357                         $profile = Profile::getByUID($item['uid']);
358                         if (!empty($profile)) {
359                                 $always_bcc = $profile['hide-friends'];
360                         }
361                 }
362
363                 if (Config::get('debug', 'total_ap_delivery')) {
364                         // Will be activated in a later step
365                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
366                 } else {
367                         // For now only send to these contacts:
368                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
369                 }
370
371                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
372
373                 if ($item['gravity'] == GRAVITY_PARENT) {
374                         $actor_profile = APContact::getByURL($item['owner-link']);
375                 } else {
376                         $actor_profile = APContact::getByURL($item['author-link']);
377                 }
378
379                 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
380
381                 if (!$item['private']) {
382                         $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
383
384                         $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
385
386                         foreach ($terms as $term) {
387                                 $profile = APContact::getByURL($term['url'], false);
388                                 if (!empty($profile)) {
389                                         $data['to'][] = $profile['url'];
390                                 }
391                         }
392                 } else {
393                         $receiver_list = Item::enumeratePermissions($item);
394
395                         foreach ($terms as $term) {
396                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
397                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
398                                         $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
399                                         if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
400                                                 continue;
401                                         }
402
403                                         if (!empty($profile = APContact::getByURL($contact['url'], false))) {
404                                                 $data['to'][] = $profile['url'];
405                                         }
406                                 }
407                         }
408
409                         foreach ($receiver_list as $receiver) {
410                                 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
411                                 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
412                                         continue;
413                                 }
414
415                                 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
416                                         if ($contact['hidden'] || $always_bcc) {
417                                                 $data['bcc'][] = $profile['url'];
418                                         } else {
419                                                 $data['cc'][] = $profile['url'];
420                                         }
421                                 }
422                         }
423                 }
424
425                 if (!empty($item['parent'])) {
426                         $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
427                         while ($parent = Item::fetch($parents)) {
428                                 if ($parent['gravity'] == GRAVITY_PARENT) {
429                                         $profile = APContact::getByURL($parent['owner-link'], false);
430                                         if (!empty($profile)) {
431                                                 if ($item['gravity'] != GRAVITY_PARENT) {
432                                                         // Comments to forums are directed to the forum
433                                                         // But comments to forums aren't directed to the followers collection
434                                                         if ($profile['type'] == 'Group') {
435                                                                 $data['to'][] = $profile['url'];
436                                                         } else {
437                                                                 $data['cc'][] = $profile['url'];
438                                                                 if (!$item['private']) {
439                                                                         $data['cc'][] = $actor_profile['followers'];
440                                                                 }
441                                                         }
442                                                 } else {
443                                                         // Public thread parent post always are directed to the followers
444                                                         if (!$item['private'] && !$forum_mode) {
445                                                                 $data['cc'][] = $actor_profile['followers'];
446                                                         }
447                                                 }
448                                         }
449                                 }
450
451                                 // Don't include data from future posts
452                                 if ($parent['id'] >= $last_id) {
453                                         continue;
454                                 }
455
456                                 $profile = APContact::getByURL($parent['author-link'], false);
457                                 if (!empty($profile)) {
458                                         if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
459                                                 $data['to'][] = $profile['url'];
460                                         } else {
461                                                 $data['cc'][] = $profile['url'];
462                                         }
463                                 }
464                         }
465                         DBA::close($parents);
466                 }
467
468                 $data['to'] = array_unique($data['to']);
469                 $data['cc'] = array_unique($data['cc']);
470                 $data['bcc'] = array_unique($data['bcc']);
471
472                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
473                         unset($data['to'][$key]);
474                 }
475
476                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
477                         unset($data['cc'][$key]);
478                 }
479
480                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
481                         unset($data['bcc'][$key]);
482                 }
483
484                 foreach ($data['to'] as $to) {
485                         if (($key = array_search($to, $data['cc'])) !== false) {
486                                 unset($data['cc'][$key]);
487                         }
488
489                         if (($key = array_search($to, $data['bcc'])) !== false) {
490                                 unset($data['bcc'][$key]);
491                         }
492                 }
493
494                 foreach ($data['cc'] as $cc) {
495                         if (($key = array_search($cc, $data['bcc'])) !== false) {
496                                 unset($data['bcc'][$key]);
497                         }
498                 }
499
500                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
501
502                 if (!$blindcopy) {
503                         unset($receivers['bcc']);
504                 }
505
506                 return $receivers;
507         }
508
509         /**
510          * Check if an inbox is archived
511          *
512          * @param string $url Inbox url
513          *
514          * @return boolean "true" if inbox is archived
515          */
516         private static function archivedInbox($url)
517         {
518                 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
519         }
520
521         /**
522          * Fetches a list of inboxes of followers of a given user
523          *
524          * @param integer $uid      User ID
525          * @param boolean $personal fetch personal inboxes
526          *
527          * @return array of follower inboxes
528          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529          * @throws \ImagickException
530          */
531         public static function fetchTargetInboxesforUser($uid, $personal = false)
532         {
533                 $inboxes = [];
534
535                 if (Config::get('debug', 'total_ap_delivery')) {
536                         // Will be activated in a later step
537                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
538                 } else {
539                         // For now only send to these contacts:
540                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
541                 }
542
543                 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
544
545                 if (!empty($uid)) {
546                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
547                 }
548
549                 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
550                 while ($contact = DBA::fetch($contacts)) {
551                         if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
552                                 continue;
553                         }
554
555                         if (Network::isUrlBlocked($contact['url'])) {
556                                 continue;
557                         }
558
559                         $profile = APContact::getByURL($contact['url'], false);
560                         if (!empty($profile)) {
561                                 if (empty($profile['sharedinbox']) || $personal) {
562                                         $target = $profile['inbox'];
563                                 } else {
564                                         $target = $profile['sharedinbox'];
565                                 }
566                                 if (!self::archivedInbox($target)) {
567                                         $inboxes[$target] = $target;
568                                 }
569                         }
570                 }
571                 DBA::close($contacts);
572
573                 return $inboxes;
574         }
575
576         /**
577          * Fetches an array of inboxes for the given item and user
578          *
579          * @param array   $item       Item array
580          * @param integer $uid        User ID
581          * @param boolean $personal   fetch personal inboxes
582          * @param integer $last_id    Last item id for adding receivers
583          * @param boolean $forum_mode "true" means that we are sending content to a forum
584          * @return array with inboxes
585          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
586          * @throws \ImagickException
587          */
588         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
589         {
590                 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
591                 if (empty($permissions)) {
592                         return [];
593                 }
594
595                 $inboxes = [];
596
597                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
598                         $item_profile = APContact::getByURL($item['author-link'], false);
599                 } else {
600                         $item_profile = APContact::getByURL($item['owner-link'], false);
601                 }
602
603                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
604                         if (empty($permissions[$element])) {
605                                 continue;
606                         }
607
608                         $blindcopy = in_array($element, ['bto', 'bcc']);
609
610                         foreach ($permissions[$element] as $receiver) {
611                                 if (Network::isUrlBlocked($receiver)) {
612                                         continue;
613                                 }
614
615                                 if ($receiver == $item_profile['followers']) {
616                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
617                                 } else {
618                                         $profile = APContact::getByURL($receiver, false);
619                                         if (!empty($profile)) {
620                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
621                                                         $target = $profile['inbox'];
622                                                 } else {
623                                                         $target = $profile['sharedinbox'];
624                                                 }
625                                                 if (!self::archivedInbox($target)) {
626                                                         $inboxes[$target] = $target;
627                                                 }
628                                         }
629                                 }
630                         }
631                 }
632
633                 return $inboxes;
634         }
635
636         /**
637          * Creates an array in the structure of the item table for a given mail id
638          *
639          * @param integer $mail_id
640          *
641          * @return array
642          * @throws \Exception
643          */
644         public static function ItemArrayFromMail($mail_id)
645         {
646                 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
647
648                 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
649
650                 // Making the post more compatible for Mastodon by:
651                 // - Making it a note and not an article (no title)
652                 // - Moving the title into the "summary" field that is used as a "content warning"
653                 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
654                 $mail['title'] = '';
655
656                 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
657                 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
658                 $mail['allow_gid'] = '';
659                 $mail['deny_cid'] = '';
660                 $mail['deny_gid'] = '';
661                 $mail['private'] = true;
662                 $mail['deleted'] = false;
663                 $mail['edited'] = $mail['created'];
664                 $mail['plink'] = $mail['uri'];
665                 $mail['thr-parent'] = $reply['uri'];
666                 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
667
668                 $mail['event-type'] = '';
669                 $mail['attach'] = '';
670
671                 $mail['parent'] = 0;
672
673                 return $mail;
674         }
675
676         /**
677          * Creates an activity array for a given mail id
678          *
679          * @param integer $mail_id
680          * @param boolean $object_mode Is the activity item is used inside another object?
681          *
682          * @return array of activity
683          * @throws \Exception
684          */
685         public static function createActivityFromMail($mail_id, $object_mode = false)
686         {
687                 $mail = self::ItemArrayFromMail($mail_id);
688                 $object = self::createNote($mail);
689
690                 $object['to'] = $object['cc'];
691                 unset($object['cc']);
692
693                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => 'test']];
694
695                 if (!$object_mode) {
696                         $data = ['@context' => ActivityPub::CONTEXT];
697                 } else {
698                         $data = [];
699                 }
700
701                 $data['id'] = $mail['uri'] . '#Create';
702                 $data['type'] = 'Create';
703                 $data['actor'] = $mail['author-link'];
704                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
705                 $data['instrument'] = self::getService();
706                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
707
708                 if (empty($data['to']) && !empty($data['cc'])) {
709                         $data['to'] = $data['cc'];
710                 }
711
712                 if (empty($data['to']) && !empty($data['bcc'])) {
713                         $data['to'] = $data['bcc'];
714                 }
715
716                 unset($data['cc']);
717                 unset($data['bcc']);
718
719                 $object['to'] = $data['to'];
720                 unset($object['cc']);
721                 unset($object['bcc']);
722
723                 $data['directMessage'] = true;
724
725                 $data['object'] = $object;
726
727                 $owner = User::getOwnerDataById($mail['uid']);
728
729                 if (!$object_mode && !empty($owner)) {
730                         return LDSignature::sign($data, $owner);
731                 } else {
732                         return $data;
733                 }
734         }
735
736         /**
737          * Returns the activity type of a given item
738          *
739          * @param array $item
740          *
741          * @return string with activity type
742          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
743          * @throws \ImagickException
744          */
745         private static function getTypeOfItem($item)
746         {
747                 $reshared = false;
748
749                 // Only check for a reshare, if it is a real reshare and no quoted reshare
750                 if (strpos($item['body'], "[share") === 0) {
751                         $announce = api_share_as_retweet($item);
752                         $reshared = !empty($announce['plink']);
753                 }
754
755                 if ($reshared) {
756                         $type = 'Announce';
757                 } elseif ($item['verb'] == ACTIVITY_POST) {
758                         if ($item['created'] == $item['edited']) {
759                                 $type = 'Create';
760                         } else {
761                                 $type = 'Update';
762                         }
763                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
764                         $type = 'Like';
765                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
766                         $type = 'Dislike';
767                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
768                         $type = 'Accept';
769                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
770                         $type = 'Reject';
771                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
772                         $type = 'TentativeAccept';
773                 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
774                         $type = 'Follow';
775                 } else {
776                         $type = '';
777                 }
778
779                 return $type;
780         }
781
782         /**
783          * Creates the activity or fetches it from the cache
784          *
785          * @param integer $item_id
786          * @param boolean $force Force new cache entry
787          *
788          * @return array with the activity
789          * @throws \Exception
790          */
791         public static function createCachedActivityFromItem($item_id, $force = false)
792         {
793                 $cachekey = 'APDelivery:createActivity:' . $item_id;
794
795                 if (!$force) {
796                         $data = Cache::get($cachekey);
797                         if (!is_null($data)) {
798                                 return $data;
799                         }
800                 }
801
802                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
803
804                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
805                 return $data;
806         }
807
808         /**
809          * Creates an activity array for a given item id
810          *
811          * @param integer $item_id
812          * @param boolean $object_mode Is the activity item is used inside another object?
813          *
814          * @return array of activity
815          * @throws \Exception
816          */
817         public static function createActivityFromItem($item_id, $object_mode = false)
818         {
819                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
820
821                 if (!DBA::isResult($item)) {
822                         return false;
823                 }
824
825                 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
826                         $owner = User::getOwnerDataById($item['uid']);
827                         if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
828                                 $type = 'Announce';
829
830                                 // Disguise forum posts as reshares. Will later be converted to a real announce
831                                 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
832                                         $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
833                         }
834                 }
835
836                 if (empty($type)) {
837                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
838                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
839                         if (DBA::isResult($conversation)) {
840                                 $data = json_decode($conversation['source'], true);
841                                 if (!empty($data)) {
842                                         return $data;
843                                 }
844                         }
845
846                         $type = self::getTypeOfItem($item);
847                 }
848
849                 if (!$object_mode) {
850                         $data = ['@context' => ActivityPub::CONTEXT];
851
852                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
853                                 $type = 'Undo';
854                         } elseif ($item['deleted']) {
855                                 $type = 'Delete';
856                         }
857                 } else {
858                         $data = [];
859                 }
860
861                 $data['id'] = $item['uri'] . '#' . $type;
862                 $data['type'] = $type;
863
864                 if (Item::isForumPost($item) && ($type != 'Announce')) {
865                         $data['actor'] = $item['author-link'];
866                 } else {
867                         $data['actor'] = $item['owner-link'];
868                 }
869
870                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
871
872                 $data['instrument'] = self::getService();
873
874                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
875
876                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
877                         $data['object'] = self::createNote($item);
878                 } elseif ($data['type'] == 'Announce') {
879                         $data = self::createAnnounce($item, $data);
880                 } elseif ($data['type'] == 'Follow') {
881                         $data['object'] = $item['parent-uri'];
882                 } elseif ($data['type'] == 'Undo') {
883                         $data['object'] = self::createActivityFromItem($item_id, true);
884                 } else {
885                         $data['diaspora:guid'] = $item['guid'];
886                         if (!empty($item['signed_text'])) {
887                                 $data['diaspora:like'] = $item['signed_text'];
888                         }
889                         $data['object'] = $item['thr-parent'];
890                 }
891
892                 if (!empty($item['contact-uid'])) {
893                         $uid = $item['contact-uid'];
894                 } else {
895                         $uid = $item['uid'];
896                 }
897
898                 $owner = User::getOwnerDataById($uid);
899
900                 if (!$object_mode && !empty($owner)) {
901                         return LDSignature::sign($data, $owner);
902                 } else {
903                         return $data;
904                 }
905
906                 /// @todo Create "conversation" entry
907         }
908
909         /**
910          * Creates an object array for a given item id
911          *
912          * @param integer $item_id
913          *
914          * @return array with the object data
915          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916          * @throws \ImagickException
917          */
918         public static function createObjectFromItemID($item_id)
919         {
920                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
921
922                 if (!DBA::isResult($item)) {
923                         return false;
924                 }
925
926                 $data = ['@context' => ActivityPub::CONTEXT];
927                 $data = array_merge($data, self::createNote($item));
928
929                 return $data;
930         }
931
932         /**
933          * Creates a location entry for a given item array
934          *
935          * @param array $item
936          *
937          * @return array with location array
938          */
939         private static function createLocation($item)
940         {
941                 $location = ['type' => 'Place'];
942
943                 if (!empty($item['location'])) {
944                         $location['name'] = $item['location'];
945                 }
946
947                 $coord = [];
948
949                 if (empty($item['coord'])) {
950                         $coord = Map::getCoordinates($item['location']);
951                 } else {
952                         $coords = explode(' ', $item['coord']);
953                         if (count($coords) == 2) {
954                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
955                         }
956                 }
957
958                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
959                         $location['latitude'] = $coord['lat'];
960                         $location['longitude'] = $coord['lon'];
961                 }
962
963                 return $location;
964         }
965
966         /**
967          * Returns a tag array for a given item array
968          *
969          * @param array $item
970          *
971          * @return array of tags
972          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
973          */
974         private static function createTagList($item)
975         {
976                 $tags = [];
977
978                 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
979                 foreach ($terms as $term) {
980                         if ($term['type'] == Term::HASHTAG) {
981                                 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
982                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
983                         } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
984                                 $contact = Contact::getDetailsByURL($term['url']);
985                                 if (!empty($contact['addr'])) {
986                                         $mention = '@' . $contact['addr'];
987                                 } else {
988                                         $mention = '@' . $term['url'];
989                                 }
990
991                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
992                         }
993                 }
994                 return $tags;
995         }
996
997         /**
998          * Adds attachment data to the JSON document
999          *
1000          * @param array  $item Data of the item that is to be posted
1001          * @param string $type Object type
1002          *
1003          * @return array with attachment data
1004          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1005          */
1006         private static function createAttachmentList($item, $type)
1007         {
1008                 $attachments = [];
1009
1010                 $arr = explode('[/attach],', $item['attach']);
1011                 if (count($arr)) {
1012                         foreach ($arr as $r) {
1013                                 $matches = false;
1014                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1015                                 if ($cnt) {
1016                                         $attributes = ['type' => 'Document',
1017                                                         'mediaType' => $matches[3],
1018                                                         'url' => $matches[1],
1019                                                         'name' => null];
1020
1021                                         if (trim($matches[4]) != '') {
1022                                                 $attributes['name'] = trim($matches[4]);
1023                                         }
1024
1025                                         $attachments[] = $attributes;
1026                                 }
1027                         }
1028                 }
1029
1030                 if ($type != 'Note') {
1031                         return $attachments;
1032                 }
1033
1034                 // Simplify image codes
1035                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1036
1037                 // Grab all pictures and create attachments out of them
1038                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1039                         foreach ($pictures[1] as $picture) {
1040                                 $imgdata = Image::getInfoFromURL($picture);
1041                                 if ($imgdata) {
1042                                         $attachments[] = ['type' => 'Document',
1043                                                 'mediaType' => $imgdata['mime'],
1044                                                 'url' => $picture,
1045                                                 'name' => null];
1046                                 }
1047                         }
1048                 }
1049
1050                 return $attachments;
1051         }
1052
1053         /**
1054          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1055          *
1056          * @param array $match Matching values for the callback
1057          * @return string Replaced mention
1058          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1059          */
1060         private static function mentionCallback($match)
1061         {
1062                 if (empty($match[1])) {
1063                         return '';
1064                 }
1065
1066                 $data = Contact::getDetailsByURL($match[1]);
1067                 if (empty($data['nick'])) {
1068                         return $match[0];
1069                 }
1070
1071                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1072         }
1073
1074         /**
1075          * Remove image elements and replaces them with links to the image
1076          *
1077          * @param string $body
1078          *
1079          * @return string with replaced elements
1080          */
1081         private static function removePictures($body)
1082         {
1083                 // Simplify image codes
1084                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1085
1086                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
1087                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
1088
1089                 return $body;
1090         }
1091
1092         /**
1093          * Fetches the "context" value for a givem item array from the "conversation" table
1094          *
1095          * @param array $item
1096          *
1097          * @return string with context url
1098          * @throws \Exception
1099          */
1100         private static function fetchContextURLForItem($item)
1101         {
1102                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1103                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1104                         $context_uri = $conversation['conversation-href'];
1105                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1106                         $context_uri = $conversation['conversation-uri'];
1107                 } else {
1108                         $context_uri = $item['parent-uri'] . '#context';
1109                 }
1110                 return $context_uri;
1111         }
1112
1113         /**
1114          * Returns if the post contains sensitive content ("nsfw")
1115          *
1116          * @param integer $item_id
1117          *
1118          * @return boolean
1119          * @throws \Exception
1120          */
1121         private static function isSensitive($item_id)
1122         {
1123                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1124                 return DBA::exists('term', $condition);
1125         }
1126
1127         /**
1128          * Creates event data
1129          *
1130          * @param array $item
1131          *
1132          * @return array with the event data
1133          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1134          */
1135         public static function createEvent($item)
1136         {
1137                 $event = [];
1138                 $event['name'] = $item['event-summary'];
1139                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
1140                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1141
1142                 if (!$item['event-nofinish']) {
1143                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1144                 }
1145
1146                 if (!empty($item['event-location'])) {
1147                         $item['location'] = $item['event-location'];
1148                         $event['location'] = self::createLocation($item);
1149                 }
1150
1151                 return $event;
1152         }
1153
1154         /**
1155          * Creates a note/article object array
1156          *
1157          * @param array $item
1158          *
1159          * @return array with the object data
1160          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1161          * @throws \ImagickException
1162          */
1163         public static function createNote($item)
1164         {
1165                 if ($item['event-type'] == 'event') {
1166                         $type = 'Event';
1167                 } elseif (!empty($item['title'])) {
1168                         $type = 'Article';
1169                 } else {
1170                         $type = 'Note';
1171                 }
1172
1173                 if ($item['deleted']) {
1174                         $type = 'Tombstone';
1175                 }
1176
1177                 $data = [];
1178                 $data['id'] = $item['uri'];
1179                 $data['type'] = $type;
1180
1181                 if ($item['deleted']) {
1182                         return $data;
1183                 }
1184
1185                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1186
1187                 if ($item['uri'] != $item['thr-parent']) {
1188                         $data['inReplyTo'] = $item['thr-parent'];
1189                 } else {
1190                         $data['inReplyTo'] = null;
1191                 }
1192
1193                 $data['diaspora:guid'] = $item['guid'];
1194                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1195
1196                 if ($item['created'] != $item['edited']) {
1197                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1198                 }
1199
1200                 $data['url'] = $item['plink'];
1201                 $data['attributedTo'] = $item['author-link'];
1202                 $data['sensitive'] = self::isSensitive($item['id']);
1203                 $data['context'] = self::fetchContextURLForItem($item);
1204
1205                 if (!empty($item['title'])) {
1206                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1207                 }
1208
1209                 $permission_block = self::createPermissionBlockForItem($item, false);
1210
1211                 $body = $item['body'];
1212
1213                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1214                         $body = self::prependMentions($body, $permission_block);
1215                 }
1216
1217                 if ($type == 'Note') {
1218                         $body = self::removePictures($body);
1219                 } elseif (($type == 'Article') && empty($data['summary'])) {
1220                         $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1221                 }
1222
1223                 if ($type == 'Event') {
1224                         $data = array_merge($data, self::createEvent($item));
1225                 } else {
1226                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1227                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1228
1229                         $data['content'] = BBCode::convert($body, false, 7);
1230                 }
1231
1232                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1233
1234                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1235                         $data['diaspora:comment'] = $item['signed_text'];
1236                 }
1237
1238                 $data['attachment'] = self::createAttachmentList($item, $type);
1239                 $data['tag'] = self::createTagList($item);
1240
1241                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1242                         $data['location'] = self::createLocation($item);
1243                 }
1244
1245                 if (!empty($item['app'])) {
1246                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1247                 }
1248
1249                 $data = array_merge($data, $permission_block);
1250
1251                 return $data;
1252         }
1253
1254         /**
1255          * Creates an announce object entry
1256          *
1257          * @param array $item
1258          * @param array $data activity data
1259          *
1260          * @return array with activity data
1261          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1262          * @throws \ImagickException
1263          */
1264         private static function createAnnounce($item, $data)
1265         {
1266                 $announce = api_share_as_retweet($item);
1267                 if (empty($announce['plink'])) {
1268                         $data['type'] = 'Create';
1269                         $data['object'] = self::createNote($item);
1270                         return $data;
1271                 }
1272
1273                 // Fetch the original id of the object
1274                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1275                 if (!empty($activity)) {
1276                         $ldactivity = JsonLD::compact($activity);
1277                         $id = JsonLD::fetchElement($ldactivity, '@id');
1278                         if (!empty($id)) {
1279                                 $data['object'] = $id;
1280                                 return $data;
1281                         }
1282                 }
1283
1284                 $data['type'] = 'Create';
1285                 $data['object'] = self::createNote($item);
1286                 return $data;
1287         }
1288
1289         /**
1290          * Creates an activity id for a given contact id
1291          *
1292          * @param integer $cid Contact ID of target
1293          *
1294          * @return bool|string activity id
1295          */
1296         public static function activityIDFromContact($cid)
1297         {
1298                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1299                 if (!DBA::isResult($contact)) {
1300                         return false;
1301                 }
1302
1303                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1304                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1305                 return System::baseUrl() . '/activity/' . $uuid;
1306         }
1307
1308         /**
1309          * Transmits a contact suggestion to a given inbox
1310          *
1311          * @param integer $uid           User ID
1312          * @param string  $inbox         Target inbox
1313          * @param integer $suggestion_id Suggestion ID
1314          *
1315          * @return boolean was the transmission successful?
1316          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1317          */
1318         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1319         {
1320                 $owner = User::getOwnerDataById($uid);
1321
1322                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1323
1324                 $data = ['@context' => ActivityPub::CONTEXT,
1325                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1326                         'type' => 'Announce',
1327                         'actor' => $owner['url'],
1328                         'object' => $suggestion['url'],
1329                         'content' => $suggestion['note'],
1330                         'instrument' => self::getService(),
1331                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1332                         'cc' => []];
1333
1334                 $signed = LDSignature::sign($data, $owner);
1335
1336                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1337                 return HTTPSignature::transmit($signed, $inbox, $uid);
1338         }
1339
1340         /**
1341          * Transmits a profile relocation to a given inbox
1342          *
1343          * @param integer $uid   User ID
1344          * @param string  $inbox Target inbox
1345          *
1346          * @return boolean was the transmission successful?
1347          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1348          */
1349         public static function sendProfileRelocation($uid, $inbox)
1350         {
1351                 $owner = User::getOwnerDataById($uid);
1352
1353                 $data = ['@context' => ActivityPub::CONTEXT,
1354                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1355                         'type' => 'dfrn:relocate',
1356                         'actor' => $owner['url'],
1357                         'object' => $owner['url'],
1358                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1359                         'instrument' => self::getService(),
1360                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1361                         'cc' => []];
1362
1363                 $signed = LDSignature::sign($data, $owner);
1364
1365                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1366                 return HTTPSignature::transmit($signed, $inbox, $uid);
1367         }
1368
1369         /**
1370          * Transmits a profile deletion to a given inbox
1371          *
1372          * @param integer $uid   User ID
1373          * @param string  $inbox Target inbox
1374          *
1375          * @return boolean was the transmission successful?
1376          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1377          */
1378         public static function sendProfileDeletion($uid, $inbox)
1379         {
1380                 $owner = User::getOwnerDataById($uid);
1381
1382                 if (empty($owner)) {
1383                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1384                         return false;
1385                 }
1386
1387                 if (empty($owner['uprvkey'])) {
1388                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1389                         return false;
1390                 }
1391
1392                 $data = ['@context' => ActivityPub::CONTEXT,
1393                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1394                         'type' => 'Delete',
1395                         'actor' => $owner['url'],
1396                         'object' => $owner['url'],
1397                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1398                         'instrument' => self::getService(),
1399                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1400                         'cc' => []];
1401
1402                 $signed = LDSignature::sign($data, $owner);
1403
1404                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1405                 return HTTPSignature::transmit($signed, $inbox, $uid);
1406         }
1407
1408         /**
1409          * Transmits a profile change to a given inbox
1410          *
1411          * @param integer $uid   User ID
1412          * @param string  $inbox Target inbox
1413          *
1414          * @return boolean was the transmission successful?
1415          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1416          * @throws \ImagickException
1417          */
1418         public static function sendProfileUpdate($uid, $inbox)
1419         {
1420                 $owner = User::getOwnerDataById($uid);
1421                 $profile = APContact::getByURL($owner['url']);
1422
1423                 $data = ['@context' => ActivityPub::CONTEXT,
1424                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1425                         'type' => 'Update',
1426                         'actor' => $owner['url'],
1427                         'object' => self::getProfile($uid),
1428                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1429                         'instrument' => self::getService(),
1430                         'to' => [$profile['followers']],
1431                         'cc' => []];
1432
1433                 $signed = LDSignature::sign($data, $owner);
1434
1435                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1436                 return HTTPSignature::transmit($signed, $inbox, $uid);
1437         }
1438
1439         /**
1440          * Transmits a given activity to a target
1441          *
1442          * @param string  $activity Type name
1443          * @param string  $target   Target profile
1444          * @param integer $uid      User ID
1445          * @return bool
1446          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1447          * @throws \ImagickException
1448          * @throws \Exception
1449          */
1450         public static function sendActivity($activity, $target, $uid, $id = '')
1451         {
1452                 $profile = APContact::getByURL($target);
1453
1454                 $owner = User::getOwnerDataById($uid);
1455
1456                 if (empty($id)) {
1457                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1458                 }
1459
1460                 $data = ['@context' => ActivityPub::CONTEXT,
1461                         'id' => $id,
1462                         'type' => $activity,
1463                         'actor' => $owner['url'],
1464                         'object' => $profile['url'],
1465                         'instrument' => self::getService(),
1466                         'to' => [$profile['url']]];
1467
1468                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1469
1470                 $signed = LDSignature::sign($data, $owner);
1471                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1472         }
1473
1474         /**
1475          * Transmits a "follow object" activity to a target
1476          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1477          *
1478          * @param string  $object Object URL
1479          * @param string  $target Target profile
1480          * @param integer $uid    User ID
1481          * @return bool
1482          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1483          * @throws \ImagickException
1484          * @throws \Exception
1485          */
1486         public static function sendFollowObject($object, $target, $uid = 0)
1487         {
1488                 $profile = APContact::getByURL($target);
1489
1490                 if (empty($uid)) {
1491                         // Fetch the list of administrators
1492                         $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1493
1494                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1495                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1496                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1497                         $uid = $first_user['uid'];
1498                 }
1499
1500                 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1501                         'author-id' => Contact::getPublicIdByUserId($uid)];
1502                 if (Item::exists($condition)) {
1503                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1504                         return false;
1505                 }
1506
1507                 $owner = User::getOwnerDataById($uid);
1508
1509                 $data = ['@context' => ActivityPub::CONTEXT,
1510                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1511                         'type' => 'Follow',
1512                         'actor' => $owner['url'],
1513                         'object' => $object,
1514                         'instrument' => self::getService(),
1515                         'to' => [$profile['url']]];
1516
1517                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1518
1519                 $signed = LDSignature::sign($data, $owner);
1520                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1521         }
1522
1523         /**
1524          * Transmit a message that the contact request had been accepted
1525          *
1526          * @param string  $target Target profile
1527          * @param         $id
1528          * @param integer $uid    User ID
1529          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1530          * @throws \ImagickException
1531          */
1532         public static function sendContactAccept($target, $id, $uid)
1533         {
1534                 $profile = APContact::getByURL($target);
1535
1536                 $owner = User::getOwnerDataById($uid);
1537                 $data = ['@context' => ActivityPub::CONTEXT,
1538                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1539                         'type' => 'Accept',
1540                         'actor' => $owner['url'],
1541                         'object' => ['id' => $id, 'type' => 'Follow',
1542                                 'actor' => $profile['url'],
1543                                 'object' => $owner['url']],
1544                         'instrument' => self::getService(),
1545                         'to' => [$profile['url']]];
1546
1547                 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1548
1549                 $signed = LDSignature::sign($data, $owner);
1550                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1551         }
1552
1553         /**
1554          * Reject a contact request or terminates the contact relation
1555          *
1556          * @param string  $target Target profile
1557          * @param         $id
1558          * @param integer $uid    User ID
1559          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1560          * @throws \ImagickException
1561          */
1562         public static function sendContactReject($target, $id, $uid)
1563         {
1564                 $profile = APContact::getByURL($target);
1565
1566                 $owner = User::getOwnerDataById($uid);
1567                 $data = ['@context' => ActivityPub::CONTEXT,
1568                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1569                         'type' => 'Reject',
1570                         'actor' => $owner['url'],
1571                         'object' => ['id' => $id, 'type' => 'Follow',
1572                                 'actor' => $profile['url'],
1573                                 'object' => $owner['url']],
1574                         'instrument' => self::getService(),
1575                         'to' => [$profile['url']]];
1576
1577                 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1578
1579                 $signed = LDSignature::sign($data, $owner);
1580                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1581         }
1582
1583         /**
1584          * Transmits a message that we don't want to follow this contact anymore
1585          *
1586          * @param string  $target Target profile
1587          * @param integer $uid    User ID
1588          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1589          * @throws \ImagickException
1590          * @throws \Exception
1591          */
1592         public static function sendContactUndo($target, $cid, $uid)
1593         {
1594                 $profile = APContact::getByURL($target);
1595
1596                 $object_id = self::activityIDFromContact($cid);
1597                 if (empty($object_id)) {
1598                         return;
1599                 }
1600
1601                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1602
1603                 $owner = User::getOwnerDataById($uid);
1604                 $data = ['@context' => ActivityPub::CONTEXT,
1605                         'id' => $id,
1606                         'type' => 'Undo',
1607                         'actor' => $owner['url'],
1608                         'object' => ['id' => $object_id, 'type' => 'Follow',
1609                                 'actor' => $owner['url'],
1610                                 'object' => $profile['url']],
1611                         'instrument' => self::getService(),
1612                         'to' => [$profile['url']]];
1613
1614                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1615
1616                 $signed = LDSignature::sign($data, $owner);
1617                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1618         }
1619
1620         private static function prependMentions($body, array $permission_block)
1621         {
1622                 if (Config::get('system', 'disable_implicit_mentions')) {
1623                         return $body;
1624                 }
1625
1626                 $mentions = [];
1627
1628                 foreach ($permission_block['to'] as $profile_url) {
1629                         $profile = Contact::getDetailsByURL($profile_url);
1630                         if (!empty($profile['addr'])
1631                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1632                                 && !strstr($body, $profile['addr'])
1633                                 && !strstr($body, $profile_url)
1634                         ) {
1635                                 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1636                         }
1637                 }
1638
1639                 $mentions[] = $body;
1640
1641                 return implode(' ', $mentions);
1642         }
1643 }