]> git.mxchange.org Git - friendica.git/blob - src/Worker/Notifier.php
Merge pull request #12917 from annando/remove-tab
[friendica.git] / src / Worker / Notifier.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\LDSignature;
46 use Friendica\Util\Network;
47 use Friendica\Util\Strings;
48
49 /*
50  * The notifier is typically called with:
51  *
52  *              Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
53  *
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.
56  */
57
58 class Notifier
59 {
60         public static function execute(string $cmd, int $post_uriid, int $sender_uid = 0)
61         {
62                 $a = DI::app();
63
64                 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]);
65
66                 $target_id = $post_uriid;
67                 $top_level = false;
68                 $recipients = [];
69                 $url_recipients = [];
70
71                 $delivery_contacts_stmt = null;
72                 $target_item = [];
73                 $parent = [];
74                 $thr_parent = [];
75                 $items = [];
76                 $delivery_queue_count = 0;
77                 $ap_contacts = [];
78
79                 if ($cmd == Delivery::MAIL) {
80                         $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
81                         if (!DBA::isResult($message)) {
82                                 return;
83                         }
84                         $uid = $message['uid'];
85                         $recipients[] = $message['contact-id'];
86
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);
94                         }
95                 } elseif ($cmd == Delivery::SUGGESTION) {
96                         $suggest = DI::fsuggest()->selectOneById($target_id);
97                         $uid = $suggest->uid;
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) {
102                         $uid = $target_id;
103
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);
106                 } else {
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]);
110                                 return;
111                         }
112                         $target_id = $post['id'];
113
114                         // find ancestors
115                         $condition = ['id' => $target_id, 'visible' => true];
116                         $target_item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
117                         $target_item = Post\Media::addHTMLAttachmentToItem($target_item);
118
119                         if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
120                                 Logger::info('No target item', ['cmd' => $cmd, 'target' => $target_id]);
121                                 return;
122                         }
123
124                         if (!empty($target_item['contact-uid'])) {
125                                 $uid = $target_item['contact-uid'];
126                         } elseif (!empty($target_item['uid'])) {
127                                 $uid = $target_item['uid'];
128                         } else {
129                                 Logger::info('Only public users, quitting', ['target' => $target_id]);
130                                 return;
131                         }
132
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]);
138                                 return;
139                         }
140
141                         $items = Post::toArray($items_stmt);
142
143                         // avoid race condition with deleting entries
144                         if ($items[0]['deleted']) {
145                                 foreach ($items as $item) {
146                                         $item['deleted'] = 1;
147                                 }
148                         }
149
150                         $top_level = $target_item['gravity'] == Item::GRAVITY_PARENT;
151                 }
152
153                 $owner = User::getOwnerDataById($uid);
154                 if (!$owner) {
155                         Logger::info('Owner not found', ['cmd' => $cmd, 'target' => $target_id]);
156                         return;
157                 }
158
159                 // Should the post be transmitted to Diaspora?
160                 $diaspora_delivery = ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY);
161
162                 // If this is a public conversation, notify the feed hub
163                 $public_message = true;
164
165                 $unlisted = false;
166
167                 // Do a PuSH
168                 $push_notify = false;
169
170                 // Deliver directly to a forum, don't PuSH
171                 $direct_forum_delivery = false;
172
173                 $followup = false;
174                 $recipients_followup = [];
175
176                 if (!empty($target_item) && !empty($items)) {
177                         $parent = $items[0];
178
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;
184                         }
185
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']]);
187
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'];
192                         }
193
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;
201                                 }
202                                 Logger::info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]);
203                         }
204
205                         $unlisted = $target_item['private'] == Item::UNLISTED;
206
207                         // This is IMPORTANT!!!!
208
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.
212
213                         // if $parent['wall'] == 1 we will already have the parent message in our array
214                         // and we will relay the whole lot.
215
216                         $localhost = str_replace('www.','', DI::baseUrl()->getHost());
217                         if (strpos($localhost,':')) {
218                                 $localhost = substr($localhost,0,strpos($localhost,':'));
219                         }
220                         /**
221                          *
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.
225                          *
226                          */
227
228                         $relay_to_owner = false;
229
230                         if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
231                                 $relay_to_owner = true;
232                         }
233
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.
237
238                         if (!$target_item['origin']) {
239                                 $relay_to_owner = false;
240                         }
241                         if ($parent['origin']) {
242                                 $relay_to_owner = false;
243                         }
244
245                         // Special treatment for forum posts
246                         if (Item::isForumPost($target_item['uri-id'])) {
247                                 $relay_to_owner = true;
248                                 $direct_forum_delivery = true;
249                         }
250
251                         // Avoid that comments in a forum thread are sent to OStatus
252                         if (Item::isForumPost($parent['uri-id'])) {
253                                 $direct_forum_delivery = true;
254                         }
255
256                         $exclusive_delivery = false;
257
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']]);
266                                         }
267                                 }
268                         }
269
270                         if ($relay_to_owner) {
271                                 // local followup to remote post
272                                 $followup = true;
273                                 $public_message = false; // not public
274                                 $recipients = [$parent['contact-id']];
275                                 $recipients_followup  = [$parent['contact-id']];
276
277                                 Logger::info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]);
278
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))
282                                         $push_notify = true;
283
284                                 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
285                                         $push_notify = true;
286
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'];
294                                                 }
295                                                 DBA::close($followup_contacts_stmt);
296                                         }
297                                 }
298
299                                 if ($direct_forum_delivery) {
300                                         $push_notify = false;
301                                 }
302
303                                 Logger::info('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"));
304                         } elseif ($exclusive_delivery) {
305                                 $followup = true;
306
307                                 foreach ($exclusive_targets as $target) {
308                                         $cid = Contact::getIdForURL($target['url'], $uid, false);
309                                         if ($cid) {
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']]);
312                                         }
313                                 }
314                         } else {
315                                 $followup = false;
316
317                                 Logger::info('Distributing directly', ['target' => $target_id, 'guid' => $target_item['guid']]);
318
319                                 // don't send deletions onward for other people's stuff
320
321                                 if ($target_item['deleted'] && !intval($target_item['wall'])) {
322                                         Logger::notice('Ignoring delete notification for non-wall item');
323                                         return;
324                                 }
325
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
331                                 }
332
333                                 $aclFormatter = DI::aclFormatter();
334
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']));
339
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));
348                                                         } else {
349                                                                 $url_recipients[] = substr($person,4);
350                                                         }
351                                                 }
352                                         }
353                                 }
354
355                                 if (count($url_recipients)) {
356                                         Logger::notice('Deliver', ['target' => $target_id, 'guid' => $target_item['guid'], 'recipients' => $url_recipients]);
357                                 }
358
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);
362
363                                 // If this is a public message and pubmail is set on the parent, include all your email contacts
364                                 if (
365                                         function_exists('imap_open')
366                                         && !DI::config()->get('system','imap_disabled')
367                                         && $public_message
368                                         && intval($target_item['pubmail'])
369                                 ) {
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'];
373                                         }
374                                         DBA::close($mail_contacts_stmt);
375                                 }
376                         }
377
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;
382
383                                 Logger::info('Some parent is OStatus for ' . $target_item['guid'] . ' - Author: ' . $thr_parent['author-id'] . ' - Owner: ' . $thr_parent['owner-id']);
384
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'];
390                                 }
391
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'];
397                                 }
398
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'];
405                                         }
406                                 }
407
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;
415                                 }
416                         } else {
417                                 $networks = [Protocol::DFRN, Protocol::MAIL];
418                         }
419                 } else {
420                         $public_message = false;
421                 }
422
423                 if (empty($delivery_contacts_stmt)) {
424                         if ($followup) {
425                                 $recipients = $recipients_followup;
426                         }
427                         $condition = ['id' => $recipients, 'self' => false, 'uid' => [0, $uid],
428                                 'blocked' => false, 'pending' => false, 'archive' => false];
429                         if (!empty($networks)) {
430                                 $condition['network'] = $networks;
431                         }
432                         $delivery_contacts_stmt = DBA::select('contact', ['id', 'addr', 'url', 'network', 'protocol', 'baseurl', 'gsid', 'batch'], $condition);
433                 }
434
435                 $conversants = [];
436                 $batch_delivery = false;
437
438                 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
439                         $participants = [];
440
441                         if ($diaspora_delivery && !$unlisted) {
442                                 $batch_delivery = true;
443
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']]);
447
448                                 // Fetch the participation list
449                                 // The function will ensure that there are no duplicates
450                                 $participants = Diaspora::participantsForThread($target_item, $participants);
451                         }
452
453                         $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
454                                 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
455
456                         $contacts = DBA::selectToArray('contact', ['id', 'url', 'addr', 'name', 'network', 'protocol', 'baseurl', 'gsid'], $condition);
457
458                         $conversants = array_merge($contacts, $participants);
459
460                         $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, true, $conversants, $ap_contacts, []);
461
462                         $push_notify = true;
463                 }
464
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);
467
468                 $delivery_queue_count += self::deliverOStatus($target_id, $target_item, $owner, $url_recipients, $public_message, $push_notify);
469
470                 if (!empty($target_item)) {
471                         Logger::info('Calling hooks for ' . $cmd . ' ' . $target_id);
472
473                         Hook::fork($a->getQueueValue('priority'), 'notifier_normal', $target_item);
474
475                         Hook::callAll('notifier_end', $target_item);
476
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;
482                                 }
483
484                                 Post\DeliveryData::incrementQueueCount($target_item['uri-id'], $delivery_queue_count);
485                         }
486                 }
487
488                 return;
489         }
490
491         /**
492          * Deliver the message to the contacts
493          *
494          * @param string $cmd
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
504          *
505          * @return int Count of delivery queue
506          * @throws InternalServerErrorException
507          * @throws Exception
508          */
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
510         {
511                 $a = DI::app();
512                 $delivery_queue_count = 0;
513
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']]);
516                         return 0;
517                 }
518
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']]);
524                                         continue;
525                                 }
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]);
531                                         } else {
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']]);
533                                         }
534                                 } else {
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']]);
536                                 }
537                                 continue;
538                         }
539
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']]);
544                                 continue;
545                         }
546
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']]);
549                                 continue;
550                         }
551
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']]);
554                                 continue;
555                         }
556
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']]);
559                                 continue;
560                         }
561
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]);
565                                 continue;
566                         }
567
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]);
571                                 continue;
572                         }
573
574                         if (empty($contact['gsid'])) {
575                                 $reachable = GServer::reachable($contact);
576                         } elseif (!DI::config()->get('system', 'bulk_delivery')) {
577                                 $reachable = GServer::isReachableById($contact['gsid']);
578                         } else {
579                                 $reachable = !GServer::isDefunctById($contact['gsid']);
580                         }
581
582                         if (!$reachable) {
583                                 Logger::info('Server is not reachable', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
584                                 continue;
585                         }
586
587                         Logger::info('Delivery', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'guid' => $target_item['guid'] ?? '', 'to' => $contact]);
588
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];
595                         } else {
596                                 $deliver_options = ['priority' => $a->getQueueValue('priority'), 'created' => $a->getQueueValue('created'), 'dont_fork' => true];
597                         }
598
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']);
604                         } else {
605                                 if (Worker::add($deliver_options, 'Delivery', $cmd, $post_uriid, (int)$contact['id'], $sender_uid)) {
606                                         $delivery_queue_count++;
607                                 }
608                         }
609
610                         Worker::coolDown();
611                 }
612                 return $delivery_queue_count;
613         }
614
615         /**
616          * Deliver the message via OStatus
617          *
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
624          *
625          * @return int Count of sent Salmon notifications
626          * @throws InternalServerErrorException
627          * @throws Exception
628          */
629         private static function deliverOStatus(int $target_id, array $target_item, array $owner, array $url_recipients, bool $public_message, bool $push_notify): int
630         {
631                 $a = DI::app();
632                 $delivery_queue_count = 0;
633
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]);
641
642                                 $delivery_queue_count++;
643                                 Salmon::slapper($owner, $url, $slap);
644                                 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::OSTATUS);
645                         }
646                 }
647
648                 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
649                 if ($push_notify) {
650                         Logger::info('Activating internal PuSH', ['uid' => $owner['uid']]);
651
652                         // Handling the pubsubhubbub requests
653                         PushSubscriber::publishFeed($owner['uid'], $a->getQueueValue('priority'));
654                 }
655                 return $delivery_queue_count;
656         }
657
658         /**
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.
661          *
662          * @param array  $contact    Receiver of the post
663          * @param array  $item       The post
664          * @param array  $thr_parent The thread parent
665          *
666          * @return bool
667          */
668         private static function skipActivityPubForDiaspora(array $contact, array $item, array $thr_parent): bool
669         {
670                 // No skipping needs to be done when delivery isn't done to Diaspora
671                 if ($contact['network'] != Protocol::DIASPORA) {
672                         return false;
673                 }
674
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)) {
677                         return true;
678                 }
679
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)) {
682                         return true;
683                 }
684
685                 return false;
686         }
687
688         /**
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.
692          *
693          * @param string $cmd     Notifier command
694          * @param array  $owner   Sender of the post
695          * @param string $network Receiver network
696          *
697          * @return bool
698          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
699          * @throws \ImagickException
700          */
701         private static function isRemovalActivity(string $cmd, array $owner, string $network): bool
702         {
703                 return ($cmd == Delivery::DELETION) && $owner['account_removed'] && in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA]);
704         }
705
706         /**
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
710          *
711          * @return bool
712          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
713          * @throws \ImagickException
714          */
715         private static function notifySelfRemoval(int $self_user_id, int $priority, string $created): bool
716         {
717                 $owner = User::getOwnerDataById($self_user_id);
718                 if (empty($self_user_id) || empty($owner)) {
719                         return false;
720                 }
721
722                 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
723                 if (!DBA::isResult($contacts_stmt)) {
724                         return false;
725                 }
726
727                 while($contact = DBA::fetch($contacts_stmt)) {
728                         Contact::terminateFriendship($contact);
729                 }
730                 DBA::close($contacts_stmt);
731
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);
737                         Worker::coolDown();
738                 }
739
740                 return true;
741         }
742
743         /**
744          * @param string $cmd
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
750          *
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
755          */
756         private static function activityPubDelivery($cmd, array $target_item, array $parent, array $thr_parent, int $priority, string $created, $owner): array
757         {
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' => []];
762                 }
763
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' => []];
768                 }
769
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' => []];
774                 }
775
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' => []];
780                 }
781
782                 $inboxes = [];
783                 $relay_inboxes = [];
784
785                 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
786
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']);
792                         }
793                 }
794
795                 if ($target_item['origin']) {
796                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
797
798                         if (in_array($target_item['private'], [Item::PUBLIC])) {
799                                 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($target_item['id'], $inboxes);
800                                 $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes();
801                         }
802
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']);
810
811                         if (in_array($target_item['private'], [Item::PUBLIC])) {
812                                 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($parent['id'], $inboxes);
813                         }
814
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); 
817                 } else {
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' => []];
820                 }
821
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' => []];
825                 }
826
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' => []];
832                 }
833
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' => []];
837                 }
838
839                 $delivery_queue_count = 0;
840                 $contacts = [];
841
842                 foreach ($inboxes as $inbox => $receivers) {
843                         $contacts = array_merge($contacts, $receivers);
844
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']]);
850                                                 continue;
851                                         }
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]);
857                                                 } else {
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']]);
859                                                 }
860                                         } else {
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']]);
862                                         }
863                                         continue;
864                                 }
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']]);
867                         }
868
869                         Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
870
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);
875                         } else {
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++;
879                                 }
880                         }
881                         Worker::coolDown();
882                 }
883
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]);
887
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);
892                         } else {
893                                 if (Worker::add(['priority' => $priority, 'dont_fork' => true], 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, [], $target_item['uri-id'])) {
894                                         $delivery_queue_count++;
895                                 }
896                         }
897                         Worker::coolDown();
898                 }
899
900                 return ['count' => $delivery_queue_count, 'contacts' => $contacts];
901         }
902 }