]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Merge pull request #7151 from annando/ap-mail-mastodon
[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\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                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
426                 while ($parent = Item::fetch($parents)) {
427                         if ($parent['gravity'] == GRAVITY_PARENT) {
428                                 $profile = APContact::getByURL($parent['owner-link'], false);
429                                 if (!empty($profile)) {
430                                         if ($item['gravity'] != GRAVITY_PARENT) {
431                                                 // Comments to forums are directed to the forum
432                                                 // But comments to forums aren't directed to the followers collection
433                                                 if ($profile['type'] == 'Group') {
434                                                         $data['to'][] = $profile['url'];
435                                                 } else {
436                                                         $data['cc'][] = $profile['url'];
437                                                         if (!$item['private']) {
438                                                                 $data['cc'][] = $actor_profile['followers'];
439                                                         }
440                                                 }
441                                         } else {
442                                                 // Public thread parent post always are directed to the followes
443                                                 if (!$item['private'] && !$forum_mode) {
444                                                         $data['cc'][] = $actor_profile['followers'];
445                                                 }
446                                         }
447                                 }
448                         }
449
450                         // Don't include data from future posts
451                         if ($parent['id'] >= $last_id) {
452                                 continue;
453                         }
454
455                         $profile = APContact::getByURL($parent['author-link'], false);
456                         if (!empty($profile)) {
457                                 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
458                                         $data['to'][] = $profile['url'];
459                                 } else {
460                                         $data['cc'][] = $profile['url'];
461                                 }
462                         }
463                 }
464                 DBA::close($parents);
465
466                 $data['to'] = array_unique($data['to']);
467                 $data['cc'] = array_unique($data['cc']);
468                 $data['bcc'] = array_unique($data['bcc']);
469
470                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
471                         unset($data['to'][$key]);
472                 }
473
474                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
475                         unset($data['cc'][$key]);
476                 }
477
478                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
479                         unset($data['bcc'][$key]);
480                 }
481
482                 foreach ($data['to'] as $to) {
483                         if (($key = array_search($to, $data['cc'])) !== false) {
484                                 unset($data['cc'][$key]);
485                         }
486
487                         if (($key = array_search($to, $data['bcc'])) !== false) {
488                                 unset($data['bcc'][$key]);
489                         }
490                 }
491
492                 foreach ($data['cc'] as $cc) {
493                         if (($key = array_search($cc, $data['bcc'])) !== false) {
494                                 unset($data['bcc'][$key]);
495                         }
496                 }
497
498                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
499
500                 if (!$blindcopy) {
501                         unset($receivers['bcc']);
502                 }
503
504                 return $receivers;
505         }
506
507         /**
508          * Check if an inbox is archived
509          *
510          * @param string $url Inbox url
511          *
512          * @return boolean "true" if inbox is archived
513          */
514         private static function archivedInbox($url)
515         {
516                 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
517         }
518
519         /**
520          * Fetches a list of inboxes of followers of a given user
521          *
522          * @param integer $uid      User ID
523          * @param boolean $personal fetch personal inboxes
524          *
525          * @return array of follower inboxes
526          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527          * @throws \ImagickException
528          */
529         public static function fetchTargetInboxesforUser($uid, $personal = false)
530         {
531                 $inboxes = [];
532
533                 if (Config::get('debug', 'total_ap_delivery')) {
534                         // Will be activated in a later step
535                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
536                 } else {
537                         // For now only send to these contacts:
538                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
539                 }
540
541                 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
542
543                 if (!empty($uid)) {
544                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
545                 }
546
547                 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
548                 while ($contact = DBA::fetch($contacts)) {
549                         if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
550                                 continue;
551                         }
552
553                         if (Network::isUrlBlocked($contact['url'])) {
554                                 continue;
555                         }
556
557                         $profile = APContact::getByURL($contact['url'], false);
558                         if (!empty($profile)) {
559                                 if (empty($profile['sharedinbox']) || $personal) {
560                                         $target = $profile['inbox'];
561                                 } else {
562                                         $target = $profile['sharedinbox'];
563                                 }
564                                 if (!self::archivedInbox($target)) {
565                                         $inboxes[$target] = $target;
566                                 }
567                         }
568                 }
569                 DBA::close($contacts);
570
571                 return $inboxes;
572         }
573
574         /**
575          * Fetches an array of inboxes for the given item and user
576          *
577          * @param array   $item       Item array
578          * @param integer $uid        User ID
579          * @param boolean $personal   fetch personal inboxes
580          * @param integer $last_id    Last item id for adding receivers
581          * @param boolean $forum_mode "true" means that we are sending content to a forum
582          * @return array with inboxes
583          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
584          * @throws \ImagickException
585          */
586         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
587         {
588                 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
589                 if (empty($permissions)) {
590                         return [];
591                 }
592
593                 $inboxes = [];
594
595                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
596                         $item_profile = APContact::getByURL($item['author-link'], false);
597                 } else {
598                         $item_profile = APContact::getByURL($item['owner-link'], false);
599                 }
600
601                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
602                         if (empty($permissions[$element])) {
603                                 continue;
604                         }
605
606                         $blindcopy = in_array($element, ['bto', 'bcc']);
607
608                         foreach ($permissions[$element] as $receiver) {
609                                 if (Network::isUrlBlocked($receiver)) {
610                                         continue;
611                                 }
612
613                                 if ($receiver == $item_profile['followers']) {
614                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
615                                 } else {
616                                         $profile = APContact::getByURL($receiver, false);
617                                         if (!empty($profile)) {
618                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
619                                                         $target = $profile['inbox'];
620                                                 } else {
621                                                         $target = $profile['sharedinbox'];
622                                                 }
623                                                 if (!self::archivedInbox($target)) {
624                                                         $inboxes[$target] = $target;
625                                                 }
626                                         }
627                                 }
628                         }
629                 }
630
631                 return $inboxes;
632         }
633
634         /**
635          * Creates an array in the structure of the item table for a given mail id
636          *
637          * @param integer $mail_id
638          *
639          * @return array
640          * @throws \Exception
641          */
642         public static function ItemArrayFromMail($mail_id)
643         {
644                 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
645
646                 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
647
648                 // Making the post more compatible for Mastodon by:
649                 // - Making it a note and not an article (no title)
650                 // - Moving the title into the "summary" field that is used as a "content warning"
651                 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
652                 $mail['title'] = '';
653
654                 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
655                 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
656                 $mail['allow_gid'] = '';
657                 $mail['deny_cid'] = '';
658                 $mail['deny_gid'] = '';
659                 $mail['private'] = true;
660                 $mail['deleted'] = false;
661                 $mail['edited'] = $mail['created'];
662                 $mail['plink'] = $mail['uri'];
663                 $mail['thr-parent'] = $reply['uri'];
664                 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
665
666                 $mail['event-type'] = '';
667                 $mail['attach'] = '';
668
669                 $mail['parent'] = 0;
670
671                 return $mail;
672         }
673
674         /**
675          * Creates an activity array for a given mail id
676          *
677          * @param integer $mail_id
678          * @param boolean $object_mode Is the activity item is used inside another object?
679          *
680          * @return array of activity
681          * @throws \Exception
682          */
683         public static function createActivityFromMail($mail_id, $object_mode = false)
684         {
685                 $mail = self::ItemArrayFromMail($mail_id);
686                 $object = self::createNote($mail);
687
688                 $object['to'] = $object['cc'];
689                 unset($object['cc']);
690
691                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => 'test']];
692
693                 if (!$object_mode) {
694                         $data = ['@context' => ActivityPub::CONTEXT];
695                 } else {
696                         $data = [];
697                 }
698
699                 $data['id'] = $mail['uri'] . '#Create';
700                 $data['type'] = 'Create';
701                 $data['actor'] = $mail['author-link'];
702                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
703                 $data['instrument'] = self::getService();
704                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
705
706                 if (empty($data['to']) && !empty($data['cc'])) {
707                         $data['to'] = $data['cc'];
708                 }
709
710                 if (empty($data['to']) && !empty($data['bcc'])) {
711                         $data['to'] = $data['bcc'];
712                 }
713
714                 unset($data['cc']);
715                 unset($data['bcc']);
716
717                 $object['to'] = $data['to'];
718                 unset($object['cc']);
719                 unset($object['bcc']);
720
721                 $data['directMessage'] = true;
722
723                 $data['object'] = $object;
724
725                 $owner = User::getOwnerDataById($mail['uid']);
726
727                 if (!$object_mode && !empty($owner)) {
728                         return LDSignature::sign($data, $owner);
729                 } else {
730                         return $data;
731                 }
732         }
733
734         /**
735          * Returns the activity type of a given item
736          *
737          * @param array $item
738          *
739          * @return string with activity type
740          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
741          * @throws \ImagickException
742          */
743         private static function getTypeOfItem($item)
744         {
745                 $reshared = false;
746
747                 // Only check for a reshare, if it is a real reshare and no quoted reshare
748                 if (strpos($item['body'], "[share") === 0) {
749                         $announce = api_share_as_retweet($item);
750                         $reshared = !empty($announce['plink']);
751                 }
752
753                 if ($reshared) {
754                         $type = 'Announce';
755                 } elseif ($item['verb'] == ACTIVITY_POST) {
756                         if ($item['created'] == $item['edited']) {
757                                 $type = 'Create';
758                         } else {
759                                 $type = 'Update';
760                         }
761                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
762                         $type = 'Like';
763                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
764                         $type = 'Dislike';
765                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
766                         $type = 'Accept';
767                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
768                         $type = 'Reject';
769                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
770                         $type = 'TentativeAccept';
771                 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
772                         $type = 'Follow';
773                 } else {
774                         $type = '';
775                 }
776
777                 return $type;
778         }
779
780         /**
781          * Creates the activity or fetches it from the cache
782          *
783          * @param integer $item_id
784          * @param boolean $force Force new cache entry
785          *
786          * @return array with the activity
787          * @throws \Exception
788          */
789         public static function createCachedActivityFromItem($item_id, $force = false)
790         {
791                 $cachekey = 'APDelivery:createActivity:' . $item_id;
792
793                 if (!$force) {
794                         $data = Cache::get($cachekey);
795                         if (!is_null($data)) {
796                                 return $data;
797                         }
798                 }
799
800                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
801
802                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
803                 return $data;
804         }
805
806         /**
807          * Creates an activity array for a given item id
808          *
809          * @param integer $item_id
810          * @param boolean $object_mode Is the activity item is used inside another object?
811          *
812          * @return array of activity
813          * @throws \Exception
814          */
815         public static function createActivityFromItem($item_id, $object_mode = false)
816         {
817                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
818
819                 if (!DBA::isResult($item)) {
820                         return false;
821                 }
822
823                 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
824                         $owner = User::getOwnerDataById($item['uid']);
825                         if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
826                                 $type = 'Announce';
827
828                                 // Disguise forum posts as reshares. Will later be converted to a real announce
829                                 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
830                                         $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
831                         }
832                 }
833
834                 if (empty($type)) {
835                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
836                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
837                         if (DBA::isResult($conversation)) {
838                                 $data = json_decode($conversation['source'], true);
839                                 if (!empty($data)) {
840                                         return $data;
841                                 }
842                         }
843
844                         $type = self::getTypeOfItem($item);
845                 }
846
847                 if (!$object_mode) {
848                         $data = ['@context' => ActivityPub::CONTEXT];
849
850                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
851                                 $type = 'Undo';
852                         } elseif ($item['deleted']) {
853                                 $type = 'Delete';
854                         }
855                 } else {
856                         $data = [];
857                 }
858
859                 $data['id'] = $item['uri'] . '#' . $type;
860                 $data['type'] = $type;
861
862                 if (Item::isForumPost($item) && ($type != 'Announce')) {
863                         $data['actor'] = $item['author-link'];
864                 } else {
865                         $data['actor'] = $item['owner-link'];
866                 }
867
868                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
869
870                 $data['instrument'] = self::getService();
871
872                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
873
874                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
875                         $data['object'] = self::createNote($item);
876                 } elseif ($data['type'] == 'Announce') {
877                         $data = self::createAnnounce($item, $data);
878                 } elseif ($data['type'] == 'Follow') {
879                         $data['object'] = $item['parent-uri'];
880                 } elseif ($data['type'] == 'Undo') {
881                         $data['object'] = self::createActivityFromItem($item_id, true);
882                 } else {
883                         $data['diaspora:guid'] = $item['guid'];
884                         if (!empty($item['signed_text'])) {
885                                 $data['diaspora:like'] = $item['signed_text'];
886                         }
887                         $data['object'] = $item['thr-parent'];
888                 }
889
890                 if (!empty($item['contact-uid'])) {
891                         $uid = $item['contact-uid'];
892                 } else {
893                         $uid = $item['uid'];
894                 }
895
896                 $owner = User::getOwnerDataById($uid);
897
898                 if (!$object_mode && !empty($owner)) {
899                         return LDSignature::sign($data, $owner);
900                 } else {
901                         return $data;
902                 }
903
904                 /// @todo Create "conversation" entry
905         }
906
907         /**
908          * Creates an object array for a given item id
909          *
910          * @param integer $item_id
911          *
912          * @return array with the object data
913          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
914          * @throws \ImagickException
915          */
916         public static function createObjectFromItemID($item_id)
917         {
918                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
919
920                 if (!DBA::isResult($item)) {
921                         return false;
922                 }
923
924                 $data = ['@context' => ActivityPub::CONTEXT];
925                 $data = array_merge($data, self::createNote($item));
926
927                 return $data;
928         }
929
930         /**
931          * Creates a location entry for a given item array
932          *
933          * @param array $item
934          *
935          * @return array with location array
936          */
937         private static function createLocation($item)
938         {
939                 $location = ['type' => 'Place'];
940
941                 if (!empty($item['location'])) {
942                         $location['name'] = $item['location'];
943                 }
944
945                 $coord = [];
946
947                 if (empty($item['coord'])) {
948                         $coord = Map::getCoordinates($item['location']);
949                 } else {
950                         $coords = explode(' ', $item['coord']);
951                         if (count($coords) == 2) {
952                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
953                         }
954                 }
955
956                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
957                         $location['latitude'] = $coord['lat'];
958                         $location['longitude'] = $coord['lon'];
959                 }
960
961                 return $location;
962         }
963
964         /**
965          * Returns a tag array for a given item array
966          *
967          * @param array $item
968          *
969          * @return array of tags
970          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
971          */
972         private static function createTagList($item)
973         {
974                 $tags = [];
975
976                 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
977                 foreach ($terms as $term) {
978                         if ($term['type'] == Term::HASHTAG) {
979                                 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
980                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
981                         } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
982                                 $contact = Contact::getDetailsByURL($term['url']);
983                                 if (!empty($contact['addr'])) {
984                                         $mention = '@' . $contact['addr'];
985                                 } else {
986                                         $mention = '@' . $term['url'];
987                                 }
988
989                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
990                         }
991                 }
992                 return $tags;
993         }
994
995         /**
996          * Adds attachment data to the JSON document
997          *
998          * @param array  $item Data of the item that is to be posted
999          * @param string $type Object type
1000          *
1001          * @return array with attachment data
1002          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1003          */
1004         private static function createAttachmentList($item, $type)
1005         {
1006                 $attachments = [];
1007
1008                 $arr = explode('[/attach],', $item['attach']);
1009                 if (count($arr)) {
1010                         foreach ($arr as $r) {
1011                                 $matches = false;
1012                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1013                                 if ($cnt) {
1014                                         $attributes = ['type' => 'Document',
1015                                                         'mediaType' => $matches[3],
1016                                                         'url' => $matches[1],
1017                                                         'name' => null];
1018
1019                                         if (trim($matches[4]) != '') {
1020                                                 $attributes['name'] = trim($matches[4]);
1021                                         }
1022
1023                                         $attachments[] = $attributes;
1024                                 }
1025                         }
1026                 }
1027
1028                 if ($type != 'Note') {
1029                         return $attachments;
1030                 }
1031
1032                 // Simplify image codes
1033                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1034
1035                 // Grab all pictures and create attachments out of them
1036                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1037                         foreach ($pictures[1] as $picture) {
1038                                 $imgdata = Image::getInfoFromURL($picture);
1039                                 if ($imgdata) {
1040                                         $attachments[] = ['type' => 'Document',
1041                                                 'mediaType' => $imgdata['mime'],
1042                                                 'url' => $picture,
1043                                                 'name' => null];
1044                                 }
1045                         }
1046                 }
1047
1048                 return $attachments;
1049         }
1050
1051         /**
1052          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1053          *
1054          * @param array $match Matching values for the callback
1055          * @return string Replaced mention
1056          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1057          */
1058         private static function mentionCallback($match)
1059         {
1060                 if (empty($match[1])) {
1061                         return '';
1062                 }
1063
1064                 $data = Contact::getDetailsByURL($match[1]);
1065                 if (empty($data['nick'])) {
1066                         return $match[0];
1067                 }
1068
1069                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1070         }
1071
1072         /**
1073          * Remove image elements and replaces them with links to the image
1074          *
1075          * @param string $body
1076          *
1077          * @return string with replaced elements
1078          */
1079         private static function removePictures($body)
1080         {
1081                 // Simplify image codes
1082                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1083
1084                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
1085                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
1086
1087                 return $body;
1088         }
1089
1090         /**
1091          * Fetches the "context" value for a givem item array from the "conversation" table
1092          *
1093          * @param array $item
1094          *
1095          * @return string with context url
1096          * @throws \Exception
1097          */
1098         private static function fetchContextURLForItem($item)
1099         {
1100                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1101                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1102                         $context_uri = $conversation['conversation-href'];
1103                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1104                         $context_uri = $conversation['conversation-uri'];
1105                 } else {
1106                         $context_uri = $item['parent-uri'] . '#context';
1107                 }
1108                 return $context_uri;
1109         }
1110
1111         /**
1112          * Returns if the post contains sensitive content ("nsfw")
1113          *
1114          * @param integer $item_id
1115          *
1116          * @return boolean
1117          * @throws \Exception
1118          */
1119         private static function isSensitive($item_id)
1120         {
1121                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1122                 return DBA::exists('term', $condition);
1123         }
1124
1125         /**
1126          * Creates event data
1127          *
1128          * @param array $item
1129          *
1130          * @return array with the event data
1131          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132          */
1133         public static function createEvent($item)
1134         {
1135                 $event = [];
1136                 $event['name'] = $item['event-summary'];
1137                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
1138                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1139
1140                 if (!$item['event-nofinish']) {
1141                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1142                 }
1143
1144                 if (!empty($item['event-location'])) {
1145                         $item['location'] = $item['event-location'];
1146                         $event['location'] = self::createLocation($item);
1147                 }
1148
1149                 return $event;
1150         }
1151
1152         /**
1153          * Creates a note/article object array
1154          *
1155          * @param array $item
1156          *
1157          * @return array with the object data
1158          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1159          * @throws \ImagickException
1160          */
1161         public static function createNote($item)
1162         {
1163                 if ($item['event-type'] == 'event') {
1164                         $type = 'Event';
1165                 } elseif (!empty($item['title'])) {
1166                         $type = 'Article';
1167                 } else {
1168                         $type = 'Note';
1169                 }
1170
1171                 if ($item['deleted']) {
1172                         $type = 'Tombstone';
1173                 }
1174
1175                 $data = [];
1176                 $data['id'] = $item['uri'];
1177                 $data['type'] = $type;
1178
1179                 if ($item['deleted']) {
1180                         return $data;
1181                 }
1182
1183                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1184
1185                 if ($item['uri'] != $item['thr-parent']) {
1186                         $data['inReplyTo'] = $item['thr-parent'];
1187                 } else {
1188                         $data['inReplyTo'] = null;
1189                 }
1190
1191                 $data['diaspora:guid'] = $item['guid'];
1192                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1193
1194                 if ($item['created'] != $item['edited']) {
1195                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1196                 }
1197
1198                 $data['url'] = $item['plink'];
1199                 $data['attributedTo'] = $item['author-link'];
1200                 $data['sensitive'] = self::isSensitive($item['id']);
1201                 $data['context'] = self::fetchContextURLForItem($item);
1202
1203                 if (!empty($item['title'])) {
1204                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1205                 }
1206
1207                 $permission_block = self::createPermissionBlockForItem($item, false);
1208
1209                 $body = $item['body'];
1210
1211                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1212                         $body = self::prependMentions($body, $permission_block);
1213                 }
1214
1215                 if ($type == 'Note') {
1216                         $body = self::removePictures($body);
1217                 } elseif (($type == 'Article') && empty($data['summary'])) {
1218                         $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1219                 }
1220
1221                 if ($type == 'Event') {
1222                         $data = array_merge($data, self::createEvent($item));
1223                 } else {
1224                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1225                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1226
1227                         $data['content'] = BBCode::convert($body, false, 7);
1228                 }
1229
1230                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1231
1232                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1233                         $data['diaspora:comment'] = $item['signed_text'];
1234                 }
1235
1236                 $data['attachment'] = self::createAttachmentList($item, $type);
1237                 $data['tag'] = self::createTagList($item);
1238
1239                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1240                         $data['location'] = self::createLocation($item);
1241                 }
1242
1243                 if (!empty($item['app'])) {
1244                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1245                 }
1246
1247                 $data = array_merge($data, $permission_block);
1248
1249                 return $data;
1250         }
1251
1252         /**
1253          * Creates an announce object entry
1254          *
1255          * @param array $item
1256          * @param array $data activity data
1257          *
1258          * @return array with activity data
1259          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1260          * @throws \ImagickException
1261          */
1262         private static function createAnnounce($item, $data)
1263         {
1264                 $announce = api_share_as_retweet($item);
1265                 if (empty($announce['plink'])) {
1266                         $data['type'] = 'Create';
1267                         $data['object'] = self::createNote($item);
1268                         return $data;
1269                 }
1270
1271                 // Fetch the original id of the object
1272                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1273                 if (!empty($activity)) {
1274                         $ldactivity = JsonLD::compact($activity);
1275                         $id = JsonLD::fetchElement($ldactivity, '@id');
1276                         if (!empty($id)) {
1277                                 $data['object'] = $id;
1278                                 return $data;
1279                         }
1280                 }
1281
1282                 $data['type'] = 'Create';
1283                 $data['object'] = self::createNote($item);
1284                 return $data;
1285         }
1286
1287         /**
1288          * Creates an activity id for a given contact id
1289          *
1290          * @param integer $cid Contact ID of target
1291          *
1292          * @return bool|string activity id
1293          */
1294         public static function activityIDFromContact($cid)
1295         {
1296                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1297                 if (!DBA::isResult($contact)) {
1298                         return false;
1299                 }
1300
1301                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1302                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1303                 return System::baseUrl() . '/activity/' . $uuid;
1304         }
1305
1306         /**
1307          * Transmits a contact suggestion to a given inbox
1308          *
1309          * @param integer $uid           User ID
1310          * @param string  $inbox         Target inbox
1311          * @param integer $suggestion_id Suggestion ID
1312          *
1313          * @return boolean was the transmission successful?
1314          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1315          */
1316         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1317         {
1318                 $owner = User::getOwnerDataById($uid);
1319
1320                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1321
1322                 $data = ['@context' => ActivityPub::CONTEXT,
1323                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1324                         'type' => 'Announce',
1325                         'actor' => $owner['url'],
1326                         'object' => $suggestion['url'],
1327                         'content' => $suggestion['note'],
1328                         'instrument' => self::getService(),
1329                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1330                         'cc' => []];
1331
1332                 $signed = LDSignature::sign($data, $owner);
1333
1334                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1335                 return HTTPSignature::transmit($signed, $inbox, $uid);
1336         }
1337
1338         /**
1339          * Transmits a profile relocation to a given inbox
1340          *
1341          * @param integer $uid   User ID
1342          * @param string  $inbox Target inbox
1343          *
1344          * @return boolean was the transmission successful?
1345          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1346          */
1347         public static function sendProfileRelocation($uid, $inbox)
1348         {
1349                 $owner = User::getOwnerDataById($uid);
1350
1351                 $data = ['@context' => ActivityPub::CONTEXT,
1352                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1353                         'type' => 'dfrn:relocate',
1354                         'actor' => $owner['url'],
1355                         'object' => $owner['url'],
1356                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1357                         'instrument' => self::getService(),
1358                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1359                         'cc' => []];
1360
1361                 $signed = LDSignature::sign($data, $owner);
1362
1363                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1364                 return HTTPSignature::transmit($signed, $inbox, $uid);
1365         }
1366
1367         /**
1368          * Transmits a profile deletion to a given inbox
1369          *
1370          * @param integer $uid   User ID
1371          * @param string  $inbox Target inbox
1372          *
1373          * @return boolean was the transmission successful?
1374          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1375          */
1376         public static function sendProfileDeletion($uid, $inbox)
1377         {
1378                 $owner = User::getOwnerDataById($uid);
1379
1380                 if (empty($owner)) {
1381                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1382                         return false;
1383                 }
1384
1385                 if (empty($owner['uprvkey'])) {
1386                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1387                         return false;
1388                 }
1389
1390                 $data = ['@context' => ActivityPub::CONTEXT,
1391                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1392                         'type' => 'Delete',
1393                         'actor' => $owner['url'],
1394                         'object' => $owner['url'],
1395                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1396                         'instrument' => self::getService(),
1397                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1398                         'cc' => []];
1399
1400                 $signed = LDSignature::sign($data, $owner);
1401
1402                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1403                 return HTTPSignature::transmit($signed, $inbox, $uid);
1404         }
1405
1406         /**
1407          * Transmits a profile change to a given inbox
1408          *
1409          * @param integer $uid   User ID
1410          * @param string  $inbox Target inbox
1411          *
1412          * @return boolean was the transmission successful?
1413          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1414          * @throws \ImagickException
1415          */
1416         public static function sendProfileUpdate($uid, $inbox)
1417         {
1418                 $owner = User::getOwnerDataById($uid);
1419                 $profile = APContact::getByURL($owner['url']);
1420
1421                 $data = ['@context' => ActivityPub::CONTEXT,
1422                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1423                         'type' => 'Update',
1424                         'actor' => $owner['url'],
1425                         'object' => self::getProfile($uid),
1426                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1427                         'instrument' => self::getService(),
1428                         'to' => [$profile['followers']],
1429                         'cc' => []];
1430
1431                 $signed = LDSignature::sign($data, $owner);
1432
1433                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1434                 return HTTPSignature::transmit($signed, $inbox, $uid);
1435         }
1436
1437         /**
1438          * Transmits a given activity to a target
1439          *
1440          * @param string  $activity Type name
1441          * @param string  $target   Target profile
1442          * @param integer $uid      User ID
1443          * @return bool
1444          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1445          * @throws \ImagickException
1446          * @throws \Exception
1447          */
1448         public static function sendActivity($activity, $target, $uid, $id = '')
1449         {
1450                 $profile = APContact::getByURL($target);
1451
1452                 $owner = User::getOwnerDataById($uid);
1453
1454                 if (empty($id)) {
1455                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1456                 }
1457
1458                 $data = ['@context' => ActivityPub::CONTEXT,
1459                         'id' => $id,
1460                         'type' => $activity,
1461                         'actor' => $owner['url'],
1462                         'object' => $profile['url'],
1463                         'instrument' => self::getService(),
1464                         'to' => [$profile['url']]];
1465
1466                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1467
1468                 $signed = LDSignature::sign($data, $owner);
1469                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1470         }
1471
1472         /**
1473          * Transmits a "follow object" activity to a target
1474          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1475          *
1476          * @param string  $object Object URL
1477          * @param string  $target Target profile
1478          * @param integer $uid    User ID
1479          * @return bool
1480          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1481          * @throws \ImagickException
1482          * @throws \Exception
1483          */
1484         public static function sendFollowObject($object, $target, $uid = 0)
1485         {
1486                 $profile = APContact::getByURL($target);
1487
1488                 if (empty($uid)) {
1489                         // Fetch the list of administrators
1490                         $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1491
1492                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1493                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1494                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1495                         $uid = $first_user['uid'];
1496                 }
1497
1498                 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1499                         'author-id' => Contact::getPublicIdByUserId($uid)];
1500                 if (Item::exists($condition)) {
1501                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1502                         return false;
1503                 }
1504
1505                 $owner = User::getOwnerDataById($uid);
1506
1507                 $data = ['@context' => ActivityPub::CONTEXT,
1508                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1509                         'type' => 'Follow',
1510                         'actor' => $owner['url'],
1511                         'object' => $object,
1512                         'instrument' => self::getService(),
1513                         'to' => [$profile['url']]];
1514
1515                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1516
1517                 $signed = LDSignature::sign($data, $owner);
1518                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1519         }
1520
1521         /**
1522          * Transmit a message that the contact request had been accepted
1523          *
1524          * @param string  $target Target profile
1525          * @param         $id
1526          * @param integer $uid    User ID
1527          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1528          * @throws \ImagickException
1529          */
1530         public static function sendContactAccept($target, $id, $uid)
1531         {
1532                 $profile = APContact::getByURL($target);
1533
1534                 $owner = User::getOwnerDataById($uid);
1535                 $data = ['@context' => ActivityPub::CONTEXT,
1536                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1537                         'type' => 'Accept',
1538                         'actor' => $owner['url'],
1539                         'object' => ['id' => $id, 'type' => 'Follow',
1540                                 'actor' => $profile['url'],
1541                                 'object' => $owner['url']],
1542                         'instrument' => self::getService(),
1543                         'to' => [$profile['url']]];
1544
1545                 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1546
1547                 $signed = LDSignature::sign($data, $owner);
1548                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1549         }
1550
1551         /**
1552          * Reject a contact request or terminates the contact relation
1553          *
1554          * @param string  $target Target profile
1555          * @param         $id
1556          * @param integer $uid    User ID
1557          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1558          * @throws \ImagickException
1559          */
1560         public static function sendContactReject($target, $id, $uid)
1561         {
1562                 $profile = APContact::getByURL($target);
1563
1564                 $owner = User::getOwnerDataById($uid);
1565                 $data = ['@context' => ActivityPub::CONTEXT,
1566                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1567                         'type' => 'Reject',
1568                         'actor' => $owner['url'],
1569                         'object' => ['id' => $id, 'type' => 'Follow',
1570                                 'actor' => $profile['url'],
1571                                 'object' => $owner['url']],
1572                         'instrument' => self::getService(),
1573                         'to' => [$profile['url']]];
1574
1575                 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1576
1577                 $signed = LDSignature::sign($data, $owner);
1578                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1579         }
1580
1581         /**
1582          * Transmits a message that we don't want to follow this contact anymore
1583          *
1584          * @param string  $target Target profile
1585          * @param integer $uid    User ID
1586          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1587          * @throws \ImagickException
1588          * @throws \Exception
1589          */
1590         public static function sendContactUndo($target, $cid, $uid)
1591         {
1592                 $profile = APContact::getByURL($target);
1593
1594                 $object_id = self::activityIDFromContact($cid);
1595                 if (empty($object_id)) {
1596                         return;
1597                 }
1598
1599                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1600
1601                 $owner = User::getOwnerDataById($uid);
1602                 $data = ['@context' => ActivityPub::CONTEXT,
1603                         'id' => $id,
1604                         'type' => 'Undo',
1605                         'actor' => $owner['url'],
1606                         'object' => ['id' => $object_id, 'type' => 'Follow',
1607                                 'actor' => $owner['url'],
1608                                 'object' => $profile['url']],
1609                         'instrument' => self::getService(),
1610                         'to' => [$profile['url']]];
1611
1612                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1613
1614                 $signed = LDSignature::sign($data, $owner);
1615                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1616         }
1617
1618         private static function prependMentions($body, array $permission_block)
1619         {
1620                 if (Config::get('system', 'disable_implicit_mentions')) {
1621                         return $body;
1622                 }
1623
1624                 $mentions = [];
1625
1626                 foreach ($permission_block['to'] as $profile_url) {
1627                         $profile = Contact::getDetailsByURL($profile_url);
1628                         if (!empty($profile['addr'])
1629                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1630                                 && !strstr($body, $profile['addr'])
1631                                 && !strstr($body, $profile_url)
1632                         ) {
1633                                 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1634                         }
1635                 }
1636
1637                 $mentions[] = $body;
1638
1639                 return implode(' ', $mentions);
1640         }
1641 }