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