<?php

define( "LOG_FOLDER",          '/home/dracula/.irssi/logs/freenode/' );
define( "MIN_SEARCH_LENGTH",   '4' );
define( "ILLEGAL_CHARS",       '&|;:(){}[]<>!"`?\\' );

$search   = $_REQUEST["s"];    
$channel  = $_REQUEST["c"];
$case     = $_REQUEST["i"];

if (strlen($channel) > 0 && strpos($channel, "#") === FALSE)
    $channel = "#" . $channel;

function parse_line($line) {
    global $search;
    
    $loc = strtok($line, " ");
    $msg = strtok("");

    $temp = split("\/", $loc);
    $filename = array_pop($temp);

    $temp = split("\.", $filename);

    $datepart = $temp[1];
    $datepart = substr($datepart, 6, 2) . "/" . substr($datepart, 4, 2) . "/" . substr($datepart, 0, 4);
    $timepart = strtok($temp[2], ":");
    $timepart = strtok("");

    $msg = str_replace($search, "<span class='match'>".$search."</span>", htmlspecialchars($msg));

    return "<tr><td class='timestamp'>" . $datepart . " " . $timepart . "</td><td>" . $msg . "</td></tr>\n";
}

function str_contains($haystack, $needle) {
    for ($i=0; $i<strlen($needle); $i++) {
        if (strpos($haystack, $needle[$i]) !== FALSE)
            return true;
    }
    return false;
}

function error($msg) {
    print "<span class='error'>$msg</span>\n";
}

function do_search() {
    global $search, $channel, $case;

    if (strlen($search) > 0) {
    
   
        if (strlen($channel) == 0)
            $retval = -1;
        elseif (str_contains($channel, ILLEGAL_CHARS))
            $retval = -2;
        elseif (strlen($search) < MIN_SEARCH_LENGTH)
            $retval = -3;
        else {
        
            $caseopt = ( $case ? "" : "-i" );
            $search = escapeshellarg($search);
            
            $channel = LOG_FOLDER . $channel . "*";
            $cmd = "nice grep $caseopt $search $channel";
            
            // $channel = escapeshellarg($channel . "*");
            // $cmd = "find " . LOG_FOLDER . " -maxdepth 1 -name $channel | xargs grep $caseopt $search";

            exec($cmd, $lines, $retval);
        }

        switch ($retval) {
        
        case 0: // Success, results found
            $cnt = count($lines);
            
            print "Found ".$cnt." result".($cnt!=1?"s":"").":<br>";
            print "<table class='results'>";
            foreach($lines as $line) {
                print parse_line($line);
            }
            print "</table>";
            break;

        case 1: // returned by 'grep'
            error("No results found");
            break;

        case 2: // returned by 'grep'
            error("Invalid channel name");
            break;
            
        case -1: // user error
            error("No channel specified");
            break;

        case -2: // user error
            error("Channel contains illegal characters");
            break;

        case -3: // user error
            error("Search string too short");
            break;

        case 126: // returned by shell
            error("Too many matches for channel '$channel'");
            break;
            
        default:
            error("Unknown error " . $retval);

        }
        
    }    
}
?>

<html>
    <head>
        <title>IRC log search</title>
        <style>
        table.results { font-family: arial; font-size: 8pt; }
        .timestamp { width: 110px; text-align: center; vertical-align: top; }
        .right { text-align: right }
        .center { text-align: center }
        .error { border: 1px solid #c22; color: #c22; padding: 2px; }
        .match { font-weight: bold; color: #a22; }
        </style>
    </head>
    
    <body>

    <form action="<? print $_SERVER["SCRIPT_NAME"]; ?>" method="post">
    <table align='center'>
    <tr>
       <td class='right'>Search text:</td>
       <td><input type="edit" size="20" name="s" value="<? echo $search; ?>"></td>
    </tr>
    <tr>
       <td class='right'>Channel:</td>
       <td><input type="edit" size="20" name="c" value="<? echo $channel; ?>"></td>
    </tr>
    <tr>
       <td class='right'>Case-sensitive:</td>
       <td><input type="checkbox" name="i" <? if ($case) echo "checked"; ?>></td>
    </tr>
    <tr>
       <td colspan='2' class='center'><input type="submit" value="Search"></td>
    </tr>
    </table>
    </form>
    
<?
    do_search();
?>

    </body>
</html>