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