<?php
/*
   The Index software may be freely distributed.
   See license.txt for details.
*/
define('COUNTFILE', ROOT . 'counts/counts.lst');

function ReadCounts()
{
    global $counts;
    // Make sure counts are only written if read correctly
    global $countsread;
    $countsread = 0;
    // The included file will set countsread to true, iff it gets read
    // completely.
    if (file_exists(COUNTFILE))
    {
        include(COUNTFILE);
    }
}


function CountIt($key)
{
    global $counts;
    global $countsread;
    // Only count if there is an key, this allows to preview without
    // having a key yet.
    if ($key != "") 
    {
        $counts[$key]++;
        if ($countsread) 
        {
            $f = fopen(COUNTFILE, "w");
            fwrite($f, "<?php\n");
            while (list($l, $v) = each($counts))
            {
                fwrite($f, "\$counts['$l'] = $v;\n");
            }
            fwrite($f, "// If we read all the way, this variable is set.\n");
            fwrite($f, "// If something goes wrong, this variable is not set\n");
            fwrite($f, "// and we will never write.\n");
            fwrite($f, "\$countsread = 1;\n");
            fwrite($f, "?>\n");
            fclose($f);
        }
    }
}

/* From php.net/manual/en/function.html-entity-decode.php */
function unhtmlentities($string)
{
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    return strtr ($string, $trans_tbl);
}

function CountAndJump($key, $url)
{
    CountIt($key);
    $url = unhtmlentities($url);
    if (    substr($url, 0, 7) != "http://"
        and substr($url, 0, 6) != "ftp://"
        and substr($url, 0, 7) != "telnet:"
        and substr($url, 0, 5) != "news:"
        ) 
    {
        $url = "http://".$GLOBALS['HTTP_HOST']
                      .dirname($GLOBALS['PHP_SELF'])
                      ."/".$url;
    }
    
    header ("Location: $url");
    exit;            
}


?>