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