]> git.mxchange.org Git - friendica.git/blob - src/Worker/Notifier.php
Exclude /api and /proxy from 2fa check
[friendica.git] / src / Worker / Notifier.php
1 <?php
2 /**
3  * @file src/Worker/Notifier.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\BaseObject;
8 use Friendica\Core\Config;
9 use Friendica\Core\Hook;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBA;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Conversation;
17 use Friendica\Model\Group;
18 use Friendica\Model\Item;
19 use Friendica\Model\ItemDeliveryData;
20 use Friendica\Model\PushSubscriber;
21 use Friendica\Model\User;
22 use Friendica\Network\Probe;
23 use Friendica\Protocol\ActivityPub;
24 use Friendica\Protocol\Diaspora;
25 use Friendica\Protocol\OStatus;
26 use Friendica\Protocol\Salmon;
27
28 require_once 'include/items.php';
29
30 /*
31  * The notifier is typically called with:
32  *
33  *              Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
34  *
35  * where COMMAND is one of the following:
36  *
37  *              activity                                (in diaspora.php, dfrn_confirm.php, profiles.php)
38  *              comment-import                  (in diaspora.php, items.php)
39  *              comment-new                             (in item.php)
40  *              drop                                    (in diaspora.php, items.php, photos.php)
41  *              edit_post                               (in item.php)
42  *              event                                   (in events.php)
43  *              like                                    (in like.php, poke.php)
44  *              mail                                    (in message.php)
45  *              suggest                                 (in fsuggest.php)
46  *              tag                                             (in photos.php, poke.php, tagger.php)
47  *              tgroup                                  (in items.php)
48  *              wall-new                                (in photos.php, item.php)
49  *              removeme                                (in Contact.php)
50  *              relocate                                (in uimport.php)
51  *
52  * and ITEM_ID is the id of the item in the database that needs to be sent to others.
53  */
54
55 class Notifier
56 {
57         public static function execute($cmd, $target_id)
58         {
59                 $a = BaseObject::getApp();
60
61                 Logger::log('Invoked: ' . $cmd . ': ' . $target_id, Logger::DEBUG);
62
63                 $top_level = false;
64                 $recipients = [];
65                 $url_recipients = [];
66
67                 $delivery_contacts_stmt = null;
68                 $target_item = [];
69                 $items = [];
70                 $delivery_queue_count = 0;
71
72                 if ($cmd == Delivery::MAIL) {
73                         $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
74                         if (!DBA::isResult($message)) {
75                                 return;
76                         }
77                         $uid = $message['uid'];
78                         $recipients[] = $message['contact-id'];
79
80                         $mail = ActivityPub\Transmitter::ItemArrayFromMail($target_id);
81                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($mail, §uid, true);
82                         foreach ($inboxes as $inbox) {
83                                 Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_id, 'inbox' => $inbox]);
84                                 Worker::add(['priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true],
85                                         'APDelivery', $cmd, $target_id, $inbox, $uid);
86                         }
87                 } elseif ($cmd == Delivery::SUGGESTION) {
88                         $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $target_id]);
89                         if (!DBA::isResult($suggest)) {
90                                 return;
91                         }
92                         $uid = $suggest['uid'];
93                         $recipients[] = $suggest['cid'];
94                 } elseif ($cmd == Delivery::REMOVAL) {
95                         return self::notifySelfRemoval($target_id, $a->queue['priority'], $a->queue['created']);
96                 } elseif ($cmd == Delivery::RELOCATION) {
97                         $uid = $target_id;
98
99                         $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
100                         $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'batch'], $condition);
101                 } else {
102                         // find ancestors
103                         $condition = ['id' => $target_id, 'visible' => true, 'moderated' => false];
104                         $target_item = Item::selectFirst([], $condition);
105
106                         if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
107                                 return;
108                         }
109
110                         if (!empty($target_item['contact-uid'])) {
111                                 $uid = $target_item['contact-uid'];
112                         } elseif (!empty($target_item['uid'])) {
113                                 $uid = $target_item['uid'];
114                         } else {
115                                 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
116                                 return;
117                         }
118
119                         $condition = ['parent' => $target_item['parent'], 'visible' => true, 'moderated' => false];
120                         $params = ['order' => ['id']];
121                         $items_stmt = Item::select([], $condition, $params);
122                         if (!DBA::isResult($items_stmt)) {
123                                 return;
124                         }
125
126                         $items = Item::inArray($items_stmt);
127
128                         // avoid race condition with deleting entries
129                         if ($items[0]['deleted']) {
130                                 foreach ($items as $item) {
131                                         $item['deleted'] = 1;
132                                 }
133                         }
134
135                         if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
136                                 Logger::log('Top level post');
137                                 $top_level = true;
138                         }
139                 }
140
141                 $owner = User::getOwnerDataById($uid);
142                 if (!$owner) {
143                         return;
144                 }
145
146                 // Should the post be transmitted to Diaspora?
147                 $diaspora_delivery = true;
148
149                 // If this is a public conversation, notify the feed hub
150                 $public_message = true;
151
152                 // Do a PuSH
153                 $push_notify = false;
154
155                 // Deliver directly to a forum, don't PuSH
156                 $direct_forum_delivery = false;
157
158                 $followup = false;
159                 $recipients_followup = [];
160
161                 if (!empty($target_item) && !empty($items)) {
162                         $parent = $items[0];
163
164                         if (!self::isRemovalActivity($cmd, $owner, Protocol::ACTIVITYPUB)) {
165                                 $delivery_queue_count += self::activityPubDelivery($cmd, $target_item, $parent, $a->queue['priority'], $a->queue['created'], $owner);
166                         }
167
168                         $fields = ['network', 'author-id', 'owner-id'];
169                         $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
170                         $thr_parent = Item::selectFirst($fields, $condition);
171
172                         Logger::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
173
174                         // This is IMPORTANT!!!!
175
176                         // We will only send a "notify owner to relay" or followup message if the referenced post
177                         // originated on our system by virtue of having our hostname somewhere
178                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
179
180                         // if $parent['wall'] == 1 we will already have the parent message in our array
181                         // and we will relay the whole lot.
182
183                         $localhost = str_replace('www.','',$a->getHostName());
184                         if (strpos($localhost,':')) {
185                                 $localhost = substr($localhost,0,strpos($localhost,':'));
186                         }
187                         /**
188                          *
189                          * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
190                          * have been known to cause runaway conditions which affected several servers, along with
191                          * permissions issues.
192                          *
193                          */
194
195                         $relay_to_owner = false;
196
197                         if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
198                                 $relay_to_owner = true;
199                         }
200
201
202                         if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
203                                 $relay_to_owner = true;
204                         }
205
206                         // until the 'origin' flag has been in use for several months
207                         // we will just use it as a fallback test
208                         // later we will be able to use it as the primary test of whether or not to relay.
209
210                         if (!$target_item['origin']) {
211                                 $relay_to_owner = false;
212                         }
213                         if ($parent['origin']) {
214                                 $relay_to_owner = false;
215                         }
216
217                         // Special treatment for forum posts
218                         if (Item::isForumPost($target_item, $owner)) {
219                                 $relay_to_owner = true;
220                                 $direct_forum_delivery = true;
221                         }
222
223                         // Avoid that comments in a forum thread are sent to OStatus
224                         if (Item::isForumPost($parent, $owner)) {
225                                 $direct_forum_delivery = true;
226                         }
227
228                         if ($relay_to_owner) {
229                                 // local followup to remote post
230                                 $followup = true;
231                                 $public_message = false; // not public
232                                 $recipients = [$parent['contact-id']];
233                                 $recipients_followup  = [$parent['contact-id']];
234
235                                 Logger::log('Followup ' . $target_item['guid'] . ' to ' . $parent['contact-id'], Logger::DEBUG);
236
237                                 //if (!$target_item['private'] && $target_item['wall'] &&
238                                 if (!$target_item['private'] &&
239                                         (strlen($target_item['allow_cid'].$target_item['allow_gid'].
240                                                 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
241                                         $push_notify = true;
242
243                                 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
244                                         $push_notify = true;
245
246                                         if ($parent["network"] == Protocol::OSTATUS) {
247                                                 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
248                                                 // Currently it is work at progress
249                                                 $condition = ['uid' => $uid, 'network' => Protocol::DFRN, 'blocked' => false, 'pending' => false, 'archive' => false];
250                                                 $followup_contacts_stmt = DBA::select('contact', ['id'], $condition);
251                                                 while($followup_contact = DBA::fetch($followup_contacts_stmt)) {
252                                                         $recipients_followup[] = $followup_contact['id'];
253                                                 }
254                                                 DBA::close($followup_contacts_stmt);
255                                         }
256                                 }
257
258                                 if ($direct_forum_delivery) {
259                                         $push_notify = false;
260                                 }
261
262                                 Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
263                         } else {
264                                 $followup = false;
265
266                                 Logger::log('Distributing directly ' . $target_item["guid"], Logger::DEBUG);
267
268                                 // don't send deletions onward for other people's stuff
269
270                                 if ($target_item['deleted'] && !intval($target_item['wall'])) {
271                                         Logger::log('Ignoring delete notification for non-wall item');
272                                         return;
273                                 }
274
275                                 if (strlen($parent['allow_cid'])
276                                         || strlen($parent['allow_gid'])
277                                         || strlen($parent['deny_cid'])
278                                         || strlen($parent['deny_gid'])) {
279                                         $public_message = false; // private recipients, not public
280                                 }
281
282                                 $allow_people = expand_acl($parent['allow_cid']);
283                                 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
284                                 $deny_people  = expand_acl($parent['deny_cid']);
285                                 $deny_groups  = Group::expand(expand_acl($parent['deny_gid']));
286
287                                 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
288                                 // a delivery fork. private groups (forum_mode == 2) do not uplink
289
290                                 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
291                                         Worker::add($a->queue['priority'], 'Notifier', 'uplink', $target_id);
292                                 }
293
294                                 foreach ($items as $item) {
295                                         $recipients[] = $item['contact-id'];
296                                         // pull out additional tagged people to notify (if public message)
297                                         if ($public_message && strlen($item['inform'])) {
298                                                 $people = explode(',',$item['inform']);
299                                                 foreach ($people as $person) {
300                                                         if (substr($person,0,4) === 'cid:') {
301                                                                 $recipients[] = intval(substr($person,4));
302                                                         } else {
303                                                                 $url_recipients[] = substr($person,4);
304                                                         }
305                                                 }
306                                         }
307                                 }
308
309                                 if (count($url_recipients)) {
310                                         Logger::log('Deliver ' . $target_item["guid"] . ' to _recipients ' . json_encode($url_recipients));
311                                 }
312
313                                 $recipients = array_unique(array_merge($recipients, $allow_people, $allow_groups));
314                                 $deny = array_unique(array_merge($deny_people, $deny_groups));
315                                 $recipients = array_diff($recipients, $deny);
316
317                                 // If this is a public message and pubmail is set on the parent, include all your email contacts
318                                 if (
319                                         function_exists('imap_open')
320                                         && !Config::get('system','imap_disabled')
321                                         && $public_message
322                                         && intval($target_item['pubmail'])
323                                 ) {
324                                         $mail_contacts_stmt = DBA::select('contact', ['id'], ['uid' => $uid, 'network' => Protocol::MAIL]);
325                                         while ($mail_contact = DBA::fetch($mail_contacts_stmt)) {
326                                                 $recipients[] = $mail_contact['id'];
327                                         }
328                                         DBA::close($mail_contacts_stmt);
329                                 }
330                         }
331
332                         // If the thread parent is OStatus then do some magic to distribute the messages.
333                         // We have not only to look at the parent, since it could be a Friendica thread.
334                         if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
335                                 $diaspora_delivery = false;
336
337                                 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
338
339                                 // Send a salmon to the parent author
340                                 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
341                                 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
342                                         Logger::log('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
343                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
344                                 }
345
346                                 // Send a salmon to the parent owner
347                                 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
348                                 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
349                                         Logger::log('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
350                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
351                                 }
352
353                                 // Send a salmon notification to every person we mentioned in the post
354                                 $arr = explode(',',$target_item['tag']);
355                                 foreach ($arr as $x) {
356                                         //Logger::log('Checking tag '.$x, Logger::DEBUG);
357                                         $matches = null;
358                                         if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
359                                                         $probed_contact = Probe::uri($matches[1]);
360                                                 if ($probed_contact["notify"] != "") {
361                                                         Logger::log('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
362                                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
363                                                 }
364                                         }
365                                 }
366
367                                 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
368                                 $networks = [Protocol::OSTATUS, Protocol::DFRN];
369                         } else {
370                                 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
371                         }
372                 } else {
373                         $public_message = false;
374                 }
375
376                 if (empty($delivery_contacts_stmt)) {
377                         if ($followup) {
378                                 $recipients = $recipients_followup;
379                         }
380                         $condition = ['id' => $recipients, 'self' => false,
381                                 'blocked' => false, 'pending' => false, 'archive' => false];
382                         if (!empty($networks)) {
383                                 $condition['network'] = $networks;
384                         }
385                         $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'batch'], $condition);
386                 }
387
388                 $conversants = [];
389                 $batch_delivery = false;
390
391                 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
392                         $relay_list = [];
393
394                         if ($diaspora_delivery) {
395                                 $batch_delivery = true;
396
397                                 $relay_list_stmt = DBA::p(
398                                         "SELECT
399                                                 `batch`,
400                                                 ANY_VALUE(`id`) AS `id`,
401                                                 ANY_VALUE(`name`) AS `name`,
402                                                 ANY_VALUE(`network`) AS `network`,
403                                                 ANY_VALUE(`protocol`) AS `protocol`
404                                         FROM `contact`
405                                         WHERE `network` = ?
406                                         AND `batch` != ''
407                                         AND `uid` = ?
408                                         AND `rel` != ?
409                                         AND NOT `blocked`
410                                         AND NOT `pending`
411                                         AND NOT `archive`
412                                         GROUP BY `batch`",
413                                         Protocol::DIASPORA,
414                                         $owner['uid'],
415                                         Contact::SHARING
416                                 );
417                                 $relay_list = DBA::toArray($relay_list_stmt);
418
419                                 // Fetch the participation list
420                                 // The function will ensure that there are no duplicates
421                                 $relay_list = Diaspora::participantsForThread($target_id, $relay_list);
422
423                                 // Add the relay to the list, avoid duplicates.
424                                 // Don't send community posts to the relay. Forum posts via the Diaspora protocol are looking ugly.
425                                 if (!$followup && !Item::isForumPost($target_item, $owner)) {
426                                         $relay_list = Diaspora::relayList($target_id, $relay_list);
427                                 }
428                         }
429
430                         $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
431                                 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
432
433                         $r2 = DBA::toArray(DBA::select('contact', ['id', 'url', 'name', 'network', 'protocol'], $condition));
434
435                         $r = array_merge($r2, $relay_list);
436
437                         if (DBA::isResult($r)) {
438                                 foreach ($r as $rr) {
439                                         if (self::isRemovalActivity($cmd, $owner, $rr['network'])) {
440                                                 Logger::log('Skipping dropping for ' . $rr['url'] . ' since the network supports account removal commands.', Logger::DEBUG);
441                                                 continue;
442                                         }
443
444                                         if (($rr['network'] == Protocol::DFRN) && ($rr['protocol'] == Protocol::ACTIVITYPUB) &&
445                                                 !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::REMOVAL, Delivery::RELOCATION])) {
446                                                 Logger::info('Contact is Friendica AP, so skipping delivery via legacy DFRN', ['url' => $rr['url']]);
447                                                 continue;
448                                         }
449
450                                         if (Config::get('debug', 'total_ap_delivery') && !empty($rr['url']) && ($rr['network'] == Protocol::DFRN) && !empty(APContact::getByURL($rr['url'], false))) {
451                                                 Logger::log('Skipping contact ' . $rr['url'] . ' since it will be delivered via AP', Logger::DEBUG);
452                                                 continue;
453                                         }
454
455                                         $conversants[] = $rr['id'];
456
457                                         $delivery_queue_count++;
458
459                                         Logger::log('Public delivery of item ' . $target_item["guid"] . ' (' . $target_id . ') to ' . json_encode($rr), Logger::DEBUG);
460
461                                         // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
462                                         // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
463                                         // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
464                                         // This is only important for high and medium priority tasks and not for Low priority jobs like deletions.
465                                         if (($rr['network'] == Protocol::DIASPORA) && in_array($a->queue['priority'], [PRIORITY_HIGH, PRIORITY_MEDIUM])) {
466                                                 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
467                                         } else {
468                                                 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
469                                         }
470                                         Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$rr['id']);
471                                 }
472                         }
473
474                         $push_notify = true;
475                 }
476
477                 // delivery loop
478                 while ($contact = DBA::fetch($delivery_contacts_stmt)) {
479                         if (self::isRemovalActivity($cmd, $owner, $contact['network'])) {
480                                 Logger::log('Skipping dropping for ' . $contact['url'] . ' since the network supports account removal commands.', Logger::DEBUG);
481                                 continue;
482                         }
483
484                         if (($contact['network'] == Protocol::DFRN) && ($contact['protocol'] == Protocol::ACTIVITYPUB) &&
485                                 !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::REMOVAL, Delivery::RELOCATION])) {
486                                 Logger::info('Contact is Friendica AP, so skipping delivery via legacy DFRN', ['url' => $contact['url']]);
487                                 continue;
488                         }
489
490                         if (Config::get('debug', 'total_ap_delivery') && ($contact['network'] == Protocol::DFRN) && !empty(APContact::getByURL($contact['url'], false))) {
491                                 Logger::log('Skipping contact ' . $contact['url'] . ' since it will be delivered via AP', Logger::DEBUG);
492                                 continue;
493                         }
494
495                         // Don't deliver to Diaspora if it already had been done as batch delivery
496                         if (($contact['network'] == Protocol::DIASPORA) && $batch_delivery) {
497                                 Logger::log('Already delivered  id ' . $target_id . ' via batch to ' . json_encode($contact), Logger::DEBUG);
498                                 continue;
499                         }
500
501                         // Don't deliver to folks who have already been delivered to
502                         if (in_array($contact['id'], $conversants)) {
503                                 Logger::log('Already delivered id ' . $target_id. ' to ' . json_encode($contact), Logger::DEBUG);
504                                 continue;
505                         }
506
507                         $delivery_queue_count++;
508
509                         Logger::log('Delivery of item ' . $target_id . ' to ' . json_encode($contact), Logger::DEBUG);
510
511                         // Ensure that posts with our own protocol arrives before Diaspora posts arrive.
512                         // Situation is that sometimes Friendica servers receive Friendica posts over the Diaspora protocol first.
513                         // The conversion in Markdown reduces the formatting, so these posts should arrive after the Friendica posts.
514                         if ($contact['network'] == Protocol::DIASPORA) {
515                                 $deliver_options = ['priority' => $a->queue['priority'], 'dont_fork' => true];
516                         } else {
517                                 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
518                         }
519                         Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$contact['id']);
520                 }
521                 DBA::close($delivery_contacts_stmt);
522
523                 $url_recipients = array_filter($url_recipients);
524                 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
525                 // They are especially used for notifications to OStatus users that don't follow us.
526                 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && !empty($target_item)) {
527                         $delivery_queue_count += count($url_recipients);
528                         $slap = OStatus::salmon($target_item, $owner);
529                         foreach ($url_recipients as $url) {
530                                 Logger::log('Salmon delivery of item ' . $target_id . ' to ' . $url);
531                                 /// @TODO Redeliver/queue these items on failure, though there is no contact record
532                                 Salmon::slapper($owner, $url, $slap);
533                                 ItemDeliveryData::incrementQueueDone($target_id);
534                         }
535                 }
536
537                 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
538                 if ($push_notify) {
539                         Logger::log('Activating internal PuSH for item '.$target_id, Logger::DEBUG);
540
541                         // Handling the pubsubhubbub requests
542                         PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
543                 }
544
545                 if (!empty($target_item)) {
546                         Logger::log('Calling hooks for ' . $cmd . ' ' . $target_id, Logger::DEBUG);
547
548                         if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
549                                 ItemDeliveryData::update($target_item['id'], ['queue_count' => $delivery_queue_count]);
550                         }
551
552                         Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
553
554                         Hook::callAll('notifier_end', $target_item);
555                 }
556
557                 return;
558         }
559
560         /**
561          * Checks if the current action is a deletion command of a account removal activity
562          * For Diaspora and ActivityPub we don't need to send single item deletion calls.
563          * These protocols do have a dedicated command for deleting a whole account.
564          *
565          * @param string $cmd     Notifier command
566          * @param array  $owner   Sender of the post
567          * @param string $network Receiver network
568          * @return bool
569          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
570          * @throws \ImagickException
571          */
572         private static function isRemovalActivity($cmd, $owner, $network)
573         {
574                 return ($cmd == Delivery::DELETION) && $owner['account_removed'] && in_array($network, [Protocol::ACTIVITYPUB, Protocol::DIASPORA]);
575         }
576
577         /**
578          * @param int    $self_user_id
579          * @param int    $priority The priority the Notifier queue item was created with
580          * @param string $created  The date the Notifier queue item was created on
581          * @return bool
582          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
583          * @throws \ImagickException
584          */
585         private static function notifySelfRemoval($self_user_id, $priority, $created)
586         {
587                 $owner = User::getOwnerDataById($self_user_id);
588                 if (!$owner) {
589                         return false;
590                 }
591
592                 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
593                 if (!DBA::isResult($contacts_stmt)) {
594                         return false;
595                 }
596
597                 while($contact = DBA::fetch($contacts_stmt)) {
598                         Contact::terminateFriendship($owner, $contact, true);
599                 }
600                 DBA::close($contacts_stmt);
601
602                 $inboxes = ActivityPub\Transmitter::fetchTargetInboxesforUser(0);
603                 foreach ($inboxes as $inbox) {
604                         Logger::info('Account removal via ActivityPub', ['uid' => $self_user_id, 'inbox' => $inbox]);
605                         Worker::add(['priority' => PRIORITY_NEGLIGIBLE, 'created' => $created, 'dont_fork' => true],
606                                 'APDelivery', Delivery::REMOVAL, '', $inbox, $self_user_id);
607                 }
608
609                 return true;
610         }
611
612         /**
613          * @param string $cmd
614          * @param array  $target_item
615          * @param array  $parent
616          * @param int    $priority The priority the Notifier queue item was created with
617          * @param string $created  The date the Notifier queue item was created on
618          * @return int The number of delivery tasks created
619          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
620          * @throws \ImagickException
621          */
622         private static function activityPubDelivery($cmd, array $target_item, array $parent, $priority, $created, $owner)
623         {
624                 $inboxes = [];
625
626                 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
627
628                 if ($target_item['origin']) {
629                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid);
630                         Logger::log('Origin item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
631                 } elseif (Item::isForumPost($target_item, $owner)) {
632                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($target_item, $uid, false, 0, true);
633                         Logger::log('Forum item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
634                 } elseif (!DBA::exists('conversation', ['item-uri' => $target_item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB])) {
635                         Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' is no AP post. It will not be distributed.', Logger::DEBUG);
636                         return 0;
637                 } elseif ($parent['origin']) {
638                         // Remote items are transmitted via the personal inboxes.
639                         // Doing so ensures that the dedicated receiver will get the message.
640                         $inboxes = ActivityPub\Transmitter::fetchTargetInboxes($parent, $uid, true, $target_item['id']);
641                         Logger::log('Remote item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . ' will be distributed.', Logger::DEBUG);
642                 }
643
644                 if (empty($inboxes)) {
645                         Logger::log('No inboxes found for item ' . $target_item['id'] . ' with URL ' . $target_item['uri'] . '. It will not be distributed.', Logger::DEBUG);
646                         return 0;
647                 }
648
649                 // Fill the item cache
650                 ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
651
652                 foreach ($inboxes as $inbox) {
653                         Logger::info('Delivery via ActivityPub', ['cmd' => $cmd, 'id' => $target_item['id'], 'inbox' => $inbox]);
654
655                         Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
656                                         'APDelivery', $cmd, $target_item['id'], $inbox, $uid);
657                 }
658
659                 return count($inboxes);
660         }
661 }