<?php header('Content-Type: text/html; charset=UTF-8');?>
<html>
<body>
<table>
<?php

function load_doc($doc, &$output_array)
{
    $table = $doc->getElementsByTagName("table")->item(4);
    $lines = $table->getElementsByTagName("tr");
    $first_line = 1;
    foreach($lines as $line)
    {
        if ($first_line)
        {
            $first_line = 0;
            continue;
        }
        $values = $line->getElementsByTagName("td");
        // Some keys are duplicated (spaces ??)
        $key = $values->item(0)->nodeValue;
        $value = $values->item(1)->nodeValue;
        if (array_key_exists($key, $output_array))
            $output_array[$key] += $value;
        else
            $output_array[$key] = $value;

    }

}

$gen_date = filemtime('./generated.html');

if (date("d", $gen_date) == date("d") &&
    date("m", $gen_date) == date("m") &&
    date("Y", $gen_date) == date("Y"))
{
    include "./generated.html";
}
else
{
    $doc = new DOMDocument();
    $doc->loadHTMLFile('./old.html');

    $old_values = array();
    if (date("d") != 2)
        load_doc($doc, $old_values);

    $output = array();
    $year = date("Y");
    $month = date("m");
    if (date("d") == 1)
    {
        if ($month > 1)
            $month = date("m")-1;
        else
        {
            $month = 12;
            $year--;
        }
    }
    else
        $month = date("m");

    exec("/usr/lib/cgi-bin/awstats.pl -config=soutade.fr -output=keyphrases -month=$month -year=$year", $output);

    $out = '';
    $new_html = '';
    foreach ($output as $line)
        $new_html .= $line;

    $doc->loadHTML($new_html);

    $new_values = array();
    load_doc($doc, $new_values);

    foreach($new_values as $key => $value)
    {
        if (array_key_exists($key, $old_values))
            if ($old_values[$key] == $value)
                $out .= "<tr><td>$key</td><td>$value</td><td>+0</td></tr>";
            else
                $out .= "<tr BGCOLOR=\"orange\"><td>$key</td><td>$value</td><td>+" . ($value - $old_values[$key]) . "</td></tr>";
        else
            $out .= "<tr BGCOLOR=\"green\"><td>$key</td><td>$value</td><td>+$value</td></tr>";
    }

    print $out;

    unlink('./generated.html');
    $fp = fopen('./generated.html', 'w');
    fwrite($fp, $out);
    fclose($fp);

    unlink('./old.html');
    $fp = fopen('./old.html', 'w');
    fwrite($fp, $new_html);
    fclose($fp);
}
?>
</table>
</body>
</html>