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\Worker;
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
26 use Friendica\Core\Protocol;
27 use Friendica\Core\Worker;
28 use Friendica\Database\DBA;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Conversation;
32 use Friendica\Model\Group;
33 use Friendica\Model\GServer;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\PushSubscriber;
37 use Friendica\Model\Tag;
38 use Friendica\Model\User;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Protocol\Diaspora;
42 use Friendica\Protocol\Delivery;
43 use Friendica\Protocol\OStatus;
44 use Friendica\Protocol\Salmon;
45 use Friendica\Util\LDSignature;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
50 * The notifier is typically called with:
52 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
54 * where COMMAND is one of the constants that are defined in Worker/Delivery.php
55 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
60 public static function execute(string $cmd, int $post_uriid, int $sender_uid = 0)
64 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]);
66 $target_id = $post_uriid;
71 $delivery_contacts_stmt = null;
76 $delivery_queue_count = 0;
79 if ($cmd == Delivery::MAIL) {
80 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
81 if (!DBA::isResult($message)) {
84 $uid = $message['uid'];
85 $recipients[] = $message['contact-id'];
87 $mail = ActivityPub\Transmitter::getItemArrayFromMail($target_id);
88 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($mail, $uid, true);
89 foreach ($inboxes as $inbox => $receivers) {
90 $ap_contacts = array_merge($ap_contacts, $receivers);
91 Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'target' => $target_id, 'inbox' => $inbox]);
92 Worker::add(['priority' => Worker::PRIORITY_HIGH, 'created' => $a->getQueueValue('created'), 'dont_fork' => true],
93 'APDelivery', $cmd, $target_id, $inbox, $uid, $receivers, $post_uriid);
95 } elseif ($cmd == Delivery::SUGGESTION) {
96 $suggest = DI::fsuggest()->selectOneById($target_id);
98 $recipients[] = $suggest->cid;
99 } elseif ($cmd == Delivery::REMOVAL) {
100 return self::notifySelfRemoval($target_id, $a->getQueueValue('priority'), $a->getQueueValue('created'));
101 } elseif ($cmd == Delivery::RELOCATION) {
104 $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
105 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'addr', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition);
107 $post = Post::selectFirst(['id'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
108 if (!DBA::isResult($post)) {
109 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
112 $target_id = $post['id'];
115 $condition = ['id' => $target_id, 'visible' => true];
116 $target_item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
117 $target_item = Post\Media::addHTMLAttachmentToItem($target_item);
119 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
120 Logger::info('No target item', ['cmd' => $cmd, 'target' => $target_id]);
124 if (!empty($target_item['contact-uid'])) {
125 $uid = $target_item['contact-uid'];
126 } elseif (!empty($target_item['uid'])) {
127 $uid = $target_item['uid'];
129 Logger::info('Only public users, quitting', ['target' => $target_id]);
133 $condition = ['parent' => $target_item['parent'], 'visible' => true];
134 $params = ['order' => ['id']];
135 $items_stmt = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
136 if (!DBA::isResult($items_stmt)) {
137 Logger::info('No item found', ['cmd' => $cmd, 'target' => $target_id]);
141 $items = Post::toArray($items_stmt);
143 // avoid race condition with deleting entries
144 if ($items[0]['deleted']) {
145 foreach ($items as $item) {
146 $item['deleted'] = 1;
150 $top_level = $target_item['gravity'] == Item::GRAVITY_PARENT;
153 $owner = User::getOwnerDataById($uid);
155 Logger::info('Owner not found', ['cmd' => $cmd, 'target' => $target_id]);
159 // Should the post be transmitted to Diaspora?
160 $diaspora_delivery = ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
162 // If this is a public conversation, notify the feed hub
163 $public_message = true;
168 $push_notify = false;
170 // Deliver directly to a forum, don't PuSH
171 $direct_forum_delivery = false;
174 $recipients_followup = [];
176 if (!empty($target_item) && !empty($items)) {
179 $fields = ['network', 'author-id', 'author-link', 'author-network', 'owner-id'];
180 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
181 $thr_parent = Post::selectFirst($fields, $condition);
182 if (empty($thr_parent)) {
183 $thr_parent = $parent;
186 Logger::info('Got post', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'network' => $target_item['network'], 'parent-network' => $parent['network'], 'thread-parent-network' => $thr_parent['network']]);
188 if (!self::isRemovalActivity($cmd, $owner, Protocol::ACTIVITYPUB)) {
189 $apdelivery = self::activityPubDelivery($cmd, $target_item, $parent, $thr_parent, $a->getQueueValue('priority'), $a->getQueueValue('created'), $owner);
190 $ap_contacts = $apdelivery['contacts'];
191 $delivery_queue_count += $apdelivery['count'];
194 // Only deliver threaded replies (comment to a comment) to Diaspora
195 // when the original comment author does support the Diaspora protocol.
196 if ($thr_parent['author-link'] && $target_item['parent-uri'] != $target_item['thr-parent']) {
197 $diaspora_delivery = Diaspora::isSupportedByContactUrl($thr_parent['author-link']);
198 if ($diaspora_delivery && empty($target_item['signed_text'])) {
199 Logger::debug('Post has got no Diaspora signature, so there will be no Diaspora delivery', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id']]);
200 $diaspora_delivery = false;
202 Logger::info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]);
205 $unlisted = $target_item['private'] == Item::UNLISTED;
207 // This is IMPORTANT!!!!
209 // We will only send a "notify owner to relay" or followup message if the referenced post
210 // originated on our system by virtue of having our hostname somewhere
211 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
213 // if $parent['wall'] == 1 we will already have the parent message in our array
214 // and we will relay the whole lot.
216 $localhost = str_replace('www.','', DI::baseUrl()->getHost());
217 if (strpos($localhost,':')) {
218 $localhost = substr($localhost,0,strpos($localhost,':'));
222 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
223 * have been known to cause runaway conditions which affected several servers, along with
224 * permissions issues.
228 $relay_to_owner = false;
230 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
231 $relay_to_owner = true;
234 // until the 'origin' flag has been in use for several months
235 // we will just use it as a fallback test
236 // later we will be able to use it as the primary test of whether or not to relay.
238 if (!$target_item['origin']) {
239 $relay_to_owner = false;
241 if ($parent['origin']) {
242 $relay_to_owner = false;
245 // Special treatment for forum posts
246 if (Item::isForumPost($target_item['uri-id'])) {
247 $relay_to_owner = true;
248 $direct_forum_delivery = true;
251 // Avoid that comments in a forum thread are sent to OStatus
252 if (Item::isForumPost($parent['uri-id'])) {
253 $direct_forum_delivery = true;
256 $exclusive_delivery = false;
258 $exclusive_targets = Tag::getByURIId($parent['uri-id'], [Tag::EXCLUSIVE_MENTION]);
259 if (!empty($exclusive_targets)) {
260 $exclusive_delivery = true;
261 Logger::info('Possible Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id']]);
262 foreach ($exclusive_targets as $target) {
263 if (Strings::compareLink($owner['url'], $target['url'])) {
264 $exclusive_delivery = false;
265 Logger::info('False Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]);
270 if ($relay_to_owner) {
271 // local followup to remote post
273 $public_message = false; // not public
274 $recipients = [$parent['contact-id']];
275 $recipients_followup = [$parent['contact-id']];
277 Logger::info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]);
279 if (($target_item['private'] != Item::PRIVATE) &&
280 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
281 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
284 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
287 if ($parent["network"] == Protocol::OSTATUS) {
288 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
289 // Currently it is work at progress
290 $condition = ['uid' => $uid, 'network' => Protocol::DFRN, 'blocked' => false, 'pending' => false, 'archive' => false];
291 $followup_contacts_stmt = DBA::select('contact', ['id'], $condition);
292 while($followup_contact = DBA::fetch($followup_contacts_stmt)) {
293 $recipients_followup[] = $followup_contact['id'];
295 DBA::close($followup_contacts_stmt);
299 if ($direct_forum_delivery) {
300 $push_notify = false;
303 Logger::info('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"));
304 } elseif ($exclusive_delivery) {
307 foreach ($exclusive_targets as $target) {
308 $cid = Contact::getIdForURL($target['url'], $uid, false);
310 $recipients_followup[] = $cid;
311 Logger::info('Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]);
317 Logger::info('Distributing directly', ['target' => $target_id, 'guid' => $target_item['guid']]);
319 // don't send deletions onward for other people's stuff
321 if ($target_item['deleted'] && !intval($target_item['wall'])) {
322 Logger::notice('Ignoring delete notification for non-wall item');
326 if (strlen($parent['allow_cid'])
327 || strlen($parent['allow_gid'])
328 || strlen($parent['deny_cid'])
329 || strlen($parent['deny_gid'])) {
330 $public_message = false; // private recipients, not public
333 $aclFormatter = DI::aclFormatter();
335 $allow_people = $aclFormatter->expand($parent['allow_cid']);
336 $allow_groups = Group::expand($uid, $aclFormatter->expand($parent['allow_gid']),true);
337 $deny_people = $aclFormatter->expand($parent['deny_cid']);
338 $deny_groups = Group::expand($uid, $aclFormatter->expand($parent['deny_gid']));
340 foreach ($items as $item) {
341 $recipients[] = $item['contact-id'];
342 // pull out additional tagged people to notify (if public message)
343 if ($public_message && $item['inform']) {
344 $people = explode(',',$item['inform']);
345 foreach ($people as $person) {
346 if (substr($person,0,4) === 'cid:') {
347 $recipients[] = intval(substr($person,4));
349 $url_recipients[] = substr($person,4);
355 if (count($url_recipients)) {
356 Logger::notice('Deliver', ['target' => $target_id, 'guid' => $target_item['guid'], 'recipients' => $url_recipients]);
359 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
360 $deny = array_unique(array_merge($deny_people, $deny_groups));
361 $recipients = array_diff($recipients, $deny);
363 // If this is a public message and pubmail is set on the parent, include all your email contacts
365 function_exists('imap_open')
366 && !DI::config()->get('system','imap_disabled')
368 && intval($target_item['pubmail'])
370 $mail_contacts_stmt = DBA::select('contact', ['id'], ['uid' => $uid, 'network' => Protocol::MAIL]);
371 while ($mail_contact = DBA::fetch($mail_contacts_stmt)) {
372 $recipients[] = $mail_contact['id'];
374 DBA::close($mail_contacts_stmt);
378 // If the thread parent is OStatus then do some magic to distribute the messages.
379 // We have not only to look at the parent, since it could be a Friendica thread.
380 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
381 $diaspora_delivery = false;
383 Logger::info('Some parent is OStatus for ' . $target_item['guid'] . ' - Author: ' . $thr_parent['author-id'] . ' - Owner: ' . $thr_parent['owner-id']);
385 // Send a salmon to the parent author
386 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
387 if (DBA::isResult($probed_contact) && !empty($probed_contact['notify'])) {
388 Logger::notice('Notify parent author', ['url' => $probed_contact['url'], 'notify' => $probed_contact['notify']]);
389 $url_recipients[$probed_contact['notify']] = $probed_contact['notify'];
392 // Send a salmon to the parent owner
393 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
394 if (DBA::isResult($probed_contact) && !empty($probed_contact['notify'])) {
395 Logger::notice('Notify parent owner', ['url' => $probed_contact['url'], 'notify' => $probed_contact['notify']]);
396 $url_recipients[$probed_contact['notify']] = $probed_contact['notify'];
399 // Send a salmon notification to every person we mentioned in the post
400 foreach (Tag::getByURIId($target_item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION]) as $tag) {
401 $probed_contact = Contact::getByURL($tag['url']);
402 if (!empty($probed_contact['notify'])) {
403 Logger::notice('Notify mentioned user', ['url' => $probed_contact['url'], 'notify' => $probed_contact['notify']]);
404 $url_recipients[$probed_contact['notify']] = $probed_contact['notify'];
408 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
409 $networks = [Protocol::DFRN];
410 } elseif ($diaspora_delivery) {
411 $networks = [Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
412 if (($parent['network'] == Protocol::DIASPORA) || ($thr_parent['network'] == Protocol::DIASPORA)) {
413 Logger::info('Add AP contacts', ['target' => $target_id, 'guid' => $target_item['guid']]);
414 $networks[] = Protocol::ACTIVITYPUB;
417 $networks = [Protocol::DFRN, Protocol::MAIL];
420 $public_message = false;
423 if (empty($delivery_contacts_stmt)) {
425 $recipients = $recipients_followup;
427 $condition = ['id' => $recipients, 'self' => false, 'uid' => [0, $uid],
428 'blocked' => false, 'pending' => false, 'archive' => false];
429 if (!empty($networks)) {
430 $condition['network'] = $networks;
432 $delivery_contacts_stmt = DBA::select('contact', ['id', 'addr', 'url', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition);
436 $batch_delivery = false;
438 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
441 if ($diaspora_delivery && !$unlisted) {
442 $batch_delivery = true;
444 $participants = DBA::selectToArray('contact', ['batch', 'network', 'protocol', 'baseurl', 'gsid', 'id', 'url', 'name'],
445 ["`network` = ? AND `batch` != '' AND `uid` = ? AND `rel` != ? AND NOT `blocked` AND NOT `pending` AND NOT `archive`", Protocol::DIASPORA, $owner['uid'], Contact::SHARING],
446 ['group_by' => ['batch', 'network', 'protocol']]);
448 // Fetch the participation list
449 // The function will ensure that there are no duplicates
450 $participants = Diaspora::participantsForThread($target_item, $participants);
453 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
454 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
456 $contacts = DBA::selectToArray('contact', ['id', 'url', 'addr', 'name', 'network', 'protocol', 'baseurl', 'gsid'], $condition);
458 $conversants = array_merge($contacts, $participants);
460 $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, true, $conversants, $ap_contacts, []);
465 $contacts = DBA::toArray($delivery_contacts_stmt);
466 $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, false, $contacts, $ap_contacts, $conversants);
468 $delivery_queue_count += self::deliverOStatus($target_id, $target_item, $owner, $url_recipients, $public_message, $push_notify);
470 if (!empty($target_item)) {
471 Logger::info('Calling hooks for ' . $cmd . ' ' . $target_id);
473 Hook::fork($a->getQueueValue('priority'), 'notifier_normal', $target_item);
475 Hook::callAll('notifier_end', $target_item);
477 // Workaround for pure connector posts
478 if ($cmd == Delivery::POST) {
479 if ($delivery_queue_count == 0) {
480 Post\DeliveryData::incrementQueueDone($target_item['uri-id']);
481 $delivery_queue_count = 1;
484 Post\DeliveryData::incrementQueueCount($target_item['uri-id'], $delivery_queue_count);
492 * Deliver the message to the contacts
495 * @param int $post_uriid
496 * @param int $sender_uid
497 * @param array $target_item
498 * @param array $thr_parent
499 * @param array $owner
500 * @param bool $batch_delivery
501 * @param array $contacts
502 * @param array $ap_contacts
503 * @param array $conversants
505 * @return int Count of delivery queue
506 * @throws InternalServerErrorException
509 private static function delivery(string $cmd, int $post_uriid, int $sender_uid, array $target_item, array $thr_parent, array $owner, bool $batch_delivery, bool $in_batch, array $contacts, array $ap_contacts, array $conversants = []): int
512 $delivery_queue_count = 0;
514 if (!empty($target_item['verb']) && ($target_item['verb'] == Activity::ANNOUNCE)) {
515 Logger::notice('Announces are only delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
519 foreach ($contacts as $contact) {
520 // Direct delivery of local contacts
521 if (!in_array($cmd, [Delivery::RELOCATION, Delivery::SUGGESTION, Delivery::MAIL]) && $target_uid = User::getIdForURL($contact['url'])) {
522 if ($cmd == Delivery::DELETION) {
523 Logger::info('No need to deliver deletions internally', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
526 if ($target_item['origin'] || ($target_item['network'] != Protocol::ACTIVITYPUB)) {
527 if ($target_uid != $target_item['uid']) {
528 $fields = ['protocol' => Conversation::PARCEL_LOCAL_DFRN, 'direction' => Conversation::PUSH, 'post-reason' => Item::PR_DIRECT];
529 Item::storeForUserByUriId($target_item['uri-id'], $target_uid, $fields, $target_item['uid']);
530 Logger::info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'target' => $target_uid]);
532 Logger::info('No need to deliver to myself', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
535 Logger::info('Remote item does not need to be delivered locally', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
540 // Deletions are always sent via DFRN as well.
541 // This is done until we can perform deletions of foreign comments on our own threads via AP.
542 if (($cmd != Delivery::DELETION) && in_array($contact['id'], $ap_contacts)) {
543 Logger::info('Contact is already delivered via AP, so skip delivery via legacy DFRN/Diaspora', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
547 if (!empty($contact['id']) && Contact::isArchived($contact['id'])) {
548 Logger::info('Contact is archived, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
552 if (self::isRemovalActivity($cmd, $owner, $contact['network'])) {
553 Logger::info('Contact does no supports account removal commands, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
557 if (self::skipActivityPubForDiaspora($contact, $target_item, $thr_parent)) {
558 Logger::info('Contact is from Diaspora, but the replied author is from ActivityPub, so skip delivery via Diaspora', ['id' => $post_uriid, 'uid' => $sender_uid, 'url' => $contact['url']]);
562 // Don't deliver to Diaspora if it already had been done as batch delivery
563 if (!$in_batch && $batch_delivery && ($contact['network'] == Protocol::DIASPORA)) {
564 Logger::info('Diaspora contact is already delivered via batch', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
568 // Don't deliver to folks who have already been delivered to
569 if (in_array($contact['id'], $conversants)) {
570 Logger::info('Already delivery', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
574 if (empty($contact['gsid'])) {
575 $reachable = GServer::reachable($contact);
576 } elseif (!DI::config()->get('system', 'bulk_delivery')) {
577 $reachable = GServer::isReachableById($contact['gsid']);
579 $reachable = !GServer::isDefunctById($contact['gsid']);
583 Logger::info('Server is not reachable', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
587 Logger::info('Delivery', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'guid' => $target_item['guid'] ?? '', 'to' => $contact]);
589 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
590 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
591 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
592 // This is only important for high and medium priority tasks and not for Low priority jobs like deletions.
593 if (($contact['network'] == Protocol::DIASPORA) && in_array($a->getQueueValue('priority'), [Worker::PRIORITY_HIGH, Worker::PRIORITY_MEDIUM])) {
594 $deliver_options = ['priority' => $a->getQueueValue('priority'), 'dont_fork' => true];
596 $deliver_options = ['priority' => $a->getQueueValue('priority'), 'created' => $a->getQueueValue('created'), 'dont_fork' => true];
599 if (!empty($contact['gsid']) && DI::config()->get('system', 'bulk_delivery')) {
600 $delivery_queue_count++;
601 $deliveryQueueItem = DI::deliveryQueueItemFactory()->createFromDelivery($cmd, $post_uriid, new \DateTimeImmutable($target_item['created']), $contact['id'], $contact['gsid'], $sender_uid);
602 DI::deliveryQueueItemRepo()->save($deliveryQueueItem);
603 Worker::add(['priority' => Worker::PRIORITY_HIGH, 'dont_fork' => true], 'BulkDelivery', $contact['gsid']);
605 if (Worker::add($deliver_options, 'Delivery', $cmd, $post_uriid, (int)$contact['id'], $sender_uid)) {
606 $delivery_queue_count++;
612 return $delivery_queue_count;
616 * Deliver the message via OStatus
618 * @param int $target_id
619 * @param array $target_item
620 * @param array $owner
621 * @param array $url_recipients
622 * @param bool $public_message
623 * @param bool $push_notify
625 * @return int Count of sent Salmon notifications
626 * @throws InternalServerErrorException
629 private static function deliverOStatus(int $target_id, array $target_item, array $owner, array $url_recipients, bool $public_message, bool $push_notify): int
632 $delivery_queue_count = 0;
634 $url_recipients = array_filter($url_recipients);
635 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
636 // They are especially used for notifications to OStatus users that don't follow us.
637 if (count($url_recipients) && ($public_message || $push_notify) && !empty($target_item)) {
638 $slap = OStatus::salmon($target_item, $owner);
639 foreach ($url_recipients as $url) {
640 Logger::info('Salmon delivery', ['item' => $target_id, 'to' => $url]);
642 $delivery_queue_count++;
643 Salmon::slapper($owner, $url, $slap);
644 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::OSTATUS);
648 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
650 Logger::info('Activating internal PuSH', ['uid' => $owner['uid']]);
652 // Handling the pubsubhubbub requests
653 PushSubscriber::publishFeed($owner['uid'], $a->getQueueValue('priority'));
655 return $delivery_queue_count;
659 * Checks if the current delivery shouldn't be transported to Diaspora.
660 * This is done for posts from AP authors or posts that are comments to AP authors.
662 * @param array $contact Receiver of the post
663 * @param array $item The post
664 * @param array $thr_parent The thread parent
668 private static function skipActivityPubForDiaspora(array $contact, array $item, array $thr_parent): bool
670 // No skipping needs to be done when delivery isn't done to Diaspora
671 if ($contact['network'] != Protocol::DIASPORA) {
675 // Skip the delivery to Diaspora if the item is from an ActivityPub author
676 if (!empty($item['author-network']) && ($item['author-network'] == Protocol::ACTIVITYPUB)) {
680 // Skip the delivery to Diaspora if the thread parent is from an ActivityPub author
681 if (!empty($thr_parent['author-network']) && ($thr_parent['author-network'] == Protocol::ACTIVITYPUB)) {
689 * Checks if the current action is a deletion command of a account removal activity
690 * For Diaspora and ActivityPub we don't need to send single item deletion calls.
691 * These protocols do have a dedicated command for deleting a whole account.
693 * @param string $cmd Notifier command
694 * @param array $owner Sender of the post
695 * @param string $network Receiver network
698 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
699 * @throws \ImagickException
701 private static function isRemovalActivity(string $cmd, array $owner, string $network): bool
703 return ($cmd == Delivery::DELETION) && $owner['account_removed'] && in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA]);
707 * @param int $self_user_id
708 * @param int $priority The priority the Notifier queue item was created with
709 * @param string $created The date the Notifier queue item was created on
712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
713 * @throws \ImagickException
715 private static function notifySelfRemoval(int $self_user_id, int $priority, string $created): bool
717 $owner = User::getOwnerDataById($self_user_id);
718 if (empty($self_user_id) || empty($owner)) {
722 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
723 if (!DBA::isResult($contacts_stmt)) {
727 while($contact = DBA::fetch($contacts_stmt)) {
728 Contact::terminateFriendship($contact);
730 DBA::close($contacts_stmt);
732 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser($self_user_id);
733 foreach ($inboxes as $inbox => $receivers) {
734 Logger::info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]);
735 Worker::add(['priority' => Worker::PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
736 'APDelivery', Delivery::REMOVAL, 0, $inbox, $self_user_id, $receivers);
745 * @param array $target_item
746 * @param array $parent
747 * @param array $thr_parent
748 * @param int $priority The priority the Notifier queue item was created with
749 * @param string $created The date the Notifier queue item was created on
751 * @return array 'count' => The number of delivery tasks created, 'contacts' => their contact ids
752 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
753 * @throws \ImagickException
754 * @todo Unused parameter $owner
756 private static function activityPubDelivery($cmd, array $target_item, array $parent, array $thr_parent, int $priority, string $created, $owner): array
758 // Don't deliver via AP when the starting post isn't from a federated network
759 if (!in_array($parent['network'], Protocol::FEDERATED)) {
760 Logger::info('Parent network is no federated network, so no AP delivery', ['network' => $parent['network']]);
761 return ['count' => 0, 'contacts' => []];
764 // Don't deliver via AP when the starting post is delivered via Diaspora
765 if ($parent['network'] == Protocol::DIASPORA) {
766 Logger::info('Parent network is Diaspora, so no AP delivery');
767 return ['count' => 0, 'contacts' => []];
770 // Also don't deliver when the direct thread parent was delivered via Diaspora
771 if ($thr_parent['network'] == Protocol::DIASPORA) {
772 Logger::info('Thread parent network is Diaspora, so no AP delivery');
773 return ['count' => 0, 'contacts' => []];
776 // Posts from Diaspora contacts are transmitted via Diaspora
777 if ($target_item['network'] == Protocol::DIASPORA) {
778 Logger::info('Post network is Diaspora, so no AP delivery');
779 return ['count' => 0, 'contacts' => []];
785 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
787 // Update the locally stored follower list when we deliver to a forum
788 foreach (Tag::getByURIId($target_item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
789 $target_contact = Contact::getByURL(Strings::normaliseLink($tag['url']), null, [], $uid);
790 if ($target_contact && $target_contact['contact-type'] == Contact::TYPE_COMMUNITY && $target_contact['manually-approve']) {
791 Group::updateMembersForForum($target_contact['id']);
795 if ($target_item['origin']) {
796 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
798 if (in_array($target_item['private'], [Item::PUBLIC])) {
799 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($target_item['id'], $inboxes);
800 $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes();
803 Logger::info('Origin item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
804 $check_signature = false;
805 } elseif (!Post\Activity::exists($target_item['uri-id'])) {
806 Logger::info('Remote item is no AP post. It will not be distributed.', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
807 return ['count' => 0, 'contacts' => []];
808 } elseif ($parent['origin'] && (($target_item['gravity'] != Item::GRAVITY_ACTIVITY) || DI::config()->get('system', 'redistribute_activities'))) {
809 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, false, $target_item['id']);
811 if (in_array($target_item['private'], [Item::PUBLIC])) {
812 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($parent['id'], $inboxes);
815 Logger::info('Remote item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
816 $check_signature = ($target_item['gravity'] == Item::GRAVITY_ACTIVITY);
818 Logger::info('Remote activity will not be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
819 return ['count' => 0, 'contacts' => []];
822 if (empty($inboxes) && empty($relay_inboxes)) {
823 Logger::info('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.');
824 return ['count' => 0, 'contacts' => []];
827 // Fill the item cache
828 $activity = ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
829 if (empty($activity)) {
830 Logger::info('Item cache was not created. The post will not be distributed.', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
831 return ['count' => 0, 'contacts' => []];
834 if ($check_signature && !LDSignature::isSigned($activity)) {
835 Logger::info('Unsigned remote activity will not be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
836 return ['count' => 0, 'contacts' => []];
839 $delivery_queue_count = 0;
842 foreach ($inboxes as $inbox => $receivers) {
843 $contacts = array_merge($contacts, $receivers);
845 if ((count($receivers) == 1) && Network::isLocalLink($inbox)) {
846 $contact = Contact::getById($receivers[0], ['url']);
847 if (!in_array($cmd, [Delivery::RELOCATION, Delivery::SUGGESTION, Delivery::MAIL]) && ($target_uid = User::getIdForURL($contact['url']))) {
848 if ($cmd == Delivery::DELETION) {
849 Logger::info('No need to deliver deletions internally', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
852 if ($target_item['origin'] || ($target_item['network'] != Protocol::ACTIVITYPUB)) {
853 if ($target_uid != $target_item['uid']) {
854 $fields = ['protocol' => Conversation::PARCEL_LOCAL_DFRN, 'direction' => Conversation::PUSH, 'post-reason' => Item::PR_BCC];
855 Item::storeForUserByUriId($target_item['uri-id'], $target_uid, $fields, $target_item['uid']);
856 Logger::info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
858 Logger::info('No need to deliver to myself', ['uid' => $target_uid, 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
861 Logger::info('Remote item does not need to be delivered locally', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
865 } elseif ((count($receivers) >= 1) && Network::isLocalLink($inbox)) {
866 Logger::info('Is this a thing?', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
869 Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
871 if (DI::config()->get('system', 'bulk_delivery')) {
872 $delivery_queue_count++;
873 Post\Delivery::add($target_item['uri-id'], $uid, $inbox, $target_item['created'], $cmd, $receivers);
874 Worker::add([Worker::PRIORITY_HIGH, 'dont_fork' => true], 'APDelivery', '', 0, $inbox, 0);
876 if (Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
877 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, $receivers, $target_item['uri-id'])) {
878 $delivery_queue_count++;
884 // We deliver posts to relay servers slightly delayed to priorize the direct delivery
885 foreach ($relay_inboxes as $inbox) {
886 Logger::info('Delivery to relay servers via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
888 if (DI::config()->get('system', 'bulk_delivery')) {
889 $delivery_queue_count++;
890 Post\Delivery::add($target_item['uri-id'], $uid, $inbox, $target_item['created'], $cmd, []);
891 Worker::add([Worker::PRIORITY_MEDIUM, 'dont_fork' => true], 'APDelivery', '', 0, $inbox, 0);
893 if (Worker::add(['priority' => $priority, 'dont_fork' => true], 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, [], $target_item['uri-id'])) {
894 $delivery_queue_count++;
900 return ['count' => $delivery_queue_count, 'contacts' => $contacts];