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