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