3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
25 use Friendica\Content\Feature;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Network\HTTPException;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Protocol\Relay;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\LDSignature;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
54 * ActivityPub Transmitter Protocol class
61 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
62 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
65 * Add relay servers to the list of inboxes
67 * @param array $inboxes
68 * @return array inboxes with added relay servers
70 public static function addRelayServerInboxes(array $inboxes = []): array
72 foreach (Relay::getList(['inbox']) as $contact) {
73 $inboxes[$contact['inbox']] = $contact['inbox'];
80 * Add relay servers to the list of inboxes
82 * @param array $inboxes
83 * @return array inboxes with added relay servers
85 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
87 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
92 $relays = Relay::getDirectRelayList($item_id);
97 foreach ($relays as $relay) {
98 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
99 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
105 * Subscribe to a relay and updates contact on success
107 * @param string $url Subscribe actor url
108 * @return bool success
110 public static function sendRelayFollow(string $url): bool
112 $contact = Contact::getByURL($url);
113 if (empty($contact)) {
117 $activity_id = self::activityIDFromContact($contact['id']);
118 $success = self::sendActivity('Follow', $url, 0, $activity_id);
120 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
127 * Unsubscribe from a relay and updates contact on success or forced
129 * @param string $url Subscribe actor url
130 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
131 * @return bool success
133 public static function sendRelayUndoFollow(string $url, bool $force = false): bool
135 $contact = Contact::getByURL($url);
136 if (empty($contact)) {
140 $success = self::sendContactUndo($url, $contact['id'], User::getSystemAccount());
142 if ($success || $force) {
143 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
150 * Collects a list of contacts of the given owner
152 * @param array $owner Owner array
153 * @param array $rel The relevant value(s) contact.rel should match
154 * @param string $module The name of the relevant AP endpoint module (followers|following)
155 * @param integer $page Page number
156 * @param string $requester URL of the requester
157 * @param boolean $nocache Wether to bypass caching
158 * @return array of owners
161 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, bool $nocache = false): array
164 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
165 $result = DI::cache()->get($cachekey);
166 if (!$nocache && !is_null($result)) {
173 'uid' => $owner['uid'],
182 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
184 $total = DBA::count('contact', $condition);
186 $modulePath = '/' . $module . '/';
188 $data = ['@context' => ActivityPub::CONTEXT];
189 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
190 $data['type'] = 'OrderedCollection';
191 $data['totalItems'] = $total;
194 $data['id'] .= '?' . http_build_query(['page' => $page]);
197 // When we hide our friends we will only show the pure number but don't allow more.
198 $show_contacts = ActivityPub::isAcceptedRequester($owner['uid']) && empty($owner['hide-friends']);
200 // Allow fetching the contact list when the requester is part of the list.
201 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
202 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
205 if (!$show_contacts) {
206 if (!empty($cachekey)) {
207 DI::cache()->set($cachekey, $data, Duration::DAY);
214 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
216 $data['type'] = 'OrderedCollectionPage';
219 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
220 while ($contact = DBA::fetch($contacts)) {
221 $list[] = $contact['url'];
223 DBA::close($contacts);
225 if (count($list) == 100) {
226 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
229 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
231 $data['orderedItems'] = $list;
234 if (!empty($cachekey)) {
235 DI::cache()->set($cachekey, $data, Duration::DAY);
242 * Public posts for the given owner
244 * @param array $owner Owner array
245 * @param integer $page Page number
246 * @param boolean $nocache Wether to bypass caching
248 * @return array of posts
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
255 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
256 $result = DI::cache()->get($cachekey);
257 if (!$nocache && !is_null($result)) {
262 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
264 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
265 $owner_cid, Post\Collection::FEATURED];
267 $condition = DBA::mergeConditions($condition, [
268 'uid' => $owner['uid'],
269 'author-id' => $owner_cid,
270 'private' => [Item::PUBLIC, Item::UNLISTED],
271 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
272 'network' => Protocol::FEDERATED,
273 'parent-network' => Protocol::FEDERATED,
279 $count = Post::count($condition);
281 $data = ['@context' => ActivityPub::CONTEXT];
282 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
283 $data['type'] = 'OrderedCollection';
284 $data['totalItems'] = $count;
287 $data['id'] .= '?' . http_build_query(['page' => $page]);
291 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
293 $data['type'] = 'OrderedCollectionPage';
294 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
298 while ($item = Post::fetch($items)) {
299 $activity = self::createActivityFromItem($item['id'], true);
300 if (!empty($activity)) {
306 if (count($list) == 20) {
307 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
311 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
314 $data['orderedItems'] = $list;
316 if (!empty($cachekey)) {
317 DI::cache()->set($cachekey, $data, Duration::DAY);
324 * Return the service array containing information the used software and it's url
326 * @return array with service data
328 public static function getService(): array
332 'name' => App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION,
333 'url' => (string)DI::baseUrl()
338 * Return the ActivityPub profile of the given user
340 * @param int $uid User ID
341 * @param bool $full If not full, only the basic information is returned
342 * @return array with profile data
343 * @throws HTTPException\NotFoundException
344 * @throws HTTPException\InternalServerErrorException
346 public static function getProfile(int $uid, bool $full = true): array
348 $owner = User::getOwnerDataById($uid);
349 if (!isset($owner['id'])) {
350 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid]);
351 throw new HTTPException\NotFoundException('User not found.');
354 $data = ['@context' => ActivityPub::CONTEXT];
355 $data['id'] = $owner['url'];
357 if (!empty($owner['guid'])) {
358 $data['diaspora:guid'] = $owner['guid'];
361 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
364 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
365 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
366 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
367 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
368 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
370 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
373 $data['preferredUsername'] = $owner['nick'];
374 $data['name'] = $owner['name'];
376 if (!$full && !empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
377 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
378 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
381 if ($full && !empty($owner['about'])) {
382 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
385 if ($full && (!empty($owner['xmpp']) || !empty($owner['matrix']))) {
386 $data['vcard:hasInstantMessage'] = [];
388 if (!empty($owner['xmpp'])) {
389 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
391 if (!empty($owner['matrix'])) {
392 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
396 $data['url'] = $owner['url'];
397 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
398 $data['discoverable'] = (bool)$owner['net-publish'];
399 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
400 'owner' => $owner['url'],
401 'publicKeyPem' => $owner['pubkey']];
402 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
403 if ($full && $uid != 0) {
404 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
406 $resourceid = Photo::ridFromURI($owner['photo']);
407 if (!empty($resourceid)) {
408 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
409 if (!empty($photo['type'])) {
410 $data['icon']['mediaType'] = $photo['type'];
414 if (!empty($owner['header'])) {
415 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
417 $resourceid = Photo::ridFromURI($owner['header']);
418 if (!empty($resourceid)) {
419 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
420 if (!empty($photo['type'])) {
421 $data['image']['mediaType'] = $photo['type'];
428 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
430 'type' => 'PropertyValue',
431 'name' => $profile_field->label,
432 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
436 if (!empty($custom_fields)) {
437 $data['attachment'] = $custom_fields;
441 $data['generator'] = self::getService();
443 // tags: https://kitty.town/@inmysocks/100656097926961126.json
448 * Get a minimal actor array for the C2S API
450 * @param integer $cid
453 private static function getActorArrayByCid(int $cid): array
455 $contact = Contact::getById($cid);
457 'id' => $contact['url'],
458 'type' => $data['type'] = ActivityPub::ACCOUNT_TYPES[$contact['contact-type']],
459 'url' => $contact['alias'],
460 'preferredUsername' => $contact['nick'],
461 'name' => $contact['name'],
462 'icon' => ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($cid, '', $contact['updated'])],
463 'image' => ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($cid, '', $contact['updated'])],
464 'manuallyApprovesFollowers' => (bool)$contact['manually-approve'],
465 'discoverable' => !$contact['unsearchable'],
468 if (empty($data['url'])) {
469 $data['url'] = $data['id'];
476 * @param string $username
478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
480 public static function getDeletedUser(string $username): array
483 '@context' => ActivityPub::CONTEXT,
484 'id' => DI::baseUrl() . '/profile/' . $username,
485 'type' => 'Tombstone',
486 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
487 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
488 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
493 * Returns an array with permissions of the thread parent of the given item array
497 * @return array with permissions
498 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
499 * @throws \ImagickException
501 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_group_thread): array
503 if (empty($item['thr-parent-id'])) {
507 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
508 if (empty($parent)) {
513 'to' => [$parent['author-link']],
520 $parent_profile = APContact::getByURL($parent['author-link']);
522 $item_profile = APContact::getByURL($item['author-link']);
523 $exclude[] = $item['author-link'];
525 if ($item['gravity'] == Item::GRAVITY_PARENT) {
526 $exclude[] = $item['owner-link'];
529 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc', Tag::AUDIENCE => 'audience'];
530 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC, Tag::AUDIENCE]) as $receiver) {
531 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
532 if (!$is_group_thread) {
533 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
535 } elseif (!in_array($receiver['url'], $exclude)) {
536 $permissions[$type[$receiver['type']]][] = $receiver['url'];
544 * Check if the given item id is from ActivityPub
546 * @param integer $item_id
547 * @return boolean "true" if the post is from ActivityPub
549 private static function isAPPost(int $item_id): bool
551 if (empty($item_id)) {
555 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
559 * Creates an array of permissions from an item thread
561 * @param array $item Item array
562 * @param boolean $blindcopy addressing via "bcc" or "cc"?
563 * @param integer $last_id Last item id for adding receivers
565 * @return array with permission data
566 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
567 * @throws \ImagickException
569 private static function createPermissionBlockForItem(array $item, bool $blindcopy, int $last_id = 0): array
572 $last_id = $item['id'];
582 // Check if we should always deliver our stuff via BCC
583 if (!empty($item['uid'])) {
584 $owner = User::getOwnerDataById($item['uid']);
585 if (!empty($owner)) {
586 $always_bcc = $owner['hide-friends'];
587 $is_group = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
589 $profile = APContact::getByURL($owner['url'], false);
590 $follower = $profile['followers'] ?? '';
594 if (DI::config()->get('system', 'ap_always_bcc')) {
598 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
599 if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
600 $profile = APContact::getByURL($parent['causer-link'], false);
601 $is_group_thread = isset($profile['type']) && $profile['type'] == 'Group';
603 $is_group_thread = false;
607 $parent_tags = Tag::getByURIId($item['parent-uri-id'], [Tag::AUDIENCE, Tag::MENTION]);
608 if (!empty($parent_tags)) {
609 $is_group_thread = false;
610 foreach ($parent_tags as $tag) {
611 if ($tag['type'] != Tag::AUDIENCE) {
614 $profile = APContact::getByURL($tag['url'], false);
615 if (!empty($profile) && ($profile['type'] == 'Group')) {
616 $audience[] = $tag['url'];
617 $is_group_thread = true;
620 if ($is_group_thread) {
621 foreach ($parent_tags as $tag) {
622 if (($tag['type'] == Tag::MENTION) && in_array($tag['url'], $audience)) {
626 $exclusive = !$mention;
628 } elseif ($is_group_thread) {
629 foreach (Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $term) {
630 $profile = APContact::getByURL($term['url'], false);
631 if (!empty($profile) && ($profile['type'] == 'Group')) {
632 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
633 $audience[] = $term['url'];
635 } elseif ($term['type'] == Tag::MENTION) {
642 $audience[] = $owner['url'];
645 if (self::isAnnounce($item) || self::isAPPost($last_id)) {
646 // Will be activated in a later step
647 $networks = Protocol::FEDERATED;
649 // For now only send to these contacts:
650 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
653 $data = ['to' => [], 'cc' => [], 'bcc' => [] , 'audience' => $audience];
655 if ($item['gravity'] == Item::GRAVITY_PARENT) {
656 $actor_profile = APContact::getByURL($item['owner-link']);
658 $actor_profile = APContact::getByURL($item['author-link']);
661 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION, Tag::AUDIENCE]);
663 if ($item['private'] != Item::PRIVATE) {
664 // Directly mention the original author upon a quoted reshare.
665 // Else just ensure that the original author receives the reshare.
666 $announce = self::getAnnounceArray($item);
667 if (!empty($announce['comment'])) {
668 $data['to'][] = $announce['actor']['url'];
669 } elseif (!empty($announce)) {
670 $data['cc'][] = $announce['actor']['url'];
674 $data = array_merge_recursive($data, self::fetchPermissionBlockFromThreadParent($item, $is_group_thread));
677 // Check if the item is completely public or unlisted
678 if ($item['private'] == Item::PUBLIC) {
679 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
681 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
684 foreach ($terms as $term) {
685 $profile = APContact::getByURL($term['url'], false);
686 if (!empty($profile)) {
687 if (($term['type'] == Tag::AUDIENCE) && ($profile['type'] == 'Group')) {
688 $data['audience'][] = $profile['url'];
690 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
692 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
693 $data['cc'][] = $profile['followers'];
694 $data['audience'][] = $profile['url'];
696 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
699 $data['to'][] = $profile['url'];
702 if (!$exclusive && ($item['private'] == Item::UNLISTED)) {
703 $data['to'][] = $actor_profile['followers'];
706 $receiver_list = Item::enumeratePermissions($item, true, false);
708 foreach ($terms as $term) {
709 $cid = Contact::getIdForURL($term['url'], $item['uid']);
710 if (!empty($cid) && in_array($cid, $receiver_list)) {
711 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
712 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
716 $profile = APContact::getByURL($term['url'], false);
717 if (!empty($profile)) {
718 if (($term['type'] == Tag::AUDIENCE) && ($profile['type'] == 'Group')) {
719 $data['audience'][] = $profile['url'];
721 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
723 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
724 $data['cc'][] = $profile['followers'];
725 $data['audience'][] = $profile['url'];
727 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
730 $data['to'][] = $profile['url'];
739 if ($is_group && !$exclusive && !empty($follower)) {
740 $data['cc'][] = $follower;
741 } elseif (!$exclusive) {
742 foreach ($receiver_list as $receiver) {
743 if ($receiver == -1) {
744 $data['to'][] = $actor_profile['followers'];
748 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
749 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
753 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
754 if ($contact['hidden'] || $always_bcc) {
755 $data['bcc'][] = $profile['url'];
757 $data['cc'][] = $profile['url'];
764 if (!empty($item['parent']) && (!$exclusive || ($item['private'] == Item::PRIVATE))) {
765 if ($item['private'] == Item::PRIVATE) {
766 $condition = ['parent' => $item['parent'], 'uri-id' => $item['thr-parent-id']];
768 $condition = ['parent' => $item['parent']];
770 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], $condition, ['order' => ['id']]);
771 while ($parent = Post::fetch($parents)) {
772 if ($parent['gravity'] == Item::GRAVITY_PARENT) {
773 $profile = APContact::getByURL($parent['owner-link'], false);
774 if (!empty($profile)) {
775 if ($item['gravity'] != Item::GRAVITY_PARENT) {
776 // Comments to groups are directed to the group
777 // But comments to groups aren't directed to the followers collection
778 // This rule is only valid when the actor isn't the group.
779 // The group needs to transmit their content to their followers.
780 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
781 $data['to'][] = $profile['url'];
783 $data['cc'][] = $profile['url'];
784 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers']) && (!$exclusive || !$is_group_thread)) {
785 $data['cc'][] = $actor_profile['followers'];
788 } elseif (!$exclusive && !$is_group_thread) {
789 // Public thread parent post always are directed to the followers.
790 if ($item['private'] != Item::PRIVATE) {
791 $data['cc'][] = $actor_profile['followers'];
797 // Don't include data from future posts
798 if ($parent['id'] >= $last_id) {
802 $profile = APContact::getByURL($parent['author-link'], false);
803 if (!empty($profile)) {
804 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
805 $data['to'][] = $profile['url'];
807 $data['cc'][] = $profile['url'];
811 DBA::close($parents);
814 $data['to'] = array_unique($data['to']);
815 $data['cc'] = array_unique($data['cc']);
816 $data['bcc'] = array_unique($data['bcc']);
817 $data['audience'] = array_unique($data['audience']);
819 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
820 unset($data['to'][$key]);
823 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
824 unset($data['cc'][$key]);
827 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
828 unset($data['bcc'][$key]);
831 foreach ($data['to'] as $to) {
832 if (($key = array_search($to, $data['cc'])) !== false) {
833 unset($data['cc'][$key]);
836 if (($key = array_search($to, $data['bcc'])) !== false) {
837 unset($data['bcc'][$key]);
841 foreach ($data['cc'] as $cc) {
842 if (($key = array_search($cc, $data['bcc'])) !== false) {
843 unset($data['bcc'][$key]);
847 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc']), 'audience' => array_values($data['audience'])];
850 unset($receivers['bcc']);
853 if (!$blindcopy && count($receivers['audience']) == 1) {
854 $receivers['audience'] = $receivers['audience'][0];
855 } elseif (!$receivers['audience']) {
856 unset($receivers['audience']);
863 * Store the receivers for the given item
868 public static function storeReceiversForItem(array $item)
870 $receivers = self::createPermissionBlockForItem($item, true);
871 if (empty($receivers)) {
875 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC, 'audience' => Tag::AUDIENCE] as $element => $type) {
876 if (!empty($receivers[$element])) {
877 foreach ($receivers[$element] as $receiver) {
878 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
879 $name = Receiver::PUBLIC_COLLECTION;
881 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
883 Tag::store($item['uri-id'], $type, $name, $receiver);
890 * Get a list of receivers for the provided uri-id
893 * @param boolean $blindcopy
896 public static function getReceiversForUriId(int $uri_id, bool $blindcopy)
905 foreach (Tag::getByURIId($uri_id, [Tag::TO, Tag::CC, Tag::BCC, Tag::AUDIENCE]) as $receiver) {
906 switch ($receiver['type']) {
908 $receivers['to'][] = $receiver['url'];
911 $receivers['cc'][] = $receiver['url'];
914 $receivers['bcc'][] = $receiver['url'];
917 $receivers['audience'][] = $receiver['url'];
923 unset($receivers['bcc']);
926 if (!$blindcopy && count($receivers['audience']) == 1) {
927 $receivers['audience'] = $receivers['audience'][0];
928 } elseif (!$receivers['audience']) {
929 unset($receivers['audience']);
936 * Check if an inbox is archived
938 * @param string $url Inbox url
939 * @return boolean "true" if inbox is archived
941 public static function archivedInbox(string $url): bool
943 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
947 * Check if a given contact should be delivered via AP
949 * @param array $contact Contact array
950 * @param array $networks Array with networks
951 * @return bool Whether the used protocol matches ACTIVITYPUB
954 private static function isAPContact(array $contact, array $networks): bool
956 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
960 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
964 * Fetches a list of inboxes of followers of a given user
966 * @param integer $uid User ID
967 * @param boolean $personal fetch personal inboxes
968 * @param boolean $all_ap Retrieve all AP enabled inboxes
969 * @return array of follower inboxes
970 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
971 * @throws \ImagickException
973 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
978 if (!empty($item['uid'])) {
979 $profile = User::getOwnerDataById($item['uid']);
980 if (!empty($profile)) {
981 $isGroup = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
986 // Will be activated in a later step
987 $networks = Protocol::FEDERATED;
989 // For now only send to these contacts:
990 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
999 'network' => Protocol::FEDERATED,
1000 'contact-type' => [Contact::TYPE_UNKNOWN, Contact::TYPE_PERSON, Contact::TYPE_NEWS, Contact::TYPE_ORGANISATION],
1004 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
1007 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
1008 while ($contact = DBA::fetch($contacts)) {
1009 if (!self::isAPContact($contact, $networks)) {
1013 if ($isGroup && ($contact['network'] == Protocol::DFRN)) {
1017 if (Network::isUrlBlocked($contact['url'])) {
1021 $profile = APContact::getByURL($contact['url'], false);
1022 if (!empty($profile)) {
1023 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
1024 $target = $profile['inbox'];
1026 $target = $profile['sharedinbox'];
1028 if (!self::archivedInbox($target)) {
1029 $inboxes[$target][] = $contact['id'];
1033 DBA::close($contacts);
1039 * Fetches an array of inboxes for the given item and user
1041 * @param array $item Item array
1042 * @param integer $uid User ID
1043 * @param boolean $personal fetch personal inboxes
1044 * @return array with inboxes
1045 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1046 * @throws \ImagickException
1048 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false): array
1050 $permissions = self::getReceiversForUriId($item['uri-id'], true);
1051 if (empty($permissions)) {
1057 if ($item['gravity'] == Item::GRAVITY_ACTIVITY) {
1058 $item_profile = APContact::getByURL($item['author-link'], false);
1060 $item_profile = APContact::getByURL($item['owner-link'], false);
1063 if (empty($item_profile)) {
1067 $profile_uid = User::getIdForURL($item_profile['url']);
1069 foreach (['to', 'cc', 'bto', 'bcc', 'audience'] as $element) {
1070 if (empty($permissions[$element])) {
1074 $blindcopy = in_array($element, ['bto', 'bcc']);
1076 foreach ($permissions[$element] as $receiver) {
1077 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
1081 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1082 $inboxes = array_merge_recursive($inboxes, self::fetchTargetInboxesforUser($uid, $personal, true));
1084 $profile = APContact::getByURL($receiver, false);
1085 if (!empty($profile)) {
1086 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1088 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1089 $target = $profile['inbox'];
1091 $target = $profile['sharedinbox'];
1093 if (!self::archivedInbox($target) && !in_array($contact['id'], $inboxes[$target] ?? [])) {
1094 $inboxes[$target][] = $contact['id'] ?? 0;
1105 * Creates an array in the structure of the item table for a given mail id
1107 * @param integer $mail_id Mail id
1109 * @throws \Exception
1111 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1113 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1114 if (!DBA::isResult($mail)) {
1118 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1119 if (!DBA::isResult($reply)) {
1123 // Making the post more compatible for Mastodon by:
1124 // - Making it a note and not an article (no title)
1125 // - Moving the title into the "summary" field that is used as a "content warning"
1128 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1129 $mail['title'] = '';
1132 $mail['content-warning'] = '';
1133 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1134 $mail['owner-id'] = $mail['author-id'];
1135 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1136 $mail['allow_gid'] = '';
1137 $mail['deny_cid'] = '';
1138 $mail['deny_gid'] = '';
1139 $mail['private'] = Item::PRIVATE;
1140 $mail['deleted'] = false;
1141 $mail['edited'] = $mail['created'];
1142 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1143 $mail['parent-uri'] = $reply['uri'];
1144 $mail['parent-uri-id'] = $reply['uri-id'];
1145 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1146 $mail['gravity'] = ($mail['reply'] ? Item::GRAVITY_COMMENT: Item::GRAVITY_PARENT);
1147 $mail['event-type'] = '';
1148 $mail['language'] = '';
1149 $mail['parent'] = 0;
1155 * Creates an activity array for a given mail id
1157 * @param integer $mail_id
1158 * @param boolean $object_mode Is the activity item is used inside another object?
1160 * @return array of activity
1161 * @throws \Exception
1163 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1165 $mail = self::getItemArrayFromMail($mail_id);
1169 $object = self::createNote($mail);
1171 if (!$object_mode) {
1172 $data = ['@context' => ActivityPub::CONTEXT];
1177 $data['id'] = $mail['uri'] . '/Create';
1178 $data['type'] = 'Create';
1179 $data['actor'] = $mail['author-link'];
1180 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1181 $data['instrument'] = self::getService();
1182 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1184 if (empty($data['to']) && !empty($data['cc'])) {
1185 $data['to'] = $data['cc'];
1188 if (empty($data['to']) && !empty($data['bcc'])) {
1189 $data['to'] = $data['bcc'];
1193 unset($data['bcc']);
1194 unset($data['audience']);
1196 $object['to'] = $data['to'];
1197 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1199 unset($object['cc']);
1200 unset($object['bcc']);
1201 unset($object['audience']);
1203 $data['directMessage'] = true;
1205 $data['object'] = $object;
1207 $owner = User::getOwnerDataById($mail['uid']);
1209 if (!$object_mode && !empty($owner)) {
1210 return LDSignature::sign($data, $owner);
1217 * Returns the activity type of a given item
1219 * @param array $item Item array
1220 * @return string with activity type
1221 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1222 * @throws \ImagickException
1224 private static function getTypeOfItem(array $item): string
1228 // Only check for a reshare, if it is a real reshare and no quoted reshare
1229 if (strpos($item['body'], '[share') === 0) {
1230 $announce = self::getAnnounceArray($item);
1231 $reshared = !empty($announce);
1236 } elseif ($item['verb'] == Activity::POST) {
1237 if ($item['created'] == $item['edited']) {
1242 } elseif ($item['verb'] == Activity::LIKE) {
1244 } elseif ($item['verb'] == Activity::DISLIKE) {
1246 } elseif ($item['verb'] == Activity::ATTEND) {
1248 } elseif ($item['verb'] == Activity::ATTENDNO) {
1250 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1251 $type = 'TentativeAccept';
1252 } elseif ($item['verb'] == Activity::FOLLOW) {
1254 } elseif ($item['verb'] == Activity::TAG) {
1256 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1266 * Creates the activity or fetches it from the cache
1268 * @param integer $item_id Item id
1269 * @param boolean $force Force new cache entry
1270 * @param boolean $object_mode true = Create the object, false = create the activity with the object
1271 * @param boolean $announce_activity true = the announced object is the activity, false = we announce the object link
1272 * @return array|false activity or false on failure
1273 * @throws \Exception
1275 public static function createCachedActivityFromItem(int $item_id, bool $force = false, bool $object_mode = false, $announce_activity = false)
1277 $cachekey = 'APDelivery:createActivity:' . $item_id . ':' . (int)$object_mode . ':' . (int)$announce_activity;
1280 $data = DI::cache()->get($cachekey);
1281 if (!is_null($data)) {
1286 $data = self::createActivityFromItem($item_id, $object_mode, false, $announce_activity);
1288 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1293 * Creates an activity array for a given item id
1295 * @param integer $item_id
1296 * @param boolean $object_mode true = Create the object, false = create the activity with the object
1297 * @param boolean $api_mode true = used for the API
1298 * @param boolean $announce_activity true = the announced object is the activity, false = we announce the object link
1299 * @return false|array
1300 * @throws \Exception
1302 public static function createActivityFromItem(int $item_id, bool $object_mode = false, $api_mode = false, $announce_activity = false)
1304 $condition = ['id' => $item_id];
1306 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1308 Logger::info('Fetching activity', $condition);
1309 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
1310 if (!DBA::isResult($item)) {
1313 return self::createActivityFromArray($item, $object_mode, $api_mode, $announce_activity);
1317 * Creates an activity array for a given URI-Id and uid
1319 * @param integer $uri_id
1320 * @param integer $uid
1321 * @param boolean $object_mode true = Create the object, false = create the activity with the object
1322 * @param boolean $api_mode true = used for the API
1323 * @param boolean $announce_activity true = the announced object is the activity, false = we announce the object link
1324 * @return false|array
1325 * @throws \Exception
1327 public static function createActivityFromUriId(int $uri_id, int $uid, bool $object_mode = false, $api_mode = false, $announce_activity = false)
1329 $condition = ['uri-id' => $uri_id, 'uid' => [0, $uid]];
1331 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1333 Logger::info('Fetching activity', $condition);
1334 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition, ['order' => ['uid' => true]]);
1335 if (!DBA::isResult($item)) {
1339 return self::createActivityFromArray($item, $object_mode, $api_mode, $announce_activity);
1343 * Creates an activity array for a given item id
1345 * @param integer $item_id
1346 * @param boolean $object_mode true = Create the object, false = create the activity with the object
1347 * @param boolean $api_mode true = used for the API
1348 * @param boolean $announce_activity true = the announced object is the activity, false = we announce the object link
1349 * @return false|array
1350 * @throws \Exception
1352 private static function createActivityFromArray(array $item, bool $object_mode = false, $api_mode = false, $announce_activity = false)
1354 if (!$api_mode && !$item['deleted'] && $item['network'] == Protocol::ACTIVITYPUB) {
1355 $data = Post\Activity::getByURIId($item['uri-id']);
1356 if (!$item['origin'] && !empty($data)) {
1357 if (!$object_mode) {
1358 Logger::info('Return stored conversation', ['item' => $item['id']]);
1360 } elseif (!empty($data['object'])) {
1361 Logger::info('Return stored conversation object', ['item' => $item['id']]);
1362 return $data['object'];
1367 if (!$api_mode && !$item['origin']) {
1368 Logger::debug('Post is not ours and is not stored', ['id' => $item['id'], 'uri-id' => $item['uri-id']]);
1372 $type = self::getTypeOfItem($item);
1374 if (!$object_mode) {
1375 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1377 if ($item['deleted'] && ($item['gravity'] == Item::GRAVITY_ACTIVITY)) {
1379 } elseif ($item['deleted']) {
1386 if ($type == 'Delete') {
1387 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1388 } elseif (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1389 $data['id'] = $item['uri'];
1391 $data['id'] = $item['uri'] . '/' . $type;
1394 $data['type'] = $type;
1396 if (($type != 'Announce') || ($item['gravity'] != Item::GRAVITY_PARENT)) {
1397 $link = $item['author-link'];
1398 $id = $item['author-id'];
1400 $link = $item['owner-link'];
1401 $id = $item['owner-id'];
1405 $data['actor'] = self::getActorArrayByCid($id);
1407 $data['actor'] = $link;
1410 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1412 $data['instrument'] = self::getService();
1414 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1416 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1417 $data['object'] = self::createNote($item, $api_mode);
1418 } elseif ($data['type'] == 'Add') {
1419 $data = self::createAddTag($item, $data);
1420 } elseif ($data['type'] == 'Announce') {
1421 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1422 if ($announce_activity) {
1423 $anounced_item = Post::selectFirst(['uid'], ['uri-id' => $item['thr-parent-id'], 'origin' => true]);
1424 $data['object'] = self::createActivityFromUriId($item['thr-parent-id'], $anounced_item['uid'] ?? 0);
1425 unset($data['object']['@context']);
1427 $data['object'] = $item['thr-parent'];
1430 $data = self::createAnnounce($item, $data, $api_mode);
1432 } elseif ($data['type'] == 'Follow') {
1433 $data['object'] = $item['parent-uri'];
1434 } elseif ($data['type'] == 'Undo') {
1435 $data['object'] = self::createActivityFromItem($item['id'], true);
1437 $data['diaspora:guid'] = $item['guid'];
1438 if (!empty($item['signed_text'])) {
1439 $data['diaspora:like'] = $item['signed_text'];
1441 $data['object'] = $item['thr-parent'];
1444 if (!empty($item['contact-uid'])) {
1445 $uid = $item['contact-uid'];
1447 $uid = $item['uid'];
1450 Logger::info('Fetched activity', ['item' => $item['id'], 'uid' => $uid]);
1452 // We only sign our own activities
1453 if (!$api_mode && !$object_mode && $item['origin']) {
1454 $owner = User::getOwnerDataById($uid);
1455 return LDSignature::sign($data, $owner);
1460 /// @todo Create "conversation" entry
1464 * Creates a location entry for a given item array
1466 * @param array $item Item array
1467 * @return array with location array
1469 private static function createLocation(array $item): array
1471 $location = ['type' => 'Place'];
1473 if (!empty($item['location'])) {
1474 $location['name'] = $item['location'];
1479 if (empty($item['coord'])) {
1480 $coord = Map::getCoordinates($item['location']);
1482 $coords = explode(' ', $item['coord']);
1483 if (count($coords) == 2) {
1484 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1488 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1489 $location['latitude'] = $coord['lat'];
1490 $location['longitude'] = $coord['lon'];
1497 * Returns a tag array for a given item array
1499 * @param array $item Item array
1500 * @param string $quote_url Url of the attached quote link
1501 * @return array of tags
1502 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1504 private static function createTagList(array $item, string $quote_url): array
1508 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1509 foreach ($terms as $term) {
1510 if ($term['type'] == Tag::HASHTAG) {
1511 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1512 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1514 $contact = Contact::getByURL($term['url'], false, ['addr']);
1515 if (empty($contact)) {
1518 if (!empty($contact['addr'])) {
1519 $mention = '@' . $contact['addr'];
1521 $mention = '@' . $term['url'];
1524 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1528 $announce = self::getAnnounceArray($item);
1529 // Mention the original author upon commented reshares
1530 if (!empty($announce['comment'])) {
1531 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1534 // @see https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-e232.md
1535 if (!empty($quote_url)) {
1536 // Currently deactivated because of compatibility issues with Pleroma
1538 // 'type' => 'Link',
1539 // 'mediaType' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
1540 // 'href' => $quote_url,
1541 // 'name' => '♲ ' . BBCode::convertForUriId($item['uri-id'], $quote_url, BBCode::ACTIVITYPUB)
1549 * Adds attachment data to the JSON document
1551 * @param array $item Data of the item that is to be posted
1553 * @return array with attachment data
1554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1556 private static function createAttachmentList(array $item): array
1561 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1562 if (in_array($attachment['url'], $urls)) {
1565 $urls[] = $attachment['url'];
1567 $attach = ['type' => 'Document',
1568 'mediaType' => $attachment['mimetype'],
1569 'url' => $attachment['url'],
1570 'name' => $attachment['description']];
1572 if (!empty($attachment['height'])) {
1573 $attach['height'] = $attachment['height'];
1576 if (!empty($attachment['width'])) {
1577 $attach['width'] = $attachment['width'];
1580 if (!empty($attachment['preview'])) {
1581 $attach['image'] = $attachment['preview'];
1584 $attachments[] = $attach;
1587 return $attachments;
1591 * Callback function to replace a Friendica style mention in a mention for a summary
1593 * @param array $match Matching values for the callback
1594 * @return string Replaced mention
1595 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1597 private static function mentionAddrCallback(array $match): string
1599 if (empty($match[1])) {
1603 $data = Contact::getByURL($match[1], false, ['addr']);
1604 if (empty($data['addr'])) {
1608 return '@' . $data['addr'];
1612 * Remove image elements since they are added as attachment
1614 * @param string $body HTML code
1615 * @return string with removed images
1617 private static function removePictures(string $body): string
1619 return BBCode::performWithEscapedTags($body, ['code', 'noparse', 'nobb', 'pre'], function ($text) {
1620 // Simplify image codes
1621 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1622 $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $text);
1624 // Now remove local links
1625 $text = preg_replace_callback(
1626 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1628 // We remove the link when it is a link to a local photo page
1629 if (Photo::isLocalPage($match[1])) {
1632 // otherwise we just return the link
1633 return '[url]' . $match[1] . '[/url]';
1638 // Remove all pictures
1639 return preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $text);
1644 * Returns if the post contains sensitive content ("nsfw")
1646 * @param integer $uri_id URI id
1647 * @return boolean Whether URI id was found
1648 * @throws \Exception
1650 private static function isSensitive(int $uri_id): bool
1652 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1656 * Creates event data
1658 * @param array $item Item array
1659 * @return array with the event data
1660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1662 private static function createEvent(array $item): array
1665 $event['name'] = $item['event-summary'];
1666 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1667 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1669 if (!$item['event-nofinish']) {
1670 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1673 if (!empty($item['event-location'])) {
1674 $item['location'] = $item['event-location'];
1675 $event['location'] = self::createLocation($item);
1678 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1679 $event['dfrn:adjust'] = true;
1685 * Creates a note/article object array
1687 * @param array $item
1688 * @param bool $api_mode
1689 * @return array with the object data
1690 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1691 * @throws \ImagickException
1693 public static function createNote(array $item, bool $api_mode = false): array
1699 // We are treating posts differently when they are directed to a community.
1700 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1701 // But to not risk compatibility issues we currently perform the changes only for communities.
1702 if ($item['gravity'] == Item::GRAVITY_PARENT) {
1703 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1704 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1705 if ($isCommunityPost && (count($links) == 1)) {
1706 $link = $links[0]['url'];
1709 $isCommunityPost = false;
1712 if ($item['event-type'] == 'event') {
1714 } elseif (!empty($item['title'])) {
1715 if (!$isCommunityPost || empty($link)) {
1718 // "Page" is used by Lemmy for posts that contain an external link
1725 if ($item['deleted']) {
1726 $type = 'Tombstone';
1730 $data['id'] = $item['uri'];
1731 $data['type'] = $type;
1733 if ($item['deleted']) {
1737 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1739 if ($item['uri'] != $item['thr-parent']) {
1740 $data['inReplyTo'] = $item['thr-parent'];
1742 $data['inReplyTo'] = null;
1745 $data['diaspora:guid'] = $item['guid'];
1746 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1748 if ($item['created'] != $item['edited']) {
1749 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1752 $data['url'] = $link ?? $item['plink'];
1754 $data['attributedTo'] = self::getActorArrayByCid($item['author-id']);
1756 $data['attributedTo'] = $item['author-link'];
1758 $data['sensitive'] = self::isSensitive($item['uri-id']);
1760 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1761 $data['conversation'] = $data['context'] = $item['conversation'];
1764 if (!empty($item['title'])) {
1765 $data['name'] = BBCode::toPlaintext($item['title'], false);
1768 $permission_block = self::getReceiversForUriId($item['uri-id'], false);
1770 $real_quote = false;
1772 $item = Post\Media::addHTMLAttachmentToItem($item);
1774 $body = $item['body'];
1776 if ($type == 'Note') {
1777 $body = $item['raw-body'] ?? self::removePictures($body);
1781 * @todo Improve the automated summary
1782 * This part is currently deactivated. The automated summary seems to be more
1783 * confusing than helping. But possibly we will find a better way.
1784 * So the code is left here for now as a reminder
1786 * } elseif (($type == 'Article') && empty($data['summary'])) {
1787 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1788 * $summary = preg_replace_callback($regexp, [self::class, 'mentionAddrCallback'], $body);
1789 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1793 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1794 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1797 if ($type == 'Event') {
1798 $data = array_merge($data, self::createEvent($item));
1800 if ($isCommunityPost) {
1801 // For community posts we remove the visible "!user@domain.tld".
1802 // This improves the look at systems like Lemmy.
1803 // Also in the future we should control the community delivery via other methods.
1804 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1807 if ($type == 'Page') {
1808 // When we transmit "Page" posts we have to remove the attachment.
1809 // The attachment contains the link that we already transmit in the "url" field.
1810 $body = BBCode::removeAttachment($body);
1813 $body = BBCode::setMentionsToNicknames($body);
1815 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] != $item['uri-id'])) {
1816 if (Post::exists(['uri-id' => $item['quote-uri-id'], 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN]])) {
1818 $data['quoteUrl'] = $item['quote-uri'];
1819 $body = DI::contentItem()->addShareLink($body, $item['quote-uri-id']);
1821 $body = DI::contentItem()->addSharedPost($item, $body);
1825 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1828 // The regular "content" field does contain a minimized HTML. This is done since systems like
1829 // Mastodon has got problems with - for example - embedded pictures.
1830 // The contentMap does contain the unmodified HTML.
1831 $language = self::getLanguage($item);
1832 if (!empty($language)) {
1833 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1834 $richbody = Post\Media::removeFromEndOfBody($richbody);
1835 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] != $item['uri-id'])) {
1837 $richbody = DI::contentItem()->addShareLink($richbody, $item['quote-uri-id']);
1839 $richbody = DI::contentItem()->addSharedPost($item, $richbody);
1842 $richbody = BBCode::replaceAttachment($richbody);
1844 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1847 if (!empty($item['quote-uri-id']) && ($item['quote-uri-id'] != $item['uri-id'])) {
1848 $source = DI::contentItem()->addSharedPost($item, $item['body']);
1850 $source = $item['body'];
1853 $data['source'] = ['content' => $source, 'mediaType' => "text/bbcode"];
1855 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1856 $data['diaspora:comment'] = $item['signed_text'];
1859 $data['attachment'] = self::createAttachmentList($item);
1860 $data['tag'] = self::createTagList($item, $data['quoteUrl'] ?? '');
1862 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1863 $data['location'] = self::createLocation($item);
1866 if (!empty($item['app'])) {
1867 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1870 $data = array_merge($data, $permission_block);
1876 * Fetches the language from the post, the user or the system.
1878 * @param array $item
1879 * @return string language string
1881 private static function getLanguage(array $item): string
1883 // Try to fetch the language from the post itself
1884 if (!empty($item['language'])) {
1885 $languages = array_keys(json_decode($item['language'], true));
1886 if (!empty($languages[0])) {
1887 return $languages[0];
1891 // Otherwise use the user's language
1892 if (!empty($item['uid'])) {
1893 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1894 if (!empty($user['language'])) {
1895 return $user['language'];
1899 // And finally just use the system language
1900 return DI::config()->get('system', 'language');
1904 * Creates an an "add tag" entry
1906 * @param array $item Item array
1907 * @param array $activity activity data
1908 * @return array with activity data for adding tags
1909 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1910 * @throws \ImagickException
1912 private static function createAddTag(array $item, array $activity): array
1914 $object = XML::parseString($item['object']);
1915 $target = XML::parseString($item['target']);
1917 $activity['diaspora:guid'] = $item['guid'];
1918 $activity['actor'] = $item['author-link'];
1919 $activity['target'] = (string)$target->id;
1920 $activity['summary'] = BBCode::toPlaintext($item['body']);
1921 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1927 * Creates an announce object entry
1929 * @param array $item Item array
1930 * @param array $activity activity data
1931 * @param bool $api_mode
1932 * @return array with activity data
1933 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1934 * @throws \ImagickException
1936 private static function createAnnounce(array $item, array $activity, bool $api_mode = false): array
1938 $orig_body = $item['body'];
1939 $announce = self::getAnnounceArray($item);
1940 if (empty($announce)) {
1941 $activity['type'] = 'Create';
1942 $activity['object'] = self::createNote($item, $api_mode);
1946 if (empty($announce['comment'])) {
1947 // Pure announce, without a quote
1948 $activity['type'] = 'Announce';
1949 $activity['object'] = $announce['object']['uri'];
1954 $activity['type'] = 'Create';
1955 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1956 $activity['object'] = self::createNote($item, $api_mode);
1958 /// @todo Finally decide how to implement this in AP. This is a possible way:
1959 $activity['object']['attachment'][] = self::createNote($announce['object']);
1961 $activity['object']['source']['content'] = $orig_body;
1966 * Return announce related data if the item is an announce
1968 * @param array $item
1969 * @return array Announcement array
1971 private static function getAnnounceArray(array $item): array
1973 $reshared = DI::contentItem()->getSharedPost($item, Item::DELIVER_FIELDLIST);
1974 if (empty($reshared)) {
1978 if (!in_array($reshared['post']['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1982 $profile = APContact::getByURL($reshared['post']['author-link'], false);
1983 if (empty($profile)) {
1987 return ['object' => $reshared['post'], 'actor' => $profile, 'comment' => $reshared['comment']];
1991 * Checks if the provided item array is an announce
1993 * @param array $item Item array
1994 * @return boolean Whether item is an announcement
1996 public static function isAnnounce(array $item): bool
1998 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
2002 $announce = self::getAnnounceArray($item);
2003 if (empty($announce)) {
2007 return empty($announce['comment']);
2011 * Creates an activity id for a given contact id
2013 * @param integer $cid Contact ID of target
2015 * @return bool|string activity id
2017 public static function activityIDFromContact(int $cid)
2019 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
2020 if (!DBA::isResult($contact)) {
2024 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
2025 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
2026 return DI::baseUrl() . '/activity/' . $uuid;
2030 * Transmits a contact suggestion to a given inbox
2032 * @param array $owner Sender owner-view record
2033 * @param string $inbox Target inbox
2034 * @param integer $suggestion_id Suggestion ID
2035 * @return boolean was the transmission successful?
2036 * @throws \Exception
2038 public static function sendContactSuggestion(array $owner, string $inbox, int $suggestion_id): bool
2040 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
2043 '@context' => ActivityPub::CONTEXT,
2044 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2045 'type' => 'Announce',
2046 'actor' => $owner['url'],
2047 'object' => $suggestion->url,
2048 'content' => $suggestion->note,
2049 'instrument' => self::getService(),
2050 'to' => [ActivityPub::PUBLIC_COLLECTION],
2054 $signed = LDSignature::sign($data, $owner);
2056 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2057 return HTTPSignature::transmit($signed, $inbox, $owner);
2061 * Transmits a profile relocation to a given inbox
2063 * @param array $owner Sender owner-view record
2064 * @param string $inbox Target inbox
2065 * @return boolean was the transmission successful?
2066 * @throws \Exception
2068 public static function sendProfileRelocation(array $owner, string $inbox): bool
2071 '@context' => ActivityPub::CONTEXT,
2072 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2073 'type' => 'dfrn:relocate',
2074 'actor' => $owner['url'],
2075 'object' => $owner['url'],
2076 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2077 'instrument' => self::getService(),
2078 'to' => [ActivityPub::PUBLIC_COLLECTION],
2082 $signed = LDSignature::sign($data, $owner);
2084 Logger::info('Deliver profile relocation for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2085 return HTTPSignature::transmit($signed, $inbox, $owner);
2089 * Transmits a profile deletion to a given inbox
2091 * @param array $owner Sender owner-view record
2092 * @param string $inbox Target inbox
2093 * @return boolean was the transmission successful?
2094 * @throws \Exception
2096 public static function sendProfileDeletion(array $owner, string $inbox): bool
2098 if (empty($owner['uprvkey'])) {
2099 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $owner['uid']]);
2103 $data = ['@context' => ActivityPub::CONTEXT,
2104 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2106 'actor' => $owner['url'],
2107 'object' => $owner['url'],
2108 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2109 'instrument' => self::getService(),
2110 'to' => [ActivityPub::PUBLIC_COLLECTION],
2113 $signed = LDSignature::sign($data, $owner);
2115 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2116 return HTTPSignature::transmit($signed, $inbox, $owner);
2120 * Transmits a profile change to a given inbox
2122 * @param array $owner Sender owner-view record
2123 * @param string $inbox Target inbox
2124 * @return boolean was the transmission successful?
2125 * @throws HTTPException\InternalServerErrorException
2126 * @throws HTTPException\NotFoundException
2127 * @throws \ImagickException
2129 public static function sendProfileUpdate(array $owner, string $inbox): bool
2131 $profile = APContact::getByURL($owner['url']);
2133 $data = ['@context' => ActivityPub::CONTEXT,
2134 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2136 'actor' => $owner['url'],
2137 'object' => self::getProfile($owner['uid']),
2138 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2139 'instrument' => self::getService(),
2140 'to' => [$profile['followers']],
2143 $signed = LDSignature::sign($data, $owner);
2145 Logger::info('Deliver profile update for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2146 return HTTPSignature::transmit($signed, $inbox, $owner);
2150 * Transmits a given activity to a target
2152 * @param string $activity Type name
2153 * @param string $target Target profile
2154 * @param integer $uid User ID
2155 * @param string $id Activity-identifier
2157 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2158 * @throws \ImagickException
2159 * @throws \Exception
2161 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2163 $profile = APContact::getByURL($target);
2164 if (empty($profile['inbox'])) {
2165 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2169 $owner = User::getOwnerDataById($uid);
2170 if (empty($owner)) {
2171 Logger::warning('No user found for actor, aborting', ['uid' => $uid]);
2176 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2180 '@context' => ActivityPub::CONTEXT,
2182 'type' => $activity,
2183 'actor' => $owner['url'],
2184 'object' => $profile['url'],
2185 'instrument' => self::getService(),
2186 'to' => [$profile['url']],
2189 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2191 $signed = LDSignature::sign($data, $owner);
2192 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2196 * Transmits a "follow object" activity to a target
2197 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2199 * @param string $object Object URL
2200 * @param string $target Target profile
2201 * @param integer $uid User ID
2203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2204 * @throws \ImagickException
2205 * @throws \Exception
2207 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2209 $profile = APContact::getByURL($target);
2210 if (empty($profile['inbox'])) {
2211 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2216 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2217 $admin = User::getFirstAdmin(['uid']);
2219 Logger::warning('No available admin user for transmission', ['target' => $target]);
2223 $uid = $admin['uid'];
2226 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2227 'author-id' => Contact::getPublicIdByUserId($uid)];
2228 if (Post::exists($condition)) {
2229 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2233 $owner = User::getOwnerDataById($uid);
2236 '@context' => ActivityPub::CONTEXT,
2237 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2239 'actor' => $owner['url'],
2240 'object' => $object,
2241 'instrument' => self::getService(),
2242 'to' => [$profile['url']],
2245 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2247 $signed = LDSignature::sign($data, $owner);
2248 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2252 * Transmit a message that the contact request had been accepted
2254 * @param string $target Target profile
2255 * @param string $id Object id
2256 * @param integer $uid User ID
2258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2259 * @throws \ImagickException
2261 public static function sendContactAccept(string $target, string $id, int $uid)
2263 $profile = APContact::getByURL($target);
2264 if (empty($profile['inbox'])) {
2265 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2269 $owner = User::getOwnerDataById($uid);
2271 Logger::notice('No user found for actor', ['uid' => $uid]);
2276 '@context' => ActivityPub::CONTEXT,
2277 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2279 'actor' => $owner['url'],
2283 'actor' => $profile['url'],
2284 'object' => $owner['url']
2286 'instrument' => self::getService(),
2287 'to' => [$profile['url']],
2290 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2292 $signed = LDSignature::sign($data, $owner);
2293 HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2297 * Reject a contact request or terminates the contact relation
2299 * @param string $target Target profile
2300 * @param string $objectId Object id
2301 * @param array $owner Sender owner-view record
2302 * @return bool Operation success
2303 * @throws HTTPException\InternalServerErrorException
2304 * @throws \ImagickException
2306 public static function sendContactReject(string $target, string $objectId, array $owner): bool
2308 $profile = APContact::getByURL($target);
2309 if (empty($profile['inbox'])) {
2310 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2315 '@context' => ActivityPub::CONTEXT,
2316 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2318 'actor' => $owner['url'],
2322 'actor' => $profile['url'],
2323 'object' => $owner['url']
2325 'instrument' => self::getService(),
2326 'to' => [$profile['url']],
2329 Logger::debug('Sending reject to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2331 $signed = LDSignature::sign($data, $owner);
2332 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2336 * Transmits a message that we don't want to follow this contact anymore
2338 * @param string $target Target profile
2339 * @param integer $cid Contact id
2340 * @param array $owner Sender owner-view record
2341 * @return bool success
2342 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2343 * @throws \ImagickException
2344 * @throws \Exception
2346 public static function sendContactUndo(string $target, int $cid, array $owner): bool
2348 $profile = APContact::getByURL($target);
2349 if (empty($profile['inbox'])) {
2350 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2354 $object_id = self::activityIDFromContact($cid);
2355 if (empty($object_id)) {
2359 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2362 '@context' => ActivityPub::CONTEXT,
2365 'actor' => $owner['url'],
2369 'actor' => $owner['url'],
2370 'object' => $profile['url']
2372 'instrument' => self::getService(),
2373 'to' => [$profile['url']],
2376 Logger::info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2378 $signed = LDSignature::sign($data, $owner);
2379 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2383 * Prepends mentions (@) to $body variable
2385 * @param string $body HTML code
2387 * @param string $authorLink Author link
2388 * @return string HTML code with prepended mentions
2390 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2394 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2395 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2396 if (!empty($profile['addr'])
2397 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2398 && !strstr($body, $profile['addr'])
2399 && !strstr($body, $tag['url'])
2400 && $tag['url'] !== $authorLink
2402 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2406 $mentions[] = $body;
2408 return implode(' ', $mentions);