IRC-Utils-0.12000755001750001750 011643412024 13077 5ustar00hinrikhinrik000000000000README000644001750001750 2725311643412024 14070 0ustar00hinrikhinrik000000000000IRC-Utils-0.12NAME IRC::Utils - Common utilities for IRC-related tasks SYNOPSIS use strict; use warnings; use IRC::Utils ':ALL'; my $nickname = '^Lame|BOT[moo]'; my $uppercase_nick = uc_irc($nickname); my $lowercase_nick = lc_irc($nickname); print "They're equivalent\n" if eq_irc($uppercase_nick, $lowercase_nick); my $mode_line = 'ov+b-i Bob sue stalin*!*@*'; my $hashref = parse_mode_line($mode_line); my $banmask = 'stalin*'; my $full_banmask = normalize_mask($banmask); if (matches_mask($full_banmask, 'stalin!joe@kremlin.ru')) { print "EEK!"; } my $decoded = irc_decode($raw_irc_message); print $decoded, "\n"; if (has_color($message)) { print 'COLOR CODE ALERT!\n"; } my $results_hashref = matches_mask_array(\@masks, \@items_to_match_against); my $nick = parse_user('stalin!joe@kremlin.ru'); my ($nick, $user, $host) = parse_user('stalin!joe@kremlin.ru'); DESCRIPTION The functions in this module take care of many of the tasks you are faced with when working with IRC. Mode lines, ban masks, message encoding and formatting, etc. FUNCTIONS "uc_irc" Takes one mandatory parameter, a string to convert to IRC uppercase, and one optional parameter, the casemapping of the ircd (which can be 'rfc1459', 'strict-rfc1459' or 'ascii'. Default is 'rfc1459'). Returns the IRC uppercase equivalent of the passed string. "lc_irc" Takes one mandatory parameter, a string to convert to IRC lowercase, and one optional parameter, the casemapping of the ircd (which can be 'rfc1459', 'strict-rfc1459' or 'ascii'. Default is 'rfc1459'). Returns the IRC lowercase equivalent of the passed string. "eq_irc" Takes two mandatory parameters, IRC strings (channels or nicknames) to compare. A third, optional parameter specifies the casemapping. Returns true if the two strings are equivalent, false otherwise # long version lc_irc($one, $map) eq lc_irc($two, $map) # short version eq_irc($one, $two, $map) "parse_mode_line" Takes a list representing an IRC mode line. Returns a hashref. Optionally you can also supply an arrayref and a hashref to specify valid channel modes (default: "[qw(beI k l imnpstaqr)]") and status modes (default: "{o => '@', h => '%', v => '+'}"), respectively. If the modeline couldn't be parsed the hashref will be empty. On success the following keys will be available in the hashref: 'modes', an arrayref of normalised modes; 'args', an arrayref of applicable arguments to the modes; Example: my $hashref = parse_mode_line( 'ov+b-i', 'Bob', 'sue', 'stalin*!*@*' ); # $hashref will be: { modes => [ '+o', '+v', '+b', '-i' ], args => [ 'Bob', 'sue', 'stalin*!*@*' ], } "normalize_mask" Takes one parameter, a string representing an IRC mask. Returns a normalised full mask. Example: $fullbanmask = normalize_mask( 'stalin*' ); # $fullbanmask will be: 'stalin*!*@*'; "matches_mask" Takes two parameters, a string representing an IRC mask and something to match against the IRC mask, such as a nick!user@hostname string. Returns a true value if they match, a false value otherwise. Optionally, one may pass the casemapping (see "uc_irc"), as this function uses "uc_irc" internally. "matches_mask_array" Takes two array references, the first being a list of strings representing IRC masks, the second a list of somethings to test against the masks. Returns an empty hashref if there are no matches. Otherwise, the keys will be the masks matched, each value being an arrayref of the strings that matched it. Optionally, one may pass the casemapping (see "uc_irc"), as this function uses "uc_irc" internally. "unparse_mode_line" Takes one argument, a string representing a number of mode changes. Returns a condensed version of the changes. my $mode_line = unparse_mode_line('+o+o+o-v+v'); $mode_line is now '+ooo-v+v' "gen_mode_change" Takes two arguments, strings representing a set of IRC user modes before and after a change. Returns a string representing what changed. my $mode_change = gen_mode_change('abcde', 'befmZ'); $mode_change is now '-acd+fmZ' "parse_user" Takes one parameter, a string representing a user in the form nick!user@hostname. In a scalar context it returns just the nickname. In a list context it returns a list consisting of the nick, user and hostname, respectively. "is_valid_chan_name" Takes one argument, a channel name to validate. Returns true or false if the channel name is valid or not. You can supply a second argument, an array of characters of allowed channel prefixes. Defaults to "['#', '&']". "is_valid_nick_name" Takes one argument, a nickname to validate. Returns true or false if the nickname is valid or not. "numeric_to_name" Takes an IRC server numerical reply code (e.g. '001') as an argument, and returns the corresponding name (e.g. 'RPL_WELCOME'). "name_to_numeric" Takes an IRC server reply name (e.g. 'RPL_WELCOME') as an argument, and returns the corresponding numerical code (e.g. '001'). "has_color" Takes one parameter, a string of IRC text. Returns true if it contains any IRC color codes, false otherwise. Useful if you want your bot to kick users for (ab)using colors. :) "has_formatting" Takes one parameter, a string of IRC text. Returns true if it contains any IRC formatting codes, false otherwise. "strip_color" Takes one parameter, a string of IRC text. Returns the string stripped of all IRC color codes. "strip_formatting" Takes one parameter, a string of IRC text. Returns the string stripped of all IRC formatting codes. "decode_irc" This function takes a byte string (i.e. an unmodified IRC message) and returns a text string. Since the source encoding might have been UTF-8, you should store it with UTF-8 or some other Unicode encoding in your file/database/whatever to be safe. For a more detailed discussion, see "ENCODING". use IRC::Utils qw(decode_irc); sub message_handler { my ($nick, $channel, $message) = @_; # not wise, $message is a byte string of unkown encoding print $message, "\n"; $message = decode_irc($what); # good, $message is a text string print $message, "\n"; } CONSTANTS Use the following constants to add formatting and mIRC color codes to IRC messages. Normal text: NORMAL Formatting: BOLD UNDERLINE REVERSE ITALIC FIXED Colors: WHITE BLACK BLUE GREEN RED BROWN PURPLE ORANGE YELLOW LIGHT_GREEN TEAL LIGHT_CYAN LIGHT_BLUE PINK GREY LIGHT_GREY Individual non-color formatting codes can be cancelled with their corresponding constant, but you can also cancel all of them at once with "NORMAL". To cancel the effect of color codes, you must use "NORMAL". which of course has the side effect of cancelling all other formatting codes as well. $msg = 'This word is '.YELLOW.'yellow'.NORMAL.' while this word is'.BOLD.'bold'.BOLD; $msg = UNDERLINE.BOLD.'This sentence is both underlined and bold.'.NORMAL; ENCODING Messages The only encoding requirement the IRC protocol places on its messages is that they be 8-bits and ASCII-compatible. This has resulted in most of the Western world settling on ASCII-compatible Latin-1 (usually Microsoft's CP1252, a Latin-1 variant) as a convention. Recently, popular IRC clients (mIRC, xchat, certain irssi configurations) have begun sending a mixture of CP1252 and UTF-8 over the wire to allow more characters without breaking backward compatibility (too much). They send CP1252 encoded messages if the characters fit within that encoding, otherwise falling back to UTF-8, and likewise autodetecting the encoding (UTF-8 or CP1252) of incoming messages. Since writing text with mixed encoding to a file, terminal, or database is not a good idea, you need a way to decode messages from IRC. "decode_irc" will do that. Channel names The matter is complicated further by the fact that some servers allow non-ASCII characters in channel names. IRC modules generally don't explicitly encode or decode any IRC traffic, but they do have to concatenate parts of a message (e.g. a channel name and a message) before sending it over the wire. So when you do something like "privmsg($channel, 'æði')", where $channel is the unmodified channel name (a byte string) you got from an earlier IRC message, the channel name will get double-encoded when concatenated with your message (a non-ASCII text string) if the channel name contains non-ASCII bytes. To prevent this, you can't simply decode the channel name and then use it. '#æði' in CP1252 is not the same channel as '#æði' in UTF-8, since they are encoded as different sequences of bytes, and the IRC server only cares about the byte representation. Therefore, when using a channel name you got from the server (e.g. when replying to message), you should use the original byte string (before it has been decoded with "decode_irc"), and encode any other parameters (with "encode_utf8") so that your message will be concatenated correctly. At some point, you'll probably want to print the channel name, write it to a log file or use it in a filename, so you'll eventually have to decode it, at which point the UTF-8 "#æði" and CP1252 "#æði" will have to be considered equivalent. use Encode qw(encode_utf8 encode); sub message_handler { # these three are all byte strings my ($nick, $channel, $message) = @_; # bad: if $channel has any non-ASCII bytes, they will get double-encoded privmsg($channel, 'æði'); # bad: if $message has any non-ASCII bytes, they will get double-encoded privmsg('#æði', $message); # good: both are byte strings already, so they will concatenate correctly privmsg($channel, $message); # good: both are text strings (Latin1 as per Perl's default), so # they'll be concatenated correctly privmsg('#æði', 'æði'); # good: similar to the last one, except now they're using UTF-8, which # means that the channel is actually not the same as above use utf8; privmsg('#æði', 'æði'); # good: $channel and $msg_bytes are both byte strings my $msg_bytes = encode_utf8('æði'); privmsg($channel, $msg_bytes); # good: $chan_bytes and $message are both byte strings # here we're sending a message to the utf8-encoded #æði my $utf8_bytes = encode_utf8('#æði'); privmsg($utf8_bytes, $message); # good: $chan_bytes and $message are both byte strings # here we're sending a message to the cp1252-encoded #æði my $cp1252_bytes = encode('cp1252', '#æði'); privmsg($cp1252_bytes, $message); # bad: $channel is in an undetermined encoding log_message("Got message from $channel"); # good: using the decoded version of $channel log_message("Got message from ".decode_irc($channel)); } See also Encode, perluniintro, perlunitut, perlunicode, and perlunifaq. AUTHOR Hinrik Örn Sigurðsson ("Hinrik" irc.perl.org, or "literal" @ FreeNode). Chris "BinGOs" Williams SEE ALSO POE::Component::IRC POE::Component::Server::IRC Changes000644001750001750 363611643412024 14462 0ustar00hinrikhinrik000000000000IRC-Utils-0.12Revision history for IRC-Utils 0.12 Thu Oct 6 20:48:17 GMT 2011 - strip_formatting(): Only strip cancellation codes if there are no color codes in the string 0.11 Fri Jul 29 01:36:51 GMT 2011 - Fix typo causing numerics 333 and 338 to get mixed up - Add numerics 307 and 310, used by the Rizon network (hybrid+Plexus) 0.10 Sun May 22 16:12:50 GMT 2011 - Fix failure in parse_mask() when the mask doesn't contain '!' - matches_mask(): Don't call parse_mask() on the argument first - Rename parse_mask() to normalize_mask() for clarity 0.09 Fri May 20 03:22:30 GMT 2011 - More detailed explanation of channel name encoding issues - Add eq_irc() convenience function 0.08 Mon May 9 17:33:04 GMT 2011 - Don't allow channel names to be longer than 200 bytes - Don't allow colons in channel names (RFC2812 & IRCnet, though others are more lax) 0.07 Wed Apr 27 03:32:14 GMT 2011 - Add a bunch of new numerics and their names 0.06 Sun Apr 3 02:51:37 GMT 2011 - Add support for the blink formatting code - Document chanmode and statmode parameters to parse_mode_line() - Don't allow a digit as the first character of a nickname - Change RPL_BOUNCE (005) to RPL_ISUPPORT 0.05 Sun Apr 3 00:17:00 GMT 2011 - Rename l_irc() and u_irc() to the more descriptive lc_irc and uc_irc() 0.04 Sat Apr 2 23:57:08 GMT 2011 - Add numeric_to_name() and name_to_numeric() functions 0.03 Sat Apr 2 22:30:42 GMT 2011 - Rename parse_ban_mask() to parse_mask() 0.02 Sat Apr 2 21:22:02 GMT 2011 - matches_mask(): Return nothing if mask/match parameters have no length 0.01 Sat Apr 2 20:54:37 GMT 2011 - Initial release. Combines most things from POE::Component::IRC::Common and POE::Component::Server::IRC::Common. I gave some of the functions better names and changed some of the color name constants to better match the 'standard' names in use. LICENSE000644001750001750 4402111643412024 14205 0ustar00hinrikhinrik000000000000IRC-Utils-0.12This software is copyright (c) 2011 by Hinrik Örn Sigurðsson, Chris Williams. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2011 by Hinrik Örn Sigurðsson, Chris Williams. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2011 by Hinrik Örn Sigurðsson, Chris Williams. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End dist.ini000644001750001750 110611643412024 14621 0ustar00hinrikhinrik000000000000IRC-Utils-0.12name = IRC-Utils author = Hinrik Örn Sigurðsson author = Chris Williams copyright_holder = Hinrik Örn Sigurðsson, Chris Williams license = Perl_5 [@AVAR] dist = IRC-Utils authority = cpan:HINRIK bugtracker = rt use_CompileTests = 0 nextrelease_format = %-5v %{ccc MMM d HH:mm:ss V YYYY}d github_user = hinrik git_tag_message = CPAN release %v no_AutoPrereq = 1 [Prereqs / Runtime] ; for decent Unicode support perl = 5.008001 META.yml000644001750001750 143411643412024 14432 0ustar00hinrikhinrik000000000000IRC-Utils-0.12--- abstract: 'Common utilities for IRC-related tasks' author: - 'Hinrik Örn Sigurðsson ' - 'Chris Williams ' build_requires: {} configure_requires: ExtUtils::MakeMaker: 6.30 dynamic_config: 0 generated_by: 'Dist::Zilla version 4.200006, CPAN::Meta::Converter version 2.110440' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: 1.4 name: IRC-Utils no_index: directory: - t - xt - utils requires: perl: 5.008001 resources: bugtracker: https://rt.cpan.org/Public/Dist/Display.html?Name=IRC-Utils homepage: http://metacpan.org/release/IRC-Utils license: http://dev.perl.org/licenses/ repository: git://github.com/hinrik/irc-utils.git version: 0.12 x_authority: cpan:HINRIK MANIFEST000644001750001750 20711643412024 14267 0ustar00hinrikhinrik000000000000IRC-Utils-0.12Changes LICENSE MANIFEST MANIFEST.SKIP META.json META.yml Makefile.PL README dist.ini lib/IRC/Utils.pm t/01_compile.t t/02_functions.t META.json000644001750001750 256611643412024 14611 0ustar00hinrikhinrik000000000000IRC-Utils-0.12{ "abstract" : "Common utilities for IRC-related tasks", "author" : [ "Hinrik \u00c3\u0096rn Sigur\u00c3\u00b0sson ", "Chris Williams " ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 4.200006, CPAN::Meta::Converter version 2.110440", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : "2" }, "name" : "IRC-Utils", "no_index" : { "directory" : [ "t", "xt", "utils" ] }, "prereqs" : { "configure" : { "requires" : { "ExtUtils::MakeMaker" : "6.30" } }, "runtime" : { "requires" : { "perl" : "5.008001" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "mailto" : "bug-IRC-Utils@rt.cpan.org", "web" : "https://rt.cpan.org/Public/Dist/Display.html?Name=IRC-Utils" }, "homepage" : "http://metacpan.org/release/IRC-Utils", "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "type" : "git", "url" : "git://github.com/hinrik/irc-utils.git", "web" : "http://github.com/hinrik/irc-utils" } }, "version" : "0.12", "x_authority" : "cpan:HINRIK" } Makefile.PL000644001750001750 202111643412024 15124 0ustar00hinrikhinrik000000000000IRC-Utils-0.12 use strict; use warnings; BEGIN { require 5.008001; } use ExtUtils::MakeMaker 6.30; my %WriteMakefileArgs = ( 'ABSTRACT' => 'Common utilities for IRC-related tasks', 'AUTHOR' => 'Hinrik Örn Sigurðsson , Chris Williams ', 'BUILD_REQUIRES' => {}, 'CONFIGURE_REQUIRES' => { 'ExtUtils::MakeMaker' => '6.30' }, 'DISTNAME' => 'IRC-Utils', 'EXE_FILES' => [], 'LICENSE' => 'perl', 'NAME' => 'IRC::Utils', 'PREREQ_PM' => {}, 'VERSION' => '0.12', 'test' => { 'TESTS' => 't/*.t' } ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.56) } ) { my $br = delete $WriteMakefileArgs{BUILD_REQUIRES}; my $pp = $WriteMakefileArgs{PREREQ_PM}; for my $mod ( keys %$br ) { if ( exists $pp->{$mod} ) { $pp->{$mod} = $br->{$mod} if $br->{$mod} > $pp->{$mod}; } else { $pp->{$mod} = $br->{$mod}; } } } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); MANIFEST.SKIP000644001750001750 7311643412024 15015 0ustar00hinrikhinrik000000000000IRC-Utils-0.12^IRC-Utils- ^cover_db/ ^utils/developer/ ^xt/ ^README.pod$ t000755001750001750 011643412024 13263 5ustar00hinrikhinrik000000000000IRC-Utils-0.1201_compile.t000644001750001750 13111643412024 15512 0ustar00hinrikhinrik000000000000IRC-Utils-0.12/tuse strict; use warnings FATAL => 'all'; use Test::More tests => 1; use_ok 'IRC::Utils'; 02_functions.t000644001750001750 775311643412024 16134 0ustar00hinrikhinrik000000000000IRC-Utils-0.12/tuse strict; use warnings FATAL => 'all'; use Encode qw(encode); use IRC::Utils qw(:ALL); use Test::More tests => 46; is('SIMPLE', uc_irc('simple'), 'Upper simple test'); is('simple', lc_irc('SIMPLE'), 'Lower simple test'); is('C0MPL~[X]', uc_irc('c0mpl^{x}'), 'Upper complex test'); is('c0mpl^{x}', lc_irc('C0MPL~[X]'), 'Lower complex test'); is('C0MPL~[X]', uc_irc('c0mpl~[x]', 'ascii'), 'Upper complex test ascii'); is('c0mpl^{x}', lc_irc('C0MPL^{X}', 'ascii'), 'Lower complex test ascii'); is('C0MPL~[X]', uc_irc('c0mpl~{x}', 'strict-rfc1459'), 'Upper complex test strict'); is('c0mpl^{x}', lc_irc('C0MPL^[X]', 'strict-rfc1459'), 'Lower complex test strict'); ok(eq_irc('C0MPL~[X]', 'c0mpl~{x}'), 'eq_irc() considers them equivalent'); ok(is_valid_nick_name( 'm00[^]' ), 'Nickname is valid test'); ok(!is_valid_nick_name( 'm00[=]' ), 'Nickname is invalid test'); ok(is_valid_chan_name( '#chan.nel' ), 'Channel is valid test'); ok(!is_valid_chan_name( '#chan,nel' ), 'Channel is invalid'); ok(!is_valid_chan_name( '#chan'.join('', ('a') x 200)), 'Channel name too long'); is(unparse_mode_line('+o-v-o-o+v-o+o+o'), '+o-voo+v-o+oo', 'Unparsed mode line'); is(gen_mode_change('ailowz','i'), '-alowz', 'Gen mode changes 1'); is(gen_mode_change('i','ailowz'), '+alowz', 'Gen mode changes 2'); is(gen_mode_change('i','alowz'), '-i+alowz', 'Gen mode changes 3'); my $hashref = parse_mode_line(qw(ov rita bob)); is($hashref->{modes}->[0], '+o', 'Parse mode test 1'); is($hashref->{args}->[0], 'rita', 'Parse mode test 2'); my $hashref2 = parse_mode_line(qw(-b +b!*@*)); is($hashref2->{modes}->[0], '-b', 'Parse mode test 3'); is($hashref2->{args}->[0], '+b!*@*', 'Parse mode test 4'); my $hashref3 = parse_mode_line(qw(+b -b!*@*)); is($hashref3->{modes}->[0], '+b', 'Parse mode test 5'); is($hashref3->{args}->[0], '-b!*@*', 'Parse mode test 6'); my $partial_mask = normalize_mask('*@*'); is($partial_mask, '*!*@*', 'Normalized partial mask'); my $banmask = normalize_mask('stalin*'); my $match = 'stalin!joe@kremlin.ru'; my $no_match = 'BinGOs!foo@blah.com'; is($banmask, 'stalin*!*@*', 'Parse ban mask test'); ok(matches_mask($banmask, $match), 'Matches Mask test 1'); ok(!matches_mask($banmask, $no_match), 'Matches Mask test 2'); ok(%{ matches_mask_array([$banmask], [$match]) }, 'Matches Mask array test 1'); ok(!%{ matches_mask_array([$banmask], [$no_match] ) }, 'Matches Mask array test 2'); my $nick = parse_user('BinGOs!null@fubar.com'); my @args = parse_user('BinGOs!null@fubar.com'); is($nick, 'BinGOs', 'Parse User Test 1'); is($nick, $args[0], 'Parse User Test 2'); is($args[1], 'null', 'Parse User Test 3'); is($args[2], 'fubar.com', 'Parse User Test 4'); my $colored = "\x0304,05Hi, I am a color junkie\x03"; ok(has_color($colored), 'Has Color Test'); is(strip_color($colored), 'Hi, I am a color junkie', 'Strip Color Test'); my $bg_colored = "\x03,05Hi, observe my colored background\x03"; is(strip_color($bg_colored), 'Hi, observe my colored background', 'Strip bg color test'); my $fg_colored = "\x0305Hi, observe my colored foreground\x03"; is(strip_color($fg_colored), 'Hi, observe my colored foreground', 'Strip fg color test'); my $formatted = "This is \x02bold\x0f and this is \x1funderlined\x0f"; ok(has_formatting($formatted), 'Has Formatting Test'); my $stripped = strip_formatting($formatted); is($stripped, 'This is bold and this is underlined', 'Strip Formatting Test'); my $form_color = "Foo \x0305\x02bar\x0f baz"; my $no_color = strip_color($form_color); my $no_form = strip_formatting($form_color); is($no_color, "Foo \x02bar\x0f baz", "Only stripped colors"); is($no_form, "Foo \x0305bar\x0f baz", "Only stripped formatting"); my $string = "l\372\360i"; my $cp1252_bytes = encode('cp1252', $string); my $utf8_bytes = encode('utf8', $string); is(decode_irc($cp1252_bytes), $string, 'decode_irc() works for CP1252 text'); is(decode_irc($utf8_bytes), $string, 'decode_irc() works for UTF-8 text'); is(numeric_to_name('001'), 'RPL_WELCOME', 'RFC name 001 is correct'); is(name_to_numeric('RPL_MYINFO'), '004', 'RFC code 004 is correct'); IRC000755001750001750 011643412024 14203 5ustar00hinrikhinrik000000000000IRC-Utils-0.12/libUtils.pm000644001750001750 7235311643412024 16032 0ustar00hinrikhinrik000000000000IRC-Utils-0.12/lib/IRCpackage IRC::Utils; BEGIN { $IRC::Utils::AUTHORITY = 'cpan:HINRIK'; } BEGIN { $IRC::Utils::VERSION = '0.12'; } use strict; use warnings FATAL => 'all'; use Encode qw(decode); use Encode::Guess; require Exporter; use base qw(Exporter); our @EXPORT_OK = qw( uc_irc lc_irc parse_mode_line normalize_mask matches_mask matches_mask_array unparse_mode_line gen_mode_change parse_user is_valid_nick_name eq_irc decode_irc is_valid_chan_name has_color has_formatting strip_color strip_formatting NORMAL BOLD UNDERLINE REVERSE ITALIC FIXED WHITE BLACK BLUE GREEN RED BROWN PURPLE ORANGE YELLOW LIGHT_GREEN TEAL LIGHT_CYAN LIGHT_BLUE PINK GREY LIGHT_GREY numeric_to_name name_to_numeric ); our %EXPORT_TAGS = ( ALL => [@EXPORT_OK] ); use constant { # cancel all formatting and colors NORMAL => "\x0f", # formatting BOLD => "\x02", UNDERLINE => "\x1f", REVERSE => "\x16", ITALIC => "\x1d", FIXED => "\x11", BLINK => "\x06", # mIRC colors WHITE => "\x0300", BLACK => "\x0301", BLUE => "\x0302", GREEN => "\x0303", RED => "\x0304", BROWN => "\x0305", PURPLE => "\x0306", ORANGE => "\x0307", YELLOW => "\x0308", LIGHT_GREEN => "\x0309", TEAL => "\x0310", LIGHT_CYAN => "\x0311", LIGHT_BLUE => "\x0312", PINK => "\x0313", GREY => "\x0314", LIGHT_GREY => "\x0315", }; # list originally snatched from AnyEvent::IRC::Util our %NUMERIC2NAME = ( '001' => 'RPL_WELCOME', # RFC2812 '002' => 'RPL_YOURHOST', # RFC2812 '003' => 'RPL_CREATED', # RFC2812 '004' => 'RPL_MYINFO', # RFC2812 '005' => 'RPL_ISUPPORT', # draft-brocklesby-irc-isupport-03 '008' => 'RPL_SNOMASK', # Undernet '009' => 'RPL_STATMEMTOT', # Undernet '010' => 'RPL_STATMEM', # Undernet '020' => 'RPL_CONNECTING', # IRCnet '014' => 'RPL_YOURCOOKIE', # IRCnet '042' => 'RPL_YOURID', # IRCnet '043' => 'RPL_SAVENICK', # IRCnet '050' => 'RPL_ATTEMPTINGJUNC', # aircd '051' => 'RPL_ATTEMPTINGREROUTE', # aircd '200' => 'RPL_TRACELINK', # RFC1459 '201' => 'RPL_TRACECONNECTING', # RFC1459 '202' => 'RPL_TRACEHANDSHAKE', # RFC1459 '203' => 'RPL_TRACEUNKNOWN', # RFC1459 '204' => 'RPL_TRACEOPERATOR', # RFC1459 '205' => 'RPL_TRACEUSER', # RFC1459 '206' => 'RPL_TRACESERVER', # RFC1459 '207' => 'RPL_TRACESERVICE', # RFC2812 '208' => 'RPL_TRACENEWTYPE', # RFC1459 '209' => 'RPL_TRACECLASS', # RFC2812 '210' => 'RPL_STATS', # aircd '211' => 'RPL_STATSLINKINFO', # RFC1459 '212' => 'RPL_STATSCOMMANDS', # RFC1459 '213' => 'RPL_STATSCLINE', # RFC1459 '214' => 'RPL_STATSNLINE', # RFC1459 '215' => 'RPL_STATSILINE', # RFC1459 '216' => 'RPL_STATSKLINE', # RFC1459 '217' => 'RPL_STATSQLINE', # RFC1459 '218' => 'RPL_STATSYLINE', # RFC1459 '219' => 'RPL_ENDOFSTATS', # RFC1459 '221' => 'RPL_UMODEIS', # RFC1459 '231' => 'RPL_SERVICEINFO', # RFC1459 '233' => 'RPL_SERVICE', # RFC1459 '234' => 'RPL_SERVLIST', # RFC1459 '235' => 'RPL_SERVLISTEND', # RFC1459 '239' => 'RPL_STATSIAUTH', # IRCnet '241' => 'RPL_STATSLLINE', # RFC1459 '242' => 'RPL_STATSUPTIME', # RFC1459 '243' => 'RPL_STATSOLINE', # RFC1459 '244' => 'RPL_STATSHLINE', # RFC1459 '245' => 'RPL_STATSSLINE', # Bahamut, IRCnet, Hybrid '250' => 'RPL_STATSCONN', # ircu, Unreal '251' => 'RPL_LUSERCLIENT', # RFC1459 '252' => 'RPL_LUSEROP', # RFC1459 '253' => 'RPL_LUSERUNKNOWN', # RFC1459 '254' => 'RPL_LUSERCHANNELS', # RFC1459 '255' => 'RPL_LUSERME', # RFC1459 '256' => 'RPL_ADMINME', # RFC1459 '257' => 'RPL_ADMINLOC1', # RFC1459 '258' => 'RPL_ADMINLOC2', # RFC1459 '259' => 'RPL_ADMINEMAIL', # RFC1459 '261' => 'RPL_TRACELOG', # RFC1459 '262' => 'RPL_TRACEEND', # RFC2812 '263' => 'RPL_TRYAGAIN', # RFC2812 '265' => 'RPL_LOCALUSERS', # aircd, Bahamut, Hybrid '266' => 'RPL_GLOBALUSERS', # aircd, Bahamut, Hybrid '267' => 'RPL_START_NETSTAT', # aircd '268' => 'RPL_NETSTAT', # aircd '269' => 'RPL_END_NETSTAT', # aircd '270' => 'RPL_PRIVS', # ircu '271' => 'RPL_SILELIST', # ircu '272' => 'RPL_ENDOFSILELIST', # ircu '300' => 'RPL_NONE', # RFC1459 '301' => 'RPL_AWAY', # RFC1459 '302' => 'RPL_USERHOST', # RFC1459 '303' => 'RPL_ISON', # RFC1459 '305' => 'RPL_UNAWAY', # RFC1459 '306' => 'RPL_NOWAWAY', # RFC1459 '307' => 'RPL_WHOISREGNICK', # Bahamut, Unreal, Plexus '310' => 'RPL_WHOISMODES', # Plexus '311' => 'RPL_WHOISUSER', # RFC1459 '312' => 'RPL_WHOISSERVER', # RFC1459 '313' => 'RPL_WHOISOPERATOR', # RFC1459 '314' => 'RPL_WHOWASUSER', # RFC1459 '315' => 'RPL_ENDOFWHO', # RFC1459 '317' => 'RPL_WHOISIDLE', # RFC1459 '318' => 'RPL_ENDOFWHOIS', # RFC1459 '319' => 'RPL_WHOISCHANNELS', # RFC1459 '321' => 'RPL_LISTSTART', # RFC1459 '322' => 'RPL_LIST', # RFC1459 '323' => 'RPL_LISTEND', # RFC1459 '324' => 'RPL_CHANNELMODEIS', # RFC1459 '325' => 'RPL_UNIQOPIS', # RFC2812 '328' => 'RPL_CHANNEL_URL', # Bahamut, AustHex '329' => 'RPL_CREATIONTIME', # Bahamut '330' => 'RPL_WHOISACCOUNT', # ircu '331' => 'RPL_NOTOPIC', # RFC1459 '332' => 'RPL_TOPIC', # RFC1459 '333' => 'RPL_TOPICWHOTIME', # ircu '338' => 'RPL_WHOISACTUALLY', # Bahamut, ircu '340' => 'RPL_USERIP', # ircu '341' => 'RPL_INVITING', # RFC1459 '342' => 'RPL_SUMMONING', # RFC1459 '345' => 'RPL_INVITED', # GameSurge '346' => 'RPL_INVITELIST', # RFC2812 '347' => 'RPL_ENDOFINVITELIST', # RFC2812 '348' => 'RPL_EXCEPTLIST', # RFC2812 '349' => 'RPL_ENDOFEXCEPTLIST', # RFC2812 '351' => 'RPL_VERSION', # RFC1459 '352' => 'RPL_WHOREPLY', # RFC1459 '353' => 'RPL_NAMREPLY', # RFC1459 '354' => 'RPL_WHOSPCRPL', # ircu '355' => 'RPL_NAMREPLY_', # QuakeNet '361' => 'RPL_KILLDONE', # RFC1459 '362' => 'RPL_CLOSING', # RFC1459 '363' => 'RPL_CLOSEEND', # RFC1459 '364' => 'RPL_LINKS', # RFC1459 '365' => 'RPL_ENDOFLINKS', # RFC1459 '366' => 'RPL_ENDOFNAMES', # RFC1459 '367' => 'RPL_BANLIST', # RFC1459 '368' => 'RPL_ENDOFBANLIST', # RFC1459 '369' => 'RPL_ENDOFWHOWAS', # RFC1459 '371' => 'RPL_INFO', # RFC1459 '372' => 'RPL_MOTD', # RFC1459 '373' => 'RPL_INFOSTART', # RFC1459 '374' => 'RPL_ENDOFINFO', # RFC1459 '375' => 'RPL_MOTDSTART', # RFC1459 '376' => 'RPL_ENDOFMOTD', # RFC1459 '381' => 'RPL_YOUREOPER', # RFC1459 '382' => 'RPL_REHASHING', # RFC1459 '383' => 'RPL_YOURESERVICE', # RFC2812 '384' => 'RPL_MYPORTIS', # RFC1459 '385' => 'RPL_NOTOPERANYMORE', # AustHex, Hybrid, Unreal '391' => 'RPL_TIME', # RFC1459 '392' => 'RPL_USERSSTART', # RFC1459 '393' => 'RPL_USERS', # RFC1459 '394' => 'RPL_ENDOFUSERS', # RFC1459 '395' => 'RPL_NOUSERS', # RFC1459 '396' => 'RPL_HOSTHIDDEN', # Undernet '401' => 'ERR_NOSUCHNICK', # RFC1459 '402' => 'ERR_NOSUCHSERVER', # RFC1459 '403' => 'ERR_NOSUCHCHANNEL', # RFC1459 '404' => 'ERR_CANNOTSENDTOCHAN', # RFC1459 '405' => 'ERR_TOOMANYCHANNELS', # RFC1459 '406' => 'ERR_WASNOSUCHNICK', # RFC1459 '407' => 'ERR_TOOMANYTARGETS', # RFC1459 '408' => 'ERR_NOSUCHSERVICE', # RFC2812 '409' => 'ERR_NOORIGIN', # RFC1459 '411' => 'ERR_NORECIPIENT', # RFC1459 '412' => 'ERR_NOTEXTTOSEND', # RFC1459 '413' => 'ERR_NOTOPLEVEL', # RFC1459 '414' => 'ERR_WILDTOPLEVEL', # RFC1459 '415' => 'ERR_BADMASK', # RFC2812 '421' => 'ERR_UNKNOWNCOMMAND', # RFC1459 '422' => 'ERR_NOMOTD', # RFC1459 '423' => 'ERR_NOADMININFO', # RFC1459 '424' => 'ERR_FILEERROR', # RFC1459 '425' => 'ERR_NOOPERMOTD', # Unreal '429' => 'ERR_TOOMANYAWAY', # Bahamut '430' => 'ERR_EVENTNICKCHANGE', # AustHex '431' => 'ERR_NONICKNAMEGIVEN', # RFC1459 '432' => 'ERR_ERRONEUSNICKNAME', # RFC1459 '433' => 'ERR_NICKNAMEINUSE', # RFC1459 '436' => 'ERR_NICKCOLLISION', # RFC1459 '439' => 'ERR_TARGETTOOFAST', # ircu '440' => 'ERR_SERCVICESDOWN', # Bahamut, Unreal '441' => 'ERR_USERNOTINCHANNEL', # RFC1459 '442' => 'ERR_NOTONCHANNEL', # RFC1459 '443' => 'ERR_USERONCHANNEL', # RFC1459 '444' => 'ERR_NOLOGIN', # RFC1459 '445' => 'ERR_SUMMONDISABLED', # RFC1459 '446' => 'ERR_USERSDISABLED', # RFC1459 '447' => 'ERR_NONICKCHANGE', # Unreal '449' => 'ERR_NOTIMPLEMENTED', # Undernet '451' => 'ERR_NOTREGISTERED', # RFC1459 '455' => 'ERR_HOSTILENAME', # Unreal '459' => 'ERR_NOHIDING', # Unreal '460' => 'ERR_NOTFORHALFOPS', # Unreal '461' => 'ERR_NEEDMOREPARAMS', # RFC1459 '462' => 'ERR_ALREADYREGISTRED', # RFC1459 '463' => 'ERR_NOPERMFORHOST', # RFC1459 '464' => 'ERR_PASSWDMISMATCH', # RFC1459 '465' => 'ERR_YOUREBANNEDCREEP', # RFC1459 '466' => 'ERR_YOUWILLBEBANNED', # RFC1459 '467' => 'ERR_KEYSET', # RFC1459 '469' => 'ERR_LINKSET', # Unreal '471' => 'ERR_CHANNELISFULL', # RFC1459 '472' => 'ERR_UNKNOWNMODE', # RFC1459 '473' => 'ERR_INVITEONLYCHAN', # RFC1459 '474' => 'ERR_BANNEDFROMCHAN', # RFC1459 '475' => 'ERR_BADCHANNELKEY', # RFC1459 '476' => 'ERR_BADCHANMASK', # RFC2812 '477' => 'ERR_NOCHANMODES', # RFC2812 '478' => 'ERR_BANLISTFULL', # RFC2812 '481' => 'ERR_NOPRIVILEGES', # RFC1459 '482' => 'ERR_CHANOPRIVSNEEDED', # RFC1459 '483' => 'ERR_CANTKILLSERVER', # RFC1459 '484' => 'ERR_RESTRICTED', # RFC2812 '485' => 'ERR_UNIQOPPRIVSNEEDED', # RFC2812 '488' => 'ERR_TSLESSCHAN', # IRCnet '491' => 'ERR_NOOPERHOST', # RFC1459 '492' => 'ERR_NOSERVICEHOST', # RFC1459 '493' => 'ERR_NOFEATURE', # ircu '494' => 'ERR_BADFEATURE', # ircu '495' => 'ERR_BADLOGTYPE', # ircu '496' => 'ERR_BADLOGSYS', # ircu '497' => 'ERR_BADLOGVALUE', # ircu '498' => 'ERR_ISOPERLCHAN', # ircu '501' => 'ERR_UMODEUNKNOWNFLAG', # RFC1459 '502' => 'ERR_USERSDONTMATCH', # RFC1459 '503' => 'ERR_GHOSTEDCLIENT', # Hybrid ); our %NAME2NUMERIC; while (my ($key, $val) = each %NUMERIC2NAME) { $NAME2NUMERIC{$val} = $key; } sub numeric_to_name { my ($code) = @_; return $NUMERIC2NAME{$code}; } sub name_to_numeric { my ($name) = @_; return $NAME2NUMERIC{$name}; } sub uc_irc { my ($value, $type) = @_; return if !defined $value; $type = 'rfc1459' if !defined $type; $type = lc $type; if ($type eq 'ascii') { $value =~ tr/a-z/A-Z/; } elsif ($type eq 'strict-rfc1459') { $value =~ tr/a-z{}|/A-Z[]\\/; } else { $value =~ tr/a-z{}|^/A-Z[]\\~/; } return $value; } sub lc_irc { my ($value, $type) = @_; return if !defined $value; $type = 'rfc1459' if !defined $type; $type = lc $type; if ($type eq 'ascii') { $value =~ tr/A-Z/a-z/; } elsif ($type eq 'strict-rfc1459') { $value =~ tr/A-Z[]\\/a-z{}|/; } else { $value =~ tr/A-Z[]\\~/a-z{}|^/; } return $value; } sub eq_irc { my ($first, $second, $type) = @_; return if !defined $first || !defined $second; return 1 if lc_irc($first, $type) eq lc_irc($second, $type); return; } sub parse_mode_line { my @args = @_; my $chanmodes = [qw(beI k l imnpstaqr)]; my $statmodes = 'ohv'; my $hashref = { }; my $count = 0; while (my $arg = shift @args) { if ( ref $arg eq 'ARRAY' ) { $chanmodes = $arg; next; } elsif (ref $arg eq 'HASH') { $statmodes = join '', keys %{ $arg }; next; } elsif ($arg =~ /^[-+]/ or $count == 0) { my $action = '+'; for my $char (split //, $arg) { if ($char eq '+' or $char eq '-') { $action = $char; } else { push @{ $hashref->{modes} }, $action . $char; } if (length $chanmodes->[0] && length $chanmodes->[1] && length $statmodes && $char =~ /[$statmodes$chanmodes->[0]$chanmodes->[1]]/) { push @{ $hashref->{args} }, shift @args; } if (length $chanmodes->[2] && $action eq '+' && $char =~ /[$chanmodes->[2]]/) { push @{ $hashref->{args} }, shift @args; } } } else { push @{ $hashref->{args} }, $arg; } $count++; } return $hashref; } sub normalize_mask { my ($arg) = @_; return if !defined $arg; $arg =~ s/\*{2,}/*/g; my @mask; my $remainder; if ($arg !~ /!/ and $arg =~ /@/) { $remainder = $arg; $mask[0] = '*'; } else { ($mask[0], $remainder) = split /!/, $arg, 2; } $remainder =~ s/!//g if defined $remainder; @mask[1..2] = split(/@/, $remainder, 2) if defined $remainder; $mask[2] =~ s/@//g if defined $mask[2]; for my $i (1..2) { $mask[$i] = '*' if !defined $mask[$i]; } return $mask[0] . '!' . $mask[1] . '@' . $mask[2]; } sub unparse_mode_line { my ($line) = @_; return if !defined $line || !length $line; my $action; my $return; for my $mode ( split(//,$line) ) { if ($mode =~ /^(\+|-)$/ && (!$action || $mode ne $action)) { $return .= $mode; $action = $mode; next; } $return .= $mode if ($mode ne '+' and $mode ne '-'); } $return =~ s/[+-]$//; return $return; } sub gen_mode_change { my ($before, $after) = @_; $before = '' if !defined $before; $after = '' if !defined $after; my @before = split //, $before; my @after = split //, $after; my $string = ''; my @hunks = _diff(\@before, \@after); $string .= $_->[0] . $_->[1] for @hunks; return unparse_mode_line($string); } sub is_valid_nick_name { my ($nickname) = @_; return if !defined $nickname || !length $nickname; return 1 if $nickname =~ /^[A-Za-z_`\-^\|\\\{}\[\]][A-Za-z_0-9`\-^\|\\\{}\[\]]*$/; return; } sub is_valid_chan_name { my $channel = shift; my $chantypes = shift || ['#', '&']; return if !@$chantypes; my $chanprefix = join '', @$chantypes; return if !defined $channel || !length $channel; return if bytes::length($channel) > 200; return 1 if $channel =~ /^[$chanprefix][^ \a\0\012\015,:]+$/; return; } sub matches_mask_array { my ($masks, $matches, $mapping) = @_; return if !defined $masks || !defined $matches; return if ref $masks ne 'ARRAY'; return if ref $matches ne 'ARRAY'; my $ref = { }; for my $mask (@$masks) { for my $match (@$matches) { if (matches_mask($mask, $match, $mapping)) { push @{ $ref->{ $mask } }, $match; } } } return $ref; } sub matches_mask { my ($mask, $match, $mapping) = @_; return if !defined $mask || !length $mask; return if !defined $match || !length $match; my $umask = quotemeta uc_irc($mask, $mapping); $umask =~ s/\\\*/[\x01-\xFF]{0,}/g; $umask =~ s/\\\?/[\x01-\xFF]{1,1}/g; $match = uc_irc($match, $mapping); return 1 if $match =~ /^$umask$/; return; } sub parse_user { my ($user) = @_; return if !defined $user; my ($n, $u, $h) = split /[!@]/, $user; return ($n, $u, $h) if wantarray(); return $n; } sub has_color { my ($string) = @_; return if !defined $string; return 1 if $string =~ /[\x03\x04\x1B]/; return; } sub has_formatting { my ($string) = @_; return if !defined $string; return 1 if $string =~/[\x02\x1f\x16\x1d\x11\x06]/; return; } sub strip_color { my ($string) = @_; return if !defined $string; # mIRC colors $string =~ s/\x03(?:,\d{1,2}|\d{1,2}(?:,\d{1,2})?)?//g; # RGB colors supported by some clients $string =~ s/\x04[0-9a-fA-F]{0,6}//ig; # see ECMA-48 + advice by urxvt author $string =~ s/\x1B\[.*?[\x00-\x1F\x40-\x7E]//g; # strip cancellation codes too if there are no formatting codes $string =~ s/\x0f//g if !has_formatting($string); return $string; } sub strip_formatting { my ($string) = @_; return if !defined $string; $string =~ s/[\x02\x1f\x16\x1d\x11\x06]//g; # strip cancellation codes too if there are no color codes $string =~ s/\x0f//g if !has_color($string); return $string; } sub decode_irc { my ($line) = @_; my $utf8 = guess_encoding($line, 'utf8'); return ref $utf8 ? decode('utf8', $line) : decode('cp1252', $line); } sub _diff { my ($before, $after) = @_; my %in_before; @in_before{@$before} = (); my %in_after; @in_after{@$after} = (); my (@diff, %seen); for my $seen (@$before) { next if exists $seen{$seen} || exists $in_after{$seen}; $seen{$seen} = 1; push @diff, ['-', $seen]; } %seen = (); for my $seen (@$after) { next if exists $seen{$seen} || exists $in_before{$seen}; $seen{$seen} = 1; push @diff, ['+', $seen]; } return @diff; } 1; =encoding utf8 =head1 NAME IRC::Utils - Common utilities for IRC-related tasks =head1 SYNOPSIS use strict; use warnings; use IRC::Utils ':ALL'; my $nickname = '^Lame|BOT[moo]'; my $uppercase_nick = uc_irc($nickname); my $lowercase_nick = lc_irc($nickname); print "They're equivalent\n" if eq_irc($uppercase_nick, $lowercase_nick); my $mode_line = 'ov+b-i Bob sue stalin*!*@*'; my $hashref = parse_mode_line($mode_line); my $banmask = 'stalin*'; my $full_banmask = normalize_mask($banmask); if (matches_mask($full_banmask, 'stalin!joe@kremlin.ru')) { print "EEK!"; } my $decoded = irc_decode($raw_irc_message); print $decoded, "\n"; if (has_color($message)) { print 'COLOR CODE ALERT!\n"; } my $results_hashref = matches_mask_array(\@masks, \@items_to_match_against); my $nick = parse_user('stalin!joe@kremlin.ru'); my ($nick, $user, $host) = parse_user('stalin!joe@kremlin.ru'); =head1 DESCRIPTION The functions in this module take care of many of the tasks you are faced with when working with IRC. Mode lines, ban masks, message encoding and formatting, etc. =head1 FUNCTIONS =head2 C Takes one mandatory parameter, a string to convert to IRC uppercase, and one optional parameter, the casemapping of the ircd (which can be B<'rfc1459'>, B<'strict-rfc1459'> or B<'ascii'>. Default is B<'rfc1459'>). Returns the IRC uppercase equivalent of the passed string. =head2 C Takes one mandatory parameter, a string to convert to IRC lowercase, and one optional parameter, the casemapping of the ircd (which can be B<'rfc1459'>, B<'strict-rfc1459'> or B<'ascii'>. Default is B<'rfc1459'>). Returns the IRC lowercase equivalent of the passed string. =head2 C Takes two mandatory parameters, IRC strings (channels or nicknames) to compare. A third, optional parameter specifies the casemapping. Returns true if the two strings are equivalent, false otherwise # long version lc_irc($one, $map) eq lc_irc($two, $map) # short version eq_irc($one, $two, $map) =head2 C Takes a list representing an IRC mode line. Returns a hashref. Optionally you can also supply an arrayref and a hashref to specify valid channel modes (default: C<[qw(beI k l imnpstaqr)]>) and status modes (default: C<< {o => '@', h => '%', v => '+'} >>), respectively. If the modeline couldn't be parsed the hashref will be empty. On success the following keys will be available in the hashref: B<'modes'>, an arrayref of normalised modes; B<'args'>, an arrayref of applicable arguments to the modes; Example: my $hashref = parse_mode_line( 'ov+b-i', 'Bob', 'sue', 'stalin*!*@*' ); # $hashref will be: { modes => [ '+o', '+v', '+b', '-i' ], args => [ 'Bob', 'sue', 'stalin*!*@*' ], } =head2 C Takes one parameter, a string representing an IRC mask. Returns a normalised full mask. Example: $fullbanmask = normalize_mask( 'stalin*' ); # $fullbanmask will be: 'stalin*!*@*'; =head2 C Takes two parameters, a string representing an IRC mask and something to match against the IRC mask, such as a nick!user@hostname string. Returns a true value if they match, a false value otherwise. Optionally, one may pass the casemapping (see L|/uc_irc>), as this function uses C internally. =head2 C Takes two array references, the first being a list of strings representing IRC masks, the second a list of somethings to test against the masks. Returns an empty hashref if there are no matches. Otherwise, the keys will be the masks matched, each value being an arrayref of the strings that matched it. Optionally, one may pass the casemapping (see L|/uc_irc>), as this function uses C internally. =head2 C Takes one argument, a string representing a number of mode changes. Returns a condensed version of the changes. my $mode_line = unparse_mode_line('+o+o+o-v+v'); $mode_line is now '+ooo-v+v' =head2 C Takes two arguments, strings representing a set of IRC user modes before and after a change. Returns a string representing what changed. my $mode_change = gen_mode_change('abcde', 'befmZ'); $mode_change is now '-acd+fmZ' =head2 C Takes one parameter, a string representing a user in the form nick!user@hostname. In a scalar context it returns just the nickname. In a list context it returns a list consisting of the nick, user and hostname, respectively. =head2 C Takes one argument, a channel name to validate. Returns true or false if the channel name is valid or not. You can supply a second argument, an array of characters of allowed channel prefixes. Defaults to C<['#', '&']>. =head2 C Takes one argument, a nickname to validate. Returns true or false if the nickname is valid or not. =head2 C Takes an IRC server numerical reply code (e.g. '001') as an argument, and returns the corresponding name (e.g. 'RPL_WELCOME'). =head2 C Takes an IRC server reply name (e.g. 'RPL_WELCOME') as an argument, and returns the corresponding numerical code (e.g. '001'). =head2 C Takes one parameter, a string of IRC text. Returns true if it contains any IRC color codes, false otherwise. Useful if you want your bot to kick users for (ab)using colors. :) =head2 C Takes one parameter, a string of IRC text. Returns true if it contains any IRC formatting codes, false otherwise. =head2 C Takes one parameter, a string of IRC text. Returns the string stripped of all IRC color codes. =head2 C Takes one parameter, a string of IRC text. Returns the string stripped of all IRC formatting codes. =head2 C This function takes a byte string (i.e. an unmodified IRC message) and returns a text string. Since the source encoding might have been UTF-8, you should store it with UTF-8 or some other Unicode encoding in your file/database/whatever to be safe. For a more detailed discussion, see L. use IRC::Utils qw(decode_irc); sub message_handler { my ($nick, $channel, $message) = @_; # not wise, $message is a byte string of unkown encoding print $message, "\n"; $message = decode_irc($what); # good, $message is a text string print $message, "\n"; } =head1 CONSTANTS Use the following constants to add formatting and mIRC color codes to IRC messages. Normal text: NORMAL Formatting: BOLD UNDERLINE REVERSE ITALIC FIXED Colors: WHITE BLACK BLUE GREEN RED BROWN PURPLE ORANGE YELLOW LIGHT_GREEN TEAL LIGHT_CYAN LIGHT_BLUE PINK GREY LIGHT_GREY Individual non-color formatting codes can be cancelled with their corresponding constant, but you can also cancel all of them at once with C. To cancel the effect of color codes, you must use C. which of course has the side effect of cancelling all other formatting codes as well. $msg = 'This word is '.YELLOW.'yellow'.NORMAL.' while this word is'.BOLD.'bold'.BOLD; $msg = UNDERLINE.BOLD.'This sentence is both underlined and bold.'.NORMAL; =head1 ENCODING =head2 Messages The only encoding requirement the IRC protocol places on its messages is that they be 8-bits and ASCII-compatible. This has resulted in most of the Western world settling on ASCII-compatible Latin-1 (usually Microsoft's CP1252, a Latin-1 variant) as a convention. Recently, popular IRC clients (mIRC, xchat, certain irssi configurations) have begun sending a mixture of CP1252 and UTF-8 over the wire to allow more characters without breaking backward compatibility (too much). They send CP1252 encoded messages if the characters fit within that encoding, otherwise falling back to UTF-8, and likewise autodetecting the encoding (UTF-8 or CP1252) of incoming messages. Since writing text with mixed encoding to a file, terminal, or database is not a good idea, you need a way to decode messages from IRC. L|/decode_irc> will do that. =head2 Channel names The matter is complicated further by the fact that some servers allow non-ASCII characters in channel names. IRC modules generally don't explicitly encode or decode any IRC traffic, but they do have to concatenate parts of a message (e.g. a channel name and a message) before sending it over the wire. So when you do something like C<< privmsg($channel, 'æði') >>, where C<$channel> is the unmodified channel name (a byte string) you got from an earlier IRC message, the channel name will get double-encoded when concatenated with your message (a non-ASCII text string) if the channel name contains non-ASCII bytes. To prevent this, you can't simply L the channel name and then use it. C<'#æði'> in CP1252 is not the same channel as C<'#æði'> in UTF-8, since they are encoded as different sequences of bytes, and the IRC server only cares about the byte representation. Therefore, when using a channel name you got from the server (e.g. when replying to message), you should use the original byte string (before it has been decoded with L|/decode_irc>), and encode any other parameters (with L|Encode>) so that your message will be concatenated correctly. At some point, you'll probably want to print the channel name, write it to a log file or use it in a filename, so you'll eventually have to decode it, at which point the UTF-8 C<#æði> and CP1252 C<#æði> will have to be considered equivalent. use Encode qw(encode_utf8 encode); sub message_handler { # these three are all byte strings my ($nick, $channel, $message) = @_; # bad: if $channel has any non-ASCII bytes, they will get double-encoded privmsg($channel, 'æði'); # bad: if $message has any non-ASCII bytes, they will get double-encoded privmsg('#æði', $message); # good: both are byte strings already, so they will concatenate correctly privmsg($channel, $message); # good: both are text strings (Latin1 as per Perl's default), so # they'll be concatenated correctly privmsg('#æði', 'æði'); # good: similar to the last one, except now they're using UTF-8, which # means that the channel is actually not the same as above use utf8; privmsg('#æði', 'æði'); # good: $channel and $msg_bytes are both byte strings my $msg_bytes = encode_utf8('æði'); privmsg($channel, $msg_bytes); # good: $chan_bytes and $message are both byte strings # here we're sending a message to the utf8-encoded #æði my $utf8_bytes = encode_utf8('#æði'); privmsg($utf8_bytes, $message); # good: $chan_bytes and $message are both byte strings # here we're sending a message to the cp1252-encoded #æði my $cp1252_bytes = encode('cp1252', '#æði'); privmsg($cp1252_bytes, $message); # bad: $channel is in an undetermined encoding log_message("Got message from $channel"); # good: using the decoded version of $channel log_message("Got message from ".decode_irc($channel)); } See also L, L, L, L, and L. =head1 AUTHOR Hinrik Ern SigurEsson (C irc.perl.org, or C @ FreeNode). Chris C Williams =head1 SEE ALSO L L =cut