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