]> git.mxchange.org Git - friendica.git/blob - src/Worker/Notifier.php
836e4c68032701ab0976a0100ec12d86d4332189
[friendica.git] / src / Worker / Notifier.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Item;
34 use Friendica\Model\Post;
35 use Friendica\Model\PushSubscriber;
36 use Friendica\Model\Tag;
37 use Friendica\Model\User;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Protocol\OStatus;
42 use Friendica\Protocol\Relay;
43 use Friendica\Protocol\Salmon;
44
45 /*
46  * The notifier is typically called with:
47  *
48  *              Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
49  *
50  * where COMMAND is one of the constants that are defined in Worker/Delivery.php
51  * and ITEM_ID is the id of the item in the database that needs to be sent to others.
52  */
53
54 class Notifier
55 {
56         public static function execute(string $cmd, int $post_uriid, int $sender_uid = 0)
57         {
58                 $a = DI::app();
59
60                 Logger::info('Invoked', ['cmd' => $cmd, 'target' => $post_uriid, 'sender_uid' => $sender_uid]);
61
62                 if (!empty($sender_uid)) {
63                         $post = Post::selectFirst(['id'], ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
64                         if (!DBA::isResult($post)) {
65                                 Logger::warning('Post not found', ['uri-id' => $post_uriid, 'uid' => $sender_uid]);
66                                 return;
67                         }
68                         $target_id = $post['id'];
69                 } else {
70                         $target_id = $post_uriid;
71                 }
72
73                 $top_level = false;
74                 $recipients = [];
75                 $url_recipients = [];
76
77                 $delivery_contacts_stmt = null;
78                 $target_item = [];
79                 $parent = [];
80                 $thr_parent = [];
81                 $items = [];
82                 $delivery_queue_count = 0;
83                 $ap_contacts = [];
84
85                 if ($cmd == Delivery::MAIL) {
86                         $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
87                         if (!DBA::isResult($message)) {
88                                 return;
89                         }
90                         $uid = $message['uid'];
91                         $recipients[] = $message['contact-id'];
92
93                         $mail = ActivityPub\Transmitter::ItemArrayFromMail($target_id);
94                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($mail, $uid, true);
95                         foreach ($inboxes as $inbox => $receivers) {
96                                 $ap_contacts = array_merge($ap_contacts, $receivers);
97                                 Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'target' => $target_id, 'inbox' => $inbox]);
98                                 Worker::add(['priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true],
99                                         'APDelivery', $cmd, $target_id, $inbox, $uid, $receivers, $post_uriid);
100                         }
101                 } elseif ($cmd == Delivery::SUGGESTION) {
102                         $suggest = DI::fsuggest()->getById($target_id);
103                         $uid = $suggest->uid;
104                         $recipients[] = $suggest->cid;
105                 } elseif ($cmd == Delivery::REMOVAL) {
106                         return self::notifySelfRemoval($target_id, $a->queue['priority'], $a->queue['created']);
107                 } elseif ($cmd == Delivery::RELOCATION) {
108                         $uid = $target_id;
109
110                         $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
111                         $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'addr', 'network', 'protocol', 'batch'], $condition);
112                 } else {
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'] == 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 = true;
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::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
185
186                         if (!self::isRemovalActivity($cmd, $owner, Protocol::ACTIVITYPUB)) {
187                                 $apdelivery = self::activityPubDelivery($cmd, $target_item, $parent, $thr_parent, $a->queue['priority'], $a->queue['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                                 Logger::info('Threaded comment', ['diaspora_delivery' => (int)$diaspora_delivery]);
197                         }
198
199                         $unlisted = $target_item['private'] == Item::UNLISTED;
200
201                         // This is IMPORTANT!!!!
202
203                         // We will only send a "notify owner to relay" or followup message if the referenced post
204                         // originated on our system by virtue of having our hostname somewhere
205                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
206
207                         // if $parent['wall'] == 1 we will already have the parent message in our array
208                         // and we will relay the whole lot.
209
210                         $localhost = str_replace('www.','', DI::baseUrl()->getHostname());
211                         if (strpos($localhost,':')) {
212                                 $localhost = substr($localhost,0,strpos($localhost,':'));
213                         }
214                         /**
215                          *
216                          * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
217                          * have been known to cause runaway conditions which affected several servers, along with
218                          * permissions issues.
219                          *
220                          */
221
222                         $relay_to_owner = false;
223
224                         if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
225                                 $relay_to_owner = true;
226                         }
227
228                         if (($cmd === Delivery::UPLINK) && (intval($parent['forum_mode']) == 1) && !$top_level) {
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, $owner)) {
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, $owner)) {
251                                 $direct_forum_delivery = true;
252                         }
253
254                         if ($relay_to_owner) {
255                                 // local followup to remote post
256                                 $followup = true;
257                                 $public_message = false; // not public
258                                 $recipients = [$parent['contact-id']];
259                                 $recipients_followup  = [$parent['contact-id']];
260
261                                 Logger::info('Followup', ['target' => $target_id, 'guid' => $target_item['guid'], 'to' => $parent['contact-id']]);
262
263                                 if (($target_item['private'] != Item::PRIVATE) &&
264                                         (strlen($target_item['allow_cid'].$target_item['allow_gid'].
265                                                 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
266                                         $push_notify = true;
267
268                                 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
269                                         $push_notify = true;
270
271                                         if ($parent["network"] == Protocol::OSTATUS) {
272                                                 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
273                                                 // Currently it is work at progress
274                                                 $condition = ['uid' => $uid, 'network' => Protocol::DFRN, 'blocked' => false, 'pending' => false, 'archive' => false];
275                                                 $followup_contacts_stmt = DBA::select('contact', ['id'], $condition);
276                                                 while($followup_contact = DBA::fetch($followup_contacts_stmt)) {
277                                                         $recipients_followup[] = $followup_contact['id'];
278                                                 }
279                                                 DBA::close($followup_contacts_stmt);
280                                         }
281                                 }
282
283                                 if ($direct_forum_delivery) {
284                                         $push_notify = false;
285                                 }
286
287                                 Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
288                         } else {
289                                 $followup = false;
290
291                                 Logger::info('Distributing directly', ['target' => $target_id, 'guid' => $target_item['guid']]);
292
293                                 // don't send deletions onward for other people's stuff
294
295                                 if ($target_item['deleted'] && !intval($target_item['wall'])) {
296                                         Logger::log('Ignoring delete notification for non-wall item');
297                                         return;
298                                 }
299
300                                 if (strlen($parent['allow_cid'])
301                                         || strlen($parent['allow_gid'])
302                                         || strlen($parent['deny_cid'])
303                                         || strlen($parent['deny_gid'])) {
304                                         $public_message = false; // private recipients, not public
305                                 }
306
307                                 $aclFormatter = DI::aclFormatter();
308
309                                 $allow_people = $aclFormatter->expand($parent['allow_cid']);
310                                 $allow_groups = Group::expand($uid, $aclFormatter->expand($parent['allow_gid']),true);
311                                 $deny_people  = $aclFormatter->expand($parent['deny_cid']);
312                                 $deny_groups  = Group::expand($uid, $aclFormatter->expand($parent['deny_gid']));
313
314                                 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
315                                 // a delivery fork. private groups (forum_mode == 2) do not uplink
316                                 /// @todo Possibly we should not uplink when the author is the forum itself?
317
318                                 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== Delivery::UPLINK)
319                                         && ($target_item['verb'] != Activity::ANNOUNCE)) {                                              
320                                         Worker::add($a->queue['priority'], 'Notifier', Delivery::UPLINK, $post_uriid, $sender_uid);
321                                 }
322
323                                 foreach ($items as $item) {
324                                         $recipients[] = $item['contact-id'];
325                                         // pull out additional tagged people to notify (if public message)
326                                         if ($public_message && strlen($item['inform'])) {
327                                                 $people = explode(',',$item['inform']);
328                                                 foreach ($people as $person) {
329                                                         if (substr($person,0,4) === 'cid:') {
330                                                                 $recipients[] = intval(substr($person,4));
331                                                         } else {
332                                                                 $url_recipients[] = substr($person,4);
333                                                         }
334                                                 }
335                                         }
336                                 }
337
338                                 if (count($url_recipients)) {
339                                         Logger::notice('Deliver', ['target' => $target_id, 'guid' => $target_item['guid'], 'recipients' => $url_recipients]);
340                                 }
341
342                                 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
343                                 $deny = array_unique(array_merge($deny_people, $deny_groups));
344                                 $recipients = array_diff($recipients, $deny);
345
346                                 // If this is a public message and pubmail is set on the parent, include all your email contacts
347                                 if (
348                                         function_exists('imap_open')
349                                         && !DI::config()->get('system','imap_disabled')
350                                         && $public_message
351                                         && intval($target_item['pubmail'])
352                                 ) {
353                                         $mail_contacts_stmt = DBA::select('contact', ['id'], ['uid' => $uid, 'network' => Protocol::MAIL]);
354                                         while ($mail_contact = DBA::fetch($mail_contacts_stmt)) {
355                                                 $recipients[] = $mail_contact['id'];
356                                         }
357                                         DBA::close($mail_contacts_stmt);
358                                 }
359                         }
360
361                         // If the thread parent is OStatus then do some magic to distribute the messages.
362                         // We have not only to look at the parent, since it could be a Friendica thread.
363                         if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
364                                 $diaspora_delivery = false;
365
366                                 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
367
368                                 // Send a salmon to the parent author
369                                 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
370                                 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
371                                         Logger::notice('Notify parent author', ['url' => $probed_contact["url"], 'notify' => $probed_contact["notify"]]);
372                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
373                                 }
374
375                                 // Send a salmon to the parent owner
376                                 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
377                                 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
378                                         Logger::notice('Notify parent owner', ['url' => $probed_contact["url"], 'notify' => $probed_contact["notify"]]);
379                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
380                                 }
381
382                                 // Send a salmon notification to every person we mentioned in the post
383                                 foreach (Tag::getByURIId($target_item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION, Tag::IMPLICIT_MENTION]) as $tag) {
384                                         $probed_contact = Contact::getByURL($tag['url']);
385                                         if (!empty($probed_contact['notify'])) {
386                                                 Logger::notice('Notify mentioned user', ['url' => $probed_contact["url"], 'notify' => $probed_contact["notify"]]);
387                                                 $url_recipients[$probed_contact['notify']] = $probed_contact['notify'];
388                                         }
389                                 }
390
391                                 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
392                                 $networks = [Protocol::DFRN];
393                         } elseif ($diaspora_delivery) {
394                                 $networks = [Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
395                                 if (($parent['network'] == Protocol::DIASPORA) || ($thr_parent['network'] == Protocol::DIASPORA)) {
396                                         Logger::info('Add AP contacts', ['target' => $target_id, 'guid' => $target_item['guid']]);
397                                         $networks[] = Protocol::ACTIVITYPUB;
398                                 }
399                         } else {
400                                 $networks = [Protocol::DFRN, Protocol::MAIL];
401                         }
402                 } else {
403                         $public_message = false;
404                 }
405
406                 if (empty($delivery_contacts_stmt)) {
407                         if ($followup) {
408                                 $recipients = $recipients_followup;
409                         }
410                         $condition = ['id' => $recipients, 'self' => false, 'uid' => [0, $uid],
411                                 'blocked' => false, 'pending' => false, 'archive' => false];
412                         if (!empty($networks)) {
413                                 $condition['network'] = $networks;
414                         }
415                         $delivery_contacts_stmt = DBA::select('contact', ['id', 'addr', 'url', 'network', 'protocol', 'batch'], $condition);
416                 }
417
418                 $conversants = [];
419                 $batch_delivery = false;
420
421                 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
422                         $relay_list = [];
423
424                         if ($diaspora_delivery && !$unlisted) {
425                                 $batch_delivery = true;
426
427                                 $relay_list_stmt = DBA::p(
428                                         "SELECT
429                                                 `batch`, `network`, `protocol`,
430                                                 ANY_VALUE(`id`) AS `id`,
431                                                 ANY_VALUE(`url`) AS `url`,
432                                                 ANY_VALUE(`name`) AS `name`
433                                         FROM `contact`
434                                         WHERE `network` = ?
435                                         AND `batch` != ''
436                                         AND `uid` = ?
437                                         AND `rel` != ?
438                                         AND NOT `blocked`
439                                         AND NOT `pending`
440                                         AND NOT `archive`
441                                         GROUP BY `batch`, `network`, `protocol`",
442                                         Protocol::DIASPORA,
443                                         $owner['uid'],
444                                         Contact::SHARING
445                                 );
446                                 $relay_list = DBA::toArray($relay_list_stmt);
447
448                                 // Fetch the participation list
449                                 // The function will ensure that there are no duplicates
450                                 $relay_list = Diaspora::participantsForThread($target_item, $relay_list);
451
452                                 // Add the relay to the list, avoid duplicates.
453                                 // Don't send community posts to the relay. Forum posts via the Diaspora protocol are looking ugly.
454                                 if (!$followup && !Item::isForumPost($target_item, $owner) && !self::isForumPost($target_item)) {
455                                         $relay_list = Relay::getList($target_id, $relay_list, [Protocol::DFRN, Protocol::DIASPORA]);
456                                 }
457                         }
458
459                         $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
460                                 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
461
462                         $contacts = DBA::toArray(DBA::select('contact', ['id', 'url', 'addr', 'name', 'network', 'protocol'], $condition));
463
464                         $conversants = array_merge($contacts, $relay_list);
465
466                         $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, true, $conversants, $ap_contacts, []);
467
468                         $push_notify = true;
469                 }
470
471                 $contacts = DBA::toArray($delivery_contacts_stmt);
472                 $delivery_queue_count += self::delivery($cmd, $post_uriid, $sender_uid, $target_item, $thr_parent, $owner, $batch_delivery, false, $contacts, $ap_contacts, $conversants);
473
474                 $delivery_queue_count += self::deliverOStatus($target_id, $target_item, $owner, $url_recipients, $public_message, $push_notify);
475
476                 if (!empty($target_item)) {
477                         Logger::log('Calling hooks for ' . $cmd . ' ' . $target_id, Logger::DEBUG);
478
479                         Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
480
481                         Hook::callAll('notifier_end', $target_item);
482
483                         // Workaround for pure connector posts
484                         if (in_array($cmd, [Delivery::POST, Delivery::POKE])) {
485                                 if ($delivery_queue_count == 0) {
486                                         Post\DeliveryData::incrementQueueDone($target_item['uri-id']);
487                                         $delivery_queue_count = 1;
488                                 }
489
490                                 Post\DeliveryData::incrementQueueCount($target_item['uri-id'], $delivery_queue_count);
491                         }
492                 }
493
494                 return;
495         }
496
497         /**
498          * Deliver the message to the contacts
499          *
500          * @param string $cmd 
501          * @param int $post_uriid 
502          * @param int $sender_uid
503          * @param array $target_item 
504          * @param array $thr_parent 
505          * @param array $owner 
506          * @param bool $batch_delivery 
507          * @param array $contacts 
508          * @param array $ap_contacts 
509          * @param array $conversants 
510          * @return int 
511          * @throws InternalServerErrorException 
512          * @throws Exception 
513          */
514         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 = [])
515         {
516                 $a = DI::app(); 
517                 $delivery_queue_count = 0;
518
519                 foreach ($contacts as $contact) {
520                         // Ensure that local contacts are delivered via DFRN
521                         if (Contact::isLocal($contact['url'])) {
522                                 $contact['network'] = Protocol::DFRN;
523                         }
524
525                         if (in_array($contact['id'], $ap_contacts)) {
526                                 Logger::info('Contact is already delivered via AP, so skip delivery via legacy DFRN/Diaspora', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
527                                 continue;
528                         }
529
530                         if (!empty($contact['id']) && Contact::isArchived($contact['id'])) {
531                                 Logger::info('Contact is archived, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
532                                 continue;
533                         }
534
535                         if (self::isRemovalActivity($cmd, $owner, $contact['network'])) {
536                                 Logger::info('Contact does no supports account removal commands, so skip delivery', ['target' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact['url']]);
537                                 continue;
538                         }
539
540                         if (self::skipActivityPubForDiaspora($contact, $target_item, $thr_parent)) {
541                                 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']]);
542                                 continue;
543                         }
544
545                         // Don't deliver to Diaspora if it already had been done as batch delivery
546                         if (!$in_batch && $batch_delivery && ($contact['network'] == Protocol::DIASPORA)) {
547                                 Logger::info('Diaspora contact is already delivered via batch', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
548                                 continue;
549                         }
550
551                         // Don't deliver to folks who have already been delivered to
552                         if (in_array($contact['id'], $conversants)) {
553                                 Logger::info('Already delivery', ['id' => $post_uriid, 'uid' => $sender_uid, 'contact' => $contact]);
554                                 continue;
555                         }
556
557                         Logger::info('Delivery', ['batch' => $in_batch, 'target' => $post_uriid, 'uid' => $sender_uid, 'guid' => $target_item['guid'] ?? '', 'to' => $contact]);
558
559                         // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
560                         // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
561                         // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
562                         // This is only important for high and medium priority tasks and not for Low priority jobs like deletions.
563                         if (($contact['network'] == Protocol::DIASPORA) && in_array($a->queue['priority'], [PRIORITY_HIGH, PRIORITY_MEDIUM])) {
564                                 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
565                         } else {
566                                 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
567                         }
568
569                         if (Worker::add($deliver_options, 'Delivery', $cmd, $post_uriid, (int)$contact['id'], $sender_uid)) {
570                                 $delivery_queue_count++;
571                         }
572                 }
573                 return $delivery_queue_count;
574         }
575
576         /**
577          * Deliver the message via OStatus
578          *
579          * @param int $target_id 
580          * @param array $target_item 
581          * @param array $owner 
582          * @param array $url_recipients 
583          * @param bool $public_message 
584          * @param bool $push_notify 
585          * @return int 
586          * @throws InternalServerErrorException 
587          * @throws Exception 
588          */
589         private static function deliverOStatus(int $target_id, array $target_item, array $owner, array $url_recipients, bool $public_message, bool $push_notify)
590         {
591                 $a = DI::app(); 
592                 $delivery_queue_count = 0;
593
594                 $url_recipients = array_filter($url_recipients);
595                 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
596                 // They are especially used for notifications to OStatus users that don't follow us.
597                 if (!DI::config()->get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && !empty($target_item)) {
598                         $slap = OStatus::salmon($target_item, $owner);
599                         foreach ($url_recipients as $url) {
600                                 Logger::info('Salmon delivery', ['item' => $target_id, 'to' => $url]);
601
602                                 $delivery_queue_count++;
603                                 Salmon::slapper($owner, $url, $slap);
604                                 Post\DeliveryData::incrementQueueDone($target_item['uri-id'], Post\DeliveryData::OSTATUS);
605                         }
606                 }
607
608                 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
609                 if ($push_notify) {
610                         Logger::info('Activating internal PuSH', ['item' => $target_id]);
611
612                         // Handling the pubsubhubbub requests
613                         PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
614                 }
615                 return $delivery_queue_count;
616         }
617
618         /**
619          * Checks if the current delivery shouldn't be transported to Diaspora.
620          * This is done for posts from AP authors or posts that are comments to AP authors.
621          *
622          * @param array  $contact    Receiver of the post
623          * @param array  $item       The post
624          * @param array  $thr_parent The thread parent
625          * @return bool
626          */
627         private static function skipActivityPubForDiaspora(array $contact, array $item, array $thr_parent)
628         {
629                 // No skipping needs to be done when delivery isn't done to Diaspora
630                 if ($contact['network'] != Protocol::DIASPORA) {
631                         return false;
632                 }
633
634                 // Skip the delivery to Diaspora if the item is from an ActivityPub author
635                 if (!empty($item['author-network']) && ($item['author-network'] == Protocol::ACTIVITYPUB)) {
636                         return true;
637                 }
638
639                 // Skip the delivery to Diaspora if the thread parent is from an ActivityPub author
640                 if (!empty($thr_parent['author-network']) && ($thr_parent['author-network'] == Protocol::ACTIVITYPUB)) {
641                         return true;
642                 }
643
644                 return false;
645         }
646
647         /**
648          * Checks if the current action is a deletion command of a account removal activity
649          * For Diaspora and ActivityPub we don't need to send single item deletion calls.
650          * These protocols do have a dedicated command for deleting a whole account.
651          *
652          * @param string $cmd     Notifier command
653          * @param array  $owner   Sender of the post
654          * @param string $network Receiver network
655          * @return bool
656          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
657          * @throws \ImagickException
658          */
659         private static function isRemovalActivity($cmd, $owner, $network)
660         {
661                 return ($cmd == Delivery::DELETION) && $owner['account_removed'] && in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA]);
662         }
663
664         /**
665          * @param int    $self_user_id
666          * @param int    $priority The priority the Notifier queue item was created with
667          * @param string $created  The date the Notifier queue item was created on
668          * @return bool
669          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670          * @throws \ImagickException
671          */
672         private static function notifySelfRemoval($self_user_id, $priority, $created)
673         {
674                 $owner = User::getOwnerDataById($self_user_id);
675                 if (!$owner) {
676                         return false;
677                 }
678
679                 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
680                 if (!DBA::isResult($contacts_stmt)) {
681                         return false;
682                 }
683
684                 while($contact = DBA::fetch($contacts_stmt)) {
685                         Contact::terminateFriendship($owner, $contact, true);
686                 }
687                 DBA::close($contacts_stmt);
688
689                 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser(0);
690                 foreach ($inboxes as $inbox => $receivers) {
691                         Logger::info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]);
692                         Worker::add(['priority' => PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
693                                 'APDelivery', Delivery::REMOVAL, 0, $inbox, $self_user_id, $receivers);
694                 }
695
696                 return true;
697         }
698
699         /**
700          * @param string $cmd
701          * @param array  $target_item
702          * @param array  $parent
703          * @param array  $thr_parent
704          * @param int    $priority The priority the Notifier queue item was created with
705          * @param string $created  The date the Notifier queue item was created on
706          * @return array 'count' => The number of delivery tasks created, 'contacts' => their contact ids
707          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
708          * @throws \ImagickException
709          */
710         private static function activityPubDelivery($cmd, array $target_item, array $parent, array $thr_parent, $priority, $created, $owner)
711         {
712                 // Don't deliver via AP when the starting post isn't from a federated network
713                 if (!in_array($parent['network'], Protocol::FEDERATED)) {
714                         return ['count' => 0, 'contacts' => []];
715                 }
716
717                 // Don't deliver via AP when the starting post is delivered via Diaspora
718                 if ($parent['network'] == Protocol::DIASPORA) {
719                         return ['count' => 0, 'contacts' => []];
720                 }
721
722                 // Also don't deliver when the direct thread parent was delivered via Diaspora
723                 if ($thr_parent['network'] == Protocol::DIASPORA) {
724                         return ['count' => 0, 'contacts' => []];
725                 }
726
727                 // Posts from Diaspora contacts are transmitted via Diaspora
728                 if ($target_item['network'] == Protocol::DIASPORA) {
729                         return ['count' => 0, 'contacts' => []];
730                 }
731
732                 $inboxes = [];
733                 $relay_inboxes = [];
734
735                 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
736
737                 if ($target_item['origin']) {
738                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
739
740                         if (in_array($target_item['private'], [Item::PUBLIC])) {
741                                 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($target_item['id'], $inboxes);
742                                 $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes();
743                         }
744
745                         Logger::log('Origin item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
746                 } elseif (Item::isForumPost($target_item, $owner)) {
747                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid, false, 0, true);
748                         Logger::log('Forum item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
749                 } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
750                         Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
751                         return ['count' => 0, 'contacts' => []];
752                 } elseif ($parent['origin']) {
753                         // Remote items are transmitted via the personal inboxes.
754                         // Doing so ensures that the dedicated receiver will get the message.
755                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, true, $target_item['id']);
756
757                         if (in_array($target_item['private'], [Item::PUBLIC])) {
758                                 $inboxes = ActivityPub\Transmitter::addRelayServerInboxesForItem($parent['id'], $inboxes);
759                                 $relay_inboxes = ActivityPub\Transmitter::addRelayServerInboxes([]);
760                         }
761
762                         Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
763                 }
764
765                 if (empty($inboxes) && empty($relay_inboxes)) {
766                         Logger::log('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
767                         return ['count' => 0, 'contacts' => []];
768                 }
769
770                 // Fill the item cache
771                 ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
772
773                 $delivery_queue_count = 0;
774                 $contacts = [];
775
776                 foreach ($inboxes as $inbox => $receivers) {
777                         $contacts = array_merge($contacts, $receivers);
778
779                         Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
780
781                         if (Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
782                                         'APDelivery', $cmd, $target_item['id'], $inbox, $uid, $receivers, $target_item['uri-id'])) {
783                                 $delivery_queue_count++;
784                         }
785                 }
786
787                 // We deliver posts to relay servers slightly delayed to priorize the direct delivery
788                 foreach ($relay_inboxes as $inbox) {
789                         Logger::info('Delivery to relay servers via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
790
791                         if (Worker::add(['priority' => $priority, 'dont_fork' => true], 'APDelivery', $cmd, $target_item['id'], $inbox, $uid, [], $target_item['uri-id'])) {
792                                 $delivery_queue_count++;
793                         }
794                 }
795
796                 return ['count' => $delivery_queue_count, 'contacts' => $contacts];
797         }
798
799         /**
800          * Check if the delivered item is a forum post
801          *
802          * @param array $item
803          * @return boolean
804          */
805         public static function isForumPost(array $item)
806         {
807                 return ($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode']);
808         }
809 }