]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
82ee97c9ededb6732852499608607582e0fcb85d
[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                 $data['contentMap']['text/html'] = BBCode::convert($item['body'], false);
1274                 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1275
1276                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1277
1278                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1279                         $data['diaspora:comment'] = $item['signed_text'];
1280                 }
1281
1282                 $data['attachment'] = self::createAttachmentList($item, $type);
1283                 $data['tag'] = self::createTagList($item);
1284
1285                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1286                         $data['location'] = self::createLocation($item);
1287                 }
1288
1289                 if (!empty($item['app'])) {
1290                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1291                 }
1292
1293                 $data = array_merge($data, $permission_block);
1294
1295                 return $data;
1296         }
1297
1298         /**
1299          * Creates an an "add tag" entry
1300          *
1301          * @param array $item
1302          * @param array $data activity data
1303          *
1304          * @return array with activity data for adding tags
1305          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1306          * @throws \ImagickException
1307          */
1308         private static function createAddTag($item, $data)
1309         {
1310                 $object = XML::parseString($item['object'], false);
1311                 $target = XML::parseString($item["target"], false);
1312
1313                 $data['diaspora:guid'] = $item['guid'];
1314                 $data['actor'] = $item['author-link'];
1315                 $data['target'] = (string)$target->id;
1316                 $data['summary'] = BBCode::toPlaintext($item['body']);
1317                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1318
1319                 return $data;
1320         }
1321
1322         /**
1323          * Creates an announce object entry
1324          *
1325          * @param array $item
1326          * @param array $data activity data
1327          *
1328          * @return array with activity data
1329          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1330          * @throws \ImagickException
1331          */
1332         private static function createAnnounce($item, $data)
1333         {
1334                 $orig_body = $item['body'];
1335                 $announce = api_share_as_retweet($item);
1336                 if (empty($announce['plink'])) {
1337                         $data['type'] = 'Create';
1338                         $data['object'] = self::createNote($item);
1339                         return $data;
1340                 }
1341
1342                 // Fetch the original id of the object
1343                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1344                 if (!empty($activity)) {
1345                         $ldactivity = JsonLD::compact($activity);
1346                         $id = JsonLD::fetchElement($ldactivity, '@id');
1347                         $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1348                         if (!empty($id)) {
1349                                 if (empty($announce['share-pre-body'])) {
1350                                         // Pure announce, without a quote
1351                                         $data['type'] = 'Announce';
1352                                         $data['object'] = $id;
1353                                         return $data;
1354                                 }
1355
1356                                 // Quote
1357                                 $data['type'] = 'Create';
1358                                 $item['body'] = trim($announce['share-pre-body']) . "\n" . $id;
1359                                 $data['object'] = self::createNote($item);
1360
1361                                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1362                                 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1363
1364                                 $data['object']['source']['content'] = $orig_body;
1365                                 return $data;
1366                         }
1367                 }
1368
1369                 $item['body'] = $orig_body;
1370                 $data['type'] = 'Create';
1371                 $data['object'] = self::createNote($item);
1372                 return $data;
1373         }
1374
1375         /**
1376          * Creates an activity id for a given contact id
1377          *
1378          * @param integer $cid Contact ID of target
1379          *
1380          * @return bool|string activity id
1381          */
1382         public static function activityIDFromContact($cid)
1383         {
1384                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1385                 if (!DBA::isResult($contact)) {
1386                         return false;
1387                 }
1388
1389                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1390                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1391                 return System::baseUrl() . '/activity/' . $uuid;
1392         }
1393
1394         /**
1395          * Transmits a contact suggestion to a given inbox
1396          *
1397          * @param integer $uid           User ID
1398          * @param string  $inbox         Target inbox
1399          * @param integer $suggestion_id Suggestion ID
1400          *
1401          * @return boolean was the transmission successful?
1402          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1403          */
1404         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1405         {
1406                 $owner = User::getOwnerDataById($uid);
1407
1408                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1409
1410                 $data = ['@context' => ActivityPub::CONTEXT,
1411                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1412                         'type' => 'Announce',
1413                         'actor' => $owner['url'],
1414                         'object' => $suggestion['url'],
1415                         'content' => $suggestion['note'],
1416                         'instrument' => self::getService(),
1417                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1418                         'cc' => []];
1419
1420                 $signed = LDSignature::sign($data, $owner);
1421
1422                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1423                 return HTTPSignature::transmit($signed, $inbox, $uid);
1424         }
1425
1426         /**
1427          * Transmits a profile relocation to a given inbox
1428          *
1429          * @param integer $uid   User ID
1430          * @param string  $inbox Target inbox
1431          *
1432          * @return boolean was the transmission successful?
1433          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1434          */
1435         public static function sendProfileRelocation($uid, $inbox)
1436         {
1437                 $owner = User::getOwnerDataById($uid);
1438
1439                 $data = ['@context' => ActivityPub::CONTEXT,
1440                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1441                         'type' => 'dfrn:relocate',
1442                         'actor' => $owner['url'],
1443                         'object' => $owner['url'],
1444                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1445                         'instrument' => self::getService(),
1446                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1447                         'cc' => []];
1448
1449                 $signed = LDSignature::sign($data, $owner);
1450
1451                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1452                 return HTTPSignature::transmit($signed, $inbox, $uid);
1453         }
1454
1455         /**
1456          * Transmits a profile deletion to a given inbox
1457          *
1458          * @param integer $uid   User ID
1459          * @param string  $inbox Target inbox
1460          *
1461          * @return boolean was the transmission successful?
1462          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1463          */
1464         public static function sendProfileDeletion($uid, $inbox)
1465         {
1466                 $owner = User::getOwnerDataById($uid);
1467
1468                 if (empty($owner)) {
1469                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1470                         return false;
1471                 }
1472
1473                 if (empty($owner['uprvkey'])) {
1474                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1475                         return false;
1476                 }
1477
1478                 $data = ['@context' => ActivityPub::CONTEXT,
1479                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1480                         'type' => 'Delete',
1481                         'actor' => $owner['url'],
1482                         'object' => $owner['url'],
1483                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1484                         'instrument' => self::getService(),
1485                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1486                         'cc' => []];
1487
1488                 $signed = LDSignature::sign($data, $owner);
1489
1490                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1491                 return HTTPSignature::transmit($signed, $inbox, $uid);
1492         }
1493
1494         /**
1495          * Transmits a profile change to a given inbox
1496          *
1497          * @param integer $uid   User ID
1498          * @param string  $inbox Target inbox
1499          *
1500          * @return boolean was the transmission successful?
1501          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1502          * @throws \ImagickException
1503          */
1504         public static function sendProfileUpdate($uid, $inbox)
1505         {
1506                 $owner = User::getOwnerDataById($uid);
1507                 $profile = APContact::getByURL($owner['url']);
1508
1509                 $data = ['@context' => ActivityPub::CONTEXT,
1510                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1511                         'type' => 'Update',
1512                         'actor' => $owner['url'],
1513                         'object' => self::getProfile($uid),
1514                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1515                         'instrument' => self::getService(),
1516                         'to' => [$profile['followers']],
1517                         'cc' => []];
1518
1519                 $signed = LDSignature::sign($data, $owner);
1520
1521                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1522                 return HTTPSignature::transmit($signed, $inbox, $uid);
1523         }
1524
1525         /**
1526          * Transmits a given activity to a target
1527          *
1528          * @param string  $activity Type name
1529          * @param string  $target   Target profile
1530          * @param integer $uid      User ID
1531          * @return bool
1532          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1533          * @throws \ImagickException
1534          * @throws \Exception
1535          */
1536         public static function sendActivity($activity, $target, $uid, $id = '')
1537         {
1538                 $profile = APContact::getByURL($target);
1539                 if (empty($profile['inbox'])) {
1540                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1541                         return;
1542                 }
1543
1544                 $owner = User::getOwnerDataById($uid);
1545
1546                 if (empty($id)) {
1547                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1548                 }
1549
1550                 $data = ['@context' => ActivityPub::CONTEXT,
1551                         'id' => $id,
1552                         'type' => $activity,
1553                         'actor' => $owner['url'],
1554                         'object' => $profile['url'],
1555                         'instrument' => self::getService(),
1556                         'to' => [$profile['url']]];
1557
1558                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1559
1560                 $signed = LDSignature::sign($data, $owner);
1561                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1562         }
1563
1564         /**
1565          * Transmits a "follow object" activity to a target
1566          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1567          *
1568          * @param string  $object Object URL
1569          * @param string  $target Target profile
1570          * @param integer $uid    User ID
1571          * @return bool
1572          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1573          * @throws \ImagickException
1574          * @throws \Exception
1575          */
1576         public static function sendFollowObject($object, $target, $uid = 0)
1577         {
1578                 $profile = APContact::getByURL($target);
1579                 if (empty($profile['inbox'])) {
1580                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1581                         return;
1582                 }
1583
1584                 if (empty($uid)) {
1585                         // Fetch the list of administrators
1586                         $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1587
1588                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1589                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1590                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1591                         $uid = $first_user['uid'];
1592                 }
1593
1594                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1595                         'author-id' => Contact::getPublicIdByUserId($uid)];
1596                 if (Item::exists($condition)) {
1597                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1598                         return false;
1599                 }
1600
1601                 $owner = User::getOwnerDataById($uid);
1602
1603                 $data = ['@context' => ActivityPub::CONTEXT,
1604                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1605                         'type' => 'Follow',
1606                         'actor' => $owner['url'],
1607                         'object' => $object,
1608                         'instrument' => self::getService(),
1609                         'to' => [$profile['url']]];
1610
1611                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1612
1613                 $signed = LDSignature::sign($data, $owner);
1614                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1615         }
1616
1617         /**
1618          * Transmit a message that the contact request had been accepted
1619          *
1620          * @param string  $target Target profile
1621          * @param         $id
1622          * @param integer $uid    User ID
1623          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1624          * @throws \ImagickException
1625          */
1626         public static function sendContactAccept($target, $id, $uid)
1627         {
1628                 $profile = APContact::getByURL($target);
1629                 if (empty($profile['inbox'])) {
1630                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1631                         return;
1632                 }
1633
1634                 $owner = User::getOwnerDataById($uid);
1635                 $data = ['@context' => ActivityPub::CONTEXT,
1636                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1637                         'type' => 'Accept',
1638                         'actor' => $owner['url'],
1639                         'object' => [
1640                                 'id' => (string)$id,
1641                                 'type' => 'Follow',
1642                                 'actor' => $profile['url'],
1643                                 'object' => $owner['url']
1644                         ],
1645                         'instrument' => self::getService(),
1646                         'to' => [$profile['url']]];
1647
1648                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1649
1650                 $signed = LDSignature::sign($data, $owner);
1651                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1652         }
1653
1654         /**
1655          * Reject a contact request or terminates the contact relation
1656          *
1657          * @param string  $target Target profile
1658          * @param         $id
1659          * @param integer $uid    User ID
1660          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1661          * @throws \ImagickException
1662          */
1663         public static function sendContactReject($target, $id, $uid)
1664         {
1665                 $profile = APContact::getByURL($target);
1666                 if (empty($profile['inbox'])) {
1667                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1668                         return;
1669                 }
1670
1671                 $owner = User::getOwnerDataById($uid);
1672                 $data = ['@context' => ActivityPub::CONTEXT,
1673                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1674                         'type' => 'Reject',
1675                         'actor' => $owner['url'],
1676                         'object' => [
1677                                 'id' => (string)$id,
1678                                 'type' => 'Follow',
1679                                 'actor' => $profile['url'],
1680                                 'object' => $owner['url']
1681                         ],
1682                         'instrument' => self::getService(),
1683                         'to' => [$profile['url']]];
1684
1685                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1686
1687                 $signed = LDSignature::sign($data, $owner);
1688                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1689         }
1690
1691         /**
1692          * Transmits a message that we don't want to follow this contact anymore
1693          *
1694          * @param string  $target Target profile
1695          * @param integer $uid    User ID
1696          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1697          * @throws \ImagickException
1698          * @throws \Exception
1699          */
1700         public static function sendContactUndo($target, $cid, $uid)
1701         {
1702                 $profile = APContact::getByURL($target);
1703                 if (empty($profile['inbox'])) {
1704                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1705                         return;
1706                 }
1707
1708                 $object_id = self::activityIDFromContact($cid);
1709                 if (empty($object_id)) {
1710                         return;
1711                 }
1712
1713                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1714
1715                 $owner = User::getOwnerDataById($uid);
1716                 $data = ['@context' => ActivityPub::CONTEXT,
1717                         'id' => $id,
1718                         'type' => 'Undo',
1719                         'actor' => $owner['url'],
1720                         'object' => ['id' => $object_id, 'type' => 'Follow',
1721                                 'actor' => $owner['url'],
1722                                 'object' => $profile['url']],
1723                         'instrument' => self::getService(),
1724                         'to' => [$profile['url']]];
1725
1726                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1727
1728                 $signed = LDSignature::sign($data, $owner);
1729                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1730         }
1731
1732         private static function prependMentions($body, array $permission_block)
1733         {
1734                 if (Config::get('system', 'disable_implicit_mentions')) {
1735                         return $body;
1736                 }
1737
1738                 $mentions = [];
1739
1740                 foreach ($permission_block['to'] as $profile_url) {
1741                         $profile = Contact::getDetailsByURL($profile_url);
1742                         if (!empty($profile['addr'])
1743                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1744                                 && !strstr($body, $profile['addr'])
1745                                 && !strstr($body, $profile_url)
1746                         ) {
1747                                 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1748                         }
1749                 }
1750
1751                 $mentions[] = $body;
1752
1753                 return implode(' ', $mentions);
1754         }
1755 }