3 * @file src/Worker/Notifier.php
5 namespace Friendica\Worker;
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;
27 require_once 'include/items.php';
30 * The notifier is typically called with:
32 * Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
34 * where COMMAND is one of the following:
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)
51 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
56 public static function execute($cmd, $target_id)
58 $a = BaseObject::getApp();
60 Logger::log('Invoked: ' . $cmd . ': ' . $target_id, Logger::DEBUG);
66 $delivery_contacts_stmt = null;
69 $delivery_queue_count = 0;
71 if ($cmd == Delivery::MAIL) {
72 $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $target_id]);
73 if (!DBA::isResult($message)) {
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)) {
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) {
90 $condition = ['uid' => $target_id, 'self' => false, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
91 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
94 $condition = ['id' => $target_id, 'visible' => true, 'moderated' => false];
95 $target_item = Item::selectFirst([], $condition);
97 if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
101 if (!empty($target_item['contact-uid'])) {
102 $uid = $target_item['contact-uid'];
103 } elseif (!empty($target_item['uid'])) {
104 $uid = $target_item['uid'];
106 Logger::log('Only public users for item ' . $target_id, Logger::DEBUG);
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)) {
117 $items = Item::inArray($items_stmt);
119 // avoid race condition with deleting entries
120 if ($items[0]['deleted']) {
121 foreach ($items as $item) {
122 $item['deleted'] = 1;
126 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
127 Logger::log('Top level post');
132 $owner = User::getOwnerDataById($uid);
137 // Should the post be transmitted to Diaspora?
138 $diaspora_delivery = true;
140 // If this is a public conversation, notify the feed hub
141 $public_message = true;
144 $push_notify = false;
146 // Deliver directly to a forum, don't PuSH
147 $direct_forum_delivery = false;
150 $recipients_followup = [];
152 if (!empty($target_item) && !empty($items)) {
155 $delivery_queue_count += self::activityPubDelivery($cmd, $target_item, $parent, $a->queue['priority'], $a->queue['created']);
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);
161 Logger::log('GUID: ' . $target_item["guid"] . ': Parent is ' . $parent['network'] . '. Thread parent is ' . $thr_parent['network'], Logger::DEBUG);
163 // This is IMPORTANT!!!!
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.
169 // if $parent['wall'] == 1 we will already have the parent message in our array
170 // and we will relay the whole lot.
172 $localhost = str_replace('www.','',$a->getHostName());
173 if (strpos($localhost,':')) {
174 $localhost = substr($localhost,0,strpos($localhost,':'));
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.
184 $relay_to_owner = false;
186 if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
187 $relay_to_owner = true;
191 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
192 $relay_to_owner = true;
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.
199 if (!$target_item['origin']) {
200 $relay_to_owner = false;
202 if ($parent['origin']) {
203 $relay_to_owner = false;
206 // Special treatment for forum posts
207 if (self::isForumPost($target_item, $owner)) {
208 $relay_to_owner = true;
209 $direct_forum_delivery = true;
212 // Avoid that comments in a forum thread are sent to OStatus
213 if (self::isForumPost($parent, $owner)) {
214 $direct_forum_delivery = true;
217 if ($relay_to_owner) {
218 // local followup to remote post
220 $public_message = false; // not public
221 $recipients = [$parent['contact-id']];
222 $recipients_followup = [$parent['contact-id']];
224 Logger::log('Followup ' . $target_item['guid'] . ' to ' . $parent['contact-id'], Logger::DEBUG);
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))
232 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
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'];
243 DBA::close($followup_contacts_stmt);
247 if ($direct_forum_delivery) {
248 $push_notify = false;
251 Logger::log('Notify ' . $target_item["guid"] .' via PuSH: ' . ($push_notify ? "Yes":"No"), Logger::DEBUG);
255 Logger::log('Distributing directly ' . $target_item["guid"], Logger::DEBUG);
257 // don't send deletions onward for other people's stuff
259 if ($target_item['deleted'] && !intval($target_item['wall'])) {
260 Logger::log('Ignoring delete notification for non-wall item');
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
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']));
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
279 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
280 Worker::add($a->queue['priority'], 'Notifier', 'uplink', $target_id);
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));
292 $url_recipients[] = substr($person,4);
298 if (count($url_recipients)) {
299 Logger::log('Deliver ' . $target_item["guid"] . ' to _recipients ' . json_encode($url_recipients));
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);
306 // If this is a public message and pubmail is set on the parent, include all your email contacts
308 function_exists('imap_open')
309 && !Config::get('system','imap_disabled')
311 && intval($target_item['pubmail'])
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'];
317 DBA::close($mail_contacts_stmt);
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;
326 Logger::log('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], Logger::DEBUG);
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"];
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"];
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);
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"];
356 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
357 $networks = [Protocol::OSTATUS, Protocol::DFRN];
359 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
362 $public_message = false;
365 if (empty($delivery_contacts_stmt)) {
367 $recipients = $recipients_followup;
369 $condition = ['id' => $recipients, 'self' => false,
370 'blocked' => false, 'pending' => false, 'archive' => false];
371 if (!empty($networks)) {
372 $condition['network'] = $networks;
374 $delivery_contacts_stmt = DBA::select('contact', ['id', 'url', 'network', 'batch'], $condition);
378 $batch_delivery = false;
380 if ($public_message && !in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
383 if ($diaspora_delivery) {
384 $batch_delivery = true;
386 $relay_list_stmt = DBA::p(
389 ANY_VALUE(`id`) AS `id`,
390 ANY_VALUE(`name`) AS `name`,
391 ANY_VALUE(`network`) AS `network`
405 $relay_list = DBA::toArray($relay_list_stmt);
407 // Fetch the participation list
408 // The function will ensure that there are no duplicates
409 $relay_list = Diaspora::participantsForThread($target_id, $relay_list);
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);
418 $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
419 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
421 $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
423 $r = array_merge($r2, $relay_list);
425 if (DBA::isResult($r)) {
426 foreach ($r as $rr) {
427 $conversants[] = $rr['id'];
429 $delivery_queue_count++;
431 Logger::log('Public delivery of item ' . $target_item["guid"] . ' (' . $target_id . ') to ' . json_encode($rr), Logger::DEBUG);
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];
439 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
441 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$rr['id']);
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);
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);
462 $delivery_queue_count++;
464 Logger::log('Delivery of item ' . $target_id . ' to ' . json_encode($contact), Logger::DEBUG);
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];
472 $deliver_options = ['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true];
474 Worker::add($deliver_options, 'Delivery', $cmd, $target_id, (int)$contact['id']);
476 DBA::close($delivery_contacts_stmt);
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);
493 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
495 Logger::log('Activating internal PuSH for item '.$target_id, Logger::DEBUG);
497 // Handling the pubsubhubbub requests
498 PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
501 if (!empty($target_item)) {
502 Logger::log('Calling hooks for ' . $cmd . ' ' . $target_id, Logger::DEBUG);
504 if (in_array($cmd, [Delivery::POST, Delivery::COMMENT])) {
505 ItemDeliveryData::update($target_item['id'], ['queue_count' => $delivery_queue_count]);
508 Hook::fork($a->queue['priority'], 'notifier_normal', $target_item);
510 Hook::callAll('notifier_end', $target_item);
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
521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
522 * @throws \ImagickException
524 private static function notifySelfRemoval($self_user_id, $priority, $created)
526 $owner = User::getOwnerDataById($self_user_id);
531 $contacts_stmt = DBA::select('contact', [], ['self' => false, 'uid' => $self_user_id]);
532 if (!DBA::isResult($contacts_stmt)) {
536 while($contact = DBA::fetch($contacts_stmt)) {
537 Contact::terminateFriendship($owner, $contact, true);
539 DBA::close($contacts_stmt);
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);
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
561 private static function activityPubDelivery($cmd, array $target_item, array $parent, $priority, $created)
565 $uid = $target_item['contact-uid'] ?: $target_item['uid'];
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);
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);
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);
585 // Fill the item cache
586 ActivityPub\Transmitter::createCachedActivityFromItem($target_item['id'], true);
588 foreach ($inboxes as $inbox) {
589 Logger::log('Deliver ' . $target_item['id'] .' to ' . $inbox .' via ActivityPub', Logger::DEBUG);
591 Worker::add(['priority' => $priority, 'created' => $created, 'dont_fork' => true],
592 'APDelivery', $cmd, $target_item['id'], $inbox, $uid);
595 return count($inboxes);
598 private static function isForumPost(array $item, array $owner)
600 if (($item['author-id'] == $item['owner-id']) ||
601 ($owner['id'] == $item['contact-id']) ||
602 ($item['uri'] != $item['parent-uri'])) {
606 return self::isForum($item['contact-id']);
609 private static function isForum($contactid)
611 $fields = ['forum', 'prv'];
612 $condition = ['id' => $contactid];
613 $contact = DBA::selectFirst('contact', $fields, $condition);
614 if (!DBA::isResult($contact)) {
615 // Should never happen
620 return ($contact['forum'] || $contact['prv']);