#!/usr/bin/perl -w

# nom du fichier: raMWbot.pl


                   #########################################
                   # auteur: ramware                       # 
                   # email: ramware@mailcity.com           #
                   # organisation: CyberYana               #
                   # email: cyberyana@conseiller.net       #
                   # url: http://cyberyana.free.fr         #
                   # Editeur: Emacs 20.4.1                 #
                   #########################################

###################
# Annonce du script

IRC::register("raMWbot Script", "1.0.2", "", "");

IRC::print "\0035 Chargement du script \0030raMWbot \0035version 1.0.1\n";

#IRC::print "@_\n";

IRC::print "\0035 Taper \0030 /aj help\0035 pour l'autoconnexion à des canaux\n";

IRC::print "\0035 Taper \0030 /j\0035 canal sans \0030#\0035 pour connecter un canal\n";

IRC::print "\0035 Taper \0030 /lamaz \0035pour envoyer un msg coloré d'attention\n";

IRC::print "\0035 Taper \0030 /away nick msg \0035pour se mettre away avec changement de nick\n";

IRC::print "\0035 Taper \0030 /away \0035pour revenir de l'état away\n";

IRC::print "\0035 Taper \0030 /fuck nick \0035pour ban&kick un nick\n";




#################
# chope des infos

IRC::get_info(0); #version Xchat
IRC::get_info(1); #pseudonyme par défault
IRC::get_info(2); #contexte de salon courant
IRC::get_info(3); #serveur IRC


#################
#Auto join canal#
#################

# définition de variables

$hd=$ENV{"HOME"};
$pmt="\02***\02";
$lsoffset=4;
$oschar="0";
$ajsendto=">>$hd/.xchat/auto-join-canal-list";
$ajwriteto=">$hd/.xchat/auto-join-canal-list";
$ajgetfrom="$hd/.xchat/auto-join-canal-list";
$ajdisable=">$hd/.xchat/.ajoff";

# sous-routines

sub out
{
IRC::print "@_\n";
}
sub aout
{
&out("$pmt aj\02.\02pl: @_");
}
sub rargs
{
 my $i=0;my $out;
 if (@_){$i=@_[0];}
 while (@args[$i]){$out="$out @args[$i]";$i++;}
 return substr($out,1,length($out));
}
sub totc
{
 my $i=0;
 open(READ, $ajgetfrom);
 my @read=<READ>;
 close(READ);
 while(@read[$i]){$i++;}
 return $i/2;
}
sub getc
{
 my $i=-2;
 if (@_[1] eq "desc"){$i++;}
 open(READ, $ajgetfrom);
 my @read=<READ>;
 close(READ);
 return $read[$i+$_[0]*2];
}
sub ajcheck
{
if (! -f "$hd/.xchat/.ajoff") 
{
&ajjoin();
}
}
sub ajjoin
{
 my $m=IRC::get_info(3);
 if (!$m) 
{
&aout("no connection to autojoin channel(s).");return 1;
}
 if (&totc() < 1) 
{
&zout("no autojoin channels to join.");return 1;
}
&aout("attempting to join autojoin channel(s).");
 my $i=0;
 while (&totc() > $i) 
{
  my $m=&getc($i, "chan");
  IRC::command "/join $m";
  $i++;
}
 return 1;
}
sub jhandler
{
 my @args=split(/ /, $_[0]);my $i=0;my $m;
 while (@args[$i]) 
{
  $m="";
  if (substr(@args[$i],0,1) ne "#"){$m="#"}
  IRC::send_raw "JOIN $m@args[$i]\n";
  $i++;
}
 return 1;
}
sub ajhandler
{
 @args=split(/ /, shift); ############@args is the equivalent of @ARGV.
 if (! -d "$hd/.xchat")
{
  my $success=mkdir "$hd/.xchat",022;
  if ($success)
  {
      &aout("~/.xchat n'éxiste pas, création accomplie avec succés.");
  }
  else {&aout("erreur lors de la création de ~/.xchat, halte.");return 1;}
}
 if (@args[0] eq "add")
{
  if (!@args[2])
  {
      &aout("/aj \02add\02 <\02#canall\02> <\02titre\02>");return 1;
  }
  my $chan=$args[1];
  my $rargs=&rargs(2);
  if (substr($chan,0,1) ne "#"){$chan="#$chan";}
  open(READ, $ajsendto) || &aout("erreur d'ouverture de $ajsendto.");
  print READ "$chan\n$rargs\n";
  close(READ);
  &aout("le canal $chan a été ajouté à la liste des canaux autojoingnables.");
 }
 elsif (@args[0] eq "del")
{
  if (!@args[1] || int(@args[1]) != @args[1])
  {
      &aout("/aj \02del\02 [\02#\02]");return 1;
  }
  if (@args[1] > &totc() || @args[1] < 1)
  {
      &aout("numéro invalide sélectionné.");return 1;
  }
  my $i=0;my $j=0;
  open(READ, $ajgetfrom) || &aout("erreur d'ouverture de $ajgetfrom.");
  my @read=<READ>;
  close(READ);
  open(SEND, $ajwriteto) || &aout("erreur d'ouverture de $ajwriteto.");
  while (@read[$i]){
   if (@args[1]*2-2 == $i || $j eq "1")
{
    if ($j eq "1")
    {
	$j--;
    }
    else 
    {
	my @m=@read[$i];$m=@m[0];chomp $m;$j++;
    }
}
   else 
{
    print SEND "@read[$i]";
}
   $i++;
}
  close(SEND);
  &aout("numéro effacé: @args[1]. ($m)");
}
 elsif (@args[0] eq "list")
{
  my $i=1;my $j;
  &aout("la liste des canaux auto-joingnables.");
  while ($i <= &totc())
{
   my $m=&getc($i, "desc");chomp $m;
   my $n=&getc($i, "chan");chomp $n;
   my $num=$lsoffset-length($i);my $nu=0;my $j;
   while ($num > $nu){$j="$oschar$j";$nu++;}
   &out("$pmt (\02$j$i\02)\02 $m (\02$n\02)");
   $i++;
}
  if ($i eq "1")
{
&aout("pas de canal trouvé.");return 1;
}
&aout("liste complètée.");
}
 elsif (@args[0] eq "join")
{
&ajjoin();
}

elsif (@args[0] eq "clear")
{
  if (! -f "$hd/.xchat/ajlist")
  {
      &aout("pas de liste de canaux à réinitialiser.");
  }

  else 
  {
      my $success=unlink "$hd/.xchat/ajlist";
      if ($success)
  {
      &aout("réinitialisation de la liste des canaux accomplie.");
  }

  else 
  {
      &aout("réinitialisation de la liste des canaux non-accomplie.");
  }
  }
}

 elsif (@args[0] eq "toggle"){
  my $m;
  if (-f "$hd/.xchat/.ajoff"){
   my $success=unlink "$hd/.xchat/.ajoff";
   if (!$success){&aout("autojoin disable file was cleared un-successfully.");}
   $m="enabled"
  }
  else {
   open(READ, $ajdisable) || &aout("error opening $ajdisable.");
   close(READ);
   $m="disabled"
  }
  &aout("autojoin on connect is now: $m.");
 }
 elsif (@args[0] eq "help"){
  &aout("-- \02syntax help for /aj.\02 --");
  &aout("(\02add    \02)\02 add a channel to your autojoin.");
  &aout("(\02del    \02)\02 delete a stored autojoin numeric value.");
  &aout("(\02list   \02)\02 list current channel(s) in storage.");
  &aout("(\02join   \02)\02 join channel(s) in your autojoin.");
  &aout("(\02clear  \02)\02 clear autojoin channel(s) in storage.");
  &aout("(\02toggle \02)\02 turn on/off the on connect autojoin.");
 }
 else {&aout("/aj [\02add\02|\02del\02|\02list\02|\02join\02|\02clear\02|\02toggle\02|\02help\02]");}
 return 1;
}

# initialisation des descripteurs de commandes

IRC::add_command_handler("aj", "ajhandler");
#IRC::add_command_handler("autojoin", "ajhandler");
#IRC::add_command_handler("join", "jhandler");
#IRC::add_command_handler("j", "jhandler");
IRC::add_message_handler("001", "ajcheck"); 


###############
#Extended Join#
###############

# hee IRC tu pogne les commande JOIN et J ac le / sur la routine: mon_join

#IRC::add_command_handler("join", "mon_join");
IRC::add_command_handler("j", "mon_join");

# La routine mon_join

sub mon_join

{
  @chan = split(/ /,$_[0]);
  $i = 0;
  while ($chan[$i])

  {
      $chan[$i] =~ s/#//;
      $chan[$i] =  "#" . $chan[$i];
      IRC::send_raw "JOIN $chan[$i]\n";
      $i++;
  }
  return 1;
}

#########
#Auto OP#
#########

$do_log = 0;       # log tous les msg des serveurs IRC dans un fichier
$do_autoop = 1;    # make auto-op with some users in some channels
$do_autotopic = 1; # NA / send topic in some channels
$do_ping = 0;      # make ping irc server. This may make connection more reliable under slow links.
                   # auto-reconnect are generaly handled more gracefully.

# la liste des canaux et des IP à auto-oper!
# les canaux sont séparés par",". Pas d'espace attention !
# hum, pourquoi po une syntaxe comme : #channel[/IRCnet] or #channel[/irc.server.net] ...
# liste HASH de variable avec écriture simplifiée (qw)

%auto_op = qw (
~Doz@d254.dhcp212-78.cybercable.fr #cyberyana,#québec2001
~ramware@d254.dhcp212-78.cybercable.fr #cyberyana
~sya@d254.dhcp212-78.cybercable.fr #cyberyana,#artnac
);

# paramètres de configuration des non-utilisateurs (pas de modif nécessaires)
#
$verbose = 0;
$time_delay = 600;  ################################ delai en secondes entre un ping ... pong !
$log = $ENV{"HOME"} . "/.xchat/" . "inbound.log";


#IRC::print "\0035Chargement du auto-op script \n";

if ($do_log) {
    open (LOG, ">>$log") || IRC::print "\0035:: auto-op: erreur en ouvrant le fichier de log";
  # auto-flush ...
  select((select(LOG), $| = 1)[0]);
}

IRC::add_message_handler("INBOUND", "inbound_handler");

IRC::add_timeout_handler($time_delay * 1000, "ping_timeout_handler") if ($do_ping);


sub ping_timeout_handler
{ 
  # 1: on continue, 0 on arrete
  IRC::add_timeout_handler($time_delay * 1000, "ping_timeout_handler");
  # PING :irc.twiny.net
  IRC::command("/ping");
  $last_pong = time;
  return 0;
}


sub inbound_handler
{ 

  local($line) = @_;

########################################################################
  # IRC::print "inbound_handler() ''$line''\n";

  # ERROR
  # ERROR :Closing Link: quinquin[~marc@yod.stna.dgac.fr] (Ping timeout)
  # ERROR :Closing Link: quinquin[unknown@143.196.31.73] (Unauthorized connection)
  # :Joker31 KILLSESSION #linux-31 corneille -> fermeture d'une fenetre sur un #chan

#######################################################################
  # ping-pong
  # PING :salambo.Enserb.U-Bordeaux.Fr
  # PING :corneille


  if($line =~ m/PING :(.*)/ && $do_ping) {
     $host = $1;
     $delay = time - $last_ping{$host};
     # glob value
     $last_ping{$host} = time;

     # IRC::print "$line\n";
     IRC::print "PING from $host : $delay\n" if ($last_ping{$host} != 0 && $verbose == 1);
  }

 #######################################################
  # pong
  # :salambo.Enserb.U-Bordeaux.Fr PONG salambo.Enserb.U-Bordeaux.Fr :Joker31

  if($line =~ m/ PONG /) {
     # IRC::print "$line\n";
     ($host,$foo, $nick) = $line =~ /^:(.*) PONG (.*) :(.*)/;
     $delay = time - $last_pong{$host};
     $last_pong{$host} = time;
     # IRC::print "PONG from $host $delay\n";
     return 1; # attention : 1, le dernier plugin !
  }
########################################################
  # 331 : no topic is set ! send "/raw TOPIC #channel" before !
  # :irc.twiny.net 331 quinquin #linux-31 :No topic is set.
  # topic : topic status
  # :corneille 332 Joker31 #linux-31 :linux-31, le canal du CULTe : http://savage.iut-blagnac.fr/
  # topic : notification
  # Joker31!~marc@yod.stna.dgac.fr TOPIC #linux-31 :linux-31, le canal du CULTe ...

  # :irc.twiny.net 331 quinquin #linux-31 :No topic is set.


  if($line =~ m/:(.*) 331 (.*) (.*) :No topic is set./) {
     $channel = $3;
     if( $channel eq "#cyberyana") {
         IRC::send_raw "TOPIC $channel Le canal de la CyberYana <http://cyberyana.free.fr>\r\n";
     }
     return 1;
  }
#############################################################

  # join
  # :quinquin!~marc@yod.stna.dgac.fr JOIN :#linux-31
  # if($line =~ m/:(.+?)\!(.+?) JOIN :(.*)/) {

  if($line =~ m/:(.+?)\!(.+?) JOIN :(.*)/) {

     $nick = $1;
     $addr = $2;
     $chan = $3;

     if($do_autoop) {
       foreach $myuser (keys %auto_op) {
         if("$nick\!$addr" =~ m/$myuser/i) {
            # on met les noms des canals comme suit: #chan1[,#chan2]* ...
            $chans = $auto_op{$myuser};
            foreach $mychan (split(/\,/, $chans)) {
              if( $mychan eq $chan) {
                IRC::command("/MODE $chan +o $nick");
              }
            }
         }
       }
     }


################################################################

if ( $channel eq "#cyberyana") 
{
# TOPIC #cyberyana Le Canal de la CyberYana Org. http://cyberyana.free.fr
IRC::send_raw "TOPIC $channel\n";
IRC::send_raw "TOPIC $channel Le Canal de la CyberYana Org. http://cyberyana.free.fr\n";
}

if ( $channel eq "#québec2001") 
{
# TOPIC #québec2001 Le Canal de sadics et compagnie ;-)
IRC::send_raw "TOPIC $channel\n";
IRC::send_raw "TOPIC $channel Le Canal de sadics et compagnie ;-)\n";
}
################################################################  


}

  printf LOG "%s\n", $line if ($do_log);
  return 0;
}


_END_

###########
#Away Nick#
###########

&p("Away script (yistd)");
IRC::register ("awayscript", "0.1", "", ""); 
IRC::add_command_handler("away", handleaway); 

sub handleaway {
        my($temp) = $_[0];
        my(@c) = split(/ /,$temp);
           if ($c[0] =~ m/set/i) {
               if(open(FILE,">/home/ramware/.xchat/xawaynick.tmp")){
                   print FILE "$c[1]\n";
                   close(FILE);
                   &p("Set away nick to $c[1]\n");
               }
               return 1;
               
           } elsif ($c[0] ne "") {
               if (-e "xawaynick.tmp") {
                  my($currentn) = IRC::get_info(1);
                  if(open(FILE,">/home/ramware/.xchat/xchatnick.tmp")) {
                      print FILE "$currentn\n";
                      close(FILE);
                  }
                  if(open(FILE,"/home/ramware/.xchat/xawaynick.tmp")) {
                      my($awayn) = <FILE>;
                      chop($awayn);
                      $newaway = $awayn;
                      close(FILE);
                      &c("/NICK $newaway");
                  } 
                  return 0;
                  
               } else {
                   &p("Please set an away nick with /away set AWAYNICK\n");
               }
           } else {
               if(open(FILE,"</home/ramware/.xchat/xchatnick.tmp")) {
                   my($goodnick) = <FILE>;
                   chop($goodnick);
                   close(FILE);
                   &c("/NICK $goodnick");
                   return 0;
               }
           }
}

    
sub p {
    IRC::print("@_");
}

sub c {
    IRC::command("@_");
}

################ RemoteControl v0.10 - An mIRC-esque Remote system.
#Remote Control#
################ Alex Roberts <bse@error.fsnet.co.uk> 1999

# synopsis
# mot-clef:reponse[:#canal]

# la reponse peut inclure:
#	<NICK>	:	le nick de la personne qui emet le mot-clef
#	<CHAN>	:	le nom du canal où le mot-clef est mentionné

#la liste de motclef = fichier: remotecontrol
# Location de la liste des mots-clef
$remotelist = "/home/ramware/.xchat/remotecontrol";

IRC::print "\0035Chargement du script remotecontrol\003\n";
IRC::add_message_handler ("PRIVMSG", "msg_handler");

# Reload is broken, seems to destroy the remotes array
IRC::add_command_handler("reloadremote", "reload");

# Charge la liste de mots-clefs si elle existe

if 
(open(REMOTES, $remotelist)) 
{
	IRC::print ("\0035Chargement de la liste de mots-clefs\003\n");
	$list = "";
	$list = <REMOTES>;
	@remotes = split('\n',$list);
	close(REMOTES);
} 
else 
{
	IRC::print("\0035 Ne trouve pas la liste des mots-clefs !!! \003\n");
}


sub msg_handler 
{
	my $line = shift (@_);
	$line =~ /:(.*)!(\S+) PRIVMSG (.*) :(.*)/i;
	
	$thenick = $1;
	$thechan = $3;
	$thetext = $4;
	@words = split(' ', $4);

#######################################foreach my $testwords (@words) {

	foreach my $remote (@remotes) {
			
		@message = split (/:/, $remote);
			
if 
($thetext =~ /$message[0]/i)
{
####### display the actual message
if 
($thetext !~ /ACTION/) 
{
   IRC::print "\0032<\003$thenick\0032>\003 $thetext\n";
} 
else 
{
       $thetext =~ s/ACTION//;
       IRC::print "\0032*\003 $thenick$thetext\n";
}
		    
# substitue tout mot-clef dans le message (nicks, canals, etc)

		    $message[1] =~ s/<NICK>/$thenick/;
		    $message[1] =~ s/<CHAN>/$thechan/;

#vérifie si le message est limité à un canal

if 
($message[2]) 
{
    if 
	($message[2] =~ /$thechan/) 
	{
	  IRC::command "$message[1]"; # dit la reponse au message
	    return 1;
	} 
    else 
        {
	    return 1;
	}
}

IRC::command "$message[1]"; # message isnt channel limited, lets say it then..
return 1;
		}
	}
	#}
	return 0;
}


sub reload 
{
	# load the remotes list

	if (open(REMOTES, $remotelist)) {
		IRC::print ("\002Reloading the Remotes List - $remotelist\002\n\n");
		$list = "";
		$list = <REMOTES>;
		@remotes = split('\n',$list);
		close(REMOTES);
	} else {
		IRC::print("\002I couldn't open $remotelist \002\n\n");
	}
}

#####################
############lamaz

IRC::add_command_handler("lamaz", "lamaz_handler");

sub lamaz_handler {
	$cur_chan = IRC::get_info(2);
	$msg = shift(@_);
if
($msg) 
{
IRC::command("/say %C1,11!%C11,1B%C1,11O%C11,1L%C1,11J%C11,1é%C1,11M%C11,1O%C1,11ï%C1,11!%C13,11 - $msg je t'aime !");
} 
######## C11,1:bleu clair/noir/C12,1:bleu/C13,1:violet sur noir:C13,11:violet sur blanc
######## 
else 
{
IRC::command("/say %C1,11!%C11,1B%C1,11O%C11,1L%C1,11J%C11,1é%C1,11M%C11,1O%C1,11ï%C1,11!%C13,11 - $msg je sent quelque chose durcir !!!!!!!");
}
return 1;
}




############fuck

IRC::add_command_handler("fuck", "fuck_handler");

sub fuck_handler {
$msg = shift(@_);
IRC::command("/ban  $msg ");
IRC::command("/kick  $msg   : fuck U !");
return 1;
}

#
# unban.pl - unban by number ;-)
#
# Usage:
#      /banlist [channel]             - show banlist
#      /unban nr[,nr[...]] [channel]  - unban the ban(s) with number nr 
#                                       (from /banlist) on channel 
#      /exlist [channel]              - show exempt ban list
#      /unex nr[,nr[...]] [channel]   - remove exempt ban with number nr 
#                                        (from /exlist) on channel 
#      /invlist [channel]             - show always invite list
#      /uninv nr[,nr[...]] [channel]  - remove always invite entry with 
#                                       number nr (from /invlist) on channel 
# ...if chan is not given, uses current window's channel (if there is one)  
# 
# Example:
# $ /banlist
# +--------[ ban list #a_channel ]----------------------------
# |  1: *!*@p3E9BF205.dip.t-dialin.net
# |  2: *!*metaller@p3EE073A1.dip.t-dialin.net
# |  3: *!*magic*@*
# |  4: *!*@*magic-internet.de
# $ /unban 1,2
# --- Vetinari sets modes [#a_channel -bb *!*@p3E9BF205.dip.t-dialin.net *!*metaller@p3EE073A1.dip.t-dialin.net]
#
# Changes:
#   0.1.1: support mutiple bans to be removed at once.
#          HINT: do not use more numbers than your ircserver supports, 
#          i.e. 3 on IRCnet
#
# Author: Vetinari <iranitev@gmx.net>
#
package IRC::XChat::UnBan;

my $script_name    = 'unban.pl';
my $script_version = '0.1.1';

IRC::register($script_name, $script_version, "", "");
IRC::print("\cC0\cB$script_name\cB version\cC3 $script_version\cO "
           . "by \cB\cC4V\cC7etinari\cO loading...\n");

use vars qw(%invlist %exlist %banlist);
my $pkg = __PACKAGE__;

IRC::add_command_handler("BANLIST", "${pkg}::handle_banlist");
IRC::add_command_handler("UNBAN",   "${pkg}::handle_unban");
IRC::add_message_handler("367",     "${pkg}::handle_367");
IRC::add_message_handler("368",     "${pkg}::handle_368");


sub trim {
	local($_) = shift;
	s/^\s*//;
	s/\s*$//;
	return $_;
}

sub handle_banlist {
	my $chan = trim(shift);
	if (!defined $chan || $chan =~ /^\s*$/) {
		$chan = IRC::get_info(2);
	}
	@{$banlist{lc $chan}} = ();
	IRC::send_raw("MODE $chan +b\r\n");
	return 1;
}

sub handle_unban {
	my $nr   = trim(shift);
	my $chan = "";
	my @nrs  = ();
	if ($nr =~ /\s/) {
		($nr,$chan) = split /\s+/, $nr;
	} 
	if ($nr =~ /,/) {
		@nrs = split /,/, $nr;
	} else {
		$nrs[0] = $nr;
	}
	if (!defined $chan || $chan =~ /^$/) {
		$chan = IRC::get_info(2);
		if ($chan =~ /^$/) {
			IRC::print("UNBAN: usage: /UNBAN <NR>[,<NR>[...]] [<CHAN>]\n");
			return 1;
		}
	}

	my @remove = ();
	foreach my $num (@nrs) {
		my $mask = $banlist{lc $chan}[$num-1];
		if (!defined $mask || $mask =~ /^$/) {
			IRC::print("UNBAN: number '$num' not in ban list\n");
		} else {
			push @remove, $mask;
		}
	}
	if (@remove) {
		my $b    = "b" x (scalar @remove);
		my $list = join " ", @remove;
		IRC::send_raw("MODE $chan -$b $list\r\n");
	}
	@{$banlist{lc $chan}} = ();
	return 1;
}

sub handle_367 {
	my $line = trim(shift);
	$line =~ /:\S+\s+367\s+\S+\s+(\S+)\s+(\S+)/;
	my ($chan,$mask) = ($1,$2);
	push @{$banlist{lc $chan}}, $mask;
	return 1;
}

sub handle_368 {
	my $line = trim(shift);
	$line =~ /:\S+\s+368\s+\S+\s+(\S+)\s+:.*/;
	my $chan = $1;

IRC::print("\cB\cC0\015\cC9-----\cB-\cB-\cB-[ "
               . "\cC0ban list \cC0\cB$chan\cB \cC9]--\cC3\cB"
               . "---\cB-\cB-\cB----\cC14\cB----\cB-----"
               . "\cB----\cB----\n"
            );
	my $count = 1;
	foreach my $mask (@{$banlist{lc $chan}}) {
		my $nr = sprintf "% 2d", $count;
		IRC::print("\cC9|\cC0 $nr: $mask\cO\n");
		++$count;
	}
	return 1;
}

1;
# end 

