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