archive

- Random tools & helpful resources for IRC
git clone git://git.acid.vegas/archive.git
Log | Files | Refs | Archive

trigger.pl (42790B)

      1 # trigger.pl - execute a command or replace text, triggered by an event in irssi
      2 # Do /TRIGGER HELP or look at http://wouter.coekaerts.be/irssi/ for help
      3 
      4 # Copyright (C) 2002-2010  Wouter Coekaerts <wouter@coekaerts.be>
      5 #
      6 # This program is free software; you can redistribute it and/or modify
      7 # it under the terms of the GNU General Public License as published by
      8 # the Free Software Foundation; either version 2 of the License, or
      9 # (at your option) any later version.
     10 #
     11 # This program is distributed in the hope that it will be useful,
     12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
     13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     14 # GNU General Public License for more details.
     15 #
     16 # You should have received a copy of the GNU General Public License
     17 # along with this program; if not, write to the Free Software
     18 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     19 
     20 use strict;
     21 use Irssi 20020324 qw(command_bind command_runsub command signal_add_first signal_continue signal_stop signal_remove);
     22 use Text::ParseWords;
     23 use IO::File;
     24 use vars qw($VERSION %IRSSI);
     25 
     26 $VERSION = '1.0+';
     27 %IRSSI = (
     28 	authors     => 'Wouter Coekaerts',
     29 	contact     => 'wouter@coekaerts.be',
     30 	name        => 'trigger',
     31 	description => 'execute a command or replace text, triggered by an event in irssi',
     32 	license     => 'GPLv2 or later',
     33 	url         => 'http://wouter.coekaerts.be/irssi/',
     34 	changed     => '$LastChangedDate: 2009-02-07 21:35:47 +0100 (Sat, 07 Feb 2009) $',
     35 );
     36 
     37 sub cmd_help {
     38 	Irssi::print (<<'SCRIPTHELP_EOF', MSGLEVEL_CLIENTCRAP);
     39 
     40 TRIGGER LIST
     41 TRIGGER SAVE
     42 TRIGGER RELOAD
     43 TRIGGER MOVE <number> <number>
     44 TRIGGER DELETE <number>
     45 TRIGGER CHANGE <number> ...
     46 TRIGGER ADD ...
     47 
     48 %U%_When to match%_%U 
     49 %UOn which types of event to trigger%U 
     50      These are simply specified by -name_of_the_type
     51      The normal IRC event types are:
     52           publics, %|privmsgs, (pub|priv)actions, (pub|priv)notices, (pub|priv)ctcps, (pub|priv)ctcpreplies, joins, parts, quits, kicks, topics, invites, nick_changes, dcc_msgs, dcc_actions, dcc_ctcps
     53           mode_channel: %|a mode on the (whole) channel (like +t, +i, +b)
     54           mode_nick: %|a mode on someone in the channel (like +o, +v)
     55      -all is an alias for all of those.
     56      Additionally, there is:
     57           rawin: %|raw text incoming from the server
     58           send_command: %|commands you give to irssi
     59           send_text: %|lines you type that aren't commands
     60           beep: %|when irssi beeps
     61           notify_join: %|someone in you notify list comes online
     62           notify_part: %|someone in your notify list goes offline
     63           notify_away: %|someone in your notify list goes away
     64           notify_unaway: %|someone in your notify list goes unaway
     65           notify_unidle: %|someone in your notify list stops idling
     66           (pub|priv)flood: %|flood in a channel or in private detected. See /set flood. Be careful, these flood signals can trigger many times for one flood (unless you have autoignore enabled)
     67 
     68 %UFilters (conditions) the event has to satisfy%U 
     69 They all take one parameter. If you can give a list, seperate elements by space and use quotes around the list.
     70 All filters except for -pattern and -regexp can also be inversed by prefixing with -not_.
     71      -pattern: %|The message must match the given pattern. ? and * can be used as wildcards
     72      -regexp: %|The message must match the given regexp. (see man perlre)
     73        %|if -nocase is given as an option, the regexp or pattern is matched case insensitive
     74      -tags: %|The servertag must be in the given list of tags
     75      -channels: %|The event must be in one of the given list of channels.
     76                 Examples: %|-channels '#chan1 #chan2' or -channels 'IRCNet/#channel'
     77                           %|-channels 'EFNet/' means every channel on EFNet and is the same as -tags 'EFNet'
     78      -masks: %|The person who triggers it must match one of the given list of masks
     79      -hasmode: %|The person who triggers it must have the give mode
     80                Examples: %|'-o' means not opped, '+ov' means opped OR voiced, '-o&-v' means not opped AND not voiced
     81      -hasflag: %|Only trigger if friends.pl (friends_shasta.pl) or people.pl is loaded and the person who triggers it has the given flag in the script (same syntax as -hasmode)
     82      -other_masks
     83      -other_hasmode
     84      -other_hasflag: %|Same as above but for the victim for kicks or mode_nick.
     85 
     86 %U%_What to do when it matches%_%U 
     87      -command: Execute the given Irssi-command
     88                 %|You are able to use $1, $2 and so on generated by your regexp pattern.
     89                 %|For multiple commands ; can be used as seperator
     90                 %|The following variables are also expanded:
     91                    $T: %|Server tag
     92                    $C: %|Channel name
     93                    $N: %|Nickname of the person who triggered this command
     94                    $A: %|His address (foo@bar.com),
     95                    $I: %|His ident (foo)
     96                    $H: %|His hostname (bar.com)
     97                    $M: %|The complete message
     98                    ${other}: %|The victim for kicks or mode_nick
     99                    ${mode_type}: %|The type ('+' or '-') for a mode_channel or mode_nick
    100                    ${mode_char}: %|The mode char ('o' for ops, 'b' for ban,...)
    101                    ${mode_arg} : %|The argument to the mode (if there is one)
    102                 %|$\X, with X being one of the above expands (e.g. $\M), escapes all non-alphanumeric characters, so it can be used with /eval or /exec. Don't use /eval or /exec without this, it's not safe.
    103      -replace: %|replaces the matching part with the given replacement in the event (requires a -regexp or -pattern)
    104      -once: %|remove the trigger if it is triggered, so it only executes once and then is forgotten.
    105      -stop: %|stops the signal. It won't get displayed by Irssi. Like /IGNORE
    106      -debug: %|print some debugging info
    107 
    108 %U%_Other options%_%U 
    109      -disabled: %|Same as removing it, but keeps it in case you might need it later
    110      -name: %|Give the trigger a name. You can refer to the trigger with this name in add/del/change commands
    111 
    112 %U%_Examples%_%U 
    113  Knockout people who do a !list:
    114    %#/TRIGGER ADD %|-publics -channels "#channel1 #channel2" -nocase -regexp ^!list -command "KN $N This is not a warez channel!"
    115  React to !echo commands from people who are +o in your friends-script:
    116    %#/TRIGGER ADD %|-publics -regexp '^!echo (.*)' -hasflag '+o' -command 'say echo: $1'
    117  Ignore all non-ops on #channel:
    118    %#/TRIGGER ADD %|-publics -actions -channels "#channel" -hasmode '-o' -stop
    119  Send a mail to yourself every time a topic is changed:
    120    %#/TRIGGER ADD %|-topics -command 'exec echo $\N changed topic of $\C to: $\M | mail you@somewhere.com -s topic'
    121 
    122 
    123 %U%_Examples with -replace%_%U 
    124  %|Replace every occurence of shit with sh*t, case insensitive:
    125    %#/TRIGGER ADD %|-all -nocase -regexp shit -replace sh*t
    126  %|Strip all colorcodes from *!lamer@*:
    127    %#/TRIGGER ADD %|-all -masks *!lamer@* -regexp '\x03\d?\d?(,\d\d?)?|\x02|\x1f|\x16|\x06' -replace ''
    128  %|Never let *!bot1@foo.bar or *!bot2@foo.bar hilight you
    129  %|(this works by cutting your nick in 2 different parts, 'myn' and 'ick' here)
    130  %|you don't need to understand the -replace argument, just trust that it works if the 2 parts separately don't hilight:
    131    %#/TRIGGER ADD %|-all masks '*!bot1@foo.bar *!bot2@foo.bar' -regexp '(myn)(ick)' -nocase -replace '$1\x02\x02$2'
    132  %|Avoid being hilighted by !top10 in eggdrops with stats.mod (but show your nick in bold):
    133    %#/TRIGGER ADD %|-publics -regexp '(Top.0\(.*\): 1.*)(my)(nick)' -replace '$1\x02$2\x02\x02$3\x02'
    134  %|Convert a Windows-1252 Euro to an ISO-8859-15 Euro (same effect as euro.pl):
    135    %#/TRIGGER ADD %|-regexp '\x80' -replace '\xA4'
    136  %|Show tabs as spaces, not the inverted I (same effect as tab_stop.pl):
    137    %#/TRIGGER ADD %|-all -regexp '\t' -replace '    '
    138 SCRIPTHELP_EOF
    139 } # /
    140 
    141 my @triggers; # array of all triggers
    142 my %triggers_by_type; # hash mapping types on triggers of that type
    143 my $recursion_depth = 0;
    144 my $changed_since_last_save = 0;
    145 
    146 ###############
    147 ### formats ###
    148 ###############
    149 
    150 Irssi::theme_register([
    151 	'trigger_header' => 'Triggers:',
    152 	'trigger_line' => '%#$[-4]0 $1',
    153 	'trigger_added' => 'Trigger $0 added: $1',
    154 	'trigger_not_found' => 'Trigger {hilight $0} not found',
    155 	'trigger_saved' => 'Triggers saved to $0',
    156 	'trigger_loaded' => 'Triggers loaded from $0'
    157 ]);
    158 
    159 #########################################
    160 ### catch the signals & do your thing ###
    161 #########################################
    162 
    163 # trigger types with a message and a channel
    164 my @allchanmsg_types = qw(publics pubactions pubnotices pubctcps pubctcpreplies parts quits kicks topics);
    165 # trigger types with a message
    166 my @allmsg_types = (@allchanmsg_types, qw(privmsgs privactions privnotices privctcps privctcpreplies dcc_msgs dcc_actions dcc_ctcps));
    167 # trigger types with a channel
    168 my @allchan_types = (@allchanmsg_types, qw(mode_channel mode_nick joins invites pubflood));
    169 # trigger types in -all
    170 my @all_types = (@allmsg_types, qw(mode_channel mode_nick joins invites nick_changes));
    171 # trigger types with a server
    172 my @all_server_types = (@all_types, qw(rawin notify_join notify_part notify_away notify_unaway notify_unidle pubflood privflood));
    173 # all trigger types
    174 my @trigger_types = (@all_server_types, qw(send_command send_text beep));
    175 #trigger types that are not in -all
    176 #my @notall_types = grep {my $a=$_; return (!grep {$_ eq $a} @all_types);} @trigger_types;
    177 my @notall_types = qw(rawin notify_join notify_part notify_away notify_unaway notify_unidle send_command send_text beep pubflood privflood);
    178 
    179 my @signals = (
    180 # "message public", SERVER_REC, char *msg, char *nick, char *address, char *target
    181 {
    182 	'types' => ['publics'],
    183 	'signal' => 'message public',
    184 	'sub' => sub {check_signal_message(\@_,1,$_[0],$_[4],$_[2],$_[3],'publics');},
    185 },
    186 # "message private", SERVER_REC, char *msg, char *nick, char *address
    187 {
    188 	'types' => ['privmsgs'],
    189 	'signal' => 'message private',
    190 	'sub' => sub {check_signal_message(\@_,1,$_[0],undef,$_[2],$_[3],'privmsgs');},
    191 },
    192 # "message irc action", SERVER_REC, char *msg, char *nick, char *address, char *target
    193 {
    194 	'types' => ['privactions','pubactions'],
    195 	'signal' => 'message irc action',
    196 	'sub' => sub {
    197 		if ($_[4] eq $_[0]->{nick}) {
    198 			check_signal_message(\@_,1,$_[0],undef,$_[2],$_[3],'privactions');
    199 		} else {
    200 			check_signal_message(\@_,1,$_[0],$_[4],$_[2],$_[3],'pubactions');
    201 		}
    202 	},
    203 },
    204 # "message irc notice", SERVER_REC, char *msg, char *nick, char *address, char *target
    205 {
    206 	'types' => ['privnotices','pubnotices'],
    207 	'signal' => 'message irc notice',
    208 	'sub' => sub {
    209 		if ($_[4] eq $_[0]->{nick}) {
    210 			check_signal_message(\@_,1,$_[0],undef,$_[2],$_[3],'privnotices');
    211 		} else {
    212 			check_signal_message(\@_,1,$_[0],$_[4],$_[2],$_[3],'pubnotices');
    213 		}
    214 	}
    215 },
    216 # "message join", SERVER_REC, char *channel, char *nick, char *address
    217 {
    218 	'types' => ['joins'],
    219 	'signal' => 'message join',
    220 	'sub' => sub {check_signal_message(\@_,-1,$_[0],$_[1],$_[2],$_[3],'joins');}
    221 },
    222 # "message part", SERVER_REC, char *channel, char *nick, char *address, char *reason
    223 {
    224 	'types' => ['parts'],
    225 	'signal' => 'message part',
    226 	'sub' => sub {check_signal_message(\@_,4,$_[0],$_[1],$_[2],$_[3],'parts');}
    227 },
    228 # "message quit", SERVER_REC, char *nick, char *address, char *reason
    229 {
    230 	'types' => ['quits'],
    231 	'signal' => 'message quit',
    232 	'sub' => sub {check_signal_message(\@_,3,$_[0],undef,$_[1],$_[2],'quits');}
    233 },
    234 # "message kick", SERVER_REC, char *channel, char *nick, char *kicker, char *address, char *reason
    235 {
    236 	'types' => ['kicks'],
    237 	'signal' => 'message kick',
    238 	'sub' => sub {check_signal_message(\@_,5,$_[0],$_[1],$_[3],$_[4],'kicks',{'other'=>$_[2]});}
    239 },
    240 # "message topic", SERVER_REC, char *channel, char *topic, char *nick, char *address
    241 {
    242 	'types' => ['topics'],
    243 	'signal' => 'message topic',
    244 	'sub' => sub {check_signal_message(\@_,2,$_[0],$_[1],$_[3],$_[4],'topics');}
    245 },
    246 # "message invite", SERVER_REC, char *channel, char *nick, char *address
    247 {
    248 	'types' => ['invites'],
    249 	'signal' => 'message invite',
    250 	'sub' => sub {check_signal_message(\@_,-1,$_[0],$_[1],$_[2],$_[3],'invites');}
    251 },
    252 # "message nick", SERVER_REC, char *newnick, char *oldnick, char *address
    253 {
    254 	'types' => ['nick_changes'],
    255 	'signal' => 'message nick',
    256 	'sub' => sub {check_signal_message(\@_,-1,$_[0],undef,$_[1],$_[3],'nick_changes');}
    257 },
    258 # "message dcc", DCC_REC *dcc, char *msg
    259 {
    260 	'types' => ['dcc_msgs'],
    261 	'signal' => 'message dcc',
    262 	'sub' => sub {check_signal_message(\@_,1,$_[0]->{'server'},undef,$_[0]->{'nick'},undef,'dcc_msgs');
    263 	}
    264 },
    265 # "message dcc action", DCC_REC *dcc, char *msg
    266 {
    267 	'types' => ['dcc_actions'],
    268 	'signal' => 'message dcc action',
    269 	'sub' => sub {check_signal_message(\@_,1,$_[0]->{'server'},undef,$_[0]->{'nick'},undef,'dcc_actions');}
    270 },
    271 # "message dcc ctcp", DCC_REC *dcc, char *cmd, char *data
    272 {
    273 	'types' => ['dcc_ctcps'],
    274 	'signal' => 'message dcc ctcp',
    275 	'sub' => sub {check_signal_message(\@_,1,$_[0]->{'server'},undef,$_[0]->{'nick'},undef,'dcc_ctcps');}
    276 },
    277 # "server incoming", SERVER_REC, char *data
    278 {
    279 	'types' => ['rawin'],
    280 	'signal' => 'server incoming',
    281 	'sub' => sub {check_signal_message(\@_,1,$_[0],undef,undef,undef,'rawin');}
    282 },
    283 # "send command", char *args, SERVER_REC, WI_ITEM_REC
    284 {
    285 	'types' => ['send_command'],
    286 	'signal' => 'send command',
    287 	'sub' => sub {
    288 		sig_send_text_or_command(\@_,1);
    289 	}
    290 },
    291 # "send text", char *line, SERVER_REC, WI_ITEM_REC
    292 {
    293 	'types' => ['send_text'],
    294 	'signal' => 'send text',
    295 	'sub' => sub {
    296 		sig_send_text_or_command(\@_,0);
    297 	}
    298 },
    299 # "beep"
    300 {
    301 	'types' => ['beep'],
    302 	'signal' => 'beep',
    303 	'sub' => sub {check_signal_message(\@_,-1,undef,undef,undef,undef,'beep');}
    304 },
    305 # "event "<cmd>, SERVER_REC, char *args, char *sender_nick, char *sender_address
    306 {
    307 	'types' => ['mode_channel', 'mode_nick'],
    308 	'signal' => 'event mode',
    309 	'sub' => sub {
    310 		my ($server, $event_args, $nickname, $address) = @_;
    311 		my ($target, $modes, $modeargs) = split(/ /, $event_args, 3);
    312 		return if (!$server->ischannel($target));
    313 		my (@modeargs) = split(/ /,$modeargs);
    314 		my ($pos, $type, $event_type, $arg) = (0, '+');
    315 		foreach my $char (split(//,$modes)) {
    316 			if ($char eq "+" || $char eq "-") {
    317 				$type = $char;
    318 			} else {
    319 				if ($char =~ /[Oovh]/) { # mode_nick
    320 					$event_type = 'mode_nick';
    321 					$arg = $modeargs[$pos++];
    322 				} elsif ($char =~ /[beIqdk]/ || ( $char =~ /[lfJ]/ && $type eq '+')) { # chan_mode with arg
    323 					$event_type = 'mode_channel';
    324 					$arg = $modeargs[$pos++];
    325 				} else { # chan_mode without arg
    326 					$event_type = 'mode_channel';
    327 					$arg = undef;
    328 				}
    329 				check_signal_message(\@_,-1,$server,$target,$nickname,$address,$event_type,{
    330 					'mode_type' => $type,
    331 					'mode_char' => $char,
    332 					'mode_arg' => $arg,
    333 					'other' => ($event_type eq 'mode_nick') ? $arg : undef
    334 				});
    335 			}
    336 		}
    337 	}
    338 },
    339 # "notifylist joined", SERVER_REC, char *nick, char *user, char *host, char *realname, char *awaymsg
    340 {
    341 	'types' => ['notify_join'],
    342 	'signal' => 'notifylist joined',
    343 	'sub' => sub {check_signal_message(\@_, 5, $_[0], undef, $_[1], $_[2].'@'.$_[3], 'notify_join', {'realname' => $_[4]});}
    344 },
    345 {
    346 	'types' => ['notify_part'],
    347 	'signal' => 'notifylist left',
    348 	'sub' => sub {check_signal_message(\@_, 5, $_[0], undef, $_[1], $_[2].'@'.$_[3], 'notify_left', {'realname' => $_[4]});}
    349 },
    350 {
    351 	'types' => ['notify_unidle'],
    352 	'signal' => 'notifylist unidle',
    353 	'sub' => sub {check_signal_message(\@_, 5, $_[0], undef, $_[1], $_[2].'@'.$_[3], 'notify_unidle', {'realname' => $_[4]});}
    354 },
    355 {
    356 	'types' => ['notify_away', 'notify_unaway'],
    357 	'signal' => 'notifylist away changed',
    358 	'sub' => sub {check_signal_message(\@_, 5, $_[0], undef, $_[1], $_[2].'@'.$_[3], ($_[5] ? 'notify_away' : 'notify_unaway'), {'realname' => $_[4]});}
    359 },
    360 # "ctcp msg", SERVER_REC, char *args, char *nick, char *addr, char *target
    361 {
    362 	'types' => ['pubctcps', 'privctcps'],
    363 	'signal' => 'ctcp msg',
    364 	'sub' => sub {
    365 		my ($server, $args, $nick, $addr, $target) = @_;
    366 		if ($target eq $server->{'nick'}) {
    367 			check_signal_message(\@_, 1, $server, undef, $nick, $addr, 'privctcps');
    368 		} else {
    369 			check_signal_message(\@_, 1, $server, $target, $nick, $addr, 'pubctcps');
    370 		}
    371 	}
    372 },
    373 # "ctcp reply", SERVER_REC, char *args, char *nick, char *addr, char *target
    374 {
    375 	'types' => ['pubctcpreplies', 'privctcpreplies'],
    376 	'signal' => 'ctcp reply',
    377 	'sub' => sub {
    378 		my ($server, $args, $nick, $addr, $target) = @_;
    379 		if ($target eq $server->{'nick'}) {
    380 			check_signal_message(\@_, 1, $server, undef, $nick, $addr, 'privctcpreplies');
    381 		} else {
    382 			check_signal_message(\@_, 1, $server, $target, $nick, $addr, 'pubctcpreplies');
    383 		}
    384 	}
    385 },
    386 # "flood", SERVER_REC, char *nick, char *host, int level, char *target
    387 {
    388 	'types' => ['pubflood', 'privflood'],
    389 	'signal' => 'flood',
    390 	'sub' => sub {
    391 		my ($server, $nick, $host, $level, $target) = @_;
    392 		if ($target eq $server->{'nick'}) {
    393 			check_signal_message(\@_, -1, $server, undef, $nick, $host, 'privflood');
    394 		} else {
    395 			check_signal_message(\@_, -1, $server, $target, $nick, $host, 'pubflood');
    396 		}
    397 	}
    398 }
    399 );
    400 
    401 sub sig_send_text_or_command {
    402 	my ($signal, $iscommand) = @_;
    403 	my ($line, $server, $item) = @$signal;
    404 	my ($channelname,$nickname,$address) = (undef,undef,undef);
    405 	if ($item && (ref($item) eq 'Irssi::Irc::Channel' || ref($item) eq 'Irssi::Silc::Channel')) {
    406 		$channelname = $item->{'name'};
    407 	} elsif ($item && ref($item) eq 'Irssi::Irc::Query') { # TODO Silc query ?
    408 		$nickname = $item->{'name'};
    409 		$address = $item->{'address'}
    410 	}
    411 	# TODO pass context also for non-channels (queries and other stuff)
    412 	check_signal_message($signal,0,$server,$channelname,$nickname,$address,$iscommand ? 'send_command' : 'send_text');
    413 
    414 }
    415 
    416 my %filters = (
    417 'tags' => {
    418 	'types' => \@all_server_types,
    419 	'sub' => sub {
    420 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    421 		
    422 		if (!defined($server)) {
    423 			return 0;
    424 		}
    425 		my $matches = 0;
    426 		foreach my $tag (split(/ /,$param)) {
    427 			if (lc($server->{'tag'}) eq lc($tag)) {
    428 				$matches = 1;
    429 				last;
    430 			}
    431 		}
    432 		return $matches;
    433 	}
    434 },
    435 'channels' => {
    436 	'types' => \@allchan_types,
    437 	'sub' => sub {
    438 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    439 		
    440 		if (!defined($channelname) || !defined($server)) {
    441 			return 0;
    442 		}
    443 		my $matches = 0;
    444 		foreach my $trigger_channel (split(/ /,$param)) {
    445 			if (lc($channelname) eq lc($trigger_channel)
    446 				|| lc($server->{'tag'}.'/'.$channelname) eq lc($trigger_channel)
    447 				|| lc($server->{'tag'}.'/') eq lc($trigger_channel)) {
    448 				$matches = 1;
    449 				last; # this channel matches, stop checking channels
    450 			}
    451 		}
    452 		return $matches;
    453 	}
    454 },
    455 'masks' => {
    456 	'types' => \@all_types,
    457 	'sub' => sub {
    458 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    459 		return  (defined($nickname) && defined($address) && defined($server) && $server->masks_match($param, $nickname, $address));
    460 	}
    461 },
    462 'other_masks' => {
    463 	'types' => ['kicks', 'mode_nick'],
    464 	'sub' => sub {
    465 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    466 		return 0 unless defined($extra->{'other'});
    467 		my $other_address = get_address($extra->{'other'}, $server, $channelname);
    468 		return defined($other_address) && $server->masks_match($param, $extra->{'other'}, $other_address);
    469 	}
    470 },
    471 'hasmode' => {
    472 	'types' => \@all_types,
    473 	'sub' => sub {
    474 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    475 		return hasmode($param, $nickname, $server, $channelname);
    476 	}
    477 },
    478 'other_hasmode' => {
    479 	'types' => ['kicks', 'mode_nick'],
    480 	'sub' => sub {
    481 		my ($param,$signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    482 		return defined($extra->{'other'}) && hasmode($param, $extra->{'other'}, $server, $channelname);
    483 	}
    484 },
    485 'hasflag' => {
    486 	'types' => \@all_types,
    487 	'sub' => sub {
    488 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    489 		return 0 unless defined($nickname) && defined($address) && defined($server);
    490 		my $flags = get_flags ($server->{'chatnet'},$channelname,$nickname,$address);
    491 		return defined($flags) && check_modes($flags,$param);
    492 	}
    493 },
    494 'other_hasflag' => {
    495 	'types' => ['kicks', 'mode_nick'],
    496 	'sub' => sub {
    497 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    498 		return 0 unless defined($extra->{'other'});
    499 		my $other_address = get_address($extra->{'other'}, $server, $channelname);
    500 		return 0 unless defined($other_address);
    501 		my $flags = get_flags ($server->{'chatnet'},$channelname,$extra->{'other'},$other_address);
    502 		return defined($flags) && check_modes($flags,$param);
    503 	}
    504 },
    505 'mode_type' => {
    506 	'types' => ['mode_channel', 'mode_nick'],
    507 	'sub' => sub {
    508 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    509 		return (($param) eq $extra->{'mode_type'});
    510 	}
    511 },
    512 'mode_char' => {
    513 	'types' => ['mode_channel', 'mode_nick'],
    514 	'sub' => sub {
    515 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    516 		return (($param) eq $extra->{'mode_char'});
    517 	}
    518 },
    519 'mode_arg' => {
    520 	'types' => ['mode_channel', 'mode_nick'],
    521 	'sub' => sub {
    522 		my ($param, $signal,$parammessage,$server,$channelname,$nickname,$address,$condition,$extra) = @_;
    523 		return (($param) eq $extra->{'mode_arg'});
    524 	}
    525 }
    526 );
    527 
    528 sub get_address {
    529 	my ($nick, $server, $channel) = @_;
    530 	my $nickrec = get_nickrec($nick, $server, $channel);
    531 	return $nickrec ? $nickrec->{'host'} : undef;
    532 }
    533 sub get_nickrec {
    534 	my ($nick, $server, $channel) = @_;
    535 	return unless defined($server) && defined($channel) && defined($nick);
    536 	my $chanrec = $server->channel_find($channel);
    537 	return $chanrec ? $chanrec->nick_find($nick) : undef;
    538 }
    539 
    540 sub hasmode {
    541 	my ($param, $nickname, $server, $channelname) = @_;
    542 	my $nickrec = get_nickrec($nickname, $server, $channelname);
    543 	return 0 unless defined $nickrec;
    544 	my $modes =
    545 		($nickrec->{'op'} ? 'o' : '')
    546 		. ($nickrec->{'voice'} ? 'v' : '')
    547 		. ($nickrec->{'halfop'} ? 'h' : '')
    548 	;
    549 	return check_modes($modes, $param);
    550 }
    551 
    552 # list of all switches
    553 my @trigger_switches = (@trigger_types, qw(all nocase stop once debug disabled));
    554 # parameters (with an argument)
    555 my @trigger_params = qw(pattern regexp command replace name);
    556 # all options that can be used to set filters, including negative matches (not_<filter>)
    557 my @trigger_filter_options = map(($_,'not_'.$_), keys(%filters));
    558 # list of all options (including switches) for /TRIGGER ADD
    559 my @trigger_add_options = (@trigger_switches, @trigger_params, @trigger_filter_options);
    560 # same for /TRIGGER CHANGE, this includes the -no<option>'s
    561 my @trigger_options = map(($_,'no'.$_) ,@trigger_add_options);
    562 
    563 # check the triggers on $signal's $parammessage parameter, for triggers with $condition set
    564 #  on $server in $channelname, for $nickname!$address
    565 # set $parammessage to -1 if the signal doesn't have a message
    566 # for signal without channel, nick or address, set to undef
    567 sub check_signal_message {
    568 	my ($signal, $parammessage, $server, $channelname, $nickname, $address, $condition, $extra) = @_;
    569 	my ($changed, $stopped, $context, $need_rebuild);
    570 	my $message = ($parammessage == -1) ? '' : $signal->[$parammessage];
    571 
    572 	return if (!$triggers_by_type{$condition});
    573 	
    574 	if ($recursion_depth > 10) {
    575 		Irssi::print("Trigger error: Maximum recursion depth reached, aborting trigger.", MSGLEVEL_CLIENTERROR);
    576 		return;
    577 	}
    578 	$recursion_depth++;
    579 
    580 TRIGGER:	
    581 	foreach my $trigger (@{$triggers_by_type{$condition}}) {
    582 		# check filters
    583 		foreach my $trigfilter (filters_for_trigger($trigger)) {
    584 			my $filter_sub = $trigfilter->{'filter'}->{'sub'};
    585 			my $filter_matches = !!(&$filter_sub($trigfilter->{'param'}, $signal, $parammessage, $server, $channelname, $nickname, $address, $condition, $extra));
    586 			if ($filter_matches != $trigfilter->{'must_match'}) { # if it didn't match, or if it's a -not_* filter and it did match
    587 				next TRIGGER;
    588 			}
    589 		}
    590 		
    591 		# check regexp (and keep matches in @- and @+, so don't make a this a {block})
    592 		next if ($trigger->{'compregexp'} && ($parammessage == -1 || $message !~ m/$trigger->{'compregexp'}/));
    593 		
    594 		# if we got this far, it fully matched, and we need to do the replace/command/stop/once
    595 		my $expands = $extra;
    596 		$expands->{'M'} = $message,;
    597 		$expands->{'T'} = (defined($server)) ? $server->{'tag'} : '';
    598 		$expands->{'C'} = $channelname;
    599 		$expands->{'N'} = $nickname;
    600 		$expands->{'A'} = $address;
    601 		$expands->{'I'} = ((!defined($address)) ? '' : substr($address,0,index($address,'@')));
    602 		$expands->{'H'} = ((!defined($address)) ? '' : substr($address,index($address,'@')+1));
    603 		$expands->{'$'} = '$';
    604 		$expands->{';'} = ';';
    605 
    606 		if (defined($trigger->{'replace'})) { # it's a -replace
    607 			$message =~ s/$trigger->{'compregexp'}/do_expands($trigger->{'compreplace'},$expands,$message)/ge;
    608 			$changed = 1;
    609 		}
    610 		
    611 		if ($trigger->{'command'}) { # it's a (nonempty) -command
    612 			my $command = $trigger->{'command'};
    613 			# $1 = the stuff behind the $ we want to expand: a number, or a character from %expands
    614 			$command = do_expands($command, $expands, $message);
    615 			
    616 			if (defined($server)) {
    617 				if (defined($channelname) && $server->channel_find($channelname)) {
    618 					$context = $server->channel_find($channelname);
    619 				} else {
    620 					$context = $server;
    621 				}
    622 			} else {
    623 				$context = undef;
    624 			}
    625 			
    626 			if (defined($context)) {
    627 				$context->command("eval $command");
    628 			} else {
    629 				Irssi::command("eval $command");
    630 			}
    631 		}
    632 
    633 		if ($trigger->{'debug'}) {
    634 			print("DEBUG: trigger $condition pmesg=$parammessage message=$message server=$server->{tag} channel=$channelname nick=$nickname address=$address " . join(' ',map {$_ . '=' . $extra->{$_}} keys(%$extra)));
    635 		}
    636 		
    637 		if ($trigger->{'stop'}) {
    638 			$stopped = 1;
    639 		}
    640 		
    641 		if ($trigger->{'once'}) {
    642 			# find this trigger in the real trigger list, and remove it
    643 			for (my $realindex=0; $realindex < scalar(@triggers); $realindex++) {
    644 				if ($triggers[$realindex] == $trigger) {
    645 					splice (@triggers,$realindex,1);
    646 					last;
    647 				}
    648 			}
    649 			$need_rebuild = 1;
    650 		}
    651 	}
    652 
    653 	if ($need_rebuild) {
    654 		rebuild();
    655 		$changed_since_last_save = 1;
    656 	}
    657 	if ($stopped) { # stopped with -stop
    658 		signal_stop();
    659 	} elsif ($changed) { # changed with -replace
    660 		$signal->[$parammessage] = $message;
    661 		signal_continue(@$signal);
    662 	}
    663 	$recursion_depth--;
    664 }
    665 
    666 # return array of filters for the given trigger
    667 sub filters_for_trigger($) {
    668 	my ($trigger) = @_;
    669 	return values(%{$trigger->{'filters'}});
    670 }
    671 
    672 # used in check_signal_message to expand $'s
    673 # $inthis is a string that can contain $ stuff (like 'foo$1bar$N')
    674 sub do_expands {
    675 	my ($inthis, $expands, $from) = @_;
    676 	# @+ and @- are copied because there are two s/// nested, and the inner needs the $1 and $2,... of the outer one
    677 	my @plus = @+;
    678 	my @min = @-;
    679 	my $p = \@plus; my $m = \@min;
    680 	$inthis =~ s/\$(\\*(\d+|[^0-9x{]|x[0-9a-fA-F][0-9a-fA-F]|{.*?}))/expand_and_escape($1,$expands,$m,$p,$from)/ge;	
    681 	return $inthis;
    682 }
    683 
    684 # \ $ and ; need extra escaping because we use eval
    685 sub expand_and_escape {
    686 	my $retval = expand(@_);
    687 	$retval =~ s/([\\\$;])/\\\1/g;
    688 	return $retval;
    689 }
    690 
    691 # used in do_expands (via expand_and_escape), to_expand is the part after the $
    692 sub expand {
    693 	my ($to_expand, $expands, $min, $plus, $from) = @_;
    694 	if ($to_expand =~ /^\d+$/) { # a number => look up in $vars
    695 		# from man perlvar:
    696 		# $3 is the same as "substr $var, $-[3], $+[3] - $-[3])"
    697 		return ($to_expand > @{$min} ? '' : substr($from,$min->[$to_expand],$plus->[$to_expand]-$min->[$to_expand]));
    698 	} elsif ($to_expand =~ s/^\\//) { # begins with \, so strip that from to_expand
    699 		my $exp = expand($to_expand,$expands,$min,$plus,$from); # first expand without \
    700 		$exp =~ s/([^a-zA-Z0-9])/\\\1/g; # escape non-word chars
    701 		return $exp;
    702 	} elsif ($to_expand =~ /^x([0-9a-fA-F]{2})/) { # $xAA
    703 		return chr(hex($1));
    704 	} elsif ($to_expand =~ /^{(.*?)}$/) { # ${foo}
    705 		return expand($1, $expands, $min, $plus, $from);
    706 	} else { # look up in $expands
    707 		return $expands->{$to_expand};
    708 	}
    709 }
    710 
    711 sub check_modes {
    712 	my ($has_modes, $need_modes) = @_;
    713 	my $matches;
    714 	my $switch = 1; # if a '-' if found, will be 0 (meaning the modes should not be set)
    715 	foreach my $need_mode (split /&/, $need_modes) {
    716 		$matches = 0;
    717 		foreach my $char (split //, $need_mode) {
    718 			if ($char eq '-') {
    719 				$switch = 0;
    720 			} elsif ($char eq '+') {
    721 				$switch = 1;
    722 			} elsif ((index($has_modes, $char) != -1) == $switch) {
    723 				$matches = 1;
    724 				last;
    725 			}
    726 		}
    727 		if (!$matches) {
    728 			return 0;
    729 		}
    730 	}
    731 	return 1;
    732 }
    733 
    734 # get someones flags from people.pl or friends(_shasta).pl
    735 sub get_flags {
    736 	my ($chatnet, $channel, $nick, $address) = @_;
    737 	my $flags;
    738 	no strict 'refs';
    739 	if (%{ 'Irssi::Script::people::' }) {
    740 		if (defined ($channel)) {
    741 			$flags = (&{ 'Irssi::Script::people::find_local_flags' }($chatnet,$channel,$nick,$address));
    742 		} else {
    743 			$flags = (&{ 'Irssi::Script::people::find_global_flags' }($chatnet,$nick,$address));
    744 		}
    745 		$flags = join('',keys(%{$flags}));
    746 	} else {
    747 		my $shasta;
    748 		if (%{ 'Irssi::Script::friends_shasta::' }) {
    749 			$shasta = 'friends_shasta';
    750 		} elsif (defined &{ 'Irssi::Script::friends::get_idx' }) {
    751 			$shasta = 'friends';
    752 		} else {
    753 			return undef;
    754 		}
    755 		my $idx = (&{ 'Irssi::Script::'.$shasta.'::get_idx' }($nick, $address));
    756 		if ($idx == -1) {
    757 			return '';
    758 		}
    759 		$flags = (&{ 'Irssi::Script::'.$shasta.'::get_friends_flags' }($idx,undef));
    760 		if ($channel) {
    761 			$flags .= (&{ 'Irssi::Script::'.$shasta.'::get_friends_flags' }($idx,$channel));
    762 		}
    763 	}
    764 	return $flags;
    765 }
    766 
    767 ########################################################
    768 ### internal stuff called by manage, needed by above ###
    769 ########################################################
    770 
    771 my %mask_to_regexp = ();
    772 foreach my $i (0..255) {
    773     my $ch = chr $i;
    774     $mask_to_regexp{$ch} = "\Q$ch\E";
    775 }
    776 $mask_to_regexp{'?'} = '(.)';
    777 $mask_to_regexp{'*'} = '(.*)';
    778 
    779 sub compile_trigger {
    780 	my ($trigger) = @_;
    781 	my $regexp;
    782 	
    783 	if ($trigger->{'regexp'}) {
    784 		$regexp = $trigger->{'regexp'};
    785 	} elsif ($trigger->{'pattern'}) {
    786 		$regexp = $trigger->{'pattern'};
    787 		$regexp =~ s/(.)/$mask_to_regexp{$1}/g;
    788 	} else {
    789 		delete $trigger->{'compregexp'};
    790 		return;
    791 	}
    792 	
    793 	if ($trigger->{'nocase'}) {
    794 		$regexp = '(?i)' . $regexp;
    795 	}
    796 	
    797 	$trigger->{'compregexp'} = qr/$regexp/;
    798 	
    799 	if(defined($trigger->{'replace'})) {
    800 		(my $replace = $trigger->{'replace'}) =~ s/\$/\$\$/g;
    801 		$trigger->{'compreplace'} = Irssi::parse_special($replace);
    802 	}
    803 }
    804 
    805 # rebuilds triggers_by_type and updates signal binds
    806 sub rebuild {
    807 	%triggers_by_type = ();
    808 	foreach my $trigger (@triggers) {
    809 		if (!$trigger->{'disabled'}) {
    810 			if ($trigger->{'all'}) {
    811 				# -all is an alias for all types in @all_types for which the filters can apply
    812 ALLTYPES:
    813 				foreach my $type (@all_types) {
    814 					# check if all filters can apply to $type
    815 					foreach my $trigfilter (filters_for_trigger($trigger)) {
    816 						if (! grep {$_ eq $type} @{$trigfilter->{'filter'}->{'types'}}) {
    817 							next ALLTYPES;
    818 						}
    819 					}
    820 					push @{$triggers_by_type{$type}}, ($trigger);
    821 				}
    822 			}
    823 			
    824 			foreach my $type ($trigger->{'all'} ? @notall_types : @trigger_types) {
    825 				if ($trigger->{$type}) {
    826 					push @{$triggers_by_type{$type}}, ($trigger);
    827 				}
    828 			}
    829 		}
    830 	}
    831 	
    832 	foreach my $signal (@signals) {
    833 		my $should_bind = 0;
    834 		foreach my $type (@{$signal->{'types'}}) {
    835 			if (defined($triggers_by_type{$type})) {
    836 				$should_bind = 1;
    837 			}
    838 		}
    839 		if ($should_bind && !$signal->{'bind'}) {
    840 			signal_add_first($signal->{'signal'}, $signal->{'sub'});
    841 			$signal->{'bind'} = 1;
    842 		} elsif (!$should_bind && $signal->{'bind'}) {
    843 			signal_remove($signal->{'signal'}, $signal->{'sub'});
    844 			$signal->{'bind'} = 0;
    845 		}
    846 	}
    847 }
    848 
    849 ################################
    850 ### manage the triggers-list ###
    851 ################################
    852 
    853 my $trigger_file; # cached setting
    854 
    855 sub sig_setup_changed {
    856 	$trigger_file = Irssi::settings_get_str('trigger_file');
    857 }
    858 
    859 sub autosave {
    860 	cmd_save() if ($changed_since_last_save);
    861 }
    862 
    863 # TRIGGER SAVE
    864 sub cmd_save {
    865 	my $io = new IO::File $trigger_file, "w";
    866 	if (defined $io) {
    867 		$io->print("#Triggers file version $VERSION\n");
    868 		foreach my $trigger (@triggers) {
    869 			$io->print(to_string($trigger) . "\n");
    870 		}
    871 		$io->close;
    872 	}
    873 	Irssi::printformat(MSGLEVEL_CLIENTNOTICE, 'trigger_saved', $trigger_file);
    874 	$changed_since_last_save = 0;
    875 }
    876 
    877 # save on unload
    878 sub UNLOAD {
    879 	cmd_save();
    880 }
    881 
    882 # TRIGGER LOAD
    883 sub cmd_load {
    884 	sig_setup_changed(); # make sure we've read the trigger_file setting
    885 	my $converted = 0;
    886 	my $io = new IO::File $trigger_file, "r";
    887 	if (not defined $io) {
    888 		if (-e $trigger_file) {
    889 			Irssi::print("Error opening triggers file", MSGLEVEL_CLIENTERROR);
    890 		}
    891 		return;
    892 	}
    893 	if (defined $io) {
    894 		@triggers = ();
    895 		my $text;
    896 		$text = $io->getline;
    897 		my $file_version = '';
    898 		if ($text =~ /^#Triggers file version (.*)\n/) {
    899 			$file_version = $1;
    900 		}
    901 		if ($file_version lt '0.6.1+2') {
    902 			no strict 'vars';
    903 			$text .= $_ foreach ($io->getlines);
    904 			my $rep = eval "$text";
    905 			if (! ref $rep) {
    906 				Irssi::print("Error in triggers file");
    907 				return;
    908 			}
    909 			my @old_triggers = @$rep;
    910 		
    911 			for (my $index=0;$index < scalar(@old_triggers);$index++) { 
    912 				my $trigger = $old_triggers[$index];
    913 	
    914 				if ($file_version lt '0.6.1') {
    915 					# convert old names: notices => pubnotices, actions => pubactions
    916 					foreach $oldname ('notices','actions') {
    917 						if ($trigger->{$oldname}) {
    918 							delete $trigger->{$oldname};
    919 							$trigger->{'pub'.$oldname} = 1;
    920 							$converted = 1;
    921 						}
    922 					}
    923 				}
    924 				if ($file_version lt '0.6.1+1' && $trigger->{'modifiers'}) {
    925 					if ($trigger->{'modifiers'} =~ /i/) {
    926 						$trigger->{'nocase'} = 1;
    927 						Irssi::print("Trigger: trigger ".($index+1)." had 'i' in it's modifiers, it has been converted to -nocase");
    928 					}
    929 					if ($trigger->{'modifiers'} !~ /^[ig]*$/) {
    930 						Irssi::print("Trigger: trigger ".($index+1)." had unrecognised modifier '". $trigger->{'modifiers'} ."', which couldn't be converted.");
    931 					}
    932 					delete $trigger->{'modifiers'};
    933 					$converted = 1;
    934 				}
    935 				
    936 				# convert to text with compat, and then to new trigger hash
    937 				$text = to_string($trigger,1);
    938 				my @args = &shellwords($text . ' a');
    939 				my $trigger = parse_options({},@args);
    940 				if ($trigger) {
    941 					push @triggers, $trigger;
    942 				}
    943 			}
    944 		} else { # new format
    945 			while ( $text = $io->getline ) {
    946 				chop($text);
    947 				next if ($text =~ /^[ ]*$|^#/);
    948 				my @args = &shellwords($text . ' a');
    949 				my $trigger = parse_options({},@args);
    950 				if ($trigger) {
    951 					push @triggers, $trigger;
    952 				}
    953 			}
    954 		}
    955 	}
    956 	Irssi::printformat(MSGLEVEL_CLIENTNOTICE, 'trigger_loaded', $trigger_file);
    957 	if ($converted) {
    958 		Irssi::print("Trigger: Triggers file will be in new format next time it's saved.");
    959 	}
    960 	rebuild();
    961 }
    962 
    963 # escape for printing with to_string
    964 # <<abcdef>>      => << 'abcdef' >>
    965 # <<abc'def>>     => << "abc'def" >>
    966 # <<abc'def\x02>> => << 'abc'\''def\x02' >>
    967 sub param_to_string {
    968 	my ($text) = @_;
    969 	# avoid ugly escaping if we can use "-quotes without other escaping (no " or \)
    970 	if ($text =~ /^[^"\\]*'[^"\\]$/) {
    971 		return ' "' . $text . '" ';
    972 	}
    973 	# "'" signs without a (odd number of) \ in front of them, need be to escaped as '\''
    974 	# this is ugly :(
    975 	$text =~ s/(^|[^\\](\\\\)*)'/$1'\\''/g;
    976 	return " '$text' ";
    977 }
    978 
    979 # converts a trigger back to "-switch -options 'foo'" form
    980 # if $compat, $trigger is in the old format (used to convert)
    981 sub to_string {
    982 	my ($trigger, $compat) = @_;
    983 	my $string;
    984 	
    985 	foreach my $switch (@trigger_switches) {
    986 		if ($trigger->{$switch}) {
    987 			$string .= '-'.$switch.' ';
    988 		}
    989 	}
    990 	
    991 	if ($compat) {
    992 		foreach my $filter (keys(%filters)) {
    993 			if ($trigger->{$filter}) {
    994 				$string .= '-' . $filter . param_to_string($trigger->{$filter});
    995 			}
    996 		}
    997 	} else {
    998 		foreach my $trigfilter (filters_for_trigger($trigger)) {
    999 			$string .= '-' . $trigfilter->{'option'} . param_to_string($trigfilter->{'param'});
   1000 		}
   1001 	}
   1002 
   1003 	foreach my $param (@trigger_params) {
   1004 		if ($trigger->{$param} || ($param eq 'replace' && defined($trigger->{'replace'}))) {
   1005 			$string .= '-' . $param . param_to_string($trigger->{$param});
   1006 		}
   1007 	}
   1008 	return $string;
   1009 }
   1010 
   1011 # find a trigger (for REPLACE and DELETE), returns index of trigger, or -1 if not found
   1012 sub find_trigger {
   1013 	my ($data) = @_;
   1014 	if ($data =~ /^[0-9]*$/ and defined($triggers[$data-1])) {
   1015 		return $data-1;
   1016 	} else {
   1017 		for (my $i=0; $i < scalar(@triggers); $i++) {
   1018 			if ($triggers[$i]->{'name'} eq $data) {
   1019 				return $i;
   1020 			}
   1021 		}
   1022 	}
   1023 	Irssi::printformat(MSGLEVEL_CLIENTCRAP, 'trigger_not_found', $data);
   1024 	return -1; # not found
   1025 }
   1026 
   1027 
   1028 # TRIGGER ADD <options>
   1029 sub cmd_add {
   1030 	my ($data, $server, $item) = @_;
   1031 	my @args = shellwords($data . ' a');
   1032 	
   1033 	my $trigger = parse_options({}, @args);
   1034 	if ($trigger) {
   1035 		push @triggers, $trigger;
   1036 		Irssi::printformat(MSGLEVEL_CLIENTCRAP, 'trigger_added', scalar(@triggers), to_string($trigger));
   1037 		rebuild();
   1038 		$changed_since_last_save = 1;
   1039 	}
   1040 }
   1041 
   1042 # TRIGGER CHANGE <nr> <options>
   1043 sub cmd_change {
   1044 	my ($data, $server, $item) = @_;
   1045 	my @args = shellwords($data . ' a');
   1046 	my $index = find_trigger(shift @args);
   1047 	if ($index != -1) {
   1048 		if(parse_options($triggers[$index], @args)) {
   1049 			Irssi::print("Trigger " . ($index+1) ." changed to: ". to_string($triggers[$index]));
   1050 		}
   1051 		rebuild();
   1052 		$changed_since_last_save = 1;
   1053 	}
   1054 }
   1055 
   1056 # parses options for TRIGGER ADD and TRIGGER CHANGE
   1057 # if invalid args returns undef, else changes $thetrigger and returns it
   1058 sub parse_options {
   1059 	my ($thetrigger,@args) = @_;
   1060 	my ($trigger, $option);
   1061 	
   1062 	if (pop(@args) ne 'a') {
   1063 		Irssi::print("Syntax error, probably missing a closing quote", MSGLEVEL_CLIENTERROR);
   1064 		return undef;
   1065 	}
   1066 	
   1067 	%$trigger = %$thetrigger; # make a copy to prevent changing the given trigger if args doesn't parse
   1068 ARGS:	for (my $arg = shift @args; $arg; $arg = shift @args) {
   1069 		# expand abbreviated options, put in $option
   1070 		$arg =~ s/^-//;
   1071 		$option = undef;
   1072 		foreach my $ioption (@trigger_options) {
   1073 			if (index($ioption, $arg) == 0) { # -$opt starts with $arg
   1074 				if ($option) { # another already matched
   1075 					Irssi::print("Ambiguous option: $arg", MSGLEVEL_CLIENTERROR);
   1076 					return undef;
   1077 				}
   1078 				$option = $ioption;
   1079 				last if ($arg eq $ioption); # exact match is unambiguous
   1080 			}
   1081 		}
   1082 		if (!$option) {
   1083 			Irssi::print("Unknown option: $arg", MSGLEVEL_CLIENTERROR);
   1084 			return undef;
   1085 		}
   1086 
   1087 		# -<param> <value> or -no<param>
   1088 		foreach my $param (@trigger_params) {
   1089 			if ($option eq $param) {
   1090 				$trigger->{$param} = shift @args;
   1091 				next ARGS;
   1092 			}
   1093 			if ($option eq 'no'.$param) {
   1094 				$trigger->{$param} = undef;
   1095 				next ARGS;
   1096 			}
   1097 		}
   1098 
   1099 		# -[no]<switch>
   1100 		foreach my $switch (@trigger_switches) {
   1101 			# -<switch>
   1102 			if ($option eq $switch) {
   1103 				$trigger->{$switch} = 1;
   1104 				next ARGS;
   1105 			}
   1106 			# -no<switch>
   1107 			elsif ($option eq 'no'.$switch) {
   1108 				$trigger->{$switch} = undef;
   1109 				next ARGS;
   1110 			}
   1111 		}
   1112 		
   1113 		# -[not_]<filter> <value>
   1114 		if ($option =~ /^(not_)?(.*)$/ && $filters{$2}) {
   1115 			$trigger->{'filters'}->{$option} = {
   1116 				option => $option,
   1117 				must_match => ($1 ne 'not_'), # if false, trigger must only be done if filter sub returns false
   1118 				filter_name => $2,
   1119 				filter => $filters{$2},
   1120 				param => shift @args
   1121 			};
   1122 			
   1123 			next ARGS;
   1124 		}
   1125 		
   1126 		# -no<filter>
   1127 		if ($option =~ /^no(.*)$/ && $filters{$1}) {
   1128 			delete $trigger->{'filters'}->{$option};
   1129 		}
   1130 	}
   1131 	
   1132 	if (defined($trigger->{'replace'}) && ! $trigger->{'regexp'} && !$trigger->{'pattern'}) {
   1133 		Irssi::print("Trigger error: Can't have -replace without -regexp", MSGLEVEL_CLIENTERROR);
   1134 		return undef;
   1135 	}
   1136 
   1137 	if ($trigger->{'pattern'} && $trigger->{'regexp'}) {
   1138 		Irssi::print("Trigger error: Can't have -pattern and -regexp in same trigger", MSGLEVEL_CLIENTERROR);
   1139 		return undef;
   1140 	}
   1141 	
   1142 	# remove types that are implied by -all
   1143 	if ($trigger->{'all'}) {
   1144 		foreach my $type (@all_types) {
   1145 			delete $trigger->{$type};
   1146 		}
   1147 	}
   1148 	
   1149 	# remove types for which the filters don't apply
   1150 	foreach my $type (@trigger_types) {
   1151 		if ($trigger->{$type}) {
   1152 			foreach my $trigfilter (filters_for_trigger($trigger)) {
   1153 				if (!grep {$_ eq $type} @{$trigfilter->{'filter'}->{'types'}}) {
   1154 					Irssi::print("Warning: the filter -" . $trigfilter->{'option'} . " can't apply to an event of type -$type, so I'm removing that type from this trigger.");
   1155 					delete $trigger->{$type};
   1156 				}
   1157 			}
   1158 		}
   1159 	}
   1160 
   1161 	# check if it has at least one type
   1162 	my $has_a_type;
   1163 	foreach my $type (@trigger_types) {
   1164 		if ($trigger->{$type}) {
   1165 			$has_a_type = 1;
   1166 			last;
   1167 		}
   1168 	}
   1169 	if (!$has_a_type && !$trigger->{'all'}) {
   1170 		Irssi::print("Warning: this trigger doesn't trigger on any type of message. you probably want to add -publics or -all");
   1171 	}
   1172 	
   1173 	compile_trigger($trigger);
   1174 	%$thetrigger = %$trigger; # copy changes to real trigger
   1175 	return $thetrigger;
   1176 }
   1177 
   1178 # TRIGGER DELETE <num>
   1179 sub cmd_del {
   1180 	my ($data, $server, $item) = @_;
   1181 	my @args = shellwords($data);
   1182 	my $index = find_trigger(shift @args);
   1183 	if ($index != -1) {
   1184 		Irssi::print("Deleted ". ($index+1) .": ". to_string($triggers[$index]));
   1185 		splice (@triggers,$index,1);
   1186 		rebuild();
   1187 		$changed_since_last_save = 1;
   1188 	}
   1189 }
   1190 
   1191 # TRIGGER MOVE <num> <num>
   1192 sub cmd_move {
   1193 	my ($data, $server, $item) = @_;
   1194 	my @args = &shellwords($data);
   1195 	my $index = find_trigger(shift @args);
   1196 	if ($index != -1) {
   1197 		my $newindex = shift @args;
   1198 		if ($newindex < 1 || $newindex > scalar(@triggers)) {
   1199 			Irssi::print("$newindex is not a valid trigger number");
   1200 			return;
   1201 		}
   1202 		Irssi::print("Moved from ". ($index+1) ." to $newindex: ". to_string($triggers[$index]));
   1203 		$newindex -= 1; # array starts counting from 0
   1204 		my $trigger = splice (@triggers,$index,1); # remove from old place
   1205 		splice (@triggers,$newindex,0,($trigger)); # insert at new place
   1206 		rebuild();
   1207 		$changed_since_last_save = 1;
   1208 	}
   1209 }
   1210 
   1211 # TRIGGER LIST
   1212 sub cmd_list {
   1213 	Irssi::printformat(MSGLEVEL_CLIENTCRAP, 'trigger_header');
   1214 	my $i=1;
   1215 	foreach my $trigger (@triggers) {
   1216 		Irssi::printformat(MSGLEVEL_CLIENTCRAP, 'trigger_line', $i++, to_string($trigger));
   1217 	}
   1218 }
   1219 
   1220 ######################
   1221 ### initialisation ###
   1222 ######################
   1223 
   1224 command_bind('trigger help',\&cmd_help);
   1225 command_bind('help trigger',\&cmd_help);
   1226 command_bind('trigger add',\&cmd_add);
   1227 command_bind('trigger change',\&cmd_change);
   1228 command_bind('trigger move',\&cmd_move);
   1229 command_bind('trigger list',\&cmd_list);
   1230 command_bind('trigger delete',\&cmd_del);
   1231 command_bind('trigger save',\&cmd_save);
   1232 command_bind('trigger reload',\&cmd_load);
   1233 command_bind 'trigger' => sub {
   1234     my ( $data, $server, $item ) = @_;
   1235     $data =~ s/\s+$//g;
   1236     command_runsub('trigger', $data, $server, $item);
   1237 };
   1238 
   1239 Irssi::signal_add('setup saved', \&autosave);
   1240 Irssi::signal_add('setup changed', \&sig_setup_changed);
   1241 
   1242 # This makes tab completion work
   1243 Irssi::command_set_options('trigger add',join(' ',@trigger_add_options));
   1244 Irssi::command_set_options('trigger change',join(' ',@trigger_options));
   1245 
   1246 Irssi::settings_add_str($IRSSI{'name'}, 'trigger_file', Irssi::get_irssi_dir()."/triggers");
   1247 
   1248 cmd_load();