3 require_once("boot.php");
6 * This file was at one time responsible for doing all deliveries, but this caused
7 * big problems on shared hosting systems, where the process might get killed by the
8 * hosting provider and nothing would get delivered.
9 * It now only delivers one message under certain cases, and invokes a queued
10 * delivery mechanism (include/deliver.php) to deliver individual contacts at
11 * controlled intervals.
12 * This has a much better chance of surviving random processes getting killed
13 * by the hosting provider.
14 * A lot of this code is duplicated in include/deliver.php until we have time to go back
15 * and re-structure the delivery procedure based on the obstacles that have been thrown at
16 * us by hosting providers.
19 function notifier_run($argv, $argc){
27 @include(".htconfig.php");
28 require_once("dba.php");
29 $db = new dba($db_host, $db_user, $db_pass, $db_data);
30 unset($db_host, $db_user, $db_pass, $db_data);
33 require_once("session.php");
34 require_once("datetime.php");
35 require_once('include/items.php');
36 require_once('include/bbcode.php');
38 load_config('config');
39 load_config('system');
46 $a->set_baseurl(get_config('system','url'));
48 logger('notifier: invoked: ' . print_r($argv,true));
55 $item_id = intval($argv[2]);
66 $recipients = array();
67 $url_recipients = array();
74 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
77 if(! count($message)){
80 $uid = $message[0]['uid'];
81 $recipients[] = $message[0]['contact-id'];
85 elseif($cmd === 'expire') {
88 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
89 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
97 elseif($cmd === 'suggest') {
101 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
104 if(! count($suggest))
106 $uid = $suggest[0]['uid'];
107 $recipients[] = $suggest[0]['cid'];
113 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
117 if((! count($r)) || (! intval($r[0]['parent']))) {
121 $target_item = $r[0];
122 $parent_id = intval($r[0]['parent']);
124 $updated = $r[0]['edited'];
129 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
130 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d ORDER BY `id` ASC",
134 if(! count($items)) {
138 // avoid race condition with deleting entries
140 if($items[0]['deleted']) {
141 foreach($items as $item)
142 $item['deleted'] = 1;
145 if((count($items) == 1) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
146 logger('notifier: top level post');
152 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
153 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
154 `user`.`page-flags`, `user`.`prvnets`
155 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
156 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
165 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
167 $hub = get_config('system','huburl');
169 // If this is a public conversation, notify the feed hub
170 $public_message = true;
172 // fill this in with a single salmon slap if applicable
175 if(! ($mail || $fsuggest)) {
177 require_once('include/group.php');
181 // This is IMPORTANT!!!!
183 // We will only send a "notify owner to relay" or followup message if the referenced post
184 // originated on our system by virtue of having our hostname somewhere
185 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
187 // if $parent['wall'] == 1 we will already have the parent message in our array
188 // and we will relay the whole lot.
190 // expire sends an entire group of expire messages and cannot be forwarded.
191 // However the conversation owner will be a part of the conversation and will
192 // be notified during this run.
193 // Other DFRN conversation members will be alerted during polled updates.
197 // Diaspora members currently are not notified of expirations, and other networks have
198 // either limited or no ability to process deletions. We should at least fix Diaspora
199 // by stringing togther an array of retractions and sending them onward.
202 $localhost = $a->get_hostname();
203 if(strpos($localhost,':'))
204 $localhost = substr($localhost,0,strpos($localhost,':'));
208 * Be VERY CAREFUL if you make any changes to the following line. Seemingly innocuous changes
209 * have been known to cause runaway conditions which affected several servers, along with
210 * permissions issues.
214 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
215 logger('notifier: followup', LOGGER_DEBUG);
216 // local followup to remote post
218 $public_message = false; // not public
219 $conversant_str = dbesc($parent['contact-id']);
224 // don't send deletions onward for other people's stuff
226 if($target_item['deleted'] && (! intval($target_item['wall']))) {
227 logger('notifier: ignoring delete notification for non-wall item');
231 if((strlen($parent['allow_cid']))
232 || (strlen($parent['allow_gid']))
233 || (strlen($parent['deny_cid']))
234 || (strlen($parent['deny_gid']))) {
235 $public_message = false; // private recipients, not public
238 $allow_people = expand_acl($parent['allow_cid']);
239 $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
240 $deny_people = expand_acl($parent['deny_cid']);
241 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
243 $conversants = array();
245 foreach($items as $item) {
246 $recipients[] = $item['contact-id'];
247 $conversants[] = $item['contact-id'];
248 // pull out additional tagged people to notify (if public message)
249 if($public_message && strlen($item['inform'])) {
250 $people = explode(',',$item['inform']);
251 foreach($people as $person) {
252 if(substr($person,0,4) === 'cid:') {
253 $recipients[] = intval(substr($person,4));
254 $conversants[] = intval(substr($person,4));
257 $url_recipients[] = substr($person,4);
263 logger('notifier: url_recipients' . print_r($url_recipients,true));
265 $conversants = array_unique($conversants);
268 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
269 $deny = array_unique(array_merge($deny_people,$deny_groups));
270 $recipients = array_diff($recipients,$deny);
272 $conversant_str = dbesc(implode(', ',$conversants));
275 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
281 $feed_template = get_markup_template('atom_feed.tpl');
282 $mail_template = get_markup_template('atom_mail.tpl');
287 $hubxml = feed_hublinks();
289 $birthday = feed_birthday($owner['uid'],$owner['timezone']);
291 if(strlen($birthday))
292 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
294 $atom .= replace_macros($feed_template, array(
295 '$version' => xmlify(FRIENDIKA_VERSION),
296 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
297 '$feed_title' => xmlify($owner['name']),
298 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
300 '$salmon' => '', // private feed, we don't use salmon here
301 '$name' => xmlify($owner['name']),
302 '$profile_page' => xmlify($owner['url']),
303 '$photo' => xmlify($owner['photo']),
304 '$thumb' => xmlify($owner['thumb']),
305 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
306 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
307 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
308 '$birthday' => $birthday
312 $public_message = false; // mail is not public
314 $body = fix_private_photos($item['body'],$owner['uid']);
316 $atom .= replace_macros($mail_template, array(
317 '$name' => xmlify($owner['name']),
318 '$profile_page' => xmlify($owner['url']),
319 '$thumb' => xmlify($owner['thumb']),
320 '$item_id' => xmlify($item['uri']),
321 '$subject' => xmlify($item['title']),
322 '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
323 '$content' => xmlify($body),
324 '$parent_id' => xmlify($item['parent-uri'])
328 $public_message = false; // suggestions are not public
330 $sugg_template = get_markup_template('atom_suggest.tpl');
332 $atom .= replace_macros($sugg_template, array(
333 '$name' => xmlify($item['name']),
334 '$url' => xmlify($item['url']),
335 '$photo' => xmlify($item['photo']),
336 '$request' => xmlify($item['request']),
337 '$note' => xmlify($item['note'])
340 // We don't need this any more
342 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
349 foreach($items as $item) { // there is only one item
350 if(! $item['parent'])
352 if($item['id'] == $item_id) {
353 logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
354 $slap = atom_entry($item,'html',$owner,$owner,false);
355 $atom .= atom_entry($item,'text',$owner,$owner,false);
360 foreach($items as $item) {
362 if(! $item['parent'])
365 // private emails may be in included in public conversations. Filter them.
367 if(($public_message) && $item['private'])
371 $contact = get_item_contact($item,$contacts);
378 // we only need the current item, but include the parent because without it
379 // older sites without a corresponding dfrn_notify change may do the wrong thing.
381 if($item_id == $item['id'] || $item['id'] == $item['parent'])
382 $atom .= atom_entry($item,'text',$contact,$owner,true);
385 $atom .= atom_entry($item,'text',$contact,$owner,true);
387 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
388 $slaps[] = atom_entry($item,'html',$contact,$owner,true);
392 $atom .= '</feed>' . "\r\n";
394 logger('notifier: ' . $atom, LOGGER_DATA);
396 logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
398 // If this is a public message and pubmail is set on the parent, include all your email contacts
400 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
402 if(! $mail_disabled) {
403 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
404 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
405 && (intval($target_item['pubmail']))) {
406 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
412 $recipients[] = $rr['id'];
418 $recip_str = $parent['contact-id'];
420 $recip_str = implode(', ', $recipients);
422 $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
427 require_once('include/salmon.php');
429 $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
435 foreach($r as $contact) {
436 if((! $mail) && (! $fsuggest) && (! $followup) && (! $contact['self'])) {
437 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
439 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
442 intval($contact['id'])
447 foreach($r as $contact) {
451 // potentially more than one recipient. Start a new process and space them out a bit.
452 // we will deliver single recipient types of message and email receipients here.
454 if((! $mail) && (! $fsuggest) && (! $followup)) {
455 proc_run('php','include/delivery.php',$cmd,$item_id,$contact['id']);
457 @time_sleep_until(microtime(true) + (float) $interval);
463 logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest");
465 switch($contact['network']) {
468 // perform local delivery if we are on the same site
470 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
472 if(link_compare($basepath,$a->get_baseurl())) {
474 $nickname = basename($contact['url']);
475 if($contact['issued-id'])
476 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
478 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
480 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
481 `contact`.`pubkey` AS `cpubkey`,
482 `contact`.`prvkey` AS `cprvkey`,
483 `contact`.`thumb` AS `thumb`,
484 `contact`.`url` as `url`,
485 `contact`.`name` as `senderName`,
488 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
489 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
490 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
492 AND `user`.`account_expired` = 0 LIMIT 1",
498 require_once('library/simplepie/simplepie.inc');
499 logger('mod-delivery: local delivery');
500 local_delivery($x[0],$atom);
507 logger('notifier: dfrndelivery: ' . $contact['name']);
508 $deliver_status = dfrn_deliver($owner,$contact,$atom);
510 logger('notifier: dfrn_delivery returns ' . $deliver_status);
512 if($deliver_status == (-1)) {
513 logger('notifier: delivery failed: queuing message');
514 // queue message for redelivery
515 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
516 VALUES ( %d, '%s', '%s', '%s') ",
517 intval($contact['id']),
518 dbesc(datetime_convert()),
519 dbesc(datetime_convert()),
524 case NETWORK_OSTATUS:
526 // Do not send to otatus if we are not configured to send to public networks
527 if($owner['prvnets'])
529 if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
532 if($followup && $contact['notify']) {
533 logger('notifier: slapdelivery: ' . $contact['name']);
534 $deliver_status = slapper($owner,$contact['notify'],$slap);
536 if($deliver_status == (-1)) {
537 // queue message for redelivery
538 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
539 VALUES ( %d, '%s', '%s', '%s') ",
540 intval($contact['id']),
541 dbesc(datetime_convert()),
542 dbesc(datetime_convert()),
550 // only send salmon if public - e.g. if it's ok to notify
551 // a public hub, it's ok to send a salmon
553 if((count($slaps)) && ($public_message) && (! $expire)) {
554 logger('notifier: slapdelivery: ' . $contact['name']);
555 foreach($slaps as $slappy) {
556 if($contact['notify']) {
557 $deliver_status = slapper($owner,$contact['notify'],$slappy);
558 if($deliver_status == (-1)) {
559 // queue message for redelivery
560 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
561 VALUES ( %d, '%s', '%s', '%s') ",
562 intval($contact['id']),
563 dbesc(datetime_convert()),
564 dbesc(datetime_convert()),
576 if(get_config('system','dfrn_only'))
579 // WARNING: does not currently convert to RFC2047 header encodings, etc.
581 $addr = $contact['addr'];
585 if($cmd === 'wall-new' || $cmd === 'comment-new') {
588 if($cmd === 'wall-new')
591 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
603 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
606 if(! count($local_user))
610 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
613 if($r1 && $r1[0]['reply_to'])
614 $reply_to = $r1[0]['reply_to'];
616 $subject = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
617 $headers = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
620 $headers .= 'Reply-to: ' . $reply_to . "\n";
622 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
624 if($it['uri'] !== $it['parent-uri']) {
625 $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
626 if(! strlen($it['title'])) {
627 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
628 dbesc($it['parent-uri'])
631 $subtitle = $r[0]['title'];
633 if(strncasecmp($subtitle,'RE:',3))
634 $subject = $subtitle;
636 $subject = 'Re: ' . $subtitle;
642 $headers .= 'MIME-Version: 1.0' . "\n";
643 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
644 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
645 $html = prepare_body($it);
646 $message = '<html><body>' . $html . '</body></html>';
647 logger('notifier: email delivery to ' . $addr);
648 mail($addr, $subject, $message, $headers);
651 case NETWORK_DIASPORA:
652 require_once('include/diaspora.php');
654 if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
657 // special handling for followup to public post
658 // all other public posts processed as public batches further below
660 if($public_message) {
662 diaspora_send_followup($target_item,$owner,$contact, true);
666 if(! $contact['pubkey'])
669 if($target_item['verb'] === ACTIVITY_DISLIKE) {
673 elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
675 diaspora_send_retraction($target_item,$owner,$contact);
679 // send comments, likes and retractions of likes to owner to relay
680 diaspora_send_followup($target_item,$owner,$contact);
683 elseif($target_item['parent'] != $target_item['id']) {
684 // we are the relay - send comments, likes and unlikes to our conversants
685 diaspora_send_relay($target_item,$owner,$contact);
688 elseif(($top_level) && (! $walltowall)) {
689 // currently no workable solution for sending walltowall
690 diaspora_send_status($target_item,$owner,$contact);
697 case NETWORK_FACEBOOK:
698 if(get_config('system','dfrn_only'))
706 // send additional slaps to mentioned remote tags (@foo@example.com)
708 if($slap && count($url_recipients) && ($followup || $top_level) && $public_message && (! $expire)) {
709 if(! get_config('system','dfrn_only')) {
710 foreach($url_recipients as $url) {
712 logger('notifier: urldelivery: ' . $url);
713 $deliver_status = slapper($owner,$url,$slap);
714 // TODO: redeliver/queue these items on failure, though there is no contact record
721 if($public_message) {
723 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
724 AND `uid` = %d AND `rel` != %d ORDER BY rand() ",
725 dbesc(NETWORK_DIASPORA),
726 intval($owner['uid']),
727 intval(CONTACT_IS_SHARING)
730 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
731 WHERE `network` = '%s' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0
732 AND `rel` != %d order by rand() ",
734 intval($owner['uid']),
735 intval(CONTACT_IS_SHARING)
738 $r = array_merge($r2,$r1);
741 logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
743 // throw everything into the queue in case we get killed
746 if((! $mail) && (! $fsuggest) && (! $followup)) {
747 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
757 // except for Diaspora batch jobs
758 // Don't deliver to folks who have already been delivered to
760 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
761 logger('notifier: already delivered id=' . $rr['id']);
765 if((! $mail) && (! $fsuggest) && (! $followup)) {
766 logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
767 proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
769 @time_sleep_until(microtime(true) + (float) $interval);
776 $hubs = explode(',', $hub);
778 foreach($hubs as $h) {
782 $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
783 post_url($h,$params);
784 logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
786 sleep(7); // try and avoid multiple hubs responding at precisely the same time
794 call_hooks('notifier_normal',$target_item);
796 call_hooks('notifier_end',$target_item);
802 if (array_search(__file__,get_included_files())===0){
803 notifier_run($argv,$argc);