]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
545ac22c699b0a668cfe486c7d17f617dd01d123
[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\Content\Text\BBCode;
10 use Friendica\Content\Text\Plaintext;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\Item;
21 use Friendica\Model\Profile;
22 use Friendica\Model\Photo;
23 use Friendica\Model\Term;
24 use Friendica\Model\User;
25 use Friendica\Protocol\Activity;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\HTTPSignature;
29 use Friendica\Util\Images;
30 use Friendica\Util\JsonLD;
31 use Friendica\Util\LDSignature;
32 use Friendica\Util\Map;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
35
36 require_once 'include/api.php';
37 require_once 'mod/share.php';
38
39 /**
40  * @brief ActivityPub Transmitter Protocol class
41  *
42  * To-Do:
43  * - Undo Announce
44  */
45 class Transmitter
46 {
47         /**
48          * collects the lost of followers of the given owner
49          *
50          * @param array   $owner Owner array
51          * @param integer $page  Page number
52          *
53          * @return array of owners
54          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
55          */
56         public static function getFollowers($owner, $page = null)
57         {
58                 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
59                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
60                 $count = DBA::count('contact', $condition);
61
62                 $data = ['@context' => ActivityPub::CONTEXT];
63                 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
64                 $data['type'] = 'OrderedCollection';
65                 $data['totalItems'] = $count;
66
67                 // When we hide our friends we will only show the pure number but don't allow more.
68                 $profile = Profile::getByUID($owner['uid']);
69                 if (!empty($profile['hide-friends'])) {
70                         return $data;
71                 }
72
73                 if (empty($page)) {
74                         $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
75                 } else {
76                         $data['type'] = 'OrderedCollectionPage';
77                         $list = [];
78
79                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
80                         while ($contact = DBA::fetch($contacts)) {
81                                 $list[] = $contact['url'];
82                         }
83
84                         if (!empty($list)) {
85                                 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
86                         }
87
88                         $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
89
90                         $data['orderedItems'] = $list;
91                 }
92
93                 return $data;
94         }
95
96         /**
97          * Create list of following contacts
98          *
99          * @param array   $owner Owner array
100          * @param integer $page  Page numbe
101          *
102          * @return array of following contacts
103          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
104          */
105         public static function getFollowing($owner, $page = null)
106         {
107                 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
108                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
109                 $count = DBA::count('contact', $condition);
110
111                 $data = ['@context' => ActivityPub::CONTEXT];
112                 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
113                 $data['type'] = 'OrderedCollection';
114                 $data['totalItems'] = $count;
115
116                 // When we hide our friends we will only show the pure number but don't allow more.
117                 $profile = Profile::getByUID($owner['uid']);
118                 if (!empty($profile['hide-friends'])) {
119                         return $data;
120                 }
121
122                 if (empty($page)) {
123                         $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
124                 } else {
125                         $data['type'] = 'OrderedCollectionPage';
126                         $list = [];
127
128                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
129                         while ($contact = DBA::fetch($contacts)) {
130                                 $list[] = $contact['url'];
131                         }
132
133                         if (!empty($list)) {
134                                 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
135                         }
136
137                         $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
138
139                         $data['orderedItems'] = $list;
140                 }
141
142                 return $data;
143         }
144
145         /**
146          * Public posts for the given owner
147          *
148          * @param array   $owner Owner array
149          * @param integer $page  Page numbe
150          *
151          * @return array of posts
152          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153          * @throws \ImagickException
154          */
155         public static function getOutbox($owner, $page = null)
156         {
157                 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
158
159                 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
160                         'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
161                         'deleted' => false, 'visible' => true, 'moderated' => false];
162                 $count = DBA::count('item', $condition);
163
164                 $data = ['@context' => ActivityPub::CONTEXT];
165                 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
166                 $data['type'] = 'OrderedCollection';
167                 $data['totalItems'] = $count;
168
169                 if (empty($page)) {
170                         $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
171                 } else {
172                         $data['type'] = 'OrderedCollectionPage';
173                         $list = [];
174
175                         $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
176
177                         $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
178                         while ($item = Item::fetch($items)) {
179                                 $object = self::createObjectFromItemID($item['id']);
180                                 unset($object['@context']);
181                                 $list[] = $object;
182                         }
183
184                         if (!empty($list)) {
185                                 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
186                         }
187
188                         $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
189
190                         $data['orderedItems'] = $list;
191                 }
192
193                 return $data;
194         }
195
196         /**
197          * Return the service array containing information the used software and it's url
198          *
199          * @return array with service data
200          */
201         private static function getService()
202         {
203                 return ['type' => 'Service',
204                         'name' =>  FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
205                         'url' => BaseObject::getApp()->getBaseURL()];
206         }
207
208         /**
209          * Return the ActivityPub profile of the given user
210          *
211          * @param integer $uid User ID
212          * @return array with profile data
213          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
214          */
215         public static function getProfile($uid)
216         {
217                 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
218                         'account_removed' => false, 'verified' => true];
219                 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
220                 $user = DBA::selectFirst('user', $fields, $condition);
221                 if (!DBA::isResult($user)) {
222                         return [];
223                 }
224
225                 $fields = ['locality', 'region', 'country-name'];
226                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
227                 if (!DBA::isResult($profile)) {
228                         return [];
229                 }
230
231                 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
232                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
233                 if (!DBA::isResult($contact)) {
234                         return [];
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['photo']];
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::FEDERATED;
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, true);
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::FEDERATED;
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 (Contact::isLocal($contact['url'])) {
553                                 continue;
554                         }
555
556                         if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
557                                 continue;
558                         }
559
560                         if (Network::isUrlBlocked($contact['url'])) {
561                                 continue;
562                         }
563
564                         $profile = APContact::getByURL($contact['url'], false);
565                         if (!empty($profile)) {
566                                 if (empty($profile['sharedinbox']) || $personal) {
567                                         $target = $profile['inbox'];
568                                 } else {
569                                         $target = $profile['sharedinbox'];
570                                 }
571                                 if (!self::archivedInbox($target)) {
572                                         $inboxes[$target] = $target;
573                                 }
574                         }
575                 }
576                 DBA::close($contacts);
577
578                 return $inboxes;
579         }
580
581         /**
582          * Fetches an array of inboxes for the given item and user
583          *
584          * @param array   $item       Item array
585          * @param integer $uid        User ID
586          * @param boolean $personal   fetch personal inboxes
587          * @param integer $last_id    Last item id for adding receivers
588          * @param boolean $forum_mode "true" means that we are sending content to a forum
589          * @return array with inboxes
590          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
591          * @throws \ImagickException
592          */
593         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
594         {
595                 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
596                 if (empty($permissions)) {
597                         return [];
598                 }
599
600                 $inboxes = [];
601
602                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
603                         $item_profile = APContact::getByURL($item['author-link'], false);
604                 } else {
605                         $item_profile = APContact::getByURL($item['owner-link'], false);
606                 }
607
608                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
609                         if (empty($permissions[$element])) {
610                                 continue;
611                         }
612
613                         $blindcopy = in_array($element, ['bto', 'bcc']);
614
615                         foreach ($permissions[$element] as $receiver) {
616                                 if (Network::isUrlBlocked($receiver)) {
617                                         continue;
618                                 }
619
620                                 if ($receiver == $item_profile['followers']) {
621                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
622                                 } else {
623                                         if (Contact::isLocal($receiver)) {
624                                                 continue;
625                                         }
626
627                                         $profile = APContact::getByURL($receiver, false);
628                                         if (!empty($profile)) {
629                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
630                                                         $target = $profile['inbox'];
631                                                 } else {
632                                                         $target = $profile['sharedinbox'];
633                                                 }
634                                                 if (!self::archivedInbox($target)) {
635                                                         $inboxes[$target] = $target;
636                                                 }
637                                         }
638                                 }
639                         }
640                 }
641
642                 return $inboxes;
643         }
644
645         /**
646          * Creates an array in the structure of the item table for a given mail id
647          *
648          * @param integer $mail_id
649          *
650          * @return array
651          * @throws \Exception
652          */
653         public static function ItemArrayFromMail($mail_id)
654         {
655                 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
656
657                 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
658
659                 // Making the post more compatible for Mastodon by:
660                 // - Making it a note and not an article (no title)
661                 // - Moving the title into the "summary" field that is used as a "content warning"
662                 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
663                 $mail['title'] = '';
664
665                 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
666                 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
667                 $mail['allow_gid'] = '';
668                 $mail['deny_cid'] = '';
669                 $mail['deny_gid'] = '';
670                 $mail['private'] = true;
671                 $mail['deleted'] = false;
672                 $mail['edited'] = $mail['created'];
673                 $mail['plink'] = $mail['uri'];
674                 $mail['thr-parent'] = $reply['uri'];
675                 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
676
677                 $mail['event-type'] = '';
678                 $mail['attach'] = '';
679
680                 $mail['parent'] = 0;
681
682                 return $mail;
683         }
684
685         /**
686          * Creates an activity array for a given mail id
687          *
688          * @param integer $mail_id
689          * @param boolean $object_mode Is the activity item is used inside another object?
690          *
691          * @return array of activity
692          * @throws \Exception
693          */
694         public static function createActivityFromMail($mail_id, $object_mode = false)
695         {
696                 $mail = self::ItemArrayFromMail($mail_id);
697                 $object = self::createNote($mail);
698
699                 $object['to'] = $object['cc'];
700                 unset($object['cc']);
701
702                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => 'test']];
703
704                 if (!$object_mode) {
705                         $data = ['@context' => ActivityPub::CONTEXT];
706                 } else {
707                         $data = [];
708                 }
709
710                 $data['id'] = $mail['uri'] . '#Create';
711                 $data['type'] = 'Create';
712                 $data['actor'] = $mail['author-link'];
713                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
714                 $data['instrument'] = self::getService();
715                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
716
717                 if (empty($data['to']) && !empty($data['cc'])) {
718                         $data['to'] = $data['cc'];
719                 }
720
721                 if (empty($data['to']) && !empty($data['bcc'])) {
722                         $data['to'] = $data['bcc'];
723                 }
724
725                 unset($data['cc']);
726                 unset($data['bcc']);
727
728                 $object['to'] = $data['to'];
729                 unset($object['cc']);
730                 unset($object['bcc']);
731
732                 $data['directMessage'] = true;
733
734                 $data['object'] = $object;
735
736                 $owner = User::getOwnerDataById($mail['uid']);
737
738                 if (!$object_mode && !empty($owner)) {
739                         return LDSignature::sign($data, $owner);
740                 } else {
741                         return $data;
742                 }
743         }
744
745         /**
746          * Returns the activity type of a given item
747          *
748          * @param array $item
749          *
750          * @return string with activity type
751          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
752          * @throws \ImagickException
753          */
754         private static function getTypeOfItem($item)
755         {
756                 $reshared = false;
757
758                 // Only check for a reshare, if it is a real reshare and no quoted reshare
759                 if (strpos($item['body'], "[share") === 0) {
760                         $announce = api_share_as_retweet($item);
761                         $reshared = !empty($announce['plink']);
762                 }
763
764                 if ($reshared) {
765                         $type = 'Announce';
766                 } elseif ($item['verb'] == Activity::POST) {
767                         if ($item['created'] == $item['edited']) {
768                                 $type = 'Create';
769                         } else {
770                                 $type = 'Update';
771                         }
772                 } elseif ($item['verb'] == Activity::LIKE) {
773                         $type = 'Like';
774                 } elseif ($item['verb'] == Activity::DISLIKE) {
775                         $type = 'Dislike';
776                 } elseif ($item['verb'] == Activity::ATTEND) {
777                         $type = 'Accept';
778                 } elseif ($item['verb'] == Activity::ATTENDNO) {
779                         $type = 'Reject';
780                 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
781                         $type = 'TentativeAccept';
782                 } elseif ($item['verb'] == Activity::FOLLOW) {
783                         $type = 'Follow';
784                 } elseif ($item['verb'] == Activity::TAG) {
785                         $type = 'Add';
786                 } else {
787                         $type = '';
788                 }
789
790                 return $type;
791         }
792
793         /**
794          * Creates the activity or fetches it from the cache
795          *
796          * @param integer $item_id
797          * @param boolean $force Force new cache entry
798          *
799          * @return array with the activity
800          * @throws \Exception
801          */
802         public static function createCachedActivityFromItem($item_id, $force = false)
803         {
804                 $cachekey = 'APDelivery:createActivity:' . $item_id;
805
806                 if (!$force) {
807                         $data = Cache::get($cachekey);
808                         if (!is_null($data)) {
809                                 return $data;
810                         }
811                 }
812
813                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
814
815                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
816                 return $data;
817         }
818
819         /**
820          * Creates an activity array for a given item id
821          *
822          * @param integer $item_id
823          * @param boolean $object_mode Is the activity item is used inside another object?
824          *
825          * @return array of activity
826          * @throws \Exception
827          */
828         public static function createActivityFromItem($item_id, $object_mode = false)
829         {
830                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
831
832                 if (!DBA::isResult($item)) {
833                         return false;
834                 }
835
836                 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
837                         $owner = User::getOwnerDataById($item['uid']);
838                         if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
839                                 $type = 'Announce';
840
841                                 // Disguise forum posts as reshares. Will later be converted to a real announce
842                                 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
843                                         $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
844                         }
845                 }
846
847                 if (empty($type)) {
848                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
849                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
850                         if (DBA::isResult($conversation)) {
851                                 $data = json_decode($conversation['source'], true);
852                                 if (!empty($data)) {
853                                         return $data;
854                                 }
855                         }
856
857                         $type = self::getTypeOfItem($item);
858                 }
859
860                 if (!$object_mode) {
861                         $data = ['@context' => ActivityPub::CONTEXT];
862
863                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
864                                 $type = 'Undo';
865                         } elseif ($item['deleted']) {
866                                 $type = 'Delete';
867                         }
868                 } else {
869                         $data = [];
870                 }
871
872                 $data['id'] = $item['uri'] . '#' . $type;
873                 $data['type'] = $type;
874
875                 if (Item::isForumPost($item) && ($type != 'Announce')) {
876                         $data['actor'] = $item['author-link'];
877                 } else {
878                         $data['actor'] = $item['owner-link'];
879                 }
880
881                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
882
883                 $data['instrument'] = self::getService();
884
885                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
886
887                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
888                         $data['object'] = self::createNote($item);
889                 } elseif ($data['type'] == 'Add') {
890                         $data = self::createAddTag($item, $data);
891                 } elseif ($data['type'] == 'Announce') {
892                         $data = self::createAnnounce($item, $data);
893                 } elseif ($data['type'] == 'Follow') {
894                         $data['object'] = $item['parent-uri'];
895                 } elseif ($data['type'] == 'Undo') {
896                         $data['object'] = self::createActivityFromItem($item_id, true);
897                 } else {
898                         $data['diaspora:guid'] = $item['guid'];
899                         if (!empty($item['signed_text'])) {
900                                 $data['diaspora:like'] = $item['signed_text'];
901                         }
902                         $data['object'] = $item['thr-parent'];
903                 }
904
905                 if (!empty($item['contact-uid'])) {
906                         $uid = $item['contact-uid'];
907                 } else {
908                         $uid = $item['uid'];
909                 }
910
911                 $owner = User::getOwnerDataById($uid);
912
913                 if (!$object_mode && !empty($owner)) {
914                         return LDSignature::sign($data, $owner);
915                 } else {
916                         return $data;
917                 }
918
919                 /// @todo Create "conversation" entry
920         }
921
922         /**
923          * Creates an object array for a given item id
924          *
925          * @param integer $item_id
926          *
927          * @return array with the object data
928          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
929          * @throws \ImagickException
930          */
931         public static function createObjectFromItemID($item_id)
932         {
933                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
934
935                 if (!DBA::isResult($item)) {
936                         return false;
937                 }
938
939                 $data = ['@context' => ActivityPub::CONTEXT];
940                 $data = array_merge($data, self::createNote($item));
941
942                 return $data;
943         }
944
945         /**
946          * Creates a location entry for a given item array
947          *
948          * @param array $item
949          *
950          * @return array with location array
951          */
952         private static function createLocation($item)
953         {
954                 $location = ['type' => 'Place'];
955
956                 if (!empty($item['location'])) {
957                         $location['name'] = $item['location'];
958                 }
959
960                 $coord = [];
961
962                 if (empty($item['coord'])) {
963                         $coord = Map::getCoordinates($item['location']);
964                 } else {
965                         $coords = explode(' ', $item['coord']);
966                         if (count($coords) == 2) {
967                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
968                         }
969                 }
970
971                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
972                         $location['latitude'] = $coord['lat'];
973                         $location['longitude'] = $coord['lon'];
974                 }
975
976                 return $location;
977         }
978
979         /**
980          * Returns a tag array for a given item array
981          *
982          * @param array $item
983          *
984          * @return array of tags
985          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
986          */
987         private static function createTagList($item)
988         {
989                 $tags = [];
990
991                 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
992                 foreach ($terms as $term) {
993                         if ($term['type'] == Term::HASHTAG) {
994                                 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
995                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
996                         } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
997                                 $contact = Contact::getDetailsByURL($term['url']);
998                                 if (!empty($contact['addr'])) {
999                                         $mention = '@' . $contact['addr'];
1000                                 } else {
1001                                         $mention = '@' . $term['url'];
1002                                 }
1003
1004                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1005                         }
1006                 }
1007                 return $tags;
1008         }
1009
1010         /**
1011          * Adds attachment data to the JSON document
1012          *
1013          * @param array  $item Data of the item that is to be posted
1014          * @param string $type Object type
1015          *
1016          * @return array with attachment data
1017          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018          */
1019         private static function createAttachmentList($item, $type)
1020         {
1021                 $attachments = [];
1022
1023                 $arr = explode('[/attach],', $item['attach']);
1024                 if (count($arr)) {
1025                         foreach ($arr as $r) {
1026                                 $matches = false;
1027                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1028                                 if ($cnt) {
1029                                         $attributes = ['type' => 'Document',
1030                                                         'mediaType' => $matches[3],
1031                                                         'url' => $matches[1],
1032                                                         'name' => null];
1033
1034                                         if (trim($matches[4]) != '') {
1035                                                 $attributes['name'] = trim($matches[4]);
1036                                         }
1037
1038                                         $attachments[] = $attributes;
1039                                 }
1040                         }
1041                 }
1042
1043                 if ($type != 'Note') {
1044                         return $attachments;
1045                 }
1046
1047                 // Simplify image codes
1048                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1049
1050                 // Grab all pictures without alternative descriptions and create attachments out of them
1051                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1052                         foreach ($pictures[1] as $picture) {
1053                                 $imgdata = Images::getInfoFromURLCached($picture);
1054                                 if ($imgdata) {
1055                                         $attachments[] = ['type' => 'Document',
1056                                                 'mediaType' => $imgdata['mime'],
1057                                                 'url' => $picture,
1058                                                 'name' => null];
1059                                 }
1060                         }
1061                 }
1062
1063                 // Grab all pictures with alternative description and create attachments out of them
1064                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1065                         foreach ($pictures as $picture) {
1066                                 $imgdata = Images::getInfoFromURLCached($picture[1]);
1067                                 if ($imgdata) {
1068                                         $attachments[] = ['type' => 'Document',
1069                                                 'mediaType' => $imgdata['mime'],
1070                                                 'url' => $picture[1],
1071                                                 'name' => $picture[2]];
1072                                 }
1073                         }
1074                 }
1075
1076                 return $attachments;
1077         }
1078
1079         /**
1080          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1081          *
1082          * @param array $match Matching values for the callback
1083          * @return string Replaced mention
1084          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1085          */
1086         private static function mentionCallback($match)
1087         {
1088                 if (empty($match[1])) {
1089                         return '';
1090                 }
1091
1092                 $data = Contact::getDetailsByURL($match[1]);
1093                 if (empty($data['nick'])) {
1094                         return $match[0];
1095                 }
1096
1097                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1098         }
1099
1100         /**
1101          * Remove image elements since they are added as attachment
1102          *
1103          * @param string $body
1104          *
1105          * @return string with removed images
1106          */
1107         private static function removePictures($body)
1108         {
1109                 // Simplify image codes
1110                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1111                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1112
1113                 // Now remove local links
1114                 $body = preg_replace_callback(
1115                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1116                         function ($match) {
1117                                 // We remove the link when it is a link to a local photo page
1118                                 if (Photo::isLocalPage($match[1])) {
1119                                         return '';
1120                                 }
1121                                 // otherwise we just return the link
1122                                 return '[url]' . $match[1] . '[/url]';
1123                         },
1124                         $body
1125                 );
1126
1127                 // Remove all pictures
1128                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1129
1130                 return $body;
1131         }
1132
1133         /**
1134          * Fetches the "context" value for a givem item array from the "conversation" table
1135          *
1136          * @param array $item
1137          *
1138          * @return string with context url
1139          * @throws \Exception
1140          */
1141         private static function fetchContextURLForItem($item)
1142         {
1143                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1144                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1145                         $context_uri = $conversation['conversation-href'];
1146                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1147                         $context_uri = $conversation['conversation-uri'];
1148                 } else {
1149                         $context_uri = $item['parent-uri'] . '#context';
1150                 }
1151                 return $context_uri;
1152         }
1153
1154         /**
1155          * Returns if the post contains sensitive content ("nsfw")
1156          *
1157          * @param integer $item_id
1158          *
1159          * @return boolean
1160          * @throws \Exception
1161          */
1162         private static function isSensitive($item_id)
1163         {
1164                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1165                 return DBA::exists('term', $condition);
1166         }
1167
1168         /**
1169          * Creates event data
1170          *
1171          * @param array $item
1172          *
1173          * @return array with the event data
1174          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1175          */
1176         public static function createEvent($item)
1177         {
1178                 $event = [];
1179                 $event['name'] = $item['event-summary'];
1180                 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1181                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1182
1183                 if (!$item['event-nofinish']) {
1184                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1185                 }
1186
1187                 if (!empty($item['event-location'])) {
1188                         $item['location'] = $item['event-location'];
1189                         $event['location'] = self::createLocation($item);
1190                 }
1191
1192                 return $event;
1193         }
1194
1195         /**
1196          * Creates a note/article object array
1197          *
1198          * @param array $item
1199          *
1200          * @return array with the object data
1201          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202          * @throws \ImagickException
1203          */
1204         public static function createNote($item)
1205         {
1206                 if ($item['event-type'] == 'event') {
1207                         $type = 'Event';
1208                 } elseif (!empty($item['title'])) {
1209                         $type = 'Article';
1210                 } else {
1211                         $type = 'Note';
1212                 }
1213
1214                 if ($item['deleted']) {
1215                         $type = 'Tombstone';
1216                 }
1217
1218                 $data = [];
1219                 $data['id'] = $item['uri'];
1220                 $data['type'] = $type;
1221
1222                 if ($item['deleted']) {
1223                         return $data;
1224                 }
1225
1226                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1227
1228                 if ($item['uri'] != $item['thr-parent']) {
1229                         $data['inReplyTo'] = $item['thr-parent'];
1230                 } else {
1231                         $data['inReplyTo'] = null;
1232                 }
1233
1234                 $data['diaspora:guid'] = $item['guid'];
1235                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1236
1237                 if ($item['created'] != $item['edited']) {
1238                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1239                 }
1240
1241                 $data['url'] = $item['plink'];
1242                 $data['attributedTo'] = $item['author-link'];
1243                 $data['sensitive'] = self::isSensitive($item['id']);
1244                 $data['context'] = self::fetchContextURLForItem($item);
1245
1246                 if (!empty($item['title'])) {
1247                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1248                 }
1249
1250                 $permission_block = self::createPermissionBlockForItem($item, false);
1251
1252                 $body = $item['body'];
1253
1254                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1255                         $body = self::prependMentions($body, $permission_block);
1256                 }
1257
1258                 if ($type == 'Note') {
1259                         $body = self::removePictures($body);
1260                 } elseif (($type == 'Article') && empty($data['summary'])) {
1261                         $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1262                 }
1263
1264                 if ($type == 'Event') {
1265                         $data = array_merge($data, self::createEvent($item));
1266                 } else {
1267                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1268                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1269
1270                         $data['content'] = BBCode::convert($body, false, 9);
1271                 }
1272
1273                 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1274                 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1275
1276                 $data['contentMap']['text/html'] = BBCode::convert($richbody, false);
1277                 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1278
1279                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1280
1281                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1282                         $data['diaspora:comment'] = $item['signed_text'];
1283                 }
1284
1285                 $data['attachment'] = self::createAttachmentList($item, $type);
1286                 $data['tag'] = self::createTagList($item);
1287
1288                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1289                         $data['location'] = self::createLocation($item);
1290                 }
1291
1292                 if (!empty($item['app'])) {
1293                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1294                 }
1295
1296                 $data = array_merge($data, $permission_block);
1297
1298                 return $data;
1299         }
1300
1301         /**
1302          * Creates an an "add tag" entry
1303          *
1304          * @param array $item
1305          * @param array $data activity data
1306          *
1307          * @return array with activity data for adding tags
1308          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1309          * @throws \ImagickException
1310          */
1311         private static function createAddTag($item, $data)
1312         {
1313                 $object = XML::parseString($item['object'], false);
1314                 $target = XML::parseString($item["target"], false);
1315
1316                 $data['diaspora:guid'] = $item['guid'];
1317                 $data['actor'] = $item['author-link'];
1318                 $data['target'] = (string)$target->id;
1319                 $data['summary'] = BBCode::toPlaintext($item['body']);
1320                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1321
1322                 return $data;
1323         }
1324
1325         /**
1326          * Creates an announce object entry
1327          *
1328          * @param array $item
1329          * @param array $data activity data
1330          *
1331          * @return array with activity data
1332          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1333          * @throws \ImagickException
1334          */
1335         private static function createAnnounce($item, $data)
1336         {
1337                 $orig_body = $item['body'];
1338                 $announce = api_share_as_retweet($item);
1339                 if (empty($announce['plink'])) {
1340                         $data['type'] = 'Create';
1341                         $data['object'] = self::createNote($item);
1342                         return $data;
1343                 }
1344
1345                 // Fetch the original id of the object
1346                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1347                 if (!empty($activity)) {
1348                         $ldactivity = JsonLD::compact($activity);
1349                         $id = JsonLD::fetchElement($ldactivity, '@id');
1350                         $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1351                         if (!empty($id)) {
1352                                 if (empty($announce['share-pre-body'])) {
1353                                         // Pure announce, without a quote
1354                                         $data['type'] = 'Announce';
1355                                         $data['object'] = $id;
1356                                         return $data;
1357                                 }
1358
1359                                 // Quote
1360                                 $data['type'] = 'Create';
1361                                 $item['body'] = trim($announce['share-pre-body']) . "\n" . $id;
1362                                 $data['object'] = self::createNote($item);
1363
1364                                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1365                                 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1366
1367                                 $data['object']['source']['content'] = $orig_body;
1368                                 return $data;
1369                         }
1370                 }
1371
1372                 $item['body'] = $orig_body;
1373                 $data['type'] = 'Create';
1374                 $data['object'] = self::createNote($item);
1375                 return $data;
1376         }
1377
1378         /**
1379          * Creates an activity id for a given contact id
1380          *
1381          * @param integer $cid Contact ID of target
1382          *
1383          * @return bool|string activity id
1384          */
1385         public static function activityIDFromContact($cid)
1386         {
1387                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1388                 if (!DBA::isResult($contact)) {
1389                         return false;
1390                 }
1391
1392                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1393                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1394                 return System::baseUrl() . '/activity/' . $uuid;
1395         }
1396
1397         /**
1398          * Transmits a contact suggestion to a given inbox
1399          *
1400          * @param integer $uid           User ID
1401          * @param string  $inbox         Target inbox
1402          * @param integer $suggestion_id Suggestion ID
1403          *
1404          * @return boolean was the transmission successful?
1405          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1406          */
1407         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1408         {
1409                 $owner = User::getOwnerDataById($uid);
1410
1411                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1412
1413                 $data = ['@context' => ActivityPub::CONTEXT,
1414                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1415                         'type' => 'Announce',
1416                         'actor' => $owner['url'],
1417                         'object' => $suggestion['url'],
1418                         'content' => $suggestion['note'],
1419                         'instrument' => self::getService(),
1420                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1421                         'cc' => []];
1422
1423                 $signed = LDSignature::sign($data, $owner);
1424
1425                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1426                 return HTTPSignature::transmit($signed, $inbox, $uid);
1427         }
1428
1429         /**
1430          * Transmits a profile relocation to a given inbox
1431          *
1432          * @param integer $uid   User ID
1433          * @param string  $inbox Target inbox
1434          *
1435          * @return boolean was the transmission successful?
1436          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1437          */
1438         public static function sendProfileRelocation($uid, $inbox)
1439         {
1440                 $owner = User::getOwnerDataById($uid);
1441
1442                 $data = ['@context' => ActivityPub::CONTEXT,
1443                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1444                         'type' => 'dfrn:relocate',
1445                         'actor' => $owner['url'],
1446                         'object' => $owner['url'],
1447                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1448                         'instrument' => self::getService(),
1449                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1450                         'cc' => []];
1451
1452                 $signed = LDSignature::sign($data, $owner);
1453
1454                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1455                 return HTTPSignature::transmit($signed, $inbox, $uid);
1456         }
1457
1458         /**
1459          * Transmits a profile deletion to a given inbox
1460          *
1461          * @param integer $uid   User ID
1462          * @param string  $inbox Target inbox
1463          *
1464          * @return boolean was the transmission successful?
1465          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1466          */
1467         public static function sendProfileDeletion($uid, $inbox)
1468         {
1469                 $owner = User::getOwnerDataById($uid);
1470
1471                 if (empty($owner)) {
1472                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1473                         return false;
1474                 }
1475
1476                 if (empty($owner['uprvkey'])) {
1477                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1478                         return false;
1479                 }
1480
1481                 $data = ['@context' => ActivityPub::CONTEXT,
1482                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1483                         'type' => 'Delete',
1484                         'actor' => $owner['url'],
1485                         'object' => $owner['url'],
1486                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1487                         'instrument' => self::getService(),
1488                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1489                         'cc' => []];
1490
1491                 $signed = LDSignature::sign($data, $owner);
1492
1493                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1494                 return HTTPSignature::transmit($signed, $inbox, $uid);
1495         }
1496
1497         /**
1498          * Transmits a profile change to a given inbox
1499          *
1500          * @param integer $uid   User ID
1501          * @param string  $inbox Target inbox
1502          *
1503          * @return boolean was the transmission successful?
1504          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1505          * @throws \ImagickException
1506          */
1507         public static function sendProfileUpdate($uid, $inbox)
1508         {
1509                 $owner = User::getOwnerDataById($uid);
1510                 $profile = APContact::getByURL($owner['url']);
1511
1512                 $data = ['@context' => ActivityPub::CONTEXT,
1513                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1514                         'type' => 'Update',
1515                         'actor' => $owner['url'],
1516                         'object' => self::getProfile($uid),
1517                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1518                         'instrument' => self::getService(),
1519                         'to' => [$profile['followers']],
1520                         'cc' => []];
1521
1522                 $signed = LDSignature::sign($data, $owner);
1523
1524                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1525                 return HTTPSignature::transmit($signed, $inbox, $uid);
1526         }
1527
1528         /**
1529          * Transmits a given activity to a target
1530          *
1531          * @param string  $activity Type name
1532          * @param string  $target   Target profile
1533          * @param integer $uid      User ID
1534          * @return bool
1535          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1536          * @throws \ImagickException
1537          * @throws \Exception
1538          */
1539         public static function sendActivity($activity, $target, $uid, $id = '')
1540         {
1541                 $profile = APContact::getByURL($target);
1542                 if (empty($profile['inbox'])) {
1543                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1544                         return;
1545                 }
1546
1547                 $owner = User::getOwnerDataById($uid);
1548
1549                 if (empty($id)) {
1550                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1551                 }
1552
1553                 $data = ['@context' => ActivityPub::CONTEXT,
1554                         'id' => $id,
1555                         'type' => $activity,
1556                         'actor' => $owner['url'],
1557                         'object' => $profile['url'],
1558                         'instrument' => self::getService(),
1559                         'to' => [$profile['url']]];
1560
1561                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1562
1563                 $signed = LDSignature::sign($data, $owner);
1564                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1565         }
1566
1567         /**
1568          * Transmits a "follow object" activity to a target
1569          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1570          *
1571          * @param string  $object Object URL
1572          * @param string  $target Target profile
1573          * @param integer $uid    User ID
1574          * @return bool
1575          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1576          * @throws \ImagickException
1577          * @throws \Exception
1578          */
1579         public static function sendFollowObject($object, $target, $uid = 0)
1580         {
1581                 $profile = APContact::getByURL($target);
1582                 if (empty($profile['inbox'])) {
1583                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1584                         return;
1585                 }
1586
1587                 if (empty($uid)) {
1588                         // Fetch the list of administrators
1589                         $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1590
1591                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1592                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1593                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1594                         $uid = $first_user['uid'];
1595                 }
1596
1597                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1598                         'author-id' => Contact::getPublicIdByUserId($uid)];
1599                 if (Item::exists($condition)) {
1600                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1601                         return false;
1602                 }
1603
1604                 $owner = User::getOwnerDataById($uid);
1605
1606                 $data = ['@context' => ActivityPub::CONTEXT,
1607                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1608                         'type' => 'Follow',
1609                         'actor' => $owner['url'],
1610                         'object' => $object,
1611                         'instrument' => self::getService(),
1612                         'to' => [$profile['url']]];
1613
1614                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1615
1616                 $signed = LDSignature::sign($data, $owner);
1617                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1618         }
1619
1620         /**
1621          * Transmit a message that the contact request had been accepted
1622          *
1623          * @param string  $target Target profile
1624          * @param         $id
1625          * @param integer $uid    User ID
1626          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1627          * @throws \ImagickException
1628          */
1629         public static function sendContactAccept($target, $id, $uid)
1630         {
1631                 $profile = APContact::getByURL($target);
1632                 if (empty($profile['inbox'])) {
1633                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1634                         return;
1635                 }
1636
1637                 $owner = User::getOwnerDataById($uid);
1638                 $data = ['@context' => ActivityPub::CONTEXT,
1639                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1640                         'type' => 'Accept',
1641                         'actor' => $owner['url'],
1642                         'object' => [
1643                                 'id' => (string)$id,
1644                                 'type' => 'Follow',
1645                                 'actor' => $profile['url'],
1646                                 'object' => $owner['url']
1647                         ],
1648                         'instrument' => self::getService(),
1649                         'to' => [$profile['url']]];
1650
1651                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1652
1653                 $signed = LDSignature::sign($data, $owner);
1654                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1655         }
1656
1657         /**
1658          * Reject a contact request or terminates the contact relation
1659          *
1660          * @param string  $target Target profile
1661          * @param         $id
1662          * @param integer $uid    User ID
1663          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1664          * @throws \ImagickException
1665          */
1666         public static function sendContactReject($target, $id, $uid)
1667         {
1668                 $profile = APContact::getByURL($target);
1669                 if (empty($profile['inbox'])) {
1670                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1671                         return;
1672                 }
1673
1674                 $owner = User::getOwnerDataById($uid);
1675                 $data = ['@context' => ActivityPub::CONTEXT,
1676                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1677                         'type' => 'Reject',
1678                         'actor' => $owner['url'],
1679                         'object' => [
1680                                 'id' => (string)$id,
1681                                 'type' => 'Follow',
1682                                 'actor' => $profile['url'],
1683                                 'object' => $owner['url']
1684                         ],
1685                         'instrument' => self::getService(),
1686                         'to' => [$profile['url']]];
1687
1688                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1689
1690                 $signed = LDSignature::sign($data, $owner);
1691                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1692         }
1693
1694         /**
1695          * Transmits a message that we don't want to follow this contact anymore
1696          *
1697          * @param string  $target Target profile
1698          * @param integer $uid    User ID
1699          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1700          * @throws \ImagickException
1701          * @throws \Exception
1702          */
1703         public static function sendContactUndo($target, $cid, $uid)
1704         {
1705                 $profile = APContact::getByURL($target);
1706                 if (empty($profile['inbox'])) {
1707                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1708                         return;
1709                 }
1710
1711                 $object_id = self::activityIDFromContact($cid);
1712                 if (empty($object_id)) {
1713                         return;
1714                 }
1715
1716                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1717
1718                 $owner = User::getOwnerDataById($uid);
1719                 $data = ['@context' => ActivityPub::CONTEXT,
1720                         'id' => $id,
1721                         'type' => 'Undo',
1722                         'actor' => $owner['url'],
1723                         'object' => ['id' => $object_id, 'type' => 'Follow',
1724                                 'actor' => $owner['url'],
1725                                 'object' => $profile['url']],
1726                         'instrument' => self::getService(),
1727                         'to' => [$profile['url']]];
1728
1729                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1730
1731                 $signed = LDSignature::sign($data, $owner);
1732                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1733         }
1734
1735         private static function prependMentions($body, array $permission_block)
1736         {
1737                 if (Config::get('system', 'disable_implicit_mentions')) {
1738                         return $body;
1739                 }
1740
1741                 $mentions = [];
1742
1743                 foreach ($permission_block['to'] as $profile_url) {
1744                         $profile = Contact::getDetailsByURL($profile_url);
1745                         if (!empty($profile['addr'])
1746                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1747                                 && !strstr($body, $profile['addr'])
1748                                 && !strstr($body, $profile_url)
1749                         ) {
1750                                 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1751                         }
1752                 }
1753
1754                 $mentions[] = $body;
1755
1756                 return implode(' ', $mentions);
1757         }
1758 }