<?php 
/* Variables that determine server, channel, etc */
$CONFIG = array();
$CONFIG['server'] = '127.0.0.1'// server (i.e. 127.0.0.1 if using localhost)
$CONFIG['nick'] = 'rosie'// nick (i.e. username used to loginto bitlbee)
$CONFIG['port'] = 6667// port (standard: 6667)
$CONFIG['channel'] = ''// leave this as it is
$CONFIG['name'] = 'rosie'// bot name
$CONFIG['msg_folder'] = '/var/spool/bitlbee/outgoing/'// folder for messages to rosie
$CONFIG['sent_folder'] = '/var/spool/bitlbee/sent/'// folder for messages to rosie
$CONFIG['recipients'] = array(); // just some default array without content

/* Let it run forever (no timeouts) */
set_time_limit(0);

/* The connection */
$con = array();

/* start the bot... */
init();

function 
init()
{
    global 
$con$CONFIG;
    
/* We need this to see if we need to JOIN (the channel) during
       the first iteration of the main loop */
    
$firstTime true;

    
/* Connect to the irc server */
    
$con['socket'] = fsockopen($CONFIG['server'], $CONFIG['port']);

    
/* Check that we have connected */
    
if (!$con['socket']) {
        print (
"Could not connect to: "$CONFIG['server'] ." on port "$CONFIG['port']);
    } else {

        
/* Send the username and nick */
        
cmd_send("USER "$CONFIG['nick'] ." rosie rosie.cego.dk :"$CONFIG['name']);
        
cmd_send("NICK "$CONFIG['nick'] ." cego.dk");

        
/* Set stream timeout so we can check for new files too */
        
stream_set_timeout($con['socket'],2);

        
/* Here is the loop. Read the incoming data (from the socket connection) */
        
while (true) {
            
$con['buffer']['all'] = trim(fgets($con['socket'], 4096));
            if (
$con['buffer']['all'] != '') {
                
/* Think of $con['buffer']['all'] as a line of chat messages.
                   We are getting a 'line' and getting rid of whitespace around it. */
                
log_to_file($con['buffer']['all']);

                
/* Pring the line/buffer to the console
                   I used &lt;- to identify incoming data, -&gt; for outgoing. This is so that
                   you can identify messages that appear in the console. */
                
print date('[d/m @ H:i]').'<- '.$con['buffer']['all'] ."\n";

                
/* Update all active users */
                
if (preg_match("/^:[a-z0-9\.\-_]+ 353 ".$CONFIG['nick']." = &bitlbee :(.+)$/i",$con['buffer']['all'],$match)) {
                    
$users preg_split("/ /",$match[1]);

                    
// reset recipients array
                    
$CONFIG['recipients'] = array();
                    foreach(
$users as $user) {
                        
$user preg_replace("/^[+\-@]/","",$user);
                        if (
$user != 'root' && $user != $CONFIG['nick'])
                            
$CONFIG['recipients'][] = $user;
                    }
                }

                
/* Flag if we are logged in */
                
if (preg_match("/Logging in: Logged in$/",$con['buffer']['all'])) {
                    
$con['logged_in'] = 1;
                }

                
/* If we have triggered a reply next message */
                
if (isset($con['reply_next'])) {
                    
cmd_send('PRIVMSG '.$con['last_username'].' :'.$con['buffer']['all']);
                    unset(
$con['reply_next']);
                    unset(
$con['last_username']);
                }

                
/* If the server is PINGing, then PONG. This is to tell the server that
                   we are still here, and have not lost the connection */
                
if (substr($con['buffer']['all'], 06) == 'PING :') {
                    
/* PONG : is followed by the line that the server
                       sent us when PINGing */
                    
cmd_send('PONG :'.substr($con['buffer']['all'], 6));
                    
/* If this is the first time we have reached this point,
                       then JOIN the channel */
                    
if ($firstTime == true){
                        
cmd_send("JOIN "$CONFIG['channel']);
                        
/* The next time we get here, it will NOT be the firstTime */
                        
$firstTime false;
                    }
                    
/* Make sure that we have a NEW line of chats to analyse. If we don't,
                       there is no need to parse the data again */
                
} elseif (isset($old_buffer) && $old_buffer != $con['buffer']['all']) {
                    
/* Determine the patterns to be passed
                       to parse_buffer(). buffer is in the form:
                       :username!~identd@hostname JOIN :#php
                       :username!~identd@hostname PRIVMSG #PHP :action text
                       :username!~identd@hostname command channel :text */
                    // log the buffer to "log.txt" (file must have
                    // already been created).
                    //log_to_file($con['buffer']['all']);
                    // make sense of the buffer
                    
parse_buffer();
                    
// now process any commands issued to the bot
                    
process_commands();

                    
//check whether its from the root and contains the final intro message to pass identify
                    
if (isset($con['buffer']['text'])) {
                        
$find strpos($con['buffer']['text'],"If you've never used BitlBee before, please do read the help information using the");
                    } else {
                        
$find 0;
                    }
                    if(
$find !== false){
                        if(
$con['buffer']['username']== "root"){
                            
cmd_send("PRIVMSG root :identify <PASSWORD>"); // the password for your bitlbee account
                        
}
                    }
                    
//checks whether the request is to add the user to bot friend list
                    
if (isset($con['logged_in']) && isset($con['buffer']['text']) && preg_match("/(\d+), (.+): The user (.+) wants to add you to his\/her buddy list\.$/",$con['buffer']['text'])) {
                        if(
$con['buffer']['username'] == "root"){
                            
//accept the request to be friends
                            
cmd_send("PRIVMSG root :yes ".$match[1]);
                        }
                    }
                    if (isset(
$con['logged_in']) && isset($con['buffer']['text']) && preg_match("/(\d+), (.+): The user (.+) is not in your buddy list yet. Do you want to add him\/her now\?$/",$con['buffer']['text'])) {
                        if(
$con['buffer']['username'] == "root"){
                            
//accept the request to be friends
                            
cmd_send("PRIVMSG root :yes ".$match[1]);
                        }
                    }

                    
//get messaged from other users except root and add it into db only if its a private message
                    
if($con['buffer']['username'] != "root" && $con['buffer']['username'] != "" && $con['buffer']['hostname'] != "im.bitlbee.org" && $con['buffer']['private'] == true && $con['buffer']['text'] != "") {

                        
//send notification to the sender
                        
$command "PRIVMSG ".$con['buffer']['username']." : Your Message was received!";
                        
cmd_send($command);
                        
/* This is where you can write the code to update your mySQL table.
                         * $user contains the complete email address of the user who sent the message
                         * $message contains the message sent by the user
                         * All you need to do is just add them to your mySQL table.
                         */
                        
$user $con['buffer']['identd']."@".$con['buffer']['hostname'];
                        
$message $con['buffer']['text'];
                    }
                }
                if (isset(
$con['buffer']['all'])) {
                    
$old_buffer $con['buffer']['all'];
                } else {
                    
$old_buffer '';
                }
            }

            
// now process any messages issued to the nagios
            
process_messages();

            
// here we will trigger a recipient update
            
if (isset($con['logged_in']) && (!isset($last_user_update) || $last_user_update time()-60)) {
                
$last_user_update time();
                
cmd_send('NAMES');
            }
            
// here we will trigger a qlist command
            
if (isset($con['logged_in']) && (!isset($last_qlist) || $last_qlist time()-15)) {
                
$last_qlist time();
                
cmd_send('PRIVMSG root :qlist');
            }

        }
    }
}

/* Accepts the command as an argument, sends the command
   to the server, and then displays the command in the console
   for debugging */
function cmd_send($command)
{
    global 
$con$time$CONFIG;
    
/* Send the command. Think of it as writing to a file. */
    
fputs($con['socket'], $command."\n");
    
/* Display the command locally, for the sole purpose
       of checking output. (line is not actually not needed) */
    
print (date("[d/m @ H:i]") ."-> "$command"\n");
}

function 
log_to_file ($data)
{
    
$filename "log.txt";
    
$data .= "\n";
    
// open the log file
    
if ($fp fopen($filename"ab")) {
        
// now write to the file
        
if ((fwrite($fp$data) === FALSE)) {
            echo 
"Could not write to file.";
        }
    } else {
        echo 
"File could not be opened.";
    }
}

function 
process_commands()
{
    global 
$con$CONFIG;

    if (!isset(
$con['buffer']['text']))
        return;

    
/* TIME */
    
if(strtoupper($con['buffer']['text']) == '.TIME') {
        
$date_str date("F j, Y, g:i:s"time());
        
cmd_send('PRIVMSG '.$con['buffer']['username'].' :'.$date_str);

    
/* IRC COMMAND */
    
} elseif(preg_match("/^.cmd (.+)$/",$con['buffer']['text'],$match)) {
        
cmd_send(strtoupper($match[1]));

        
$con['reply_next'] = 1;
        
$con['last_username'] = $con['buffer']['username'];
    
/* PRINT RECIPIENTS */
    
} elseif(strtoupper($con['buffer']['text']) == '.USERS') {
        
cmd_send('PRIVMSG '.$con['buffer']['username'].' :Active users:');
        
cmd_send('PRIVMSG '.$con['buffer']['username'].' :'.implode(', ',$CONFIG['recipients']));
    }

}

function 
parse_buffer()
{
    
/*
       :username!~identd@hostname JOIN :#php
       :username!~identd@hostname PRIVMSG #PHP :action text
       :username!~identd@hostname command channel :text
     */
    
global $con$CONFIG;
    
$buffer $con['buffer']['all'];
    
$buffer explode(" "$buffer4);
    
//set private to false
    
$buffer['private'] = false;
    
/* Get username */
    
$buffer['username'] = substr($buffer[0], 1strpos($buffer['0'], "!")-1);
    
/* Get identd */
    
$posExcl strpos($buffer[0], "!");
    
$posAt strpos($buffer[0], "@");
    
$buffer['identd'] = substr($buffer[0], $posExcl+1$posAt-$posExcl-1);
    
$buffer['hostname'] = substr($buffer[0], strpos($buffer[0], "@")+1);
    
/* The user and the host, the whole shabang */
    
$buffer['user_host'] = substr($buffer[0],1);
    
/* Isolate the command the user is sending from
       the "general" text that is sent to the channel
       This is privmsg to the channel we are talking about.
       We also format $buffer['text'] so that it can be logged nicely.
     */

    
switch (strtoupper($buffer[1]))
    {
        case 
"PRIVMSG":
            
$buffer['command'] = $buffer[1];
            
$buffer['channel'] = $buffer[2];
            
$buffer['text'] = substr($buffer[3], 1);
            
$buffer['private'] = true//sets the message as private not a command, which should be captured
            
break;
        break;
    }
    
$con['buffer'] = $buffer;
}

function 
process_messages()
{
    global 
$con$CONFIG;

    if (!isset(
$con['logged_in']))
        return;

    
// read folder for new files
    
if (!$dh opendir($CONFIG['msg_folder']))
        die(
"Cannot read nagios folder.\n");

    
//log_to_file('Checking for new nagios messages.');
    
while ($file readdir($dh)) {

        if (
$file != '.' && $file != '..') {

            
// read file
            
if (!$fh fopen($CONFIG['msg_folder'].$file,'r'))
                die(
"Cannot read nagios input file.");

            
$content = array();
            while (!
feof($fh)) {
                
$buffer fgets($fh,1024);
                
$buffer preg_replace("/\n/","",$buffer);
                
$content[] = $buffer;
            }

            
$CONFIG['recipients'] = array('killerhollo');
            if (
count($CONFIG['recipients']) > 0) {
                foreach (
$CONFIG['recipients'] as $recipient) {
                    foreach (
$content as $e) {
                        
// send message
                        
cmd_send('PRIVMSG '.$recipient.' :'.$e);
                    }
                }
            }

            
fclose($fh);
            
// copy file
            
if (!copy($CONFIG['msg_folder'].$file,$CONFIG['sent_folder'].time().'_'.rand(1000,99999)))
                die(
'cannot copy files to sent folder.');

            
// delete file
            
if (!unlink($CONFIG['msg_folder'].$file))
                die(
'Could not delete nagios input file.');
        }
    } 
// end while loop

    
closedir($dh);
}

function 
update_recipients()
{
    global 
$con$CONFIG;
    
cmd_send('PRIVMSG root: blist');
}
?>