3 * @copyright Copyright (C) 2010-2022, 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\Network;
46 use Friendica\Util\Strings;
49 * The notifier is typically called with:
51 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
53 * where COMMAND is one of the constants that are defined in Worker/Delivery.php
54 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
59 public static function execute(string $cmd, int $post_uriid, int $sender_uid = 0)
63 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]);
65 $target_id = $post_uriid;
70 $delivery_contacts_stmt = null;
75 $delivery_queue_count = 0;
78 if ($cmd == Delivery::MAIL) {
79 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
80 if (!DBA::isResult($message)) {
83 $uid = $message['uid'];
84 $recipients[] = $message['contact-id'];
86 $mail = ActivityPub\Transmitter::getItemArrayFromMail($target_id);
87 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($mail, $uid, true);
88 foreach ($inboxes as $inbox => $receivers) {
89 $ap_contacts = array_merge($ap_contacts, $receivers);
90 Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'target' => $target_id, 'inbox' => $inbox]);
91 Worker::add(['priority' => Worker::PRIORITY_HIGH, 'created' => $a->getQueueValue('created'), 'dont_fork' => true],
92 'APDelivery', $cmd, $target_id, $inbox, $uid, $receivers, $post_uriid);
94 } elseif ($cmd == Delivery::SUGGESTION) {
95 $suggest = DI::fsuggest()->selectOneById($target_id);
97 $recipients[] = $suggest->cid;
98 } elseif ($cmd == Delivery::REMOVAL) {
99 return self::notifySelfRemoval($target_id, $a->getQueueValue('priority'), $a->getQueueValue('created'));
100 } elseif ($cmd == Delivery::RELOCATION) {
103 $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
104 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'addr', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition);
106 $post = Post::selectFirst(['id'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
107 if (!DBA::isResult($post)) {
108 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
111 $target_id = $post['id'];
114 $condition = ['id' => $target_id, 'visible' => true];
115 $target_item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
117 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
118 Logger::info('No target item', ['cmd' => $cmd, 'target' => $target_id]);
122 if (!empty($target_item['contact-uid'])) {
123 $uid = $target_item['contact-uid'];
124 } elseif (!empty($target_item['uid'])) {
125 $uid = $target_item['uid'];
127 Logger::info('Only public users, quitting', ['target' => $target_id]);
131 $condition = ['parent' => $target_item['parent'], 'visible' => true];
132 $params = ['order' => ['id']];
133 $items_stmt = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
134 if (!DBA::isResult($items_stmt)) {
135 Logger::info('No item found', ['cmd' => $cmd, 'target' => $target_id]);
139 $items = Post::toArray($items_stmt);
141 // avoid race condition with deleting entries
142 if ($items[0]['deleted']) {
143 foreach ($items as $item) {
144 $item['deleted'] = 1;
148 $top_level = $target_item['gravity'] == Item::GRAVITY_PARENT;
151 $owner = User::getOwnerDataById($uid);
153 Logger::info('Owner not found', ['cmd' => $cmd, 'target' => $target_id]);
157 // Should the post be transmitted to Diaspora?
158 $diaspora_delivery = ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
160 // If this is a public conversation, notify the feed hub
161 $public_message = true;
166 $push_notify = false;
168 // Deliver directly to a forum, don't PuSH
169 $direct_forum_delivery = false;
172 $recipients_followup = [];
174 if (!empty($target_item) && !empty($items)) {
177 $fields = ['network', 'author-id', 'author-link', 'author-network', 'owner-id'];
178 $condition = ['uri' => $target_item['thr-parent'], 'uid' => $target_item['uid']];
179 $thr_parent = Post::selectFirst($fields, $condition);
180 if (empty($thr_parent)) {
181 $thr_parent = $parent;
184 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']]);
186 if (!self::isRemovalActivity($cmd, $owner, Protocol::ACTIVITYPUB)) {
187 $apdelivery = self::activityPubDelivery($cmd, $target_item, $parent, $thr_parent, $a->getQueueValue('priority'), $a->getQueueValue('created'), $owner);
188 $ap_contacts = $apdelivery['contacts'];
189 $delivery_queue_count += $apdelivery['count'];
192 // Only deliver threaded replies (comment to a comment) to Diaspora
193 // when the original comment author does support the Diaspora protocol.
194 if ($thr_parent['author-link'] && $target_item['parent-uri'] != $target_item['thr-parent']) {
195 $diaspora_delivery = Diaspora::isSupportedByContactUrl($thr_parent['author-link']);
196 if ($diaspora_delivery && empty($target_item['signed_text'])) {
197 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']]);
198 $diaspora_delivery = false;
200 Logger::info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]);
203 $unlisted = $target_item['private'] == Item::UNLISTED;
205 // This is IMPORTANT!!!!
207 // We will only send a "notify owner to relay" or followup message if the referenced post
208 // originated on our system by virtue of having our hostname somewhere
209 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
211 // if $parent['wall'] == 1 we will already have the parent message in our array
212 // and we will relay the whole lot.
214 $localhost = str_replace('www.','', DI::baseUrl()->getHostname());
215 if (strpos($localhost,':')) {
216 $localhost = substr($localhost,0,strpos($localhost,':'));
220 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
221 * have been known to cause runaway conditions which affected several servers, along with
222 * permissions issues.
226 $relay_to_owner = false;
228 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
229 $relay_to_owner = true;
232 // until the 'origin' flag has been in use for several months
233 // we will just use it as a fallback test
234 // later we will be able to use it as the primary test of whether or not to relay.
236 if (!$target_item['origin']) {
237 $relay_to_owner = false;
239 if ($parent['origin']) {
240 $relay_to_owner = false;
243 // Special treatment for forum posts
244 if (Item::isForumPost($target_item['uri-id'])) {
245 $relay_to_owner = true;
246 $direct_forum_delivery = true;
249 // Avoid that comments in a forum thread are sent to OStatus
250 if (Item::isForumPost($parent['uri-id'])) {
251 $direct_forum_delivery = true;
254 $exclusive_delivery = false;
256 $exclusive_targets = Tag::getByURIId($parent['uri-id'], [Tag::EXCLUSIVE_MENTION]);
257 if (!empty($exclusive_targets)) {
258 $exclusive_delivery = true;
259 Logger::info('Possible Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id']]);
260 foreach ($exclusive_targets as $target) {
261 if (Strings::compareLink($owner['url'], $target['url'])) {
262 $exclusive_delivery = false;
263 Logger::info('False Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]);
268 if ($relay_to_owner) {
269 // local followup to remote post
271 $public_message = false; // not public
272 $recipients = [$parent['contact-id']];
273 $recipients_followup = [$parent['contact-id']];
275 Logger::info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]);
277 if (($target_item['private'] != Item::PRIVATE) &&
278 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
279 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
282 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
285 if ($parent["network"] == Protocol::OSTATUS) {
286 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
287 // Currently it is work at progress
288 $condition = ['uid' => $uid, 'network' => Protocol::DFRN, 'blocked' => false, 'pending' => false, 'archive' => false];
289 $followup_contacts_stmt = DBA::select('contact', ['id'], $condition);
290 while($followup_contact = DBA::fetch($followup_contacts_stmt)) {
291 $recipients_followup[] = $followup_contact['id'];
293 DBA::close($followup_contacts_stmt);
297 if ($direct_forum_delivery) {
298 $push_notify = false;
301 Logger::info('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"));
302 } elseif ($exclusive_delivery) {
305 foreach ($exclusive_targets as $target) {
306 $cid = Contact::getIdForURL($target['url'], $uid, false);
308 $recipients_followup[] = $cid;
309 Logger::info('Exclusively delivering', ['uid' => $target_item['uid'], 'guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'url' => $target['url']]);
315 Logger::info('Distributing directly', ['target' => $target_id, 'guid' => $target_item['guid']]);
317 // don't send deletions onward for other people's stuff
319 if ($target_item['deleted'] && !intval($target_item['wall'])) {
320 Logger::notice('Ignoring delete notification for non-wall item');
324 if (strlen($parent['allow_cid'])
325 || strlen($parent['allow_gid'])
326 || strlen($parent['deny_cid'])
327 || strlen($parent['deny_gid'])) {
328 $public_message = false; // private recipients, not public
331 $aclFormatter = DI::aclFormatter();
333 $allow_people = $aclFormatter->expand($parent['allow_cid']);
334 $allow_groups = Group::expand($uid, $aclFormatter->expand($parent['allow_gid']),true);
335 $deny_people = $aclFormatter->expand($parent['deny_cid']);
336 $deny_groups = Group::expand($uid, $aclFormatter->expand($parent['deny_gid']));
338 foreach ($items as $item) {
339 $recipients[] = $item['contact-id'];
340 // pull out additional tagged people to notify (if public message)
341 if ($public_message && $item['inform']) {
342 $people = explode(',',$item['inform']);
343 foreach ($people as $person) {
344 if (substr($person,0,4) === 'cid:') {
345 $recipients[] = intval(substr($person,4));
347 $url_recipients[] = substr($person,4);
353 if (count($url_recipients)) {
354 Logger::notice('Deliver', ['target' => $target_id, 'guid' => $target_item['guid'], 'recipients' => $url_recipients]);
357 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
358 $deny = array_unique(array_merge($deny_people, $deny_groups));
359 $recipients = array_diff($recipients, $deny);
361 // If this is a public message and pubmail is set on the parent, include all your email contacts
363 function_exists('imap_open')
364 && !DI::config()->get('system','imap_disabled')
366 && intval($target_item['pubmail'])
368 $mail_contacts_stmt = DBA::select('contact', ['id'], ['uid' => $uid, 'network' => Protocol::MAIL]);
369 while ($mail_contact = DBA::fetch($mail_contacts_stmt)) {
370 $recipients[] = $mail_contact['id'];
372 DBA::close($mail_contacts_stmt);
376 // If the thread parent is OStatus then do some magic to distribute the messages.
377 // We have not only to look at the parent, since it could be a Friendica thread.
378 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
379 $diaspora_delivery = false;
381 Logger::info('Some parent is OStatus for ' . $target_item['guid'] . ' - Author: ' . $thr_parent['author-id'] . ' - Owner: ' . $thr_parent['owner-id']);
383 // Send a salmon to the parent author
384 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
385 if (DBA::isResult($probed_contact) && !empty($probed_contact['notify'])) {
386 Logger::notice('Notify parent author', ['url' => $probed_contact['url'], 'notify' => $probed_contact['notify']]);
387 $url_recipients[$probed_contact['notify']] = $probed_contact['notify'];
390 // Send a salmon to the parent owner
391 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
392 if (DBA::isResult($probed_contact) && !empty($probed_contact['notify'])) {
393 Logger::notice('Notify parent owner', ['url' => $probed_contact['url'], 'notify' => $probed_contact['notify']]);
394 $url_recipients[$probed_contact['notify']] = $probed_contact['notify'];
397 // Send a salmon notification to every person we mentioned in the post
398 foreach (Tag::getByURIId($target_item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION]) as $tag) {
399 $probed_contact = Contact::getByURL($tag['url']);
400 if (!empty($probed_contact['notify'])) {
401 Logger::notice('Notify mentioned user', ['url' => $probed_contact['url'], 'notify' => $probed_contact['notify']]);
402 $url_recipients[$probed_contact['notify']] = $probed_contact['notify'];
406 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
407 $networks = [Protocol::DFRN];
408 } elseif ($diaspora_delivery) {
409 $networks = [Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
410 if (($parent['network'] == Protocol::DIASPORA) || ($thr_parent['network'] == Protocol::DIASPORA)) {
411 Logger::info('Add AP contacts', ['target' => $target_id, 'guid' => $target_item['guid']]);
412 $networks[] = Protocol::ACTIVITYPUB;
415 $networks = [Protocol::DFRN, Protocol::MAIL];
418 $public_message = false;
421 if (empty($delivery_contacts_stmt)) {
423 $recipients = $recipients_followup;
425 $condition = ['id' => $recipients, 'self' => false, 'uid' => [0, $uid],
426 'blocked' => false, 'pending' => false, 'archive' => false];
427 if (!empty($networks)) {
428 $condition['network'] = $networks;
430 $delivery_contacts_stmt = DBA::select('contact', ['id', 'addr', 'url', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition);
434 $batch_delivery = false;
436 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
439 if ($diaspora_delivery && !$unlisted) {
440 $batch_delivery = true;
442 $participants = DBA::selectToArray('contact', ['batch', 'network', 'protocol', 'baseurl', 'gsid', 'id', 'url', 'name'],
443 ["`network` = ? AND `batch` != '' AND `uid` = ? AND `rel` != ? AND NOT `blocked` AND NOT `pending` AND NOT `archive`", Protocol::DIASPORA, $owner['uid'], Contact::SHARING],
444 ['group_by' => ['batch', 'network', 'protocol']]);
446 // Fetch the participation list
447 // The function will ensure that there are no duplicates
448 $participants = Diaspora::participantsForThread($target_item, $participants);
451 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
452 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
454 $contacts = DBA::selectToArray('contact', ['id', 'url', 'addr', 'name', 'network', 'protocol', 'baseurl', 'gsid'], $condition);
456 $conversants = array_merge($contacts, $participants);
458 $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, true, $conversants, $ap_contacts, []);
463 $contacts = DBA::toArray($delivery_contacts_stmt);
464 $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, false, $contacts, $ap_contacts, $conversants);
466 $delivery_queue_count += self::deliverOStatus($target_id, $target_item, $owner, $url_recipients, $public_message, $push_notify);
468 if (!empty($target_item)) {
469 Logger::info('Calling hooks for ' . $cmd . ' ' . $target_id);
471 Hook::fork($a->getQueueValue('priority'), 'notifier_normal', $target_item);
473 Hook::callAll('notifier_end', $target_item);
475 // Workaround for pure connector posts
476 if ($cmd == Delivery::POST) {
477 if ($delivery_queue_count == 0) {
478 Post\DeliveryData::incrementQueueDone($target_item['uri-id']);
479 $delivery_queue_count = 1;
482 Post\DeliveryData::incrementQueueCount($target_item['uri-id'], $delivery_queue_count);
490 * Deliver the message to the contacts
493 * @param int $post_uriid
494 * @param int $sender_uid
495 * @param array $target_item
496 * @param array $thr_parent
497 * @param array $owner
498 * @param bool $batch_delivery
499 * @param array $contacts
500 * @param array $ap_contacts
501 * @param array $conversants
503 * @return int Count of delivery queue
504 * @throws InternalServerErrorException
507 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
510 $delivery_queue_count = 0;
512 if (!empty($target_item['verb']) && ($target_item['verb'] == Activity::ANNOUNCE)) {
513 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']]);
517 foreach ($contacts as $contact) {
518 // Direct delivery of local contacts
519 if (!in_array($cmd, [Delivery::RELOCATION, Delivery::SUGGESTION, Delivery::DELETION, Delivery::MAIL]) && $target_uid = User::getIdForURL($contact['url'])) {
520 if ($target_item['origin'] || ($target_item['network'] != Protocol::ACTIVITYPUB)) {
521 if ($target_uid != $target_item['uid']) {
522 $fields = ['protocol' => Conversation::PARCEL_LOCAL_DFRN, 'direction' => Conversation::PUSH, 'post-reason' => Item::PR_DIRECT];
523 Item::storeForUserByUriId($target_item['uri-id'], $target_uid, $fields, $target_item['uid']);
524 Logger::info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'target' => $target_uid]);
526 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']]);
529 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']]);
534 // Deletions are always sent via DFRN as well.
535 // This is done until we can perform deletions of foreign comments on our own threads via AP.
536 if (($cmd != Delivery::DELETION) && in_array($contact['id'], $ap_contacts)) {
537 Logger::info('Contact is already delivered via AP, so skip delivery via legacy DFRN/Diaspora', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
541 if (!empty($contact['id']) && Contact::isArchived($contact['id'])) {
542 Logger::info('Contact is archived, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
546 if (self::isRemovalActivity($cmd, $owner, $contact['network'])) {
547 Logger::info('Contact does no supports account removal commands, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
551 if (self::skipActivityPubForDiaspora($contact, $target_item, $thr_parent)) {
552 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']]);
556 // Don't deliver to Diaspora if it already had been done as batch delivery
557 if (!$in_batch && $batch_delivery && ($contact['network'] == Protocol::DIASPORA)) {
558 Logger::info('Diaspora contact is already delivered via batch', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
562 // Don't deliver to folks who have already been delivered to
563 if (in_array($contact['id'], $conversants)) {
564 Logger::info('Already delivery', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
568 if (empty($contact['gsid'])) {
569 $reachable = !GServer::reachable($contact);
570 } elseif (!DI::config()->get('system', 'bulk_delivery')) {
571 $reachable = !GServer::isReachableById($contact['gsid']);
573 $reachable = !GServer::isDefunctById($contact['gsid']);
577 Logger::info('Server is not reachable', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
581 Logger::info('Delivery', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'guid' => $target_item['guid'] ?? '', 'to' => $contact]);
583 // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
584 // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
585 // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
586 // This is only important for high and medium priority tasks and not for Low priority jobs like deletions.
587 if (($contact['network'] == Protocol::DIASPORA) && in_array($a->getQueueValue('priority'), [Worker::PRIORITY_HIGH, Worker::PRIORITY_MEDIUM])) {
588 $deliver_options = ['priority' => $a->getQueueValue('priority'), 'dont_fork' => true];
590 $deliver_options = ['priority' => $a->getQueueValue('priority'), 'created' => $a->getQueueValue('created'), 'dont_fork' => true];
593 if (!empty($contact['gsid']) && DI::config()->get('system', 'bulk_delivery')) {
594 $delivery_queue_count++;
595 Delivery::addQueue($cmd, $post_uriid, $target_item['created'], $contact['id'], $contact['gsid'], $sender_uid);
596 Worker::add(['priority' => Worker::PRIORITY_HIGH, 'dont_fork' => true], 'BulkDelivery', $contact['gsid']);
598 if (Worker::add($deliver_options, 'Delivery', $cmd, $post_uriid, (int)$contact['id'], $sender_uid)) {
599 $delivery_queue_count++;
605 return $delivery_queue_count;
609 * Deliver the message via OStatus
611 * @param int $target_id
612 * @param array $target_item
613 * @param array $owner
614 * @param array $url_recipients
615 * @param bool $public_message
616 * @param bool $push_notify
618 * @return int Count of sent Salmon notifications
619 * @throws InternalServerErrorException
622 private static function deliverOStatus(int $target_id, array $target_item, array $owner, array $url_recipients, bool $public_message, bool $push_notify): int
625 $delivery_queue_count = 0;
627 $url_recipients = array_filter($url_recipients);
628 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
629 // They are especially used for notifications to OStatus users that don't follow us.
630 if (count($url_recipients) && ($public_message || $push_notify) && !empty($target_item)) {
631 $slap = OStatus::salmon($target_item, $owner);
632 foreach ($url_recipients as $url) {
633 Logger::info('Salmon delivery', ['item' => $target_id, 'to' => $url]);
635 $delivery_queue_count++;
636 Salmon::slapper($owner, $url, $slap);
637 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::OSTATUS);
641 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
643 Logger::info('Activating internal PuSH', ['uid' => $owner['uid']]);
645 // Handling the pubsubhubbub requests
646 PushSubscriber::publishFeed($owner['uid'], $a->getQueueValue('priority'));
648 return $delivery_queue_count;
652 * Checks if the current delivery shouldn't be transported to Diaspora.
653 * This is done for posts from AP authors or posts that are comments to AP authors.
655 * @param array $contact Receiver of the post
656 * @param array $item The post
657 * @param array $thr_parent The thread parent
661 private static function skipActivityPubForDiaspora(array $contact, array $item, array $thr_parent): bool
663 // No skipping needs to be done when delivery isn't done to Diaspora
664 if ($contact['network'] != Protocol::DIASPORA) {
668 // Skip the delivery to Diaspora if the item is from an ActivityPub author
669 if (!empty($item['author-network']) && ($item['author-network'] == Protocol::ACTIVITYPUB)) {
673 // Skip the delivery to Diaspora if the thread parent is from an ActivityPub author
674 if (!empty($thr_parent['author-network']) && ($thr_parent['author-network'] == Protocol::ACTIVITYPUB)) {
682 * Checks if the current action is a deletion command of a account removal activity
683 * For Diaspora and ActivityPub we don't need to send single item deletion calls.
684 * These protocols do have a dedicated command for deleting a whole account.
686 * @param string $cmd Notifier command
687 * @param array $owner Sender of the post
688 * @param string $network Receiver network
691 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
692 * @throws \ImagickException
694 private static function isRemovalActivity(string $cmd, array $owner, string $network): bool
696 return ($cmd == Delivery::DELETION) && $owner['account_removed'] && in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA]);
700 * @param int $self_user_id
701 * @param int $priority The priority the Notifier queue item was created with
702 * @param string $created The date the Notifier queue item was created on
705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706 * @throws \ImagickException
708 private static function notifySelfRemoval(int $self_user_id, int $priority, string $created): bool
710 $owner = User::getOwnerDataById($self_user_id);
711 if (empty($self_user_id) || empty($owner)) {
715 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
716 if (!DBA::isResult($contacts_stmt)) {
720 while($contact = DBA::fetch($contacts_stmt)) {
721 Contact::terminateFriendship($contact);
723 DBA::close($contacts_stmt);
725 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser($self_user_id);
726 foreach ($inboxes as $inbox => $receivers) {
727 Logger::info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]);
728 Worker::add(['priority' => Worker::PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
729 'APDelivery', Delivery::REMOVAL, 0, $inbox, $self_user_id, $receivers);
738 * @param array $target_item
739 * @param array $parent
740 * @param array $thr_parent
741 * @param int $priority The priority the Notifier queue item was created with
742 * @param string $created The date the Notifier queue item was created on
744 * @return array 'count' => The number of delivery tasks created, 'contacts' => their contact ids
745 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
746 * @throws \ImagickException
747 * @todo Unused parameter $owner
749 private static function activityPubDelivery($cmd, array $target_item, array $parent, array $thr_parent, int $priority, string $created, $owner): array
751 // Don't deliver via AP when the starting post isn't from a federated network
752 if (!in_array($parent['network'], Protocol::FEDERATED)) {
753 Logger::info('Parent network is no federated network, so no AP delivery', ['network' => $parent['network']]);
754 return ['count' => 0, 'contacts' => []];
757 // Don't deliver via AP when the starting post is delivered via Diaspora
758 if ($parent['network'] == Protocol::DIASPORA) {
759 Logger::info('Parent network is Diaspora, so no AP delivery');
760 return ['count' => 0, 'contacts' => []];
763 // Also don't deliver when the direct thread parent was delivered via Diaspora
764 if ($thr_parent['network'] == Protocol::DIASPORA) {
765 Logger::info('Thread parent network is Diaspora, so no AP delivery');
766 return ['count' => 0, 'contacts' => []];
769 // Posts from Diaspora contacts are transmitted via Diaspora
770 if ($target_item['network'] == Protocol::DIASPORA) {
771 Logger::info('Post network is Diaspora, so no AP delivery');
772 return ['count' => 0, 'contacts' => []];
778 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
780 // Update the locally stored follower list when we deliver to a forum
781 foreach (Tag::getByURIId($target_item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
782 $target_contact = Contact::getByURL(Strings::normaliseLink($tag['url']), null, [], $uid);
783 if ($target_contact && $target_contact['contact-type'] == Contact::TYPE_COMMUNITY && $target_contact['manually-approve']) {
784 Group::updateMembersForForum($target_contact['id']);
788 if ($target_item['origin']) {
789 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
791 if (in_array($target_item['private'], [Item::PUBLIC])) {
792 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($target_item['id'], $inboxes);
793 $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes();
796 Logger::info('Origin item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
797 } elseif (!Post\Activity::exists($target_item['uri-id'])) {
798 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']]);
799 return ['count' => 0, 'contacts' => []];
800 } elseif ($parent['origin'] && (($target_item['gravity'] != Item::GRAVITY_ACTIVITY) || DI::config()->get('system', 'redistribute_activities'))) {
801 $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, false, $target_item['id']);
803 if (in_array($target_item['private'], [Item::PUBLIC])) {
804 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($parent['id'], $inboxes);
807 Logger::info('Remote item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
809 Logger::info('Remote activity will not be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
810 return ['count' => 0, 'contacts' => []];
813 if (empty($inboxes) && empty($relay_inboxes)) {
814 Logger::info('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.');
815 return ['count' => 0, 'contacts' => []];
818 // Fill the item cache
819 $cache = ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
821 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']]);
822 return ['count' => 0, 'contacts' => []];
825 $delivery_queue_count = 0;
828 foreach ($inboxes as $inbox => $receivers) {
829 $contacts = array_merge($contacts, $receivers);
831 if ((count($receivers) == 1) && Network::isLocalLink($inbox)) {
832 $contact = Contact::getById($receivers[0], ['url']);
833 if (!in_array($cmd, [Delivery::RELOCATION, Delivery::SUGGESTION, Delivery::DELETION, Delivery::MAIL]) && ($target_uid = User::getIdForURL($contact['url']))) {
834 if ($target_item['origin'] || ($target_item['network'] != Protocol::ACTIVITYPUB)) {
835 if ($target_uid != $target_item['uid']) {
836 $fields = ['protocol' => Conversation::PARCEL_LOCAL_DFRN, 'direction' => Conversation::PUSH, 'post-reason' => Item::PR_BCC];
837 Item::storeForUserByUriId($target_item['uri-id'], $target_uid, $fields, $target_item['uid']);
838 Logger::info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
840 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']]);
843 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']]);
847 } elseif ((count($receivers) >= 1) && Network::isLocalLink($inbox)) {
848 Logger::info('Is this a thing?', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
851 Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
853 if (DI::config()->get('system', 'bulk_delivery')) {
854 $delivery_queue_count++;
855 Post\Delivery::add($target_item['uri-id'], $uid, $inbox, $target_item['created'], $cmd, $receivers);
856 Worker::add([Worker::PRIORITY_HIGH, 'dont_fork' => true], 'APDelivery', '', 0, $inbox, 0);
858 if (Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
859 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, $receivers, $target_item['uri-id'])) {
860 $delivery_queue_count++;
866 // We deliver posts to relay servers slightly delayed to priorize the direct delivery
867 foreach ($relay_inboxes as $inbox) {
868 Logger::info('Delivery to relay servers via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
870 if (DI::config()->get('system', 'bulk_delivery')) {
871 $delivery_queue_count++;
872 Post\Delivery::add($target_item['uri-id'], $uid, $inbox, $target_item['created'], $cmd, []);
873 Worker::add([Worker::PRIORITY_MEDIUM, 'dont_fork' => true], 'APDelivery', '', 0, $inbox, 0);
875 if (Worker::add(['priority' => $priority, 'dont_fork' => true], 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, [], $target_item['uri-id'])) {
876 $delivery_queue_count++;
882 return ['count' => $delivery_queue_count, 'contacts' => $contacts];