3 require_once("boot.php");
4 require_once('include/queue_fn.php');
7 * This file was at one time responsible for doing all deliveries, but this caused
8 * big problems on shared hosting systems, where the process might get killed by the
9 * hosting provider and nothing would get delivered.
10 * It now only delivers one message under certain cases, and invokes a queued
11 * delivery mechanism (include/deliver.php) to deliver individual contacts at
12 * controlled intervals.
13 * This has a much better chance of surviving random processes getting killed
14 * by the hosting provider.
15 * A lot of this code is duplicated in include/deliver.php until we have time to go back
16 * and re-structure the delivery procedure based on the obstacles that have been thrown at
17 * us by hosting providers.
20 function notifier_run($argv, $argc){
28 @include(".htconfig.php");
29 require_once("dba.php");
30 $db = new dba($db_host, $db_user, $db_pass, $db_data);
31 unset($db_host, $db_user, $db_pass, $db_data);
34 require_once("session.php");
35 require_once("datetime.php");
36 require_once('include/items.php');
37 require_once('include/bbcode.php');
39 load_config('config');
40 load_config('system');
47 $a->set_baseurl(get_config('system','url'));
49 logger('notifier: invoked: ' . print_r($argv,true));
56 $item_id = intval($argv[2]);
67 $recipients = array();
68 $url_recipients = array();
75 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
78 if(! count($message)){
81 $uid = $message[0]['uid'];
82 $recipients[] = $message[0]['contact-id'];
86 elseif($cmd === 'expire') {
89 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
90 AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
98 elseif($cmd === 'suggest') {
102 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
105 if(! count($suggest))
107 $uid = $suggest[0]['uid'];
108 $recipients[] = $suggest[0]['cid'];
114 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
118 if((! count($r)) || (! intval($r[0]['parent']))) {
122 $target_item = $r[0];
123 $parent_id = intval($r[0]['parent']);
125 $updated = $r[0]['edited'];
130 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
131 FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d ORDER BY `id` ASC",
135 if(! count($items)) {
139 // avoid race condition with deleting entries
141 if($items[0]['deleted']) {
142 foreach($items as $item)
143 $item['deleted'] = 1;
146 if((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
147 logger('notifier: top level post');
153 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
154 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
155 `user`.`page-flags`, `user`.`prvnets`
156 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid`
157 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
166 $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
168 $hub = get_config('system','huburl');
170 // If this is a public conversation, notify the feed hub
171 $public_message = true;
173 // fill this in with a single salmon slap if applicable
176 if(! ($mail || $fsuggest)) {
178 require_once('include/group.php');
182 // This is IMPORTANT!!!!
184 // We will only send a "notify owner to relay" or followup message if the referenced post
185 // originated on our system by virtue of having our hostname somewhere
186 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
188 // if $parent['wall'] == 1 we will already have the parent message in our array
189 // and we will relay the whole lot.
191 // expire sends an entire group of expire messages and cannot be forwarded.
192 // However the conversation owner will be a part of the conversation and will
193 // be notified during this run.
194 // Other DFRN conversation members will be alerted during polled updates.
198 // Diaspora members currently are not notified of expirations, and other networks have
199 // either limited or no ability to process deletions. We should at least fix Diaspora
200 // by stringing togther an array of retractions and sending them onward.
203 $localhost = $a->get_hostname();
204 if(strpos($localhost,':'))
205 $localhost = substr($localhost,0,strpos($localhost,':'));
209 * Be VERY CAREFUL if you make any changes to the following lines. Seemingly innocuous changes
210 * have been known to cause runaway conditions which affected several servers, along with
211 * permissions issues.
215 $relay_to_owner = false;
217 if((! $top_level) && ($parent['wall'] == 0) && (! $expire) && (stristr($target_item['uri'],$localhost))) {
218 $relay_to_owner = true;
222 if($relay_to_owner) {
223 logger('notifier: followup', LOGGER_DEBUG);
224 // local followup to remote post
226 $public_message = false; // not public
227 $conversant_str = dbesc($parent['contact-id']);
232 // don't send deletions onward for other people's stuff
234 if($target_item['deleted'] && (! intval($target_item['wall']))) {
235 logger('notifier: ignoring delete notification for non-wall item');
239 if((strlen($parent['allow_cid']))
240 || (strlen($parent['allow_gid']))
241 || (strlen($parent['deny_cid']))
242 || (strlen($parent['deny_gid']))) {
243 $public_message = false; // private recipients, not public
246 $allow_people = expand_acl($parent['allow_cid']);
247 $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
248 $deny_people = expand_acl($parent['deny_cid']);
249 $deny_groups = expand_groups(expand_acl($parent['deny_gid']));
251 $conversants = array();
253 foreach($items as $item) {
254 $recipients[] = $item['contact-id'];
255 $conversants[] = $item['contact-id'];
256 // pull out additional tagged people to notify (if public message)
257 if($public_message && strlen($item['inform'])) {
258 $people = explode(',',$item['inform']);
259 foreach($people as $person) {
260 if(substr($person,0,4) === 'cid:') {
261 $recipients[] = intval(substr($person,4));
262 $conversants[] = intval(substr($person,4));
265 $url_recipients[] = substr($person,4);
271 logger('notifier: url_recipients' . print_r($url_recipients,true));
273 $conversants = array_unique($conversants);
276 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
277 $deny = array_unique(array_merge($deny_people,$deny_groups));
278 $recipients = array_diff($recipients,$deny);
280 $conversant_str = dbesc(implode(', ',$conversants));
283 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
289 $feed_template = get_markup_template('atom_feed.tpl');
290 $mail_template = get_markup_template('atom_mail.tpl');
295 $hubxml = feed_hublinks();
297 $birthday = feed_birthday($owner['uid'],$owner['timezone']);
299 if(strlen($birthday))
300 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
302 $atom .= replace_macros($feed_template, array(
303 '$version' => xmlify(FRIENDIKA_VERSION),
304 '$feed_id' => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
305 '$feed_title' => xmlify($owner['name']),
306 '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
308 '$salmon' => '', // private feed, we don't use salmon here
309 '$name' => xmlify($owner['name']),
310 '$profile_page' => xmlify($owner['url']),
311 '$photo' => xmlify($owner['photo']),
312 '$thumb' => xmlify($owner['thumb']),
313 '$picdate' => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
314 '$uridate' => xmlify(datetime_convert('UTC','UTC',$owner['uri-date'] . '+00:00' , ATOM_TIME)) ,
315 '$namdate' => xmlify(datetime_convert('UTC','UTC',$owner['name-date'] . '+00:00' , ATOM_TIME)) ,
316 '$birthday' => $birthday
320 $public_message = false; // mail is not public
322 $body = fix_private_photos($item['body'],$owner['uid']);
324 $atom .= replace_macros($mail_template, array(
325 '$name' => xmlify($owner['name']),
326 '$profile_page' => xmlify($owner['url']),
327 '$thumb' => xmlify($owner['thumb']),
328 '$item_id' => xmlify($item['uri']),
329 '$subject' => xmlify($item['title']),
330 '$created' => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
331 '$content' => xmlify($body),
332 '$parent_id' => xmlify($item['parent-uri'])
336 $public_message = false; // suggestions are not public
338 $sugg_template = get_markup_template('atom_suggest.tpl');
340 $atom .= replace_macros($sugg_template, array(
341 '$name' => xmlify($item['name']),
342 '$url' => xmlify($item['url']),
343 '$photo' => xmlify($item['photo']),
344 '$request' => xmlify($item['request']),
345 '$note' => xmlify($item['note'])
348 // We don't need this any more
350 q("DELETE FROM `fsuggest` WHERE `id` = %d LIMIT 1",
357 foreach($items as $item) { // there is only one item
358 if(! $item['parent'])
360 if($item['id'] == $item_id) {
361 logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
362 $slap = atom_entry($item,'html',$owner,$owner,false);
363 $atom .= atom_entry($item,'text',$owner,$owner,false);
368 foreach($items as $item) {
370 if(! $item['parent'])
373 // private emails may be in included in public conversations. Filter them.
375 if(($public_message) && $item['private'])
379 $contact = get_item_contact($item,$contacts);
386 // we only need the current item, but include the parent because without it
387 // older sites without a corresponding dfrn_notify change may do the wrong thing.
389 if($item_id == $item['id'] || $item['id'] == $item['parent'])
390 $atom .= atom_entry($item,'text',$contact,$owner,true);
393 $atom .= atom_entry($item,'text',$contact,$owner,true);
395 if(($top_level) && ($public_message) && ($item['author-link'] === $item['owner-link']) && (! $expire))
396 $slaps[] = atom_entry($item,'html',$contact,$owner,true);
400 $atom .= '</feed>' . "\r\n";
402 logger('notifier: ' . $atom, LOGGER_DATA);
404 logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
406 // If this is a public message and pubmail is set on the parent, include all your email contacts
408 $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
410 if(! $mail_disabled) {
411 if((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
412 && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
413 && (intval($target_item['pubmail']))) {
414 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
420 $recipients[] = $rr['id'];
426 $recip_str = $parent['contact-id'];
428 $recip_str = implode(', ', $recipients);
430 $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
435 require_once('include/salmon.php');
437 $interval = ((get_config('system','delivery_interval') === false) ? 2 : intval(get_config('system','delivery_interval')));
443 foreach($r as $contact) {
444 if((! $mail) && (! $fsuggest) && (! $followup) && (! $contact['self'])) {
445 if(($contact['network'] === NETWORK_DIASPORA) && ($public_message))
447 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
450 intval($contact['id'])
455 foreach($r as $contact) {
459 // potentially more than one recipient. Start a new process and space them out a bit.
460 // we will deliver single recipient types of message and email receipients here.
462 if((! $mail) && (! $fsuggest) && (! $followup)) {
463 proc_run('php','include/delivery.php',$cmd,$item_id,$contact['id']);
465 @time_sleep_until(microtime(true) + (float) $interval);
471 logger("main delivery by notifier: followup=$followup mail=$mail fsuggest=$fsuggest");
473 switch($contact['network']) {
476 // perform local delivery if we are on the same site
478 $basepath = implode('/', array_slice(explode('/',$contact['url']),0,3));
480 if(link_compare($basepath,$a->get_baseurl())) {
482 $nickname = basename($contact['url']);
483 if($contact['issued-id'])
484 $sql_extra = sprintf(" AND `dfrn-id` = '%s' ", dbesc($contact['issued-id']));
486 $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($contact['dfrn-id']));
488 $x = q("SELECT `contact`.*, `contact`.`uid` AS `importer_uid`,
489 `contact`.`pubkey` AS `cpubkey`,
490 `contact`.`prvkey` AS `cprvkey`,
491 `contact`.`thumb` AS `thumb`,
492 `contact`.`url` as `url`,
493 `contact`.`name` as `senderName`,
496 LEFT JOIN `user` ON `contact`.`uid` = `user`.`uid`
497 WHERE `contact`.`blocked` = 0 AND `contact`.`pending` = 0
498 AND `contact`.`network` = '%s' AND `user`.`nickname` = '%s'
500 AND `user`.`account_expired` = 0 LIMIT 1",
506 require_once('library/simplepie/simplepie.inc');
507 logger('mod-delivery: local delivery');
508 local_delivery($x[0],$atom);
515 logger('notifier: dfrndelivery: ' . $contact['name']);
516 $deliver_status = dfrn_deliver($owner,$contact,$atom);
518 logger('notifier: dfrn_delivery returns ' . $deliver_status);
520 if($deliver_status == (-1)) {
521 logger('notifier: delivery failed: queuing message');
522 // queue message for redelivery
523 add_to_queue($contact['id'],NETWORK_DFRN,$atom);
526 case NETWORK_OSTATUS:
528 // Do not send to otatus if we are not configured to send to public networks
529 if($owner['prvnets'])
531 if(get_config('system','ostatus_disabled') || get_config('system','dfrn_only'))
534 if($followup && $contact['notify']) {
535 logger('notifier: slapdelivery: ' . $contact['name']);
536 $deliver_status = slapper($owner,$contact['notify'],$slap);
538 if($deliver_status == (-1)) {
539 // queue message for redelivery
540 add_to_queue($contact['id'],NETWORK_OSTATUS,$slap);
545 // only send salmon if public - e.g. if it's ok to notify
546 // a public hub, it's ok to send a salmon
548 if((count($slaps)) && ($public_message) && (! $expire)) {
549 logger('notifier: slapdelivery: ' . $contact['name']);
550 foreach($slaps as $slappy) {
551 if($contact['notify']) {
552 $deliver_status = slapper($owner,$contact['notify'],$slappy);
553 if($deliver_status == (-1)) {
554 // queue message for redelivery
555 add_to_queue($contact['id'],NETWORK_OSTATUS,$slappy);
565 if(get_config('system','dfrn_only'))
568 // WARNING: does not currently convert to RFC2047 header encodings, etc.
570 $addr = $contact['addr'];
574 if($cmd === 'wall-new' || $cmd === 'comment-new') {
577 if($cmd === 'wall-new')
580 $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
592 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
595 if(! count($local_user))
599 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
602 if($r1 && $r1[0]['reply_to'])
603 $reply_to = $r1[0]['reply_to'];
605 $subject = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
606 $headers = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
609 $headers .= 'Reply-to: ' . $reply_to . "\n";
611 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
613 if($it['uri'] !== $it['parent-uri']) {
614 $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
615 if(! strlen($it['title'])) {
616 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
617 dbesc($it['parent-uri'])
620 $subtitle = $r[0]['title'];
622 if(strncasecmp($subtitle,'RE:',3))
623 $subject = $subtitle;
625 $subject = 'Re: ' . $subtitle;
631 $headers .= 'MIME-Version: 1.0' . "\n";
632 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
633 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
634 $html = prepare_body($it);
635 $message = '<html><body>' . $html . '</body></html>';
636 logger('notifier: email delivery to ' . $addr);
637 mail($addr, $subject, $message, $headers);
640 case NETWORK_DIASPORA:
641 require_once('include/diaspora.php');
643 if(get_config('system','dfrn_only') || (! get_config('system','diaspora_enabled')) || (! $normal_mode))
646 // special handling for followup to public post
647 // all other public posts processed as public batches further below
649 if($public_message) {
651 diaspora_send_followup($target_item,$owner,$contact, true);
655 if(! $contact['pubkey'])
658 if($target_item['verb'] === ACTIVITY_DISLIKE) {
662 elseif(($target_item['deleted']) && ($target_item['verb'] !== ACTIVITY_LIKE)) {
664 diaspora_send_retraction($target_item,$owner,$contact);
668 // send comments, likes and retractions of likes to owner to relay
669 diaspora_send_followup($target_item,$owner,$contact);
672 elseif($target_item['parent'] != $target_item['id']) {
673 // we are the relay - send comments, likes and unlikes to our conversants
674 diaspora_send_relay($target_item,$owner,$contact);
677 elseif(($top_level) && (! $walltowall)) {
678 // currently no workable solution for sending walltowall
679 diaspora_send_status($target_item,$owner,$contact);
686 case NETWORK_FACEBOOK:
687 if(get_config('system','dfrn_only'))
695 // send additional slaps to mentioned remote tags (@foo@example.com)
697 if($slap && count($url_recipients) && ($followup || $top_level) && $public_message && (! $expire)) {
698 if(! get_config('system','dfrn_only')) {
699 foreach($url_recipients as $url) {
701 logger('notifier: urldelivery: ' . $url);
702 $deliver_status = slapper($owner,$url,$slap);
703 // TODO: redeliver/queue these items on failure, though there is no contact record
710 if($public_message) {
712 $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
713 AND `uid` = %d AND `rel` != %d ORDER BY rand() ",
714 dbesc(NETWORK_DIASPORA),
715 intval($owner['uid']),
716 intval(CONTACT_IS_SHARING)
719 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
720 WHERE `network` = '%s' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0
721 AND `rel` != %d order by rand() ",
723 intval($owner['uid']),
724 intval(CONTACT_IS_SHARING)
727 $r = array_merge($r2,$r1);
730 logger('pubdeliver: ' . print_r($r,true), LOGGER_DEBUG);
732 // throw everything into the queue in case we get killed
735 if((! $mail) && (! $fsuggest) && (! $followup)) {
736 q("insert into deliverq ( `cmd`,`item`,`contact` ) values ('%s', %d, %d )",
746 // except for Diaspora batch jobs
747 // Don't deliver to folks who have already been delivered to
749 if(($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
750 logger('notifier: already delivered id=' . $rr['id']);
754 if((! $mail) && (! $fsuggest) && (! $followup)) {
755 logger('notifier: delivery agent: ' . $rr['name'] . ' ' . $rr['id']);
756 proc_run('php','include/delivery.php',$cmd,$item_id,$rr['id']);
758 @time_sleep_until(microtime(true) + (float) $interval);
765 $hubs = explode(',', $hub);
767 foreach($hubs as $h) {
771 $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
772 post_url($h,$params);
773 logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
775 sleep(7); // try and avoid multiple hubs responding at precisely the same time
783 call_hooks('notifier_normal',$target_item);
785 call_hooks('notifier_end',$target_item);
790 if (array_search(__file__,get_included_files())===0){
791 notifier_run($argv,$argc);