$pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid)) {
        die;
    }
}
@unlink($pidTime);
@file_put_contents($pidTime, time());
@file_put_contents($pidfile, getmypid());
access_db();
$php5 = $unix->LOCATE_PHP5_BIN();
$xtime = time();
$q = new mysql_squid_builder();
$q->TablePrimaireHour(date("YmdH", $xtime));
$q->check_youtube_hour(date("YmdH", $xtime));
$q->check_SearchWords_hour(date("YmdH", $xtime));
$q->check_quota_hour(date("YmdH", $xtime));
$f[] = "#!/bin/sh";
$f[] = "export LC_ALL=C";
$f[] = "{$php5} " . __FILE__ . " >/dev/null 2>&1";
$f[] = "";
@file_put_contents("/etc/cron.hourly/SquidHourlyTables.sh", @implode("\n", $f));
@chmod("/etc/cron.hourly/SquidHourlyTables.sh", 0755);
unset($f);
function tests($fullpath)
{
    $berekley = new parse_berekley_dbs();
    $filename = basename($fullpath);
    preg_match("#([0-9]+)_#", $filename, $re);
    $xre = $re[1];
    $xtime = $berekley->TIME_FROM_HOUR_INT($re[1]);
    print_r($berekley->ACCESS_PARSE_DB($fullpath, $xtime));
function parse_realtime_events($nopid = false)
{
    events("parse_realtime_events():: nopid => {$nopid}");
    $unix = new unix();
    $TimePID = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $TimeExec = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    if (!$nopid) {
        $pid = @file_get_contents($TimePID);
        if ($unix->process_exists($pid)) {
            $timePid = $unix->PROCCESS_TIME_MIN($pid);
            events("parse_realtime_events():: Already process exists {$pid} since {$timePid}Mn");
            if ($timePid > 10) {
                $kill = $unix->find_program("kill");
                events("parse_realtime_events():: Killing {$pid} running since {$timePid}Mn");
                unix_system_kill_force($pid);
            } else {
                if ($GLOBALS["VERBOSE"]) {
                    echo "Already running PID {$pid} since {$timePid}mn";
                }
                die;
            }
        }
        @file_put_contents($TimePID, getmypid());
    }
    events("parse_realtime_events():: Time File: {$TimeExec}");
    @unlink($TimeExec);
    @file_put_contents($TimeExec, time());
    events("Wakup...");
    Wakeup();
    events("parse_realtime_events():: -> parse_realtime_hash()");
    $GLOBALS["PARSE_SECOND_TIME"] = false;
    parse_realtime_hash();
    if (!$GLOBALS["PARSE_SECOND_TIME"]) {
        return;
    }
    @mkdir("/var/log/squid/mysql-queue", 0755, true);
    if (!($handle = opendir("/var/log/squid/mysql-queue"))) {
        return;
    }
    $q = new mysql_squid_builder();
    $q->check_youtube_hour(date("YmdH"));
    $countDeFiles = 0;
    while (false !== ($filename = readdir($handle))) {
        if ($filename == ".") {
            continue;
        }
        if ($filename == "..") {
            continue;
        }
        $filepath = "/var/log/squid/mysql-queue/{$filename}";
        if (preg_match("#^UserAutDB#", $filename)) {
            $content = unserialize(@file_get_contents($filepath));
            $contentSize = filesize($filepath) / 1024;
            $ArraySize = count($content);
            $sql = "INSERT IGNORE INTO UserAutDB (zmd5,MAC,ipaddr,uid,hostname,UserAgent) VALUES " . @implode(",", $content);
            $q->QUERY_SQL($sql);
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
            } else {
                if ($GLOBALS["VERBOSE"]) {
                    echo $filepath . " ({$contentSize} KB) done with {$ArraySize} elements...\n";
                }
                @unlink($filepath);
            }
            continue;
        }
        if (preg_match("#^macscan#", $filename)) {
            $content = unserialize(@file_get_contents($filepath));
            $contentSize = filesize($filepath) / 1024;
            $ArraySize = count($content);
            $sql = "INSERT IGNORE INTO `macscan` (`MAC`,`ipaddr`) VALUES " . @implode(",", $content);
            $q->QUERY_SQL($sql);
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
            } else {
                if ($GLOBALS["VERBOSE"]) {
                    echo $filepath . " ({$contentSize} KB) done with {$ArraySize} elements...\n";
                }
                @unlink($filepath);
            }
            continue;
        }
        if (preg_match("#^YoutubeRTT#", $filename)) {
            $sql = trim(@file_get_contents($filepath));
            $contentSize = strlen($sql) / 1024;
            if (preg_match("#INSERT IGNORE INTO `(.+?)`#", $sql, $re)) {
                $tablename = $re[1];
                if (!preg_match("#youtubehours_([0-9]+)#", $tablename)) {
                    echo "***** replace {$tablename} to youtubehours_date(YmdH) ****\n";
                    $sql = str_replace($tablename, "youtubehours_" . date("YmdH"), $sql);
                }
            }
            $q->QUERY_SQL($sql);
            if (!$q->ok) {
                ToSyslog("{$q->mysql_error} in line [" . __LINE__ . "]");
                if (preg_match("#Table\\s+'.+?\\.youtubehours_(.+?)'\\s+doesn't exist#", $q->mysql_error, $re)) {
                    ToSyslog("Building youtubehours_{$re[1]} table");
                    $q->check_youtube_hour($re[1]);
                    $q->QUERY_SQL($sql);
                }
            }
            if (!$q->ok) {
                ToSyslog("Failed ->{$filename}");
                continue;
            }
            if ($GLOBALS["VERBOSE"]) {
                echo $filepath . " ({$contentSize} KB) done with 1 element...\n";
            }
            @unlink($filepath);
        }
        if (preg_match("#^sizehour_([0-9]+)\\.#", $filename, $re)) {
            $TableSizeHours = "sizehour_{$re[1]}";
            $content = unserialize(@file_get_contents($filepath));
            $contentSize = filesize($filepath) / 1024;
            $q->check_sizehour($TableSizeHours);
            $sql = "INSERT IGNORE INTO `{$TableSizeHours}` (`zDate`,`size`,`cached`) VALUES " . @implode(",", $content);
            $q->QUERY_SQL($sql);
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
            } else {
                if ($GLOBALS["VERBOSE"]) {
                    echo $filepath . " ({$contentSize} KB) done with " . count($content) . " elements...\n";
                }
                @unlink($filepath);
            }
            continue;
        }
        if (preg_match("#^searchwords_([0-9]+)\\.#", $filename, $re)) {
            $TableSource = "searchwords_{$re[1]}";
            $content = unserialize(@file_get_contents($filepath));
            $contentSize = filesize($filepath) / 1024;
            $q->check_SearchWords_hour(null, $TableSource);
            $sql = "INSERT IGNORE INTO `{$TableSource}`\n\t\t(`zmd5`,`sitename`,`zDate`,`ipaddr`,`hostname`,`uid`,`MAC`,`account`,`familysite`,`words`)\n\t\tVALUES " . @implode(",", $content);
            $q->QUERY_SQL($sql);
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
            } else {
                if ($GLOBALS["VERBOSE"]) {
                    echo $filepath . " ({$contentSize} KB) done with " . count($content) . " elements...\n";
                }
                @unlink($filepath);
            }
            continue;
        }
        if (preg_match("#^quotatemp_([0-9]+)\\.#", $filename, $re)) {
            $TableSource = "quotatemp_{$re[1]}";
            $q->check_quota_hour_tmp($re[1]);
            $q->check_quota_hour($re[1]);
            $content = unserialize(@file_get_contents($filepath));
            $contentSize = filesize($filepath) / 1024;
            $sql = "INSERT IGNORE INTO `{$TableSource}` (`xtime`,`keyr`,`ipaddr`,`familysite`,`servername`,`uid`,`MAC`,`size`) VALUES " . @implode(",", $content);
            $q->QUERY_SQL($sql);
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
            } else {
                if ($GLOBALS["VERBOSE"]) {
                    echo $filepath . " ({$contentSize} KB) done with " . count($content) . " elements...\n";
                }
                @unlink($filepath);
            }
            continue;
        }
    }
    events("{$countDeFiles} Scanned files...");
    $php = $unix->LOCATE_PHP5_BIN();
    $nohup = $unix->find_program("nohup");
    $cmd = "{$nohup} {$php} " . __FILE__ . " --tables-primaires >/dev/null 2>&1 &";
    if ($GLOBALS["VERBOSE"]) {
        echo $cmd . "\n";
    }
    shell_exec($cmd);
}
function compile_table_hour($tablesource, $xtime)
{
    $q = new mysql_squid_builder();
    $sql = "SELECT SUM(size) as size,HOUR(xtime) AS `hour`,ipaddr,uid,MAC,familysite FROM {$tablesource} GROUP BY hour,ipaddr,uid,MAC,familysite HAVING size>0";
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        echo $q->mysql_error;
        return false;
    }
    $count = mysql_num_rows($results);
    $OUS = array();
    if ($count == 0) {
        return true;
    }
    $nexttable = "quotahours_" . date('YmdH', $xtime);
    if (!$q->check_quota_hour(date("YmdH", $xtime))) {
        return false;
    }
    if (!$q->FIELD_EXISTS("{$nexttable}", "ou")) {
        $q->QUERY_SQL("ALTER IGNORE TABLE `{$nexttable}` ADD `ou`VARCHAR( 128 ) NOT NULL ,ADD INDEX( `ou` )");
    }
    if (is_file("/etc/artica-postfix/activedirectory-ou.db")) {
        $OUS = unserialize(@file_get_contents("/etc/artica-postfix/activedirectory-ou.db"));
    }
    $prefix = "INSERT IGNORE INTO {$nexttable} (keyr,size,hour,ipaddr,uid,ou,MAC,familysite,servername) VALUES ";
    $f = array();
    if ($GLOBALS["VERBOSE"]) {
        echo "{$tablesource} {$count} rows\n";
    }
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $md5 = md5(serialize($ligne));
        $ou = null;
        $uid = $ligne["uid"];
        if ($uid != null) {
            if (isset($OUS[$uid])) {
                $ou = mysql_escape_string2($OUS[$uid]);
            }
        }
        $uid = mysql_escape_string2($ligne["uid"]);
        $servername = mysql_escape_string2($ligne["familysite"]);
        $familysite = mysql_escape_string2($ligne["familysite"]);
        $ipaddr = mysql_escape_string2($ligne["ipaddr"]);
        $MAC = mysql_escape_string2($ligne["MAC"]);
        $hour = $ligne["hour"];
        $size = $ligne["size"];
        $f[] = "('{$md5}','{$size}','{$hour}','{$ipaddr}','{$uid}','{$ou}','{$MAC}','{$familysite}','{$servername}')";
        if (count($f) > 500) {
            $q->QUERY_SQL($prefix . @implode(",", $f));
            if (!$q->ok) {
                return false;
            }
            $f = array();
        }
    }
    if (count($f) > 0) {
        $q->QUERY_SQL($prefix . @implode(",", $f));
        if (!$q->ok) {
            return false;
        }
        $f = array();
    }
    return true;
}