]> git.mxchange.org Git - friendica.git/blob - src/Worker/Notifier.php
Changes after review
[friendica.git] / src / Worker / Notifier.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Worker;
23
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;
29 use Friendica\DI;
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;
47
48 /*
49  * The notifier is typically called with:
50  *
51  *              Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
52  *
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.
55  */
56
57 class Notifier
58 {
59         public static function execute(string $cmd, int $post_uriid, int $sender_uid = 0)
60         {
61                 $a = DI::app();
62
63                 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]);
64
65                 $target_id = $post_uriid;
66                 $top_level = false;
67                 $recipients = [];
68                 $url_recipients = [];
69
70                 $delivery_contacts_stmt = null;
71                 $target_item = [];
72                 $parent = [];
73                 $thr_parent = [];
74                 $items = [];
75                 $delivery_queue_count = 0;
76                 $ap_contacts = [];
77
78                 if ($cmd == Delivery::MAIL) {
79                         $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
80                         if (!DBA::isResult($message)) {
81                                 return;
82                         }
83                         $uid = $message['uid'];
84                         $recipients[] = $message['contact-id'];
85
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);
93                         }
94                 } elseif ($cmd == Delivery::SUGGESTION) {
95                         $suggest = DI::fsuggest()->selectOneById($target_id);
96                         $uid = $suggest->uid;
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) {
101                         $uid = $target_id;
102
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);
105                 } else {
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]);
109                                 return;
110                         }
111                         $target_id = $post['id'];
112
113                         // find ancestors
114                         $condition = ['id' => $target_id, 'visible' => true];
115                         $target_item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
116
117                         if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
118                                 Logger::info('No target item', ['cmd' => $cmd, 'target' => $target_id]);
119                                 return;
120                         }
121
122                         if (!empty($target_item['contact-uid'])) {
123                                 $uid = $target_item['contact-uid'];
124                         } elseif (!empty($target_item['uid'])) {
125                                 $uid = $target_item['uid'];
126                         } else {
127                                 Logger::info('Only public users, quitting', ['target' => $target_id]);
128                                 return;
129                         }
130
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]);
136                                 return;
137                         }
138
139                         $items = Post::toArray($items_stmt);
140
141                         // avoid race condition with deleting entries
142                         if ($items[0]['deleted']) {
143                                 foreach ($items as $item) {
144                                         $item['deleted'] = 1;
145                                 }
146                         }
147
148                         $top_level = $target_item['gravity'] == Item::GRAVITY_PARENT;
149                 }
150
151                 $owner = User::getOwnerDataById($uid);
152                 if (!$owner) {
153                         Logger::info('Owner not found', ['cmd' => $cmd, 'target' => $target_id]);
154                         return;
155                 }
156
157                 // Should the post be transmitted to Diaspora?
158                 $diaspora_delivery = ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
159
160                 // If this is a public conversation, notify the feed hub
161                 $public_message = true;
162
163                 $unlisted = false;
164
165                 // Do a PuSH
166                 $push_notify = false;
167
168                 // Deliver directly to a forum, don't PuSH
169                 $direct_forum_delivery = false;
170
171                 $followup = false;
172                 $recipients_followup = [];
173
174                 if (!empty($target_item) && !empty($items)) {
175                         $parent = $items[0];
176
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;
182                         }
183
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']]);
185
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'];
190                         }
191
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;
199                                 }
200                                 Logger::info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]);
201                         }
202
203                         $unlisted = $target_item['private'] == Item::UNLISTED;
204
205                         // This is IMPORTANT!!!!
206
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.
210
211                         // if $parent['wall'] == 1 we will already have the parent message in our array
212                         // and we will relay the whole lot.
213
214                         $localhost = str_replace('www.','', DI::baseUrl()->getHostname());
215                         if (strpos($localhost,':')) {
216                                 $localhost = substr($localhost,0,strpos($localhost,':'));
217                         }
218                         /**
219                          *
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.
223                          *
224                          */
225
226                         $relay_to_owner = false;
227
228                         if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
229                                 $relay_to_owner = true;
230                         }
231
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.
235
236                         if (!$target_item['origin']) {
237                                 $relay_to_owner = false;
238                         }
239                         if ($parent['origin']) {
240                                 $relay_to_owner = false;
241                         }
242
243                         // Special treatment for forum posts
244                         if (Item::isForumPost($target_item['uri-id'])) {
245                                 $relay_to_owner = true;
246                                 $direct_forum_delivery = true;
247                         }
248
249                         // Avoid that comments in a forum thread are sent to OStatus
250                         if (Item::isForumPost($parent['uri-id'])) {
251                                 $direct_forum_delivery = true;
252                         }
253
254                         $exclusive_delivery = false;
255
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']]);
264                                         }
265                                 }
266                         }
267
268                         if ($relay_to_owner) {
269                                 // local followup to remote post
270                                 $followup = true;
271                                 $public_message = false; // not public
272                                 $recipients = [$parent['contact-id']];
273                                 $recipients_followup  = [$parent['contact-id']];
274
275                                 Logger::info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]);
276
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))
280                                         $push_notify = true;
281
282                                 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
283                                         $push_notify = true;
284
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'];
292                                                 }
293                                                 DBA::close($followup_contacts_stmt);
294                                         }
295                                 }
296
297                                 if ($direct_forum_delivery) {
298                                         $push_notify = false;
299                                 }
300
301                                 Logger::info('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"));
302                         } elseif ($exclusive_delivery) {
303                                 $followup = true;
304
305                                 foreach ($exclusive_targets as $target) {
306                                         $cid = Contact::getIdForURL($target['url'], $uid, false);
307                                         if ($cid) {
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']]);
310                                         }
311                                 }
312                         } else {
313                                 $followup = false;
314
315                                 Logger::info('Distributing directly', ['target' => $target_id, 'guid' => $target_item['guid']]);
316
317                                 // don't send deletions onward for other people's stuff
318
319                                 if ($target_item['deleted'] && !intval($target_item['wall'])) {
320                                         Logger::notice('Ignoring delete notification for non-wall item');
321                                         return;
322                                 }
323
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
329                                 }
330
331                                 $aclFormatter = DI::aclFormatter();
332
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']));
337
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));
346                                                         } else {
347                                                                 $url_recipients[] = substr($person,4);
348                                                         }
349                                                 }
350                                         }
351                                 }
352
353                                 if (count($url_recipients)) {
354                                         Logger::notice('Deliver', ['target' => $target_id, 'guid' => $target_item['guid'], 'recipients' => $url_recipients]);
355                                 }
356
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);
360
361                                 // If this is a public message and pubmail is set on the parent, include all your email contacts
362                                 if (
363                                         function_exists('imap_open')
364                                         && !DI::config()->get('system','imap_disabled')
365                                         && $public_message
366                                         && intval($target_item['pubmail'])
367                                 ) {
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'];
371                                         }
372                                         DBA::close($mail_contacts_stmt);
373                                 }
374                         }
375
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;
380
381                                 Logger::info('Some parent is OStatus for ' . $target_item['guid'] . ' - Author: ' . $thr_parent['author-id'] . ' - Owner: ' . $thr_parent['owner-id']);
382
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'];
388                                 }
389
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'];
395                                 }
396
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'];
403                                         }
404                                 }
405
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;
413                                 }
414                         } else {
415                                 $networks = [Protocol::DFRN, Protocol::MAIL];
416                         }
417                 } else {
418                         $public_message = false;
419                 }
420
421                 if (empty($delivery_contacts_stmt)) {
422                         if ($followup) {
423                                 $recipients = $recipients_followup;
424                         }
425                         $condition = ['id' => $recipients, 'self' => false, 'uid' => [0, $uid],
426                                 'blocked' => false, 'pending' => false, 'archive' => false];
427                         if (!empty($networks)) {
428                                 $condition['network'] = $networks;
429                         }
430                         $delivery_contacts_stmt = DBA::select('contact', ['id', 'addr', 'url', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition);
431                 }
432
433                 $conversants = [];
434                 $batch_delivery = false;
435
436                 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
437                         $participants = [];
438
439                         if ($diaspora_delivery && !$unlisted) {
440                                 $batch_delivery = true;
441
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']]);
445
446                                 // Fetch the participation list
447                                 // The function will ensure that there are no duplicates
448                                 $participants = Diaspora::participantsForThread($target_item, $participants);
449                         }
450
451                         $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
452                                 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
453
454                         $contacts = DBA::selectToArray('contact', ['id', 'url', 'addr', 'name', 'network', 'protocol', 'baseurl', 'gsid'], $condition);
455
456                         $conversants = array_merge($contacts, $participants);
457
458                         $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, true, $conversants, $ap_contacts, []);
459
460                         $push_notify = true;
461                 }
462
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);
465
466                 $delivery_queue_count += self::deliverOStatus($target_id, $target_item, $owner, $url_recipients, $public_message, $push_notify);
467
468                 if (!empty($target_item)) {
469                         Logger::info('Calling hooks for ' . $cmd . ' ' . $target_id);
470
471                         Hook::fork($a->getQueueValue('priority'), 'notifier_normal', $target_item);
472
473                         Hook::callAll('notifier_end', $target_item);
474
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;
480                                 }
481
482                                 Post\DeliveryData::incrementQueueCount($target_item['uri-id'], $delivery_queue_count);
483                         }
484                 }
485
486                 return;
487         }
488
489         /**
490          * Deliver the message to the contacts
491          *
492          * @param string $cmd
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
502          *
503          * @return int Count of delivery queue
504          * @throws InternalServerErrorException
505          * @throws Exception
506          */
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
508         {
509                 $a = DI::app();
510                 $delivery_queue_count = 0;
511
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']]);
514                         return 0;
515                 }
516
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]);
525                                         } else {
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']]);
527                                         }
528                                 } else {
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']]);
530                                 }
531                                 continue;
532                         }
533
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']]);
538                                 continue;
539                         }
540
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']]);
543                                 continue;
544                         }
545
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']]);
548                                 continue;
549                         }
550
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']]);
553                                 continue;
554                         }
555
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]);
559                                 continue;
560                         }
561
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]);
565                                 continue;
566                         }
567
568                         if (empty($contact['gsid'])) {
569                                 $reachable = !GServer::reachable($contact);
570                         } elseif (!DI::config()->get('system', 'bulk_delivery')) {
571                                 $reachable = !GServer::isReachableById($contact['gsid']);
572                         } else {
573                                 $reachable = !GServer::isDefunctById($contact['gsid']);
574                         }
575
576                         if (!$reachable) {
577                                 Logger::info('Server is not reachable', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
578                                 continue;
579                         }
580
581                         Logger::info('Delivery', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'guid' => $target_item['guid'] ?? '', 'to' => $contact]);
582
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];
589                         } else {
590                                 $deliver_options = ['priority' => $a->getQueueValue('priority'), 'created' => $a->getQueueValue('created'), 'dont_fork' => true];
591                         }
592
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']);
597                         } else {
598                                 if (Worker::add($deliver_options, 'Delivery', $cmd, $post_uriid, (int)$contact['id'], $sender_uid)) {
599                                         $delivery_queue_count++;
600                                 }
601                         }
602
603                         Worker::coolDown();
604                 }
605                 return $delivery_queue_count;
606         }
607
608         /**
609          * Deliver the message via OStatus
610          *
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
617          *
618          * @return int Count of sent Salmon notifications
619          * @throws InternalServerErrorException
620          * @throws Exception
621          */
622         private static function deliverOStatus(int $target_id, array $target_item, array $owner, array $url_recipients, bool $public_message, bool $push_notify): int
623         {
624                 $a = DI::app();
625                 $delivery_queue_count = 0;
626
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]);
634
635                                 $delivery_queue_count++;
636                                 Salmon::slapper($owner, $url, $slap);
637                                 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::OSTATUS);
638                         }
639                 }
640
641                 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
642                 if ($push_notify) {
643                         Logger::info('Activating internal PuSH', ['uid' => $owner['uid']]);
644
645                         // Handling the pubsubhubbub requests
646                         PushSubscriber::publishFeed($owner['uid'], $a->getQueueValue('priority'));
647                 }
648                 return $delivery_queue_count;
649         }
650
651         /**
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.
654          *
655          * @param array  $contact    Receiver of the post
656          * @param array  $item       The post
657          * @param array  $thr_parent The thread parent
658          *
659          * @return bool
660          */
661         private static function skipActivityPubForDiaspora(array $contact, array $item, array $thr_parent): bool
662         {
663                 // No skipping needs to be done when delivery isn't done to Diaspora
664                 if ($contact['network'] != Protocol::DIASPORA) {
665                         return false;
666                 }
667
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)) {
670                         return true;
671                 }
672
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)) {
675                         return true;
676                 }
677
678                 return false;
679         }
680
681         /**
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.
685          *
686          * @param string $cmd     Notifier command
687          * @param array  $owner   Sender of the post
688          * @param string $network Receiver network
689          *
690          * @return bool
691          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
692          * @throws \ImagickException
693          */
694         private static function isRemovalActivity(string $cmd, array $owner, string $network): bool
695         {
696                 return ($cmd == Delivery::DELETION) && $owner['account_removed'] && in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA]);
697         }
698
699         /**
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
703          *
704          * @return bool
705          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706          * @throws \ImagickException
707          */
708         private static function notifySelfRemoval(int $self_user_id, int $priority, string $created): bool
709         {
710                 $owner = User::getOwnerDataById($self_user_id);
711                 if (empty($self_user_id) || empty($owner)) {
712                         return false;
713                 }
714
715                 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
716                 if (!DBA::isResult($contacts_stmt)) {
717                         return false;
718                 }
719
720                 while($contact = DBA::fetch($contacts_stmt)) {
721                         Contact::terminateFriendship($contact);
722                 }
723                 DBA::close($contacts_stmt);
724
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);
730                         Worker::coolDown();
731                 }
732
733                 return true;
734         }
735
736         /**
737          * @param string $cmd
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
743          *
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
748          */
749         private static function activityPubDelivery($cmd, array $target_item, array $parent, array $thr_parent, int $priority, string $created, $owner): array
750         {
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' => []];
755                 }
756
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' => []];
761                 }
762
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' => []];
767                 }
768
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' => []];
773                 }
774
775                 $inboxes = [];
776                 $relay_inboxes = [];
777
778                 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
779
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']);
785                         }
786                 }
787
788                 if ($target_item['origin']) {
789                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
790
791                         if (in_array($target_item['private'], [Item::PUBLIC])) {
792                                 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($target_item['id'], $inboxes);
793                                 $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes();
794                         }
795
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']);
802
803                         if (in_array($target_item['private'], [Item::PUBLIC])) {
804                                 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($parent['id'], $inboxes);
805                         }
806
807                         Logger::info('Remote item will be distributed', ['id' => $target_item['id'], 'url' => $target_item['uri'], 'verb' => $target_item['verb']]);
808                 } else {
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' => []];
811                 }
812
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' => []];
816                 }
817
818                 // Fill the item cache
819                 ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
820
821                 $delivery_queue_count = 0;
822                 $contacts = [];
823
824                 foreach ($inboxes as $inbox => $receivers) {
825                         $contacts = array_merge($contacts, $receivers);
826
827                         if ((count($receivers) == 1) && Network::isLocalLink($inbox)) {
828                                 $contact = Contact::getById($receivers[0], ['url']);
829                                 if (!in_array($cmd, [Delivery::RELOCATION, Delivery::SUGGESTION, Delivery::DELETION, Delivery::MAIL]) && ($target_uid = User::getIdForURL($contact['url']))) {
830                                         if ($target_item['origin'] || ($target_item['network'] != Protocol::ACTIVITYPUB)) {
831                                                 if ($target_uid != $target_item['uid']) {
832                                                         $fields = ['protocol' => Conversation::PARCEL_LOCAL_DFRN, 'direction' => Conversation::PUSH, 'post-reason' => Item::PR_BCC];
833                                                         Item::storeForUserByUriId($target_item['uri-id'], $target_uid, $fields, $target_item['uid']);
834                                                         Logger::info('Delivered locally', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
835                                                 } else {
836                                                         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']]);
837                                                 }
838                                         } else {
839                                                 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']]);
840                                         }
841                                         continue;
842                                 }
843                         } elseif ((count($receivers) >= 1) && Network::isLocalLink($inbox)) {
844                                 Logger::info('Is this a thing?', ['guid' => $target_item['guid'], 'uri-id' => $target_item['uri-id'], 'uri' => $target_item['uri']]);
845                         }
846
847                         Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
848
849                         if (DI::config()->get('system', 'bulk_delivery')) {
850                                 $delivery_queue_count++;
851                                 Post\Delivery::add($target_item['uri-id'], $uid, $inbox, $target_item['created'], $cmd, $receivers);
852                                 Worker::add([Worker::PRIORITY_HIGH, 'dont_fork' => true], 'APDelivery', '', 0, $inbox, 0);
853                         } else {
854                                 if (Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
855                                                 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, $receivers, $target_item['uri-id'])) {
856                                         $delivery_queue_count++;
857                                 }
858                         }
859                         Worker::coolDown();
860                 }
861
862                 // We deliver posts to relay servers slightly delayed to priorize the direct delivery
863                 foreach ($relay_inboxes as $inbox) {
864                         Logger::info('Delivery to relay servers via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
865
866                         if (DI::config()->get('system', 'bulk_delivery')) {
867                                 $delivery_queue_count++;
868                                 Post\Delivery::add($target_item['uri-id'], $uid, $inbox, $target_item['created'], $cmd, []);
869                                 Worker::add([Worker::PRIORITY_MEDIUM, 'dont_fork' => true], 'APDelivery', '', 0, $inbox, 0);
870                         } else {
871                                 if (Worker::add(['priority' => $priority, 'dont_fork' => true], 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, [], $target_item['uri-id'])) {
872                                         $delivery_queue_count++;
873                                 }
874                         }
875                         Worker::coolDown();
876                 }
877
878                 return ['count' => $delivery_queue_count, 'contacts' => $contacts];
879         }
880 }