mixedbytes_bot.phps

#!/usr/bin/php
<?
// Torrent announcing bot v0.1 by hellfairy
error_reporting(E_ALL);
#require('./lib.php');

$bot['nick'] = 'FiTTA';
$bot['ident'] = 'biip';
$bot['realname'] = 'erik@anderssons.ath.cx';
$bot['active'] = true; // false to shut down bot
$bot['time_boot'] = time();
$bot['version'] = 'fishy bot v0.1 by hellfairy';
$bot['chan'][] = '#mixedbytes';

$feed['url'] = 'http://tracker.mixedbytes.org/bot.php';
$feed['id'] = read_lastid();
$feed['num'] = false;
$feed['check'] = time();

$admins[] = 'c83-252-173-252.bredband.comhem.se';

$irc['server'] = 'irc.freequest.net';
$irc['port'] = '6667';
$irc['password'] = '';
$irc['connected'] = false;
$irc['joined'] = false;

while($bot['active'] === true)
{
  $irc['sock'] = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or stderr('Failed to create socket!');

  stdout('Initiating connection to irc...');
  socket_connect($irc['sock'], gethostbyname($irc['server']), $irc['port']) or stdout('Failed to connect to server!');

  ircout("NICK ".$bot['nick']."\r\n");                                                             
  ircout("USER ".$bot['ident']." localhost \"".$irc['server']."\" :".$bot['realname']."\n\n");
  
  $irc['connected'] = true;
  
  while($irc['connected'] === true)
  {
    $read[] = $irc['sock'];
    $s = socket_select($read, $write = NULL, $except = NULL, 0);     
    if($s > 0)
    {
      unset($data, $tmp, $sender, $target, $cmd, $msg);
      $data = socket_read($irc['sock'], 4096, PHP_NORMAL_READ) or ($irc['connected'] = false);
      if(rtrim($data,"\r\n")=="")
      {
        continue;
      }                                  
      if($data[0] == ':')
      {
        $tmp = explode(' ', $data);
        $sender = substr($tmp[0], 1);
        $target = $tmp[2];
        $cmd = $tmp[1];
        unset($tmp[0],$tmp[1],$tmp[2]);
        $msg = rtrim(implode(' ', $tmp), "\r\n");
        if(strcasecmp($target, $bot['nick']) == 0)
        { // target is bot
          switch($cmd)
          {
            case 336: // End of /NAMES - channel joined
              // TODO: Multichannel support.
              $irc['joined'] = true;
              break;
            case 376: // end of motd
            case 422: // motd not found
              if(count($bot['chan']) > 0)
              {
                ircout('JOIN '.implode(',',$bot['chan'])."\n");
              } else
              {
                stdout('Ready to join channels, but none specified.');
              }
              break;
            case 'PRIVMSG':
              $msg = substr($msg, 1);
              if(ord($msg[0]) == 1)
              {
                ctcp($sender, $msg);
              }
              //stdout(bin2hex($msg));
              break;
            default: stdout($sender.' -> '.$target.': '.$cmd.' - '.$msg);
          }
        } else
        { // target is channel (probably?)
          switch($cmd)
          {
            case 'PRIVMSG':
              if($target[0] == '#')
              { // channel msg
                $msg = substr($msg, 1);
                //stdout(bin2hex($msg));
                if(ord($msg[0]) == 1)
                {
                  ctcp($sender, $msg);
                }
                $tmpmsg = explode(' ', trim($msg));
		/*
                if(stristr($tmpmsg[0], '.country') && !empty($tmpmsg[1]))
                {
                  @$db = mysql_connect("localhost","user","pass");
                  mysql_select_db("geoip",$db);    
                  $ip = trim($tmpmsg[1]);          
                  require_once('/home/erik/geoip.inc.php');        
                  if(getCCfromNAME($ip, $db) !== false)     
                  {            
                    // ircout(':'.$bot['nick'].' PRIVMSG '.$bot['chan'][0].' :Ny torrent: '.urldecode($name)."\n");
                    ircout(':'.$bot['nick'].' PRIVMSG '.$bot['chan'][0].' :'.$ip.' is in '.getCOUNTRYfromNAME($ip, $db).' ('.getCCfromNAME($ip, $db).")\n");
                  } else {
                    ircout(':'.$bot['nick'].' PRIVMSG '.$bot['chan'][0].' :Could not look up '.$ip.".\n");
                  }
                  mysql_close($db);
                }
		*/    
                stdout('<'.$sender.'@'.$target.'> '.$msg);
              } else
              { // private msg to who? not me i hope.
                stdout('Warning: message to unknown target - '.$target.' from '.$sender.': '.$msg);
              }
              break;
            default: stdout($data);
          }
        }
      } else
      { // commands sent from server - ping or the such
        $tmp = explode(' ', $data);              
        if($tmp[0] == 'PING')
        {
          ircout('PONG '.$tmp[1]."\n");
        } else
        {
          stdout('CMD: '.trim($data), "\r\n");
        }
      }                                         
    }
    //sleep(1);
    announcer();
    usleep(10);
  }
  
  stdout('Disconnected? Woooh...');
  // 60 sec reconnect wait
  sleep(60);
}

$uptime = time()-$bot['time_boot'];
if($uptime > 1)
{
  stdout("Bot shutting down after ".duration(time()-$bot['time_boot'], 'long')."\n");
}

function ircout($msg)
{
  global $irc;
  stdout('ircout() -> '.trim($msg));
  return socket_write($irc['sock'], $msg, strlen($msg));
}

function stdout($msg)
{
  echo date('[Y-m-d H:i:s] ').$msg."\n";
}

function stderr($msg)
{
  echo date('[Y-m-d H:i:s] ').$msg."\n";
  exit(-1);
}

function ctcp($sender, $msg)
{
  global $bot;
  $sender = getuser($sender);
  if(substr($msg, 1,7) == 'VERSION')
  {
    ircout(':'.$bot['nick'].' NOTICE '.$sender['nick'].' :'.chr(1).'VERSION '.$bot['version'].chr(1)."\n");
  }
  stdout('got a ctcp '.$msg.' from '.$sender['nick']);  
}

function getuser($source)
{
  list($user['nick'],$user['host']) = explode("@", $source);
  list($user['nick'],$user['ident']) = explode("!", $user['nick']);
  return $user;
}

function announcer()
{
  //$feed['id'] = '0';
  //$feed['num'] = false;
  global $bot,$feed;
  if(($feed['check']+60) <= time())
  {
    $feed['check'] = time();
    stdout('announcer got triggered...');
    if($feed['num'] && $feed['id'] > 0)
    { 
      $url = $feed['url'].'?i='.$feed['id'].'&l='.$feed['num']; }
    elseif($feed['num'] && $feed['id'] == 0)
    { 
      $url = $feed['url'].'?l='.$feed['num']; }
    elseif(!$feed['num'] && $feed['id'] > 0)
    { 
      $url = $feed['url'].'?i='.$feed['id']; }
    else
    { 
      $url = $feed['url'];
    }
    #$fd = fopen($url,'rb');
    $data = '';
    #while(feof($fd)===false)
    #{
    #  $data .= fgets($fd, 4096);
    #}
    #fclose($fd);
    $data = @file_get_contents($url);
    #if($data === false)
    #{ continue; }
    if($data !== false)
{
    $lines = explode("\n", $data);
    $lines = array_reverse($lines);
    foreach($lines as $line)
    {
      if(preg_match("/(.*?)\;(.*?)\;(.*)/",$line, $tmp))
      {
        list(,$id,$rel,$name) = $tmp;
        if($id > $feed['id'])
        {
          $feed['id'] = $id;
          write_lastid($id);
          stdout("\002Ny torrent:\002 ".urldecode($name).' ( http://tracker.mixedbytes.org/release-details.php?id='.$rel.' )');
          ircout(':'.$bot['nick'].' PRIVMSG '.$bot['chan'][0].' :Ny torrent: '.urldecode($name).' ( http://tracker.mixedbytes.org/release-details.php?id='.$rel.' )'."\n");
        }
      }
    }
}
  }
}

function write_lastid($id)
{
	if (is_numeric($id))
	{
		$fp = fopen("mixedbytes_lastid.txt","w+");
		fputs($fp, $id);
		fclose($fp);
	}
}

function read_lastid()
{
	$fp = fopen("mixedbytes_lastid.txt","r");
	$last_torrent = trim(fread($fp, filesize("mixedbytes_lastid.txt")));
	fclose($fp);
	if(!is_numeric($last_torrent))
	{
		$last_torrent = "0";
	}
	return $last_torrent;
}

?>