Edgar

From S23Wiki

A PHP IRC bot based on the CodeDemons PHP IRC bot skeleton with a few extra functions like MD5 sum forward and reverse and rudimentary Wikipedia and Wiktionary lookup.

[edit] Triggers

Edgar what is your purpose  ->  Help text, link to this page
schwerer fehler / bug / error / kaputt  -> Get random excuse
!lang  -> language codes (examples: !lang es  !lang deu  !lang Georgian)
!gf  -> Googlefight (example: !gf fnord foobar)
!radio -> Current song playing 
!version / !revision -> Show current version
wann geht die sonne auf
wann geht die sonne unter
wie lang ist der tag
wie lang ist der tag
spy on  ->  Search for a nickname on different IRC networks (Example: spy on fnord)
dollar  ->  Get the Euro/Dollar conversion rate 
swear at -> Swear at a nick or something (Example: swear at John)
teach -> make Edgar teach padma a term from Wiktionary (Example: teach fnord)
0900 -> lookup the registrar of a German 0900 number (Example: 0900 666666)
http.. -> shows link title of a given URL
neue exploits -> Get latest exploits from milw0rm RSS feed (Example: gibt es neue sicherheitsluecken?) 
define ->  Get a word definition from Wiktionary (Example: define butterfly)
FNORD -> FNORD!!!!
IATA -> Get IATA airport codes from db (switched off)
SONG -> Last track played on some webradio
!svn -> show latest svn commit
!boinc -> show SETI@home statistics (Example: !boinc DrOwl  !boinc 72648)
whois-> Check the owner of an IP (Example: whois 127.0.0.1)
!geo -> Get geo/location data for an IP (Example: !geo 1.2.3.4)
!md5 -> MD5 checksums forward and reverse (Example: !md5 -f fnord  !md5 -r b15e400c8dbd6697f26385216d32a40f)
!help -> Incomplete help text
!wp -> Lookup (English or German) Wikipedia (Example: !wp en chimpanzee  !wp en Schimpanse)
!wk -> Lookup Wiktionary (Example: !wk en soup  !wp de Suppe)
!s23 -> Lookup S23 Wiki (Example: !s23 Edgar)
!r13 -> rot13 a word (Example: !r13 foobar)
!dns -> DNS lookup (Example: !dns fnord.org)


#!/usr/bin/php
<?php

/*
edgar, the php IRC bot, has its skeleton from demonbot, a demonstration from codedemons.net
own functions added and changed by members of s23.org
http://s23.org/wiki/Edgar
*/

$version = ""; //This line will be automaticaly edited by the update-script. Dont change this line!

/* Variables that determine server, channel, etc */
$CONFIG = array ();
$CONFIG['server'] = 'irc.efnet.ch'; // server (i.e. irc.gamesnet.net)
$CONFIG['nick'] = 'Edgar23'; // nick (i.e. demonbot
$CONFIG['port'] = 6667; // port (standard: 6667)
$CONFIG['channel'][] = '#s23'; // channel  (i.e. #php)
$CONFIG['channel'][] = '#seti23';
$CONFIG['channel'][] = '#bots';
$CONFIG['channel'][] = '#wiki';
$CONFIG['channel'][] = '#debian';
$CONFIG['name'] = 'Edgar Alice Pope'; // bot name (i.e. demonbot)
$CONFIG['admin_pass'] = 'XXXXXX'; // admin pass (to change settings remotely)
$CONFIG['myident'] = 'mutante';
$CONFIG['myhost'] = 'irc.s23.org';

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

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

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

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

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

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

                cmd_send("USER " . $CONFIG['name'] . " " . $CONFIG['myident'] . " " . $CONFIG['myhost'] . " " . $CONFIG['server'] . " :" . $CONFIG['nick']);
                cmd_send("NICK " . $CONFIG['nick']);

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

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

                        /* If the server is PINGing, then PONG. This is to tell the server that
                        we are still here, and have not lost the connection */

                        if (substr($con['buffer']['all'], 0, 6) == 'PING :') {
                                /* PONG : is followed by the line that the server
                                sent us when PINGing */
                                cmd_send('PONG :' . substr($con['buffer']['all'], 6));
                        }

                        /* If this is the first time we have reached this point,
                        then JOIN the channel */
                        if ($firstTime == true) {
                                foreach ($CONFIG['channel'] as $channel_name) {
                                        cmd_send("JOIN " . $channel_name);
                                }
                                /* The next time we get here, it will NOT be the firstTime */
                                $firstTime = false;
                        }
                        /* Make sure that we have a NEW line of chats to analyse. If we don't,
                        there is no need to parse the data again */
                        elseif ($old_buffer != $con['buffer']['all']) {
                                /* Determine the patterns to be passed
                                to parse_buffer(). buffer is in the form:
                                :username!~identd@hostname JOIN :#php
                                :username!~identd@hostname PRIVMSG #PHP :action text
                                :username!~identd@hostname command channel :text */

                                /*
                                Right now this bot does nothing. But this is where you would
                                add some conditions, or see what is being said in the chat, and then
                                respond. Before you try doing that you should become familiar with
                                how commands are send over IRC. Just read the console when you run this
                                script, and then you will see the patterns in chats, i.e. where the username
                                occurs, where the hostmask is, etc. All you need is functions such as
                                preg_replace_callback(), or perhaps your own function that checks for patterns
                                in the text.

                                Good Luck.
                                */
                                parse_buffer();

                                ### Triggers

                                # let the bot answer to the question "What is your purpose"
                                if (preg_match("/What.*your purpose/i", $con['buffer']['text']) || preg_match("/^(Edgar|" . $CONFIG['nick'] . ").*(purpose|bot)/i", $con['buffer']['text'])) {
                                        cmd_send(prep_text("I'm here to help you with a lot of little tools. See also https://s23.org/wiki/Edgar")); //Bitte an alle: Dieser Text kann *deutlich* verbessert werden - wie w?re es mit einer Wiki-Seite die alle (relevanten) Commandos aufzaehlt, die edgar versteht?
                                }

                                # took's trigger for random excuses for bugs
                                if (preg_match("/(schwerer? fehler| error )/i", $con['buffer']['text'])) {
                                        cmd_send(prep_text("somebody said the bug was caused by a " . get_excuse()));
                                } else
                                if (preg_match("/(fix.* (bug|error))/i", $con['buffer']['text'])) {
                                        cmd_send(prep_text("The bug is caused by a " . get_excuse() . "! Sorry - Nothing I can help with..."));
                                        if (rand(0, 1) == 0 || preg_match("/(pls|please|bitte)/i", $con['buffer']['text'])) {
                                                $foo = explode(" ", "Padma Tentacle Mutante Tentacle Mutante Cavac Took Finn Finn Finn DrOwl Fnord Cosmea Phrack Hundfred");
                                                $foo = $foo[array_rand($foo)];
                                                cmd_send(prep_text("Maybe " . $foo . " is able to fix this?"));
                                        }
                                } else
                                if (preg_match("/(kapp?ut)/i", $con['buffer']['text'])) {
                                        cmd_send(prep_text("It's a " . get_excuse() . "..."));
                                }

                                # language codes (ISO 639)

                                if (substr($con['buffer']['text'], 0, 5) == "!lang") {


                                        # check length of commandline option
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $language = $arguments[1];

                                        switch (strlen($language)) {

                                                # if 2 or 3 chars long, consider it a code
                                                case 2:
                                                case 3:
                                                $alpha=$language;
                                                $result=alpha2lang("$alpha");
                                                cmd_send(prep_text("$result"));
                                                break;

                                                # if longer, consider it a language name
                                                default:

                                                $langname=$language;
                                                $result=lang2alpha("$langname");
                                                cmd_send(prep_text("$result"));
                                        }

                                }


                                # googlefight trigger !gf
                                if (substr($con['buffer']['text'], 0, 3) == "!gf") {
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $term1 = $arguments[1];
                                        $term2 = $arguments[2];
                                        cmd_send(prep_text(googlefight($term1, $term2)));
                                }
                                # trigger for comfort radio "current song"

                                if (substr($con['buffer']['text'], 0, 6) == "!radio") {
                                        cmd_send(prep_text(comfort()));
                                }

                                # show revision number
                                if (substr($con['buffer']['text'], 0, 8) == "!version" OR substr($con['buffer']['text'], 0, 9) == "!revision") {
                                        cmd_send(prep_text("Edgar is alive again at revision " . $version));
                                }


                                # Sonnenaufgang und -untergang und so

                                if (substr($con['buffer']['text'], 0, 23) == "wann geht die sonne auf") {
                                        cmd_send(prep_text(sonne("auf")));
                                }

                                if (substr($con['buffer']['text'], 0, 25) == "wann geht die sonne unter") {
                                        cmd_send(prep_text(sonne("unter")));
                                }

                                if (substr($con['buffer']['text'], 0, 20) == "wie lang ist der tag") {
                                        cmd_send(prep_text(sonne("lang")));
                                }

                                if (substr($con['buffer']['text'], 0, 21) == "welcher tag ist heute") {
                                        cmd_send(prep_text(sonne("heute")));
                                }

                                # ircspy trigger "spy on $nick"
                                if (substr($con['buffer']['text'], 0, 6) == "spy on") {
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $nick = $arguments[2];
                                        cmd_send(prep_text("Spying on $nick..."));
                                        cmd_send(prep_text(ircspy($nick)));
                                }

                                # dollar rate
                                if (substr($con['buffer']['text'], 0, 6) == "dollar") {
                                        cmd_send(prep_text(dollar_euro()));
                                }

                                # swear at $user feature
                                if (substr($con['buffer']['text'], 0, 8) == "swear at") {
                                        $arguments=explode(" ",$con['buffer']['text']);
                                        $target=$arguments[2];
                                        $arguments=explode(" in ",$con['buffer']['text']);
                                        $language=$arguments[1];
                                        cmd_send(prep_text(swear($language,$target)));
                                }


                                # trigger to teach padma (infobot/flooterbuck) from wiktionary
                                # calls wiktionary_teach , see below


                                if (substr($con['buffer']['text'], 0, 5) == "teach") {
                                        $arguments=explode(" ",$con['buffer']['text']);
                                        $language=$arguments[1];
                                        $pagename=$arguments[2];

                                        if (isset($arguments[3])) {
                                                $pagename=$arguments[2]."_".$arguments[3];
                                        }
                                        if (isset($arguments[4])) {
                                                $pagename=$arguments[2]."_".$arguments[3]."_".$arguments[4];
                                        }
                                        if (isset($arguments[5])) {
                                                $pagename=$arguments[2]."_".$arguments[3]."_".$arguments[4]."_".$arguments[5];
                                        }

                                        if (($language=="en" OR $language=="de") AND (isset($pagename))) {
                                                cmd_send(prep_text(wiktionary_teach($language,$pagename)." \n"));
                                        } else {
                                                $pagename=$arguments[1];

                                                if (isset($arguments[2])) {
                                                        $pagename=$arguments[1]."_".$arguments[2];
                                                }
                                                if (isset($arguments[3])) {
                                                        $pagename=$arguments[1]."_".$arguments[2]."_".$arguments[3];
                                                }
                                                if (isset($arguments[4])) {
                                                        $pagename=$arguments[1]."_".$arguments[2]."_".$arguments[3]."_".$arguments[4];
                                                }
                                                $language="en";
                                                cmd_send(prep_text(wiktionary_teach($language,$pagename)." \n"));
                                        }
                                }


                                # lookup 0900 numbers
                                if (substr($con['buffer']['text'], 0, 4) == "0900") {
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $number = $arguments[1];
                                        cmd_send(prep_text(ninehundred($number)));
                                }

                                # lookup linktitles
                                if (preg_match("@^(.* |)(https?://[^ ]*).*@i", $con['buffer']['text'], $link)) {
                                        cmd_send(prep_text(linktitle($link[2])));
                                }

                                # get exploits from milw0rm.com RSS feed
                                if (preg_match("/(neue? exploits| sicherheitsluecken )/i", $con['buffer']['text'])) {
                                        cmd_send(prep_text(getexploits()));
                                }

                                # "define <word>"-trigger - Using Wiktionary like on Edgar's brother on #wiktionary Freenode

                                if (substr($con['buffer']['text'], 0, 6) == "define") {
                                        $arguments=explode(" ",$con['buffer']['text']);
                                        $language=$arguments[1];
                                        $pagename=$arguments[2];
                                        array_shift($arguments);

                                        # better code by took
                                        if (isset($arguments[2])) {
                                                $i=1; $pagename='';
                                                foreach($arguments as $arg) {
                                                        if ($i++>20) break;
                                                        $pagename .= $arg.'_';
                                                }
                                                $pagename = substr($pagename, 0, -1);
                                        }
                                        if (($language=="en" OR $language=="de") AND (isset($pagename))) {
                                                cmd_send(prep_text(wiktionary($language,$pagename)." \n"));
                                        } else {
                                                $pagename=$arguments[1];

                                                # better code by took
                                                if (isset($arguments[2])) {
                                                        $i=1; $pagename='';
                                                        foreach($arguments as $arg) {
                                                                if ($i++>20) break;
                                                                $pagename .= $arg.'_';
                                                        }
                                                        $pagename = substr($pagename, 0, -1);
                                                }
                                                $language="en";
                                                cmd_send(prep_text(wiktionary($language,$pagename)." \n"));
                                        }
                                }
                                # standard 4 character commands (!cmd)

                                switch (substr($con['buffer']['text'], 0, 4)) {

                                        case "FNOR" :
                                        cmd_send(prep_text("FNORD!!!!"));
                                        break;

                                        /* vor?bergehend abgeschaltet, da die ben?tigten tabellen in der db offenbar nicht vorhanden sind */
                                        //					case "IATA" :
                                        //						$arguments = explode(" ", $con['buffer']['text']);
                                        //						$code = $arguments[1];
                                        //						cmd_send(prep_text(iata($code)));
                                        //						break;

                                        case "SONG" :
                                        cmd_send(prep_text(lasttrack()));
                                        break;

                                        case "!svn" :
                                        cmd_send(prep_text(svn($default)));
                                        break;

                                        //case "http" :
                                        //$arguments=explode(" ",$con['buffer']['text']);
                                        //$link=$arguments[0];
                                        //cmd_send(prep_text(linktitle($link)));
                                        //break;

                                        case "!boi" :
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $user = $arguments[1];
                                        cmd_send(prep_text(boincstats($user) . " \n"));
                                        break;

                                        case "whoi" :
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $ip = $arguments[1];
                                        cmd_send(prep_text(ipwhois($ip) . " \n"));
                                        break;

                                        case "!geo" :
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $hostname = $arguments[1];
                                        cmd_send(prep_text(geoip($hostname) . " \n"));
                                        break;

                                        case "!md5" :
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $option = $arguments[1];

                                        switch ($option) {

                                                case "-f" :
                                                $cleartext = $arguments[2];
                                                $md5hash = md5_forward($cleartext);
                                                cmd_send(prep_text("The hash for '$cleartext' is: $md5hash"));
                                                break;

                                                case "-r" :
                                                $md5hash = $arguments[2];
                                                list ($statusline, $cleartext) = md5_reverse($md5hash);
                                                cmd_send(prep_text("$statusline"));
                                                break;

                                                default :
                                                cmd_send(prep_text("MD5 hashes forward and reverse. Either use !md5 -f <cleartext> OR !md5 -r <md5hash>"));
                                        }

                                        break;

                                        # Help function, NEEDS UPDATE
                                        case "!hel" :
                                        cmd_send(prep_text("I'm a very young bot. My current commands are only: !help and !md5 so far."));
                                        break;

                                        # Wikipedia (all languages, experimental)

                                        case "!wp " :

                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $language = $arguments[1];
                                        $pagename = $arguments[2];

                                        # $input=str_replace(" ","_",$input);

                                        cmd_send(prep_text(wikipedia($language, $pagename) . " \n"));
                                        break;

                                        # S23-Wiki
                                        case "!s23" :

                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $pagename = $arguments[1];

                                        # $input=str_replace(" ","_",$input);

                                        cmd_send(prep_text(s23($pagename) . " \n"));
                                        break;

                                        # Wiktionary (en and de)

                                        case "!wk " :
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $language = $arguments[1];
                                        $pagename = $arguments[2];

                                        cmd_send(prep_text(wiktionary($language, $pagename) . " \n"));
                                        break;

                                        case "!r13" :
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $input = $arguments[1];
                                        cmd_send(prep_text(rot13($input) . " \n"));
                                        break;

                                        case "!dns" :
                                        $arguments = explode(" ", $con['buffer']['text']);
                                        $input = $arguments[1];
                                        cmd_send(prep_text(dns($input) . " \n"));
                                        break;

                                }

                        }
                        $old_buffer = $con['buffer']['all'];
                }
        }
}

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

}

function prep_text($message) {
        global $con;
        return ('PRIVMSG ' . $con['buffer']['channel'] . ' :' . $message);
}

function parse_buffer() {

        /*
        :username!~identd@hostname JOIN :#php
        :username!~identd@hostname PRIVMSG #PHP :action text
        :username!~identd@hostname command channel :text
        */

        global $con, $CONFIG;

        $buffer = $con['buffer']['all'];
        $buffer = explode(" ", $buffer, 4);

        /* Get username */
        $buffer['username'] = substr($buffer[0], 1, strpos($buffer['0'], "!") - 1);

        /* Get identd */
        $posExcl = strpos($buffer[0], "!");
        $posAt = strpos($buffer[0], "@");
        $buffer['identd'] = substr($buffer[0], $posExcl +1, $posAt - $posExcl -1);
        $buffer['hostname'] = substr($buffer[0], strpos($buffer[0], "@") + 1);

        /* The user and the host, the whole shabang */
        $buffer['user_host'] = substr($buffer[0], 1);

        /* Isolate the command the user is sending from
        the "general" text that is sent to the channel
        This is  privmsg to the channel we are talking about.

        We also format $buffer['text'] so that it can be logged nicely.
        */
        switch (strtoupper($buffer[1])) {
                case "JOIN" :
                $buffer['text'] = "*JOINS: " . $buffer['username'] . " ( " . $buffer['user_host'] . " )";
                $buffer['command'] = "JOIN";
                $buffer['channel'] = $CONFIG['channel'];
                break;
                case "QUIT" :
                $buffer['text'] = "*QUITS: " . $buffer['username'] . " ( " . $buffer['user_host'] . " )";
                $buffer['command'] = "QUIT";
                $buffer['channel'] = $CONFIG['channel'];
                break;
                case "NOTICE" :
                $buffer['text'] = "*NOTICE: " . $buffer['username'];
                $buffer['command'] = "NOTICE";
                $buffer['channel'] = substr($buffer[2], 1);
                break;
                case "PART" :
                $buffer['text'] = "*PARTS: " . $buffer['username'] . " ( " . $buffer['user_host'] . " )";
                $buffer['command'] = "PART";
                $buffer['channel'] = $CONFIG['channel'];
                break;
                case "MODE" :
                $buffer['text'] = $buffer['username'] . " sets mode: " . $buffer[3];
                $buffer['command'] = "MODE";
                $buffer['channel'] = $buffer[2];
                break;
                case "NICK" :
                $buffer['text'] = "*NICK: " . $buffer['username'] . " => " . substr($buffer[2], 1) . " ( " . $buffer['user_host'] . " )";
                $buffer['command'] = "NICK";
                $buffer['channel'] = $CONFIG['channel'];
                break;

                default :
                // it is probably a PRIVMSG
                $buffer['command'] = $buffer[1];
                $buffer['channel'] = $buffer[2];
                $buffer['text'] = substr($buffer[3], 1);
                break;
        }
        $con['buffer'] = $buffer;
}

# Get geodata, latitude and longitude, from a hostname, using netip.de
# mutante/s23.org - 2008/10

function geoip($hostname) {
        $buffer=file_get_contents("http://www.netip.de/search?query=$hostname");
        $latitude=explode("var latitude",$buffer);
        $latitude=explode(";",$latitude[1]);
        $longitude=explode("var longitude",$buffer);
        $longitude=explode(";",$longitude[1]);
        $latitude=explode(" = ",$latitude[0]);
        $longitude=explode(" = ",$longitude[0]);
        return "Lat $latitude[1], Lon $longitude[1] - http://maps.google.com/maps?f=q&hl=en&geocode=&q=$latitude[1],+$longitude[1]&ie=UTF8&z=17&iwloc=addr";
}

# MD5 forward function
# input: a cleartext string
# output: the md5 hash for the input string
# by mutante/s23

function md5_forward($cleartext) {
        $md5hash = md5($cleartext);
        return $md5hash;
}

# MD5 reverse function
# input: an md5 hash
# output: the cleartext matching the input hash
# uses http://gdataonline.com/seekhash.php
# by mutante/s23

function md5_reverse($md5hash) {

        # we use the XML output of http://gdataonline.com/seekhash.php
        $url = "http://gdataonline.com/qkhash.php?mode=xml&hash=" . $md5hash;
        $buffer = file_get_contents($url);

        # check the buffer
        switch ($buffer) {

                # server answers but hash is invalid, have to check this first
                case "Hash not valid." :
                $statusline = "No success. the hash '$md5hash' is not valid.";
                break;

                default :

                # now we can try to find the <status> tag
                $status = explode("<status>", $buffer);
                $status = explode("</status>", $status[1]);
                $status = $status[0];

                switch ($status) {
                        # Success found inside <status> tag, then do the parsing
                        case "Success" :

                        $result = explode("<result>", $buffer);
                        $result = explode("</result>", $result[1]);
                        $cleartext = $result[0];

                        $hexresult = explode("<hexresult>", $buffer);
                        $hexresult = explode("</hexresult>", $hexresult[1]);
                        $hexresult = $hexresult[0];

                        $b64result = explode("<b64result>", $buffer);
                        $b64result = explode("</b64result>", $b64result[1]);
                        $b64result = $b64result[0];

                        $hits = explode("<hits>", $buffer);
                        $hits = explode("</hits>", $hits[1]);
                        $hits = explode("/", $hits[0]);
                        $hits = $hits[1];

                        # the message in case everything worked
                        $statusline = "SUCCESS - The cleartext for $md5hash is '$cleartext'. (HEX: $hexresult B64: $b64result Hits: $hits)";
                        break;

                        # hash not found inside <status>
                        case "Hash not found" :
                        $statusline = "No success. the hash '$md5hash' was not found in the database.";
                        break;

                        # All other cases, no <status> in buffer, or no reply at all from server..
                        default :
                        $statusline = "'$status' No success. No or unusual answer from the database server.";
                }
        }

        # we can only return multiple values as array
        $reverseresult[] = $statusline;
        $reverseresult[] = $cleartext;
        return $reverseresult;

}

# end reverse function

# Wikipedia function

function wikipedia($language, $pagename) {
        ini_set('user_agent', 'http://s23.org/wikistats/ | http://meta.wikimedia.org/wiki/User:Mutante | mutante@s23.org');
        $url = "http://" . $language . ".wikipedia.org/w/index.php?title=" . $pagename;
        $buffer = file_get_contents($url);

        $summary = explode("<p>", $buffer);
        $summary = $summary[1];
        $summary = explode("</p>", $summary);
        $summary = $summary[0];
        $summary = strip_tags($summary);
        $summary = str_replace("\n", " ", $summary);
        $summary = trim($summary);
        $summary = explode(". ", $summary);

        if ($summary[2]) {
                $summary = $summary[0] . ". " . $summary[1] . ". " . $summary[2] . ".";
        }
        elseif ($summary[1]) {
                $summary = $summary[0] . ". " . $summary[1] . ".";
        } else {
                $summary = $summary[0] . ".";
        }
        $summary = substr($summary, 0, 320);
        $summary = "$pagename is " . $summary . "\n";

        return $summary;
}

# S23

function s23($pagename) {
        ini_set('user_agent', 'http://s23.org/wikistats/ | http://meta.wikimedia.org/wiki/User:Mutante | mutante@s23.org');
        $url = "http://s23.org/w/index.php?title=" . $pagename;
        $buffer = file_get_contents($url);
        $summary = explode("<p>", $buffer);
        $summary = $summary[1];
        $summary = explode("</p>", $summary);
        $summary = $summary[0];
        $summary = strip_tags($summary);
        $summary = str_replace("\n", " ", $summary);
        $summary = trim($summary);
        $summary = explode(". ", $summary);

        if ($summary[2]) {
                $summary = $summary[0] . ". " . $summary[1] . ". " . $summary[2] . ".";
        }
        elseif ($summary[1]) {
                $summary = $summary[0] . ". " . $summary[1] . ".";
        } else {
                $summary = $summary[0] . ".";
        }
        $summary = substr($summary, 0, 320);
        $summary = "$pagename is " . $summary . "\n";

        return $summary;
}

# Wiktionary function

function wiktionary($language, $pagename) {
        ini_set('user_agent', 'http://s23.org/wikistats/ | http://meta.wikimedia.org/wiki/User:Mutante | mutante@s23.org');
        $url = "http://" . $language . ".wiktionary.org/wiki/" . $pagename;

        # print "$url \n";

        $buffer = file_get_contents($url);

        # print $buffer;
        switch ($language) {
                case "de" :

                $summary = explode("Bedeutungen:", $buffer);
                $summary = $summary[1];
                $summary = explode("Herkunft", $summary);
                break;

                case "en" :

                $summary = explode("<ol>", $buffer);
                $summary = $summary[1];
                $summary = explode("</ol>", $summary);
                $summary = str_replace("countable", " ", $summary);
                break;

                default :
                $summary = "Sorry, only supports en and de Wiktionary atm. But try Wikipedia (!wp <lang> <word>)";
        }

        $summary = $summary[0];
        $summary = strip_tags($summary);
        $summary = str_replace("\n", " ", $summary);
        $summary = trim($summary);
        $summary = explode(". ", $summary);

        if ($summary[2]) {
                $summary = $summary[0] . ". " . $summary[1] . ". " . $summary[2] . ".";
        }
        elseif ($summary[1]) {
                $summary = $summary[0] . ". " . $summary[1] . ".";
        } else {
                $summary = $summary[0] . ".";
        }

        $summary = substr($summary, 0, 320);
        $pagename = str_replace("_"," ",$pagename);

        $language=explode("<p><a name=\"",$buffer);
        $language=explode("\"",$language[1]);
        $language=$language[0];

        $summary = "'$pagename' is $language: " . $summary . "\n";

        return $summary;

}


function swear($language, $target) {
        ini_set('user_agent', 'a friendly IRC bot');
        if ($language=="en") {
                $url = "http://en.wiktionary.org/wiki/Category:Vulgarities";
        } else {
                $url = "http://en.wiktionary.org/wiki/Category:".$language.":Vulgarities";
        }
        $buffer = file_get_contents($url);
        $buffer = explode("<ul><li><a href=\"/wiki/",$buffer);
        array_shift($buffer);
        $word=array();
        $counter=0;
        foreach($buffer as $part) {
                $wordcut=explode("\"",$part);
                $word[$counter]=str_replace("_"," ",$wordcut[0]);
                $counter++;
        }

        $pickaword=array_rand($word);
        $sentence="$target: $word[$pickaword]\n";
        return $sentence;
}

# Rot13

function rot13($input) {
        $output = str_rot13($input);
        return $output;
}

# DNS

function dns($input) {

        if (is_numeric(substr($input, 0, 1))) {
                $ip = $input;
                $hostname = gethostbyaddr($ip);
                return $hostname;
        } else {
                $hostname = $input;
                $ip = gethostbyname($hostname);
                return $ip;
        }
}

# BOINC/SETI stats

function boincstats($user) {

        # This should probably go to external config or db!

        $s23_users = array (
        "mutante" => "72846",
        "Selvin" => "109774",
        "DrOwl" => "59517",
        "XBS" => "32021",
        "took" => "8088738",
        "finn" => "339495",
        "Republikaner" => "302926",
        "markus" => "96245",
        "DjU" => "16473",
        "talisman" => "224777",
        "qoreqyas" => "53039",
        "zakx" => "8125780",
        "phrack" => "27109",
        "hundfred" => "936073",
        "acidben" => "8577722"
        );

        if (array_key_exists($user, $s23_users)) {
                $userid = $s23_users["$user"];
        }
        elseif (is_numeric($user)) {
                $userid = $user;
        }
        elseif ($user == "team") {

                $url = "http://setiathome.berkeley.edu/team_display.php?teamid=110055";
                $buffer = file_get_contents($url);

                $name = explode("<h1>", $buffer);
                $name = explode("</h1>", $name[1]);
                $name = $name[0];

                $total = explode("Total credit</td><td class=fieldvalue>", $buffer);
                $total = explode("</td>", $total[1]);
                $total = $total[0];

                $rc_avg = explode("Recent average credit</td><td class=fieldvalue>", $buffer);
                $rc_avg = explode("</td>", $rc_avg[1]);
                $rc_avg = $rc_avg[0];

                $type = explode("Type</td><td class=fieldvalue>", $buffer);
                $type = explode("</td>", $type[1]);
                $type = $type[0];

                $newmembers = explode("New members in last day</td><td class=fieldvalue>", $buffer);
                $newmembers = explode("</td>", $newmembers[1]);
                $newmembers = $newmembers[0];

                $totmembers = explode("Total members</td><td class=fieldvalue>", $buffer);
                $totmembers = explode(" (", $totmembers[1]);
                $totmembers = $totmembers[0];

                $actmembers = explode("Active members</td><td class=fieldvalue>", $buffer);
                $actmembers = explode(" (", $actmembers[1]);
                $actmembers = $actmembers[0];

                $credmembers = explode("Members with credit</td><td class=fieldvalue>", $buffer);
                $credmembers = explode(" (", $credmembers[1]);
                $credmembers = $credmembers[0];

                $founder = explode("Founder</td><td class=fieldvalue>", $buffer);
                $founder = explode("</td>", $founder[1]);
                $founder = $founder[0];
                $founder = strip_tags($founder);
                $founder = trim($founder);

                return "SETI Team '$name' (ID: 110055 - Type: $type - Founder: $founder): Total Credit: $total - Recent Avg: $rc_avg - Members: $totmembers (Active: $actmembers - With Credit: $credmembers - New Yesterday: $newmembers)";
        } else {
                return "Bad Input. Please supply a user ID or known seti23 nick, or ask mutante to be added. \n";
        }

        $url = "http://setiathome.berkeley.edu/show_user.php?userid=$userid";
        $buffer = file_get_contents($url);

        $username = explode("<h1>Account data for ", $buffer);
        $username = explode("</h1>", $username[1]);
        $username = $username[0];

        $total = explode("Total credit</td><td class=fieldvalue>", $buffer);
        $total = explode("</td>", $total[1]);
        $total = $total[0];

        $rc_avg = explode("Recent average credit</td><td class=fieldvalue>", $buffer);
        $rc_avg = explode("</td>", $rc_avg[1]);
        $rc_avg = $rc_avg[0];

        $classic_wus = explode("SETI@home classic workunits</td><td class=fieldvalue>", $buffer);
        $classic_wus = explode("</td>", $classic_wus[1]);
        $classic_wus = $classic_wus[0];

        $classic_cpu = explode("SETI@home classic CPU time</td><td class=fieldvalue>", $buffer);
        $classic_cpu = explode("</td>", $classic_cpu[1]);
        $classic_cpu = $classic_cpu[0];

        $member_since = explode("SETI@home member since</td><td class=fieldvalue>", $buffer);
        $member_since = explode("</td>", $member_since[1]);
        $member_since = $member_since[0];

        $country = explode("Country</td><td class=fieldvalue>", $buffer);
        $country = explode("</td>", $country[1]);
        $country = $country[0];

        $url = explode("URL</td><td class=fieldvalue><a href=\"", $buffer);
        $url = explode("\">", $url[1]);
        $url = $url[0];

        return "Boinc stats for: '$username' ($userid): Total credit: $total - Recent Avg: $rc_avg - Classic WUs: $classic_wus - Classic CPU time: $classic_cpu - Member since: $member_since - Country: $country - URL: $url";
}

# last track from webradio, for finn, by mutante
function lasttrack() {
        $url = "http://fm4.orf.at/trackservicepopup/main?tmp=41";
        $buffer = file_get_contents($url);
        $buffer = str_replace("\n", "", $buffer);
        # echo $buffer;
        $heute = explode("heute:<br>", $buffer);
        $heute = explode("<br>   </td>", $heute[1]);
        $heute = explode("</i><br>", $heute[0]);
        $lasttrack = array_slice($heute, -2, 1);
        $lasttrack = strip_tags(trim($lasttrack[0]));
        $answer = "Last song played: " . $lasttrack;
        return $answer;
}

# IATA airport codes
# mutante & phrack at scrum @phrack home 02/08
function iata($code) {

        # mysql connect
        $dbhost = "localhost";
        $dbname = "edgar";
        $dbpass = "XXXXXXXXX";
        $dbdatabase = "edgar";

        mysql_connect("$dbhost", "$dbname", "$dbpass") or die(mysql_error());
        mysql_select_db("$dbdatabase") or die(mysql_error());

        $code = mysql_escape_string($code);

        if (strlen($code) > 3) {
                $query = "select * from IATA where airport like '%$code%'";
        } else {
                $query = "select * from IATA where code='$code'";
        }

        $result = mysql_query("$query") or die(mysql_error());

        while ($row = mysql_fetch_array($result)) {
                $airport = $row['airport'];
                $code = $row['code'];
        }
        #return $query;
        if ($code == "" OR $airport == "") {
                $output = "Not found!";
        } else {
                $output = "$code - $airport";
        }
        return $output;
}

# if somebody mentions a http link, return the <title> of the page
# mutante and finn in screen session, idea by finn
# advanced features by took
function linktitle($link) {
        global $linktitle_db;
        if (isset ($linktitle_db['temp_blacklist'])) {
                $largest_key = -2; //-2 for: we havent found any key yet
                $largest_key_size = -1;
                foreach ($linktitle_db['temp_blacklist'] as $key => $value) {
                        if ($value['url'] == $link && $value['expire'] > (time() - 23)) {
                                return "I just told you about that url...";
                        }
                        if ($value['expire'] > time() && $largest_key != -1) {
                                unset ($GLOBALS['linktitle_db']['temp_blacklist'][$key]);
                                $largest_key = -1; //-1 for: we dont need to delete any more rows - even if mem just was full
                        } else {
                                $size = time() - $value['expire'];
                                if ($size > $largest_key_size) {
                                        $largest_key_size = $size;
                                        $largest_key = $key;
                                }
                        }
                }
                if (count($linktitle_db['temp_blacklist']) > 100 && $largest_key >= 0) {
                        unset ($GLOBALS['linktitle_db']['temp_blacklist'][$largest_key]);
                }
        }
        $linktitle_db['temp_blacklist'][] = array (
        'url' => $link,
        'expire' => (time() + 115));

        # Add feature to detect and download image links --mutante 080223
        $image_extensions = array (
        "jpg",
        "gif",
        "png",
        "jpeg",
        "bmp",
        );

        if (in_array(strtolower(substr($link, -3)), $image_extensions)) {

                $directory = "public_html/images";
                $imagename = explode("/", $link);
                $imagename = end($imagename);

                $output = "Looks like an image. Downloading.. ";
                $image = `wget -q -P $directory $link`;
                $file = `file $directory/$imagename`;
                $size = `ls -hs $directory/$imagename | cut -d " " -f1`;
                $output .= "Saved to " . trim($file) . " size: " . trim($size) . ".";

        } elseif (stristr($link,"/wiki/")){
                # < finn__> edgar k?nnte wiki seiten ignorieren, da der titel ja nach dem letzten / abzulesen ist
                $output="";

        } else {

                $buffer = file_get_contents($link);
                preg_match('@<title>(.*?)</title>@i', str_replace(array (
                "\n",
                "\r"
                ), array (
                "",
                ""
                ), $buffer), $pieces);
                $title = $pieces[1];

                if ($title != '') {
                        $output = "Title: '" . trim(html_entity_decode($title)) . "'";
                } else {
                        if ($buffer != '') {
                                $output = "Sorry, 200 but no title";
                        } else {
                                $output = ""; // "Sorry, empty buffer"; -> (21:19:39) mutante: Edgar23: if empty buffer, just say nothing
                        }
                }

        }

        return $output;
}

# random excuses by took
function get_excuse() {
        # BOFH excuse generator
        # Written by gf, ported to php by took
        # Idea and words from http://bofh.ntk.net/ExcuseBoard.html

        $first = explode(" ", "Temporary Intermittant Partial Redundant Total Multiplexed Inherent Duplicated Dual-Homed Synchronous Bidirectional Serial Asynchronous Multiple Replicated Non-Replicated Unregistered Non-Specific Generic Migrated Localised Resignalled Dereferenced Nullified Aborted Serious Minor Major Extraneous Illegal Insufficient Viral Unsupported Outmoded Legacy Permanent Invalid Deprecated Virtual Unreportable Undetermined Undiagnosable Unfiltered Static Dynamic Delayed Immediate Nonfatal Fatal Non-Valid Unvalidated Non-Static Unreplicatable Non-Serious");

        $second = explode(" ", "Array Systems Hardware Software Firmware Backplane Logic-Subsystem Integrity Subsystem Memory Comms Integrity Checksum Protocol Parity Bus Timing Synchronisation Topology Transmission Reception Stack Framing Code Programming Peripheral Environmental Loading Operation Parameter Syntax Initialisation Execution Resource Encryption Decryption File Precondition Authentication Paging Swapfile Service Gateway Request Proxy Media Registry Configuration Metadata Streaming Retrieval Installation Library Handler");

        $third = explode(" ", "Interruption Destabilisation Destruction Desynchronisation Failure Dereferencing Overflow Underflow NMI Interrupt Corruption Anomaly Seizure Override Reclock Rejection Invalidation Halt Exhaustion Infection Incompatibility Timeout Expiry Unavailability Bug Condition Crash Dump Crashdump Stackdump Problem Lockout");

        $fourth = explode(" ", "Error Problem Warning Signal Flag");

        $out = $first[array_rand($first)] . " ";
        $out .= $second[array_rand($second)] . " ";
        $out .= $third[array_rand($third)];
        if (rand(0, 9) % 2 == 0)
        $out .= " " . $fourth[array_rand($fourth)];

        return $out;
}

# show svn logs in IRC, --mutante
# replaced with new function on 08/03/03
function svn($type) {
        $output = "Edgar SVN log: ";
        $rawsvnlog = `svn log https://s23.org/svn/`;
        $svnlog = str_replace("------------------------------------------------------------------------\n", "", $rawsvnlog);
        # remove empty lines, http://programming-oneliners.blogspot.com/2006/03/remove-blank-empty-lines-php-29.html
        $svnlog = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $svnlog);
        $svnlog = explode("\n", $svnlog);
        $latest = array_slice($svnlog, 0, 10);
        # brief revision to show on bot startup
        if ($type == "brief") {
                $output = explode("|", $latest[0]);
                $output = trim($output[0]);
        } else {
                # show latest 3 lines (revision or comment)
                $output = $latest[0] . " " . $latest[1] . " " . $latest[2];
                $output = str_replace(" 1 line", "", $output);
        }
        return $output;
}

# Googlefight implementation by mutante

function googlefight($term1, $term2) {
        $url1 = "http://www.google.de/search?q=" . $term1;
        $url2 = "http://www.google.de/search?q=" . $term2;

        #echo $url1."\n";
        #echo $url2;

        $buffer1 = file_get_contents($url1);

        # echo $buffer1;

        $pieces1 = explode("hr <b>", $buffer1);
        $piece1 = $pieces1[1];

        $pieces2 = explode("</b>", $piece1);

        $hits1 = $pieces2[0];
        $hits1 = str_replace(".", "", $hits1);
        if (!is_numeric($hits1)) {
                $hits1 = 0;
        }

        $buffer2 = file_get_contents($url2);

        $pieces1 = explode("hr <b>", $buffer2);
        $piece1 = $pieces1[1];

        $pieces2 = explode("</b>", $piece1);
        $hits2 = $pieces2[0];
        $hits2 = str_replace(".", "", $hits2);
        if (!is_numeric($hits2)) {
                $hits2 = 0;
        }

        $hits1 = number_format($hits1);
        $hits2 = number_format($hits2);

        if ($hits1 > $hits2) {
                $output .= "Googlefight: '$term1' beat '$term2' with $hits1 to $hits2 hits.";
        }
        elseif ($hits1 == 0 AND $hits2 == 0) {
                $output .= "Googlefight: No results, both terms dont have any hits. ($hits1)";
        }
        elseif ($hits1 == $hits2) {
                $output .= "Googlefight: Draw! Both terms have the same number of hits. ($hits1)";
        } else {
                $output .= "Googlefight: '$term2' beat '$term1' with $hits2 to $hits1 hits.";
        }

        return $output;
}

# spy on other irc users (searchirc.com)

function ircspy($nick) {

        $hitcount = 1;
        $baseurl = "http://searchirc.com/whois/";

        $url = $baseurl . $nick;
        $buffer = file_get_contents($url);

        $pieces = explode("href=\"/network/", $buffer);
        $pieces = array_slice($pieces, 1);

        foreach ($pieces as & $chunk) {

                $network = explode("\">", $chunk);
                $network = $network[0];

                $fnick = explode("Nick:</div></td><td bgcolor=\"#BDCFE7\" valign=\"top\" width=\"82%\" nowrap>", $chunk);
                $fnick = explode("</td>", $fnick[1]);
                $fnick = $fnick[0];

                $realname = explode("Realname:</div></td><td valign=\"top\">", $chunk);
                $realname = explode("</td>", $realname[1]);
                $realname = $realname[0];

                $channels = explode("Channels:</div></td><td valign=\"top\">", $chunk);
                $channels = explode("</td>", $channels[1]);
                $channels = $channels[0];

                $server = explode("Server:</div></td><td valign=\"top\">", $chunk);
                $server = explode("</td>", $server[1]);
                $server = $server[0];

                $status = explode("<div align=\"right\">Status:</div><div align=\"right\"></div></td><td width=\"82%\">", $chunk);
                $status = explode("</td>", $status[1]);
                $status = $status[0];

                if ($status != "No such nick") {
                        $output .= "Hit $hitcount: detected $nick on $network as $fnick ($realname) on $channels using $server. | ";
                        $hitcount++;
                }

        }

        return $output;

}

#ip-whois by phrack & mutante 20080210
function ipwhois($ip) {
        $buffer = `whois $ip`;

        $source = explode("source:", $buffer);
        $source = explode("\n", $source[1]);
        $source = trim($source[0]);
        $source = substr($source, 0, 4);

        $country = explode("ountry:", $buffer);
        if (count($country) > 2) {
                $country = $country[2];
        }
        elseif (count($country) > 1) {
                $country = $country[1];
        } else {
                $country = "";
        }
        $country = explode("\n", $country);
        $country = trim($country[0]);

        switch ($source) {

                case "RIPE" :
                $inetnum = explode("inetnum:", $buffer);
                $inetnum = explode("\n", $inetnum[1]);
                $inetnum = trim($inetnum[0]);

                $netname = explode("netname:", $buffer);
                $netname = explode("\n", $netname[1]);
                $netname = trim($netname[0]);

                $address = explode("address:", $buffer);
                $address = explode("\n", $address[1]);
                $address = trim($address[0]);

                $result = $ip . " is part of ${netname} owned by ${address} ($country) (range: ${inetnum})";

                break;
                default :

                $netrange = explode("NetRange:", $buffer);
                $netrange = explode("\n", $netrange[1]);
                $netrange = trim($netrange[0]);

                $netname2 = explode("NetName:", $buffer);
                $netname2 = explode("\n", $netname2[1]);
                $netname2 = trim($netname2[0]);

                $orgname = explode("OrgName:", $buffer);
                $orgname = explode("\n", $orgname[1]);
                $orgname = trim($orgname[0]);

                $result = $ip . " is part of ${netname2} owned by ${orgname} ($country) (range: ${netrange})";
                break;
        }

        return $result;
}

# Lookup the registrar of a German 0900 number at regtp.de
# mutante / s23

function ninehundred($number) {
        $baseurl = "http://bo2005.regtp.de/prg/srvcno/srvcno900.asp?USessionID=0&sStartDS=1&sScriptID=59&ruf_nr=${number}&Suche=Absenden";
        $buffer = file_get_contents($baseurl);
        $diensteanbieter = explode("Diensteanbieter:", $buffer);
        $diensteanbieter = explode("<br/>", $diensteanbieter[1]);

        $firma = trim(strip_tags($diensteanbieter[0]));
        $strasse = trim(strip_tags($diensteanbieter[1]));

        $ort = strip_tags(trim($diensteanbieter[3]));
        $ort = explode("\n", $ort);
        $ort = $ort[0];

        $datum = explode("Datum der Zuteilung der Rufnummer:", $buffer);
        $datum = explode("\n", $datum[1]);
        $datum = trim(strip_tags($datum[0]));

        $output = "0900-" . $number . " gehoert der " . $firma . " in " . $strasse . ", " . $ort . " und wurde registriert am " . $datum . ".";
        $output = str_replace("\n", "", $output);
        $output = str_replace("\r", "", $output);
        return $output;
}

# Wann geht die Sonne auf ? (und unter) Und wie lange dauerts noch?
# mutante / s23

function sonne($type) {

        # Cologne = 44
        $ort = 44;

        # Today and now
        $datum = `date +%d-%m-%y-%H-%M`;
        $datum = explode("-", $datum);
        $tag = $datum[0];
        $monat = $datum[1];
        $jahr = $datum[2];
        $stunde = $datum[3];
        $minute = trim($datum[4]);

        $baseurl = "http://sonne.apper.de/index.php?tag=${tag}&monat=${monat}&jahr=${jahr}&ort=${ort}&time=";
        $buffer = file_get_contents($baseurl);

        switch ($type) {

                case "auf" :

                $sonnenaufgang = explode("<b style=\"font-size:18pt;\">", $buffer);

                $daemmerung = explode("D&auml;mmerung<br /><br />", $sonnenaufgang[1]);
                $daemmerung = explode("<br />", $daemmerung[0]);
                $daemmerung = trim($daemmerung[1]);

                $sonnenaufgang = explode("</b>", $sonnenaufgang[1]);
                $sonnenaufgang = $sonnenaufgang[0];

                $sonnenaufgang = explode(":", $sonnenaufgang);
                $sonnenaufgang_std = $sonnenaufgang[0];
                $sonnenaufgang_min = $sonnenaufgang[1];

                $daemmerung = explode(":", $daemmerung);
                $daemmerung_std = $daemmerung[0];
                $daemmerung_min = $daemmerung[1];

                $restminuten1 = 60 - $minute;
                $restminuten1 = $restminuten1 + $sonnenaufgang_min;
                $reststunden1 = 24 - $stunde + $sonnenaufgang_std -1;

                if ($restminuten1 > 59) {
                        $restminuten1 = $restminuten1 -60;
                        $reststunden1 = $reststunden1 +1;
                }

                if ($stunde == $sonnenaufgang_std) {
                        $reststunden1 = 0;
                        $restminuten1 = $sonnenaufgang_min - $minute;
                        $bis_zum_aufgang = "$restminuten1 Minuten";
                } else {
                        $bis_zum_aufgang = "$reststunden1 Stunden und $restminuten1 Minuten";
                }
                $restminuten2 = 60 - $minute;
                $restminuten2 = $restminuten2 + $daemmerung_min;

                $reststunden2 = 24 - $stunde + $sonnenaufgang_std -1;

                if ($restminuten2 > 59) {
                        $restminuten2 = $restminuten2 -60;
                        $reststunden2 = $reststunden2 +1;
                }

                if ($stunde == $daemmerung_std) {
                        $reststunden2 = 0;
                        $restminuten2 = $daemmerung_min - $minute;
                        $bis_anfang_daemmerung = "$restminuten2 Minuten";
                } else {
                        $bis_anfang_daemmerung = "$reststunden2 Stunden und $restminuten2 Minuten";
                }

                $output = "Die Sonne geht morgen um ${sonnenaufgang_std}:${sonnenaufgang_min} Uhr auf und die Daemmerung beginnt ab ${daemmerung_std}:${daemmerung_min} Uhr. Noch $bis_anfang_daemmerung bis die Daemmerung anfaengt und $bis_zum_aufgang bis zum Sonnenaufgang.";

                break;

                case "unter" :

                $sonnenuntergang = explode("<b style=\"font-size:18pt;\">", $buffer);

                $daemmerung = explode("D&auml;mmerung<br /><br />", $sonnenuntergang[2]);
                $daemmerung = explode("<br />", $daemmerung[0]);
                $daemmerung = trim($daemmerung[1]);

                $sonnenuntergang = explode("</b>", $sonnenuntergang[2]);
                $sonnenuntergang = $sonnenuntergang[0];

                $sonnenuntergang = explode(":", $sonnenuntergang);
                $sonnenuntergang_std = $sonnenuntergang[0];
                $sonnenuntergang_min = $sonnenuntergang[1];

                $daemmerung = explode(":", $daemmerung);
                $daemmerung_std = $daemmerung[0];
                $daemmerung_min = $daemmerung[1];

                $restminuten1 = 60 - $minute;
                $restminuten1 = $restminuten1 + $sonnenuntergang_min;
                $reststunden1 = $sonnenuntergang_std - $stunde -1;

                if ($restminuten1 > 59) {
                        $restminuten1 = $restminuten1 -60;
                        $reststunden1 = $reststunden1 +1;
                }

                if ($stunde == $sonnenuntergang_std) {
                        $reststunden1 = 0;
                        $restminuten1 = $sonnenuntergang_min - $minute;
                        $bis_zum_untergang = "$restminuten1 Minuten";
                } else {
                        $bis_zum_untergang = "$reststunden1 Stunden und $restminuten1 Minuten";
                }

                $restminuten2 = 60 - $minute;
                $restminuten2 = $restminuten2 + $daemmerung_min;
                $reststunden2 = $daemmerung_std - $stunde -1;

                if ($restminuten2 > 59) {
                        $restminuten2 = $restminuten2 -60;
                        $reststunden2 = $reststunden2 +1;
                }

                if ($stunde == $daemmerung_std) {
                        $reststunden2 = 0;
                        $restminuten2 = $daemmerung_min - $minute;
                        $bis_ende_daemmerung = "$restminuten2 Minuten";
                } else {
                        $bis_ende_daemmerung = "$reststunden2 Stunden und $restminuten2 Minuten";
                }

                $output = "Die Sonne geht heute um ${sonnenuntergang_std}:${sonnenuntergang_min} Uhr unter und die Daemmerung dauert bis ${daemmerung_std}:${daemmerung_min} Uhr. Noch $bis_zum_untergang bis es die Sonne untergeht und $bis_ende_daemmerung bis es richtig dunkel wird.";

                break;

                case "lang" :
                $tageslaenge = explode("<b style=\"font-size:18pt;\">", $buffer);
                $tageslaenge = explode("</b></p>", $tageslaenge[3]);
                $tageslaenge = $tageslaenge[0];
                $output = "Der heutige Tag (${tag}.${monat}) ist ${tageslaenge} lang.";

                break;

                case "heute" :
                $output = "Es ist ${stunde}:${minute} Uhr am ${tag}.${monat}.${jahr}.\n";
        }

        return $output;
}

# teach padma (infobot/flooterbuck) from en.wiktionary.org

function wiktionary_teach($language,$pagename) {
        ini_set('user_agent','http://s23.org/wikistats/ | http://meta.wikimedia.org/wiki/User:Mutante | mutante@s23.org');
        $url="http://".$language.".wiktionary.org/wiki/".$pagename;

        # print "$url \n";

        $buffer = file_get_contents($url);

        # print $buffer;
        switch ($language) {
                case "de":

                $summary = explode("Bedeutungen:",$buffer);
                $summary = $summary[1];
                $summary = explode("Herkunft",$summary);
                break;

                case "en":

                $summary = explode("<ol>",$buffer);
                $summary = $summary[1];
                $summary = explode("</ol>",$summary);
                $summary = str_replace("countable"," ",$summary);
                break;

                default:
                $summary="Sorry, only supports en and de Wiktionary atm. But try Wikipedia (!wp <lang> <word>)";
                $language="en";
        }


        $summary = $summary[0];
        $summary = strip_tags($summary);
        $summary = str_replace("\n"," ",$summary);
        $summary = trim($summary);
        $summary = explode(". ",$summary);

        if ($summary[2]) {
                $summary = $summary[0].". ".$summary[1].". ".$summary[2].".";
        } elseif ($summary[1]) {
                $summary = $summary[0].". ".$summary[1].".";
        } else {
                $summary = $summary[0].".";
        }

        $summary = substr($summary,0, 160);
        $summary = trim($summary);

        $language=explode("<p><a name=\"",$buffer);
        $language=explode("\"",$language[1]);
        $language=$language[0];

        if (substr($summary,0, 1)==".") {
                return "This page doesnt seem to exist.";
        } else {
                $summary = "'$pagename' is $language: " . $summary . "\n";
                return $summary;
        }

}


# Dollarwert in Euro, von xe.com
function dollar_euro() {
        $buffer=file_get_contents("http://www.xe.com/");
        $pieces=explode("1&nbsp;EUR&nbsp;=",$buffer);
        $pieces=explode("<td align=\"center\" class=\"cur2 currencyA\">",$pieces[1]);
        $pieces=explode("</td>",$pieces[1]);
        $output = "Fuer einen Euro bekommt man heute ".$pieces[0]." Dollar.";
        return $output;
}

# Get latest exploits from milw0rm.com | http://www.milw0rm.com/rss.php
# --mutante
function getexploits() {
        $milworm_feed = "http://www.milw0rm.com/rss.php";
        $buffer = file_get_contents($milworm_feed);
        $output = "Latest exploits from milw0rm: ";
        $exploits = explode("<item>", $buffer);
        $exploits = array_slice($exploits, 1, 3);
        foreach ($exploits as $exploit) {
                $title = explode("<title>", $exploit);
                $title = explode("</title>", $title[1]);
                $title = $title[0];
                $link = explode("<link>", $exploit);
                $link = explode("</link>", $link[1]);
                $link = $link[0];
                $output .= "'$title' - " . $link . " -- ";
        }
        return $output;
}


# Function to ask comfortradio.org for the current song being played
# code by commmatoes

function comfort() {

        # Must remember to get used to commenting
        # Need to tell server we are Mozilla
        ini_set('user_agent','Mozilla');
        # Get URL
        $url="http://listen.comfortradio.org:7050/7.html";
        # URL informatoin
        $buffer=file_get_contents($url);
        # let's see what we can do here
        # echo $buffer."\n";
        # Time for some explosions
        $split=explode("<body>",$buffer);
        $split2=explode("</body>",$split[1]);
        # Let's see what we have
        # echo "Results are: \n";
        # echo $split2[0]."\n";
        # The individual output part starts here - FEAR
        $split3=explode(",",$split2[0]);

        # echo $split3."\n";
        # print_r($split3);

        /*
        this is where you will see: number of listeners, number of listeners allowed, stream bit rate, and artist/song title
        I can't be arsed to parse the song title from artist jsut yet but i think i know how because i'm somewhat crazy like that
        */
        # 2 versions of this code, separate line and one line
        $statget="$split3[0] / $split3[2]";
        $stats=str_replace(" ","",$statget);

        $output="ComfortRadio Now Playing: $split3[6] / $split3[5] kbps / Listeners $stats / http://listen.comfortradio.org:7050/listen.pls \n";
        return $output;
}


# Lookup language codes from ISO-639
# http://www.loc.gov/standards/iso639-2/langhome.html
# used by Wiktionary, Wikipedia and many other projects
# mutante/s23.org

# Functions


# Input: 2 or 3-letter code, Output: language name in English and French
function alpha2lang ($alpha) {

        switch (strlen($alpha)) {
                case 2:
                $query="select * from langcodes where alpha2='$alpha'";
                break;
                case 3:
                $query="select * from langcodes where alpha3='$alpha' or alpha3t='$alpha'";
                break;
                default:
                return "codes can only be 2 or 3 letters long! \n";
        }

        $result = mysql_magic("$query");

        if(mysql_num_rows($result)==0){
                $langnames="Could not find this code.";
        } else {
                while($row = mysql_fetch_array( $result )) {
                        $nameen=$row['nameen'];
                        $namefr=$row['namefr'];
                        $alpha2=$row['alpha2'];
                        $alpha3=$row['alpha3'];
                        $alpha3t=$row['alpha3t'];

                        $langnames="'$alpha' is $nameen - $alpha2 $alpha3 $alpha3t";
                }
        }
        return $langnames;
}

# Input: Language name in English, Output: 2 and 3-letter codes

function lang2alpha ($langname) {

        $query="select * from langcodes where nameen like '%$langname%' or namefr like '%$langname%'";
        $result = mysql_magic("$query");

        if(mysql_num_rows($result)==0){

                $langcodes="No codes found for this language name.";
        } else {
                while($row = mysql_fetch_array( $result )) {
                        $nameen=$row['nameen'];
                        $alpha2=$row['alpha2'];
                        $alpha3=$row['alpha3'];
                        $alpha3t=$row['alpha3t'];

                        $langcodes.="The language codes for $nameen are: $alpha2 $alpha3 $alpha3t \n";
                }
        }
        return $langcodes;
}


# Function to connect to MySQL, input query, output $result
function mysql_magic($query) {
        $dbhost="localhost";
        $dbdatabase="codes";
        $dbname="xxxxxx";
        $dbpass="xxxxxx";
        mysql_connect("$dbhost", "$dbname", "$dbpass") or die(mysql_error());
        mysql_select_db("$dbdatabase") or die(mysql_error());
        $result = mysql_query("$query") or die(mysql_error());
        return $result;
}

?>

Personal tools