4 use Friendica\Core\Config;
5 use Friendica\Core\Worker;
6 use Friendica\Network\Probe;
7 use Friendica\Protocol\Diaspora;
9 require_once 'include/queue_fn.php';
10 require_once 'include/html2plain.php';
11 require_once 'include/ostatus.php';
12 require_once 'include/salmon.php';
15 * This file was at one time responsible for doing all deliveries, but this caused
16 * big problems when the process was killed or stalled during the delivery process.
17 * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
21 * The notifier is typically called with:
23 * Worker::add(PRIORITY_HIGH, "notifier", COMMAND, ITEM_ID);
25 * where COMMAND is one of the following:
27 * activity (in diaspora.php, dfrn_confirm.php, profiles.php)
28 * comment-import (in diaspora.php, items.php)
29 * comment-new (in item.php)
30 * drop (in diaspora.php, items.php, photos.php)
31 * edit_post (in item.php)
32 * event (in events.php)
33 * expire (in items.php)
34 * like (in like.php, poke.php)
35 * mail (in message.php)
36 * suggest (in fsuggest.php)
37 * tag (in photos.php, poke.php, tagger.php)
38 * tgroup (in items.php)
39 * wall-new (in photos.php, item.php)
40 * removeme (in Contact.php)
41 * relocate (in uimport.php)
43 * and ITEM_ID is the id of the item in the database that needs to be sent to others.
47 function notifier_run(&$argv, &$argc){
50 require_once 'include/datetime.php';
51 require_once 'include/items.php';
52 require_once 'include/bbcode.php';
53 require_once 'include/email.php';
59 logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
66 $item_id = intval($argv[2]);
78 $recipients = array();
79 $url_recipients = array();
83 if ($cmd === 'mail') {
86 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
89 if (! count($message)) {
92 $uid = $message[0]['uid'];
93 $recipients[] = $message[0]['contact-id'];
96 } elseif ($cmd === 'expire') {
99 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
100 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
105 if (! count($items)) {
108 } elseif ($cmd === 'suggest') {
109 $normal_mode = false;
112 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
115 if (! count($suggest)) {
118 $uid = $suggest[0]['uid'];
119 $recipients[] = $suggest[0]['cid'];
121 } elseif ($cmd === 'removeme') {
122 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
123 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
124 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
125 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
126 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
133 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($item_id));
139 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
143 require_once 'include/Contact.php';
144 foreach ($r as $contact) {
145 terminate_friendship($user, $self, $contact);
148 } elseif ($cmd === 'relocate') {
149 $normal_mode = false;
153 $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
154 intval($uid), NETWORK_DFRN, NETWORK_DIASPORA);
157 $r = q("SELECT * FROM `item` WHERE `id` = %d AND visible = 1 AND moderated = 0 LIMIT 1",
161 if ((! dbm::is_result($r)) || (! intval($r[0]['parent']))) {
165 $target_item = $r[0];
166 $parent_id = intval($r[0]['parent']);
168 $updated = $r[0]['edited'];
170 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
171 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d AND visible = 1 AND moderated = 0 ORDER BY `id` ASC",
175 if (! count($items)) {
179 // avoid race condition with deleting entries
181 if ($items[0]['deleted']) {
182 foreach ($items as $item) {
183 $item['deleted'] = 1;
187 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
188 logger('notifier: top level post');
194 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
195 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
196 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
197 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
198 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
202 if (! dbm::is_result($r)) {
208 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
210 // Should the post be transmitted to Diaspora?
211 $diaspora_delivery = true;
213 // If this is a public conversation, notify the feed hub
214 $public_message = true;
217 $push_notify = false;
219 // Deliver directly to a forum, don't PuSH
220 $direct_forum_delivery = false;
222 // fill this in with a single salmon slap if applicable
225 if (! ($mail || $fsuggest || $relocate)) {
227 $slap = ostatus::salmon($target_item,$owner);
229 require_once 'include/group.php';
233 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
234 dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
236 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
238 // This is IMPORTANT!!!!
240 // We will only send a "notify owner to relay" or followup message if the referenced post
241 // originated on our system by virtue of having our hostname somewhere
242 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
244 // if $parent['wall'] == 1 we will already have the parent message in our array
245 // and we will relay the whole lot.
247 // expire sends an entire group of expire messages and cannot be forwarded.
248 // However the conversation owner will be a part of the conversation and will
249 // be notified during this run.
250 // Other DFRN conversation members will be alerted during polled updates.
254 // Diaspora members currently are not notified of expirations, and other networks have
255 // either limited or no ability to process deletions. We should at least fix Diaspora
256 // by stringing togther an array of retractions and sending them onward.
259 $localhost = str_replace('www.','',$a->get_hostname());
260 if (strpos($localhost,':')) {
261 $localhost = substr($localhost,0,strpos($localhost,':'));
265 * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
266 * have been known to cause runaway conditions which affected several servers, along with
267 * permissions issues.
271 $relay_to_owner = false;
273 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
274 $relay_to_owner = true;
278 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
279 $relay_to_owner = true;
282 // until the 'origin' flag has been in use for several months
283 // we will just use it as a fallback test
284 // later we will be able to use it as the primary test of whether or not to relay.
286 if (! $target_item['origin']) {
287 $relay_to_owner = false;
289 if ($parent['origin']) {
290 $relay_to_owner = false;
293 // Special treatment for forum posts
294 if (($target_item['author-link'] != $target_item['owner-link']) &&
295 ($owner['id'] != $target_item['contact-id']) &&
296 ($target_item['uri'] === $target_item['parent-uri'])) {
298 $fields = array('forum', 'prv');
299 $condition = array('id' => $target_item['contact-id']);
300 $contact = dba::select('contact', $fields, $condition, array('limit' => 1));
301 if (!dbm::is_result($contact)) {
302 // Should never happen
306 // Is the post from a forum?
307 if ($contact['forum'] || $contact['prv']) {
308 $relay_to_owner = true;
309 $direct_forum_delivery = true;
312 if ($relay_to_owner) {
313 logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
314 // local followup to remote post
316 $public_message = false; // not public
317 $conversant_str = dbesc($parent['contact-id']);
318 $recipients = array($parent['contact-id']);
319 $recipients_followup = array($parent['contact-id']);
321 //if (!$target_item['private'] && $target_item['wall'] &&
322 if (!$target_item['private'] &&
323 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
324 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
327 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
331 if ($parent["network"] == NETWORK_OSTATUS) {
332 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
333 // Currently it is work at progress
334 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
338 if (dbm::is_result($r)) {
339 foreach ($r as $rr) {
340 $recipients_followup[] = $rr['id'];
346 if ($direct_forum_delivery) {
347 $push_notify = false;
350 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
354 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
356 // don't send deletions onward for other people's stuff
358 if ($target_item['deleted'] && (! intval($target_item['wall']))) {
359 logger('notifier: ignoring delete notification for non-wall item');
363 if ((strlen($parent['allow_cid']))
364 || (strlen($parent['allow_gid']))
365 || (strlen($parent['deny_cid']))
366 || (strlen($parent['deny_gid']))) {
367 $public_message = false; // private recipients, not public
370 $allow_people = expand_acl($parent['allow_cid']);
371 $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
372 $deny_people = expand_acl($parent['deny_cid']);
373 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
375 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
376 // a delivery fork. private groups (forum_mode == 2) do not uplink
378 if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
379 Worker::add($a->queue['priority'], 'notifier', 'uplink', $item_id);
382 $conversants = array();
384 foreach ($items as $item) {
385 $recipients[] = $item['contact-id'];
386 $conversants[] = $item['contact-id'];
387 // pull out additional tagged people to notify (if public message)
388 if ($public_message && strlen($item['inform'])) {
389 $people = explode(',',$item['inform']);
390 foreach ($people as $person) {
391 if (substr($person,0,4) === 'cid:') {
392 $recipients[] = intval(substr($person,4));
393 $conversants[] = intval(substr($person,4));
395 $url_recipients[] = substr($person,4);
401 if (count($url_recipients))
402 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
404 $conversants = array_unique($conversants);
407 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
408 $deny = array_unique(array_merge($deny_people,$deny_groups));
409 $recipients = array_diff($recipients,$deny);
411 $conversant_str = dbesc(implode(', ',$conversants));
414 // If the thread parent is OStatus then do some magic to distribute the messages.
415 // We have not only to look at the parent, since it could be a Friendica thread.
416 if (($thr_parent && ($thr_parent[0]['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
418 $diaspora_delivery = false;
420 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
422 // Send a salmon to the parent author
423 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
424 dbesc(normalise_link($thr_parent[0]['author-link'])),
426 if (dbm::is_result($r)) {
427 $probed_contact = $r[0];
429 $probed_contact = Probe::uri($thr_parent[0]['author-link']);
432 if ($probed_contact["notify"] != "") {
433 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
434 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
437 // Send a salmon to the parent owner
438 $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
439 dbesc(normalise_link($thr_parent[0]['owner-link'])),
441 if (dbm::is_result($r)) {
442 $probed_contact = $r[0];
444 $probed_contact = Probe::uri($thr_parent[0]['owner-link']);
447 if ($probed_contact["notify"] != "") {
448 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
449 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
452 // Send a salmon notification to every person we mentioned in the post
453 $arr = explode(',',$target_item['tag']);
454 foreach ($arr as $x) {
455 //logger('Checking tag '.$x, LOGGER_DEBUG);
457 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
458 $probed_contact = Probe::uri($matches[1]);
459 if ($probed_contact["notify"] != "") {
460 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
461 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
466 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
467 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
469 $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
472 $public_message = false;
475 // If this is a public message and pubmail is set on the parent, include all your email contacts
477 $mail_disabled = ((function_exists('imap_open') && (!Config::get('system','imap_disabled'))) ? 0 : 1);
479 if (! $mail_disabled) {
480 if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
481 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
482 && (intval($target_item['pubmail']))) {
483 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
487 if (dbm::is_result($r)) {
488 foreach ($r as $rr) {
489 $recipients[] = $rr['id'];
496 $recip_str = implode(', ', $recipients_followup);
498 $recip_str = implode(', ', $recipients);
501 $r = $recipients_relocate;
503 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
504 WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
511 if (dbm::is_result($r)) {
512 foreach ($r as $contact) {
513 if ($contact['self']) {
516 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
518 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
519 'delivery', $cmd, $item_id, (int)$contact['id']);
523 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
524 // They are especially used for notifications to OStatus users that don't follow us.
526 if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
527 if (!Config::get('system','dfrn_only')) {
528 foreach ($url_recipients as $url) {
530 logger('notifier: urldelivery: ' . $url);
531 $deliver_status = slapper($owner,$url,$slap);
532 /// @TODO Redeliver/queue these items on failure, though there is no contact record
539 if ($public_message) {
544 if ($diaspora_delivery) {
546 $r0 = Diaspora::relay_list();
549 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
550 FROM `contact` WHERE `network` = '%s' AND `batch` != ''
551 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
552 dbesc(NETWORK_DIASPORA),
553 intval($owner['uid']),
554 intval(CONTACT_IS_SHARING)
558 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
559 WHERE `network` in ('%s', '%s') AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `rel` != %d",
561 dbesc(NETWORK_MAIL2),
562 intval($owner['uid']),
563 intval(CONTACT_IS_SHARING)
566 $r = array_merge($r2,$r1,$r0);
568 if (dbm::is_result($r)) {
569 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
571 foreach ($r as $rr) {
573 // except for Diaspora batch jobs
574 // Don't deliver to folks who have already been delivered to
576 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
577 logger('notifier: already delivered id=' . $rr['id']);
581 if ((! $mail) && (! $fsuggest) && (! $followup)) {
582 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
583 Worker::add(array('priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true),
584 'delivery', $cmd, $item_id, (int)$rr['id']);
593 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
595 // Set push flag for PuSH subscribers to this topic,
596 // they will be notified in queue.php
597 q("UPDATE `push_subscriber` SET `push` = 1 ".
598 "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
600 logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
602 // Handling the pubsubhubbub requests
603 Worker::add(array('priority' => PRIORITY_HIGH, 'created' => $a->queue['created'], 'dont_fork' => true),
607 logger('notifier: calling hooks', LOGGER_DEBUG);
610 call_hooks('notifier_normal',$target_item);
613 call_hooks('notifier_end',$target_item);