function wizard_certificate_save()
{
    $password = url_decode_special_tool($_POST["wizard-certificate-password"]);
    $password = mysql_escape_string2($password);
    $CommonName = url_decode_special_tool($_POST["wizard-certificate-commonname"]);
    $CommonName = strtolower(trim($CommonName));
    if ($CommonName == null) {
        echo "CommonName, no such data";
        return;
    }
    $q = new mysql();
    $sql = "SELECT CommonName  FROM sslcertificates WHERE CommonName='{$CommonName}'";
    $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
    if ($ligne["CommonName"] != null) {
        echo "{$CommonName} Already exists...\n";
        return;
    }
    $sql = "INSERT IGNORE INTO sslcertificates (CommonName,keyPassword,password) VALUES ('{$CommonName}','{$password}','{$password}')";
    $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        echo "MySQL Error:\n" . $q->mysq_error . "\n{$sql}";
        return;
    }
    $sock = new sockets();
    $CommonName = urlencode($CommonName);
    echo base64_decode($sock->getFrameWork("system.php?BuildCSR={$CommonName}"));
}
function send_to_mysql($buffer)
{
    $dbpath = "/home/artica/postfix/milter-greylist/logger/" . date("YmdH") . ".miltergreylist.db";
    if (!berekley_db_create($dbpath)) {
        return;
    }
    $db_con = @dba_open($dbpath, "w", "db4");
    if (!$db_con) {
        ToSyslog("send_to_mysql:: {$dbpath} failed connect");
        @dba_close($db_con);
        continue;
    }
    $results = explode(",", $buffer);
    $md5 = md5($buffer . time());
    $instance = $results[0];
    $publicip = $results[1];
    $mailfrom = mysql_escape_string2($results[2]);
    $rcpt = mysql_escape_string2($results[3]);
    $failed = $results[6];
    $Country = $results[7];
    $HOUR = date('H');
    $date = date("Y-m-d H:i:s");
    $tablename = "mgreyh_" . date("YmdH");
    $mailfromZ = explode("@", $mailfrom);
    $rcptZ = explode("@", $rcpt);
    $prefix = "INSERT IGNORE INTO {$tablename} (`zmd5`,`ztime`,`zhour`,`mailfrom`,`instancename`,`mailto`,`domainfrom`,`domainto`,`senderhost`,`failed`) VALUES ";
    $suffix = "('{$md5}','{$date}','{$HOUR}','{$mailfrom}','{$instance}','{$rcpt}','{$mailfromZ[1]}','{$rcptZ[1]}','{$publicip}','{$failed}')";
    $md5 = md5($suffix);
    dba_replace($md5, $suffix, $db_con);
    @dba_close($db_con);
    return;
}
function Save()
{
    $q = new mysql();
    if (!$q->TABLE_EXISTS("storage_containers", "artica_backup")) {
        $sql = "CREATE TABLE IF NOT EXISTS `artica_backup`.`storage_containers` (\n\t\t\t\t`groupid` VARCHAR( 255 ) NOT NULL,\n\t\t\t\t`enabled` smallint( 1 ) NOT NULL,\n\t\t\t\t`maxsize` INT UNSIGNED ,\n\t\t\t\t`directory` VARCHAR( 255 ) NOT NULL,\n\t\t\t\t PRIMARY KEY ( `groupid` ),\n\t\t\t\t KEY `enabled`(`enabled`)\n\t\t\t\t) ENGINE=MYISAM;";
        $q->QUERY_SQL($sql, 'artica_backup');
        if (!$q->ok) {
            echo $q->mysql_error;
            return;
        }
    }
    $_POST["directory"] = mysql_escape_string2($_POST["directory"]);
    $gid = mysql_escape_string2($_POST["gid"]);
    $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT * FROM storage_containers WHERE `groupid`='{$gid}'", "artica_backup"));
    //echo "$gid = {$ligne["directory"]} Enabled={$_POST["enabled"]}\n";
    if ($ligne["directory"] != null) {
        $q->QUERY_SQL("UPDATE storage_containers SET `maxsize`='{$_POST["maxsize"]}',\n\t\tenabled='{$_POST["enabled"]}',`directory`='{$_POST["directory"]}' WHERE `groupid`='{$gid}'", "artica_backup");
    } else {
        $q->QUERY_SQL("INSERT IGNORE INTO storage_containers (groupid,enabled,maxsize,`directory`)\n\t\t\t\tVALUES ('{$gid}','{$_POST["enabled"]}','{$_POST["maxsize"]}','{$_POST["directory"]}')", "artica_backup");
    }
    if (!$q->ok) {
        echo $q->mysql_error;
        return;
    }
}
function SaveItems(){
	$category=$_POST["category"];
	$datas=$_POST["items"];
	$q=new mysql_squid_builder();
	$tb=explode("\n",$datas);
	while (list ($num, $www) = each ($tb) ){
		if(preg_match("#tp:\/\/(.+)#", $www,$re)){$www=$re[1];}
		$www=str_replace("www.", "", $www);
		$uris[$www]=true;
	}
	$zDate=date("Y-m-d H:i:s");
	while (list ($www, $none) = each ($uris) ){
		if(trim($www)==null){continue;}
		$md5=md5("$category$www");
		echo "Saving $www\n";
		$www=mysql_escape_string2($www);
		$f[]="('$md5','$zDate','$www',1)";
	}
	
	$table="categoryuris_".$q->category_transform_name($category);
	if(!$q->CreateCategoryUrisTable(null,$table)){
		echo $q->mysql_error;
		return;
	}
	if(count($f)>0){
		$sql="INSERT IGNORE INTO `$table` (`zmd5`,`zDate`,`pattern`,`enabled`) VALUES ".@implode(",", $f);
		$q->QUERY_SQL($sql);
		if(!$q->ok){echo $q->mysql_error;return;}
		
		$sock=new sockets();
		$sock->getFrameWork("squid.php?ufdbguard-compile-database={$_POST["category"]}");
	}
	
}
function save()
{
    $q = new mysql_meta();
    $f = array();
    $f = explode("\n", $_POST["domains"]);
    while (list($index, $line) = each($f)) {
        $line = trim(strtolower($line));
        if ($line == null) {
            continue;
        }
        $line = mysql_escape_string2($line);
        $md5 = md5($line);
        $n[] = "('{$md5}','{$line}')";
    }
    $q->CheckTables();
    $q->QUERY_SQL("TRUNCATE TABLE `squid_whitelists`");
    if (count($n) > 0) {
        $q->QUERY_SQL("INSERT IGNORE INTO `squid_whitelists` (`zMD5`,`pattern`) VALUES " . @implode(",", $n));
        if (!$q->ok) {
            echo $q->mysql_error;
            return;
        }
    }
    $sock = new sockets();
    $EnableArticaMetaServer = intval($sock->GET_INFO("EnableArticaMetaServer"));
    if ($EnableArticaMetaServer == 0) {
        return;
    }
    $sock->getFrameWork("artica.php?meta-proxy-config=yes");
}
function time_save()
{
    $ID = $_POST["time-save"];
    $array_days = array(1 => "monday", 2 => "tuesday", 3 => "wednesday", 4 => "thursday", 5 => "friday", 6 => "saturday", 7 => "sunday");
    while (list($num, $maks) = each($array_days)) {
        if ($_POST["D{$num}"] == 1) {
            $TTIME["D{$num}"] = 1;
        }
    }
    $TTIME["ttime"] = $_POST["ttime"];
    $TTIME["ftime"] = $_POST["ftime"];
    $rule1 = strtotime(date("Y-m-d") . " {$TTIME["ftime"]}");
    $rule2 = strtotime(date("Y-m-d") . " {$TTIME["ttime"]}");
    if ($rule1 > $rule2) {
        $tpl = new templates();
        echo $tpl->javascript_parse_text("{fwtime_explain}");
        return;
    }
    $TTIMEZ = mysql_escape_string2(serialize($TTIME));
    $q = new mysql();
    if (!$q->FIELD_EXISTS("iptables_main", "time_restriction", "artica_backup")) {
        $sql = "ALTER TABLE `iptables_main` ADD `time_restriction` TEXT";
        $q->QUERY_SQL($sql, "artica_backup");
    }
    if (!$q->FIELD_EXISTS("iptables_main", "enablet", "artica_backup")) {
        $sql = "ALTER TABLE `iptables_main` ADD `enablet` smallint( 1 ) NOT NULL DEFAULT '0',ADD INDEX ( enablet ) ";
        $q->QUERY_SQL($sql, "artica_backup");
    }
    $sql = "UPDATE iptables_main SET `enablet`='{$_POST["enablet"]}',`time_restriction`='{$TTIMEZ}' WHERE ID='{$ID}'";
    $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        echo $q->mysql_error . "\n{$sql}";
    }
}
function Save()
{
    $_POST["rulename"] = mysql_escape_string2(url_decode_special_tool($_POST["rulename"]));
    $sql = "UPDATE haproxy_acls_rules SET \n\t\trulename='{$_POST["rulename"]}',\n\t\trule_action='{$_POST["rule_action"]}',\n\t\trule_action_data='{$_POST["rule_action_data"]}',\n\t\tzorder='{$_POST["zorder"]}'\n\t\tWHERE ID={$_POST["ruleid"]}";
    $q = new mysql();
    $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        echo $q->mysql_error;
    }
}
function import()
{
    $q = new mysql_squid_builder();
    $sql_add = "INSERT IGNORE INTO webfilter_members (`membertype`,`pattern`,`enabled`,`groupid`) VALUES ";
    $f = explode("\n", $_POST["item-import"]);
    while (list($num, $ligne) = each($f)) {
        $ligne = trim($ligne);
        if ($ligne == null) {
            continue;
        }
        $RR = mysql_fetch_array($q->QUERY_SQL("SELECT ID FROM webfilter_members WHERE pattern='{$ligne}'"));
        $ID = intval($RR["ID"]);
        $ligne = mysql_escape_string2($ligne);
        $ZZ[] = "('{$_POST["membertype"]}','{$ligne}',1,{$_POST["group_id"]})";
    }
    if (count($ZZ) == 0) {
        return;
    }
    $q->QUERY_SQL($sql_add . @implode(",", $ZZ));
}
function smtpd_client_restrictions_save()
{
    $sock = new sockets();
    $ou = $_POST["ou"];
    if ($ou == null) {
        $ou = $_SESSION["ou"];
    }
    if ($ou == null) {
        echo "Organization is null!\n";
        return;
    }
    $q = new mysql();
    while (list($num, $ligne) = each($_POST)) {
        $MAIN[$num] = $ligne;
    }
    $q->QUERY_SQL("DELETE FROM smptd_client_access WHERE `ou`='{$ou}'");
    $DATA = mysql_escape_string2(base64_decode(serialize($MAIN)));
    $q->QUERY_SQL("INSERT IGNORE INTO smptd_client_access (ou, configuration) VALUES ('{$ou}','{$DATA}')", "artica_backup");
    if (!$q->ok) {
        echo $q->mysql_error;
        return;
    }
    $sock->getFrameWork("postfix.php?smtpd-recipient-restrictions=yes");
}
function build_query_js()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $from = strtotime("{$_GET["date1"]} {$_GET["time1"]}");
    $to = strtotime("{$_GET["date2"]} {$_GET["time2"]}");
    $interval = $_GET["interval"];
    $t = $_GET["t"];
    $user = $_GET["user"];
    $md5 = md5("WEBSITES:{$from}{$to}{$interval}{$user}{$_GET["searchsites"]}{$_GET["searchuser"]}");
    $_SESSION["SQUID_STATS_DATE1"] = $_GET["date1"];
    $_SESSION["SQUID_STATS_TIME1"] = $_GET["time1"];
    $_SESSION["SQUID_STATS_DATE2"] = $_GET["date2"];
    $_SESSION["SQUID_STATS_TIME2"] = $_GET["time2"];
    $timetext1 = $tpl->time_to_date(strtotime("{$_GET["date1"]} {$_GET["time1"]}"), true);
    $timetext2 = $tpl->time_to_date(strtotime("{$_GET["date2"]} {$_GET["time2"]}"), true);
    $nextFunction = "LoadAjax('WEBFILTERING_STATS_MAIN_GRAPH','{$page}?main=yes&zmd5={$md5}&t={$t}');";
    $nextFunction_encoded = urlencode(base64_encode($nextFunction));
    $q = new mysql_squid_builder();
    $q->CheckReportTable();
    $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT ID,builded FROM reports_cache WHERE `zmd5`='{$md5}'"));
    if (intval($ligne["ID"]) == 0) {
        $array["FROM"] = $from;
        $array["TO"] = $to;
        $array["INTERVAL"] = $interval;
        $array["USER"] = $user;
        $array["categories"] = $_GET["categories"];
        $array["searchuser"] = $_GET["searchuser"];
        $serialize = mysql_escape_string2(serialize($array));
        $title = "{webfiltering}: {$timetext1} - {to} {$timetext2} and {$user} {is} {$array["searchuser"]}";
        $sql = "INSERT IGNORE INTO `reports_cache` (`zmd5`,`title`,`report_type`,`zDate`,`params`) VALUES \n\t\t('{$md5}','{$title}','WEBFILTERING',NOW(),'{$serialize}')";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            echo "alert('" . $tpl->javascript_parse_text($q->mysql_errror) . "')";
            return;
        }
        echo "Loadjs('squid.statistics.progress.php?zmd5={$md5}&NextFunction={$nextFunction_encoded}')";
        return;
    }
    if (intval($ligne["builded"] == 0)) {
        echo "\nfunction Start{$t}(){\n\tLoadjs('squid.statistics.progress.php?zmd5={$md5}&NextFunction={$nextFunction_encoded}&t={$t}');\n}\n\nif(document.getElementById('graph-{$t}')){\n\tdocument.getElementById('graph-{$t}').innerHTML='<center><img src=img/loader-big.gif></center>';\n}\nLockPage();\t\nsetTimeout('Start{$t}()',800);\n";
        return;
    }
    echo $nextFunction;
}
function AddNewSchedule_save()
{
    $users = new usersMenus();
    $q = new mysql_meta();
    $tpl = new templates();
    $task = new system_tasks();
    $task_type = $task->tasks_array;
    $info = $tpl->javascript_parse_text($task_type[$_POST["TaskType"]]);
    $defaultdesc = replace_accents($info);
    if ($_POST["TimeDescription"] == null) {
        $_POST["TimeDescription"] = $defaultdesc . " : {$_POST["TimeText"]}";
    }
    $_POST["TimeDescription"] = mysql_escape_string2($_POST["TimeDescription"]);
    $sql = "INSERT IGNORE INTO system_schedules (TimeDescription,TimeText,TaskType,enabled,uuid) \n\tVALUES('{$_POST["TimeDescription"]}','{$_POST["TimeText"]}','{$_POST["TaskType"]}',1,'{$_POST["uuid"]}')";
    if ($_POST["ID"] > 0) {
        $sql = "UPDATE system_schedules SET \n\t\t\tTimeDescription='{$_POST["TimeDescription"]}',\n\t\t\tTimeText='{$_POST["TimeText"]}',\n\t\t\tTaskType='{$_POST["TaskType"]}' WHERE ID={$_POST["ID"]}\n\t\t\t";
    }
    if (!$q->TABLE_EXISTS("system_schedules")) {
        $q->BuildTables();
    }
    $q->QUERY_SQL($sql);
    if (!$q->ok) {
        echo $q->mysql_error;
        return;
    }
    $sock = new sockets();
    $sock->getFrameWork("artica.php?build-meta-schedules=yes&uuid={$_POST["uuid"]}");
}
function new_rule(){
	$q=new mysql_squid_builder();
	$q->CheckTables(null,true);
	$rulename=mysql_escape_string2(url_decode_special_tool($_POST["new-rule"]));
	$q->QUERY_SQL("INSERT INTO wpad_rules (rulename,enabled) VALUES ('$rulename','1')");
	if(!$q->ok){echo $q->mysql_error;}
}
function _table_hours_perform($tablename)
{
    if (!isset($GLOBALS["Q"])) {
        $GLOBALS["Q"] = new mysql_squid_builder();
    }
    if (!preg_match("#ngixattck_([0-9]+)#", $tablename, $re)) {
        writelogs_squid("NOT AN HOUR TABLE `{$tablename}`", __FUNCTION__, __FILE__, __LINE__, "stats");
        return;
    }
    $q = new mysql_squid_builder();
    $time = $q->TIME_FROM_HOUR_TEMP_TABLE($tablename);
    if ($GLOBALS["VERBOSE"]) {
        echo "{$tablename} - {$time} - " . date("Y-m-d", $time) . "\n";
    }
    $sql = "SELECT HOUR(zDate) as `hour`,COUNT(keyr) as hits,`ipaddr`,`familysite`,`hostname`,`country`,`servername`\n\tFROM `{$tablename}` GROUP BY `hour`,`ipaddr`,`familysite`,`hostname`,`country`,`servername`";
    if ($GLOBALS["VERBOSE"]) {
        echo $sql . "\n";
    }
    $results = $GLOBALS["Q"]->QUERY_SQL($sql);
    if (!$GLOBALS["Q"]->ok) {
        writelogs_squid("Fatal: {$GLOBALS["Q"]->mysql_error} on `{$tablename}`\n" . @implode("\n", $GLOBALS["REPAIR_MYSQL_TABLE"]), __FUNCTION__, __FILE__, __LINE__, "stats");
        if (strpos(" {$GLOBALS["Q"]->mysql_error}", "is marked as crashed and should be repaired") > 0) {
            $q1 = new mysql();
            writelogs_squid("try to repair table `{$tablename}`", __FUNCTION__, __FILE__, __LINE__, "stats");
            $q1->REPAIR_TABLE("squidlogs", $tablename);
            writelogs_squid(@implode("\n", $GLOBALS["REPAIR_MYSQL_TABLE"]), __FUNCTION__, __FILE__, __LINE__, "stats");
        }
        return false;
    }
    if (mysql_num_rows($results) == 0) {
        return true;
    }
    $timekey = date('Ymd', $time);
    $tabledest = "ngixattckd_{$timekey}";
    if (!$q->check_nginx_attacks_DAY($timekey)) {
        return false;
    }
    $prefix = "INSERT IGNORE INTO {$tabledest} (zmd5,`hour`,`ipaddr`,`familysite`,`hostname`,`country`,`servername`,`hits`) VALUES ";
    $d = 0;
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $zmd = array();
        while (list($key, $value) = each($ligne)) {
            $ligne[$key] = mysql_escape_string2($value);
            $zmd[] = $value;
        }
        $zMD5 = md5(@implode("", $zmd));
        $f[] = "('{$zMD5}','{$ligne["hour"]}','{$ligne["ipaddr"]}','{$ligne["familysite"]}','{$ligne["hostname"]}','{$ligne["country"]}','{$ligne["servername"]}','{$ligne["hits"]}')";
        if (count($f) > 500) {
            $q->QUERY_SQL($prefix . @implode(",", $f));
            $f = array();
            if (!$q->ok) {
                writelogs_squid("Fatal: {$q->mysql_error} on `{$tabledest}`", __FUNCTION__, __FILE__, __LINE__, "stats");
                return;
            }
        }
    }
    if (count($f) > 0) {
        $q->QUERY_SQL($prefix . @implode(",", $f));
        $f = array();
        if (!$q->ok) {
            writelogs_squid("Fatal: {$q->mysql_error} on `{$tabledest}`", __FUNCTION__, __FILE__, __LINE__, "stats");
            return;
        }
    }
    return true;
}
function Save()
{
    writelogs("Saving rule", __FUNCTION__, __FILE__, __LINE__);
    $q = new mysql_squid_builder();
    $table = "transparent_networks";
    if (!$q->TABLE_EXISTS($table)) {
        $q->CheckTables(null, true);
    }
    if (!$q->FIELD_EXISTS("transparent_networks", "block")) {
        $q->QUERY_SQL("ALTER TABLE `transparent_networks` ADD `block` smallint( 1 ) NOT NULL ,ADD INDEX ( `block`)");
    }
    $editF = false;
    $ID = $_POST["ID"];
    unset($_POST["ID"]);
    if (preg_match("#[0-9A-Za-z]+-[0-9A-Za-z]+-[0-9A-Za-z]+-[0-9A-Za-z]+-[0-9A-Za-z]+-[0-9A-Za-z]+#", $_POST["pattern"])) {
        $_POST["pattern"] = strtolower($_POST["pattern"]);
        $_POST["pattern"] = str_replace("-", ":", $_POST["pattern"]);
    }
    while (list($key, $value) = each($_POST)) {
        $value = url_decode_special_tool($value);
        $fields[] = "`{$key}`";
        $values[] = "'" . mysql_escape_string2($value) . "'";
        $edit[] = "`{$key}`='" . mysql_escape_string2($value) . "'";
    }
    $sql_edit = "UPDATE `{$table}` SET " . @implode(",", $edit) . " WHERE ID='{$ID}'";
    $sql = "INSERT IGNORE INTO `{$table}` (" . @implode(",", $fields) . ") VALUES (" . @implode(",", $values) . ")";
    if ($ID > 0) {
        $sql = $sql_edit;
    }
    writelogs($sql, __FUNCTION__, __FILE__, __LINE__);
    $q->QUERY_SQL($sql);
    if (!$q->ok) {
        echo "Mysql error: `{$q->mysql_error}`";
        writelogs($q->mysql_error, __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    $tpl = new templates();
}
Example #15
0
function save()
{
    $q = new mysql();
    $table = "texttoldap";
    $tpl = new templates();
    $editF = false;
    $ID = $_POST["connection-id"];
    unset($_POST["connection-id"]);
    while (list($key, $value) = each($_POST)) {
        $value = url_decode_special_tool($value);
        $fields[] = "`{$key}`";
        $values[] = "'" . mysql_escape_string2($value) . "'";
        $edit[] = "`{$key}`='" . mysql_escape_string2($value) . "'";
    }
    $sql_edit = "UPDATE `{$table}` SET " . @implode(",", $edit) . " WHERE ID='{$ID}'";
    $sql = "INSERT IGNORE INTO `{$table}` (" . @implode(",", $fields) . ") VALUES (" . @implode(",", $values) . ")";
    if ($ID > 0) {
        $sql = $sql_edit;
    }
    $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        echo "Mysql error: `{$q->mysql_error}`";
        return;
    }
    $tpl = new templates();
    $tpl->javascript_parse_text("{success}");
}
function PostfixFullProcess($file)
{
    $q = new mysql();
    $org_file = $file;
    if (!is_file($file)) {
        return null;
    }
    $ini = new Bs_IniHandler($file);
    if (!isset($ini->_params["TIME"]["message-id"])) {
        $ini->_params["TIME"]["message-id"] = null;
    }
    if (!isset($ini->_params["TIME"]["time_end"])) {
        $ini->_params["TIME"]["time_end"] = null;
    }
    if (!isset($ini->_params["TIME"]["time_start"])) {
        $ini->_params["TIME"]["time_start"] = null;
    }
    if (!isset($ini->_params["TIME"]["mailfrom"])) {
        $ini->_params["TIME"]["mailfrom"] = null;
    }
    if (!isset($ini->_params["TIME"]["mailto"])) {
        $ini->_params["TIME"]["mailto"] = null;
    }
    if (!isset($ini->_params["TIME"]["delivery_user"])) {
        $ini->_params["TIME"]["delivery_user"] = null;
    }
    if (!isset($ini->_params["TIME"]["smtp_sender"])) {
        $ini->_params["TIME"]["smtp_sender"] = null;
    }
    if (!isset($ini->_params["TIME"]["size"])) {
        $ini->_params["TIME"]["size"] = null;
    }
    if (!isset($ini->_params["TIME"]["time_start"])) {
        $ini->_params["TIME"]["time_start"] = null;
    }
    if (!isset($ini->_params["TIME"]["time_connect"])) {
        $ini->_params["TIME"]["time_connect"] = null;
    }
    if (!isset($ini->_params["TIME"]["bounce_error"])) {
        $ini->_params["TIME"]["bounce_error"] = null;
    }
    if (!isset($ini->_params["TIME"]["delivery_success"])) {
        $ini->_params["TIME"]["delivery_success"] = null;
    }
    $delivery_success = $ini->_params["TIME"]["delivery_success"];
    $message_id = $ini->_params["TIME"]["message-id"];
    $time_end = $ini->_params["TIME"]["time_end"];
    $mailfrom = $ini->_params["TIME"]["mailfrom"];
    $mailto = $ini->_params["TIME"]["mailto"];
    $delivery_success = $ini->_params["TIME"]["delivery_success"];
    $bounce_error = $ini->_params["TIME"]["bounce_error"];
    $time_connect = $ini->_params["TIME"]["time_connect"];
    $delivery_user = $ini->_params["TIME"]["delivery_user"];
    $time_start = $ini->_params["TIME"]["time_start"];
    $smtp_sender = $ini->_params["TIME"]["smtp_sender"];
    $size = $ini->_params["TIME"]["size"];
    $search_postfix_id = true;
    if ($time_connect == null) {
        if ($time_start != null) {
            $time_connect = $time_start;
        }
    }
    $file = basename($file);
    $postfix_id = str_replace(".msg", "", $file);
    if ($GLOBALS["VERBOSE"]) {
        echo "PostfixFullProcess()::[{$postfix_id}] file:{$file}\n";
    }
    events("PostfixFullProcess()::[{$postfix_id}] file:{$file}");
    if (preg_match("#delivery temporarily suspended.+?Local configuration error#", $bounce_error)) {
        $bounce_error = "Remote Server error";
        $delivery_success = "no";
    }
    if (preg_match("#250.+?mail accepted for delivery#", $bounce_error)) {
        $bounce_error = "Sended";
        $delivery_success = "yes";
    }
    if (preg_match("#Scanning timed out#", $bounce_error)) {
        $bounce_error = "Scanning timed out";
        $delivery_success = "no";
    }
    if ($mailto == null) {
        if ($delivery_user != null) {
            $mailto = $delivery_user;
        }
    }
    if ($time_connect == null) {
        if ($time_end != null) {
            $time_connect = $time_end;
        }
    }
    if ($time_end == null) {
        if ($time_connect != null) {
            $time_end = $time_connect;
        }
    }
    if (preg_match('#(.+?)@(.+)#', $mailfrom, $re)) {
        $domain_from = $re[2];
    }
    if (preg_match('#(.+?)@(.+)#', $mailto, $re)) {
        $domain_to = $re[2];
    }
    $mailfrom = str_replace("'", '', $mailfrom);
    $mailto = str_replace("'", '', $mailto);
    if ($delivery_success == null) {
        $delivery_success = "no";
    }
    if ($message_id == null) {
        $message_id = md5(time() . $mailfrom . $mailto);
    }
    $bounce_error_array["RBL"] = true;
    $bounce_error_array["Helo command rejected"] = true;
    $bounce_error_array["Domain not found"] = true;
    $bounce_error_array["too many recipients"] = true;
    $bounce_error_array["PostScreen RBL"] = true;
    $bounce_error_array["PostScreen"] = true;
    $bounce_error_array["Scanning timed out"] = true;
    $bounce_error_array["blacklisted"] = true;
    $bounce_error_array["timed out"] = true;
    $bounce_error_array["malformed address"] = true;
    $bounce_error_array["Connection refused"] = true;
    $bounce_error_array["malformed address (ASSP)"] = true;
    if (preg_match("#lost connection with.+?\\[(.+?)\\]\\s+#", $bounce_error, $re)) {
        $bounce_error = "lost connection";
        $delivery_success = "no";
        $smtp_sender = $re[1];
    }
    if ($bounce_error_array[$bounce_error]) {
        $search_postfix_id = false;
    }
    if ($smtp_sender != null) {
        $t1 = time();
        $array_geo = GeoIP($smtp_sender);
        $t2 = time();
        if ($GLOBALS["VERBOSE"]) {
            $distanceInSeconds = round(abs($t2 - $t1));
            echo "GeoIP({$smtp_sender}) -> {$distanceInSeconds} seconds\n";
        }
        $Country = $array_geo[0];
        $City = $array_geo[1];
        $City = addslashes($City);
        $Country = addslashes($Country);
    }
    if (preg_match("#,sender_user='******'#", $mailfrom, $re)) {
        $mailfrom = $re[1];
    }
    if ($search_postfix_id) {
        $t1 = time();
        $sqlid = getid_from_postfixid($postfix_id, $q);
        $t2 = time();
        if ($GLOBALS["VERBOSE"]) {
            $distanceInSeconds = round(abs($t2 - $t1));
            echo "getid_from_postfixid({$postfix_id} -> {$distanceInSeconds} seconds\n";
        }
    }
    events("PostfixFullProcess():: {$time_connect}:: message-id=<{$message_id}> from=<{$mailfrom}> to=<{$mailto}> bounce_error=<{$bounce_error}> old id={$sqlid}");
    if ($sqlid == null) {
        $domain_to = mysql_escape_string2($domain_to);
        $mailto = mysql_escape_string2($mailto);
        $bounce_error = mysql_escape_string2($bounce_error);
        $sql = "INSERT IGNORE INTO smtp_logs (delivery_id_text,msg_id_text,time_connect,time_sended,delivery_success,sender_user,sender_domain,delivery_user,delivery_domain,bounce_error,smtp_sender,Country  )\n\t\tVALUES('{$postfix_id}','{$message_id}','{$time_connect}','{$time_end}','{$delivery_success}','{$mailfrom}','{$domain_from}','{$mailto}','{$domain_to}','{$bounce_error}','{$smtp_sender}','{$Country}');\n\t\t";
        if (strlen($message_id) > 255) {
            $message_id = md5($message_id);
        }
        events_cnx(__FUNCTION__ . "() ADD:[{$message_id}] [{$smtp_sender}] from=<{$mailfrom}> to=<{$mailto}> \"{$bounce_error}\" line:" . __LINE__);
        $t1 = time();
        $q->QUERY_SQL($sql, "artica_events");
        $t2 = time();
        if ($GLOBALS["VERBOSE"]) {
            $distanceInSeconds = round(abs($t2 - $t1));
            echo "QUERY_SQL -> ADD -> {$distanceInSeconds} seconds\n";
        }
        if ($q->ok) {
            events("PostfixFullProcess():: Delete {$org_file} line:" . __LINE__);
            @unlink($org_file);
            return true;
        } else {
            events_cnx("FAILED MYSQL {$org_file}");
            events("PostfixFullProcess():: {$q->mysql_error} line:" . __LINE__);
            if (preg_match("#Error.+?File .+?smtp_logs.+?not found#", $q->mysql_error)) {
                $unix = new unix();
                $unix->send_email_events("artica_events/smtp_logs table is crashed", "mysql claim:{$q->mysql_error}\nThe table has been deleted and rebuilded", "system");
                $sql = "DROP TABLE `smtp_logs`";
                $q->QUERY_SQL($sql, "artica_events");
                $q->BuildTables();
            }
            events($sql);
            return false;
        }
    } else {
        $mailfrom = str_replace(">, orig_to=", "", $mailfrom);
        events_cnx("EDIT:[{$sqlid}] from=<{$mailfrom}> to=<{$mailto}> bounce_error=\"{$bounce_error}\"");
        if ($mailfrom != null) {
            $FIELDS[] = "sender_user='******'";
        }
        if ($delivery_success != null) {
            $FIELDS[] = "delivery_success='{$delivery_success}'";
        }
        if ($domain_from != null) {
            $FIELDS[] = "sender_domain='{$domain_from}'";
        }
        if ($domain_to != null) {
            $FIELDS[] = "delivery_domain='{$domain_to}'";
        }
        if ($bounce_error != null) {
            $FIELDS[] = "bounce_error='{$bounce_error}'";
        }
        if ($time_connect != null) {
            $FIELDS[] = "time_connect='{$time_connect}'";
        }
        if ($time_end != null) {
            $FIELDS[] = "time_sended='{$time_end}'";
        }
        if ($message_id != null) {
            $FIELDS[] = "msg_id_text='{$message_id}'";
        }
        if ($smtp_sender != null) {
            $FIELDS[] = "smtp_sender='{$smtp_sender}'";
        }
        if ($size != null) {
            $FIELDS[] = "bytes='{$size}'";
        }
        if (count($FIELDS) > 0) {
            $Settadd = "," . @implode(",", $FIELDS);
        }
        $sql = "UPDATE smtp_logs SET delivery_id_text='{$postfix_id}'{$Settadd} WHERE id={$sqlid}";
        $t1 = time();
        $q->QUERY_SQL($sql, "artica_events");
        $t2 = time();
        if ($GLOBALS["VERBOSE"]) {
            $distanceInSeconds = round(abs($t2 - $t1));
            echo "QUERY_SQL -> UPDATE -> {$distanceInSeconds} seconds\n";
        }
        if ($q->ok) {
            @unlink($org_file);
            return true;
        } else {
            events_cnx("FAILED MYSQL {$org_file}");
            events("{$q->mysql_error}");
            events($sql);
            return false;
        }
    }
}
function graph5()
{
    $q = new mysql_squid_builder();
    $page = CurrentPageName();
    $tpl = new templates();
    $t = $_GET["t"];
    $ff = time();
    $tablename = date("Ymd", $_GET["xtime"]) . "_hour";
    $category = mysql_escape_string2($_GET["category"]);
    $sql = "SELECT SUM(size) as thits, category,uid FROM `{$tablename}`\n\tGROUP BY category,uid \n\tHAVING category='{$category}'\n\tORDER BY thits DESC LIMIT 0,10";
    $unknown = $tpl->_ENGINE_parse_body("{unknown}");
    $c = 0;
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        $tpl->javascript_senderror($q->mysql_error, $_GET["container"]);
    }
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        if (trim($ligne["uid"]) == null) {
            $ligne["uid"] = $unknown;
        }
        $ligne["thits"] = round($ligne["thits"] / 1024 / 1000);
        $PieData[$ligne["uid"]] = $ligne["thits"];
        $c++;
    }
    $tpl = new templates();
    $highcharts = new highcharts();
    $highcharts->container = $_GET["container"];
    $highcharts->PieDatas = $PieData;
    $highcharts->ChartType = "pie";
    $highcharts->PiePlotTitle = "{hits}";
    $highcharts->Title = $tpl->_ENGINE_parse_body("{$category}: {top_members_by_size} (MB)");
    echo $highcharts->BuildChart();
}
Example #18
0
function HyperCacheMirror($JustID = 0)
{
    $unix = new unix();
    $httrack = $unix->find_program("httrack");
    if (!is_file($httrack)) {
        if ($GLOBALS["VERBOSE"]) {
            echo "httrack no such binary\n";
        }
        return;
    }
    $q = new mysql_squid_builder();
    if (!$q->FIELD_EXISTS("artica_caches_mirror", "ToDelete")) {
        $sql = "ALTER TABLE `artica_caches_mirror` ADD `ToDelete` SMALLINT(1) NOT NULL DEFAULT '0',ADD INDEX(`ToDelete`)";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            squid_admin_enforce(1, "Fatal: MySQL error", $q->mysql_error, __FILE__, __LINE__);
            return;
        }
    }
    if (!$q->FIELD_EXISTS("artica_caches_mirror", "RunEvents")) {
        $sql = "ALTER TABLE `artica_caches_mirror` ADD `RunEvents` TEXT";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            squid_admin_enforce(1, "Fatal: MySQL error", $q->mysql_error, __FILE__, __LINE__);
            return;
        }
    }
    $nice = EXEC_NICE();
    $sql = "SELECT * FROM artica_caches_mirror WHERE enabled=1 AND `ToDelete`=0";
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        squid_admin_enforce(1, "Fatal: MySQL error", $q->mysql_error, __FILE__, __LINE__);
        return;
    }
    if (!isset($GLOBALS["HyperCacheStoragePath"])) {
        $sock = new sockets();
        $GLOBALS["HyperCacheStoragePath"] = $sock->GET_INFO("HyperCacheStoragePath");
        if ($GLOBALS["HyperCacheStoragePath"] == null) {
            $GLOBALS["HyperCacheStoragePath"] = "/home/artica/proxy-cache";
        }
    }
    $t1 = time();
    $count = 0;
    if (mysql_num_rows($results) == 0) {
        return;
    }
    $proxyport = $unix->squid_internal_port();
    $HyperCache = new HyperCache();
    while ($ligne = mysql_fetch_assoc($results)) {
        if ($JustID > 0) {
            if ($ligne["ID"] != $JustID) {
                events("Scrapping rule ID {$ligne["ID"]} !skipped", 0, 2, __LINE__);
                continue;
            }
        }
        $t = time();
        $count++;
        $sitename = $ligne["sitename"];
        $sitename_path = $HyperCache->HyperCacheUriToHostname($sitename);
        $workingdir = $GLOBALS["HyperCacheStoragePath"] . "/mirror/{$sitename_path}";
        $TimeExec = $ligne["TimeExec"];
        $TimeExecLast = $unix->file_time_min("{$workingdir}/TimeExec");
        if (!$GLOBALS["FORCE"]) {
            events("Scrapping {$sitename} require {$TimeExec}mn, current {$TimeExecLast}Mn", 0, 2, __LINE__);
            if ($TimeExecLast < $TimeExec) {
                continue;
            }
        }
        events("Scrapping rule ID {$ligne["ID"]} for {$sitename}", 0, 2, __LINE__);
        $minrate = $ligne["minrate"];
        $maxfilesize = $ligne["maxfilesize"];
        $maxsitesize = $ligne["maxsitesize"];
        $maxfilesize = $maxfilesize * 1000;
        $maxsitesize = $maxsitesize * 1000;
        $minrate = $minrate * 1000;
        $update = null;
        $resultsCMD = array();
        $pidpath = "{$GLOBALS["HyperCacheStoragePath"]}/mirror/{$sitename_path}/hts-in_progress.lock";
        if (!is_dir($workingdir)) {
            @mkdir($workingdir, 0755, true);
        }
        @chown("{$GLOBALS["HyperCacheStoragePath"]}/mirror", "squid");
        @chgrp("{$GLOBALS["HyperCacheStoragePath"]}/mirror", "squid");
        @chown("{$GLOBALS["HyperCacheStoragePath"]}/mirror/{$sitename_path}", "squid");
        @chgrp("{$GLOBALS["HyperCacheStoragePath"]}/mirror/{$sitename_path}", "squid");
        if (is_file($pidpath)) {
            $PID = HyperCacheMirror_pid($pidpath);
            if ($unix->process_exists($PID)) {
                events("Scrapping rule ID {$ligne["ID"]} for {$sitename} Process {$PID} already running since " . $unix->PROCESS_TIME_INT($PID), 0, 2, __LINE__);
                continue;
            }
        }
        @file_put_contents("{$workingdir}/TimeExec", time());
        if (is_file("{$workingdir}/hts-cache")) {
            $update = " --update";
        }
        $cmdline = array();
        $cmdline[] = "{$httrack} \"{$sitename}\" --quiet{$update} -%U squid --proxy 127.0.0.1:{$proxyport}";
        $cmdline[] = "--stay-on-same-domain -u2 -C1 -I0 -N100 --robots=0 --max-files={$maxfilesize}";
        $cmdline[] = "--max-size={$maxsitesize}";
        $cmdline[] = "-O \"{$workingdir}\" 2>&1";
        squid_admin_enforce(2, "Scrapping {$sitename} using proxy 127.0.0.1:{$proxyport}...", null, __FILE__, __LINE__);
        $cmd = @implode(" ", $cmdline);
        if ($GLOBALS["VERBOSE"]) {
            echo "{$cmd}\n";
        }
        exec($cmd, $resultsCMD);
        if ($GLOBALS["VERBOSE"]) {
            echo @implode("\n", $resultsCMD);
        }
        $dirsize = $unix->DIRSIZE_BYTES($workingdir);
        $took = $unix->distanceOfTimeInWords($t, time(), true);
        $dirsizeText = round($dirsize / 1024 / 1000, 2);
        squid_admin_enforce(2, "Mirror on {$sitename} done took {$took} size={$dirsizeText} MB", null, __FILE__, __LINE__);
        $logs = mysql_escape_string2(@file_get_contents("{$workingdir}/hts-log.txt"));
        $q->QUERY_SQL("UPDATE artica_caches_mirror SET \n\t\t\t\tsize='{$dirsize}',`RunEvents`='{$logs}' WHERE ID={$ligne["ID"]}", "artica_backup");
        if (!$q->ok) {
            squid_admin_enforce(1, "MySQL error", $q->mysql_error, __FILE__, __LINE__);
        }
    }
    $took = $unix->distanceOfTimeInWords($t1, time(), true);
    squid_admin_enforce(2, "{$count} web site(s) scrapped took {$took}", null, __FILE__, __LINE__);
}
function perform($table_source, $zDate)
{
    $f = array();
    $q = new mysql_squid_builder();
    $sql = "SELECT SUM( hits ) AS hits, SUM( size ) AS size, category FROM {$table_source} GROUP BY category";
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        ufdbguard_admin_events("Fatal {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "stats");
        die;
    }
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $category = mysql_escape_string2($ligne["category"]);
        $f[] = "('{$zDate}','{$category}','{$ligne["size"]}','{$ligne["hits"]}')";
    }
    if (count($f) > 0) {
        $sql = "INSERT INTO generic_categories (`zDate`,`category`,`size`,`hits`) VALUES " . @implode(",", $f);
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            ufdbguard_admin_events("Fatal {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "stats");
            die;
        }
    }
}
        echo "Uid {$re[1]}\n";
        $MAIN[$IPADDR]["uid"] = trim($re[1]);
        continue;
    }
}
if (count($MAIN) == 0) {
    return;
}
$q = new mysql_squid_builder();
$sql = "CREATE TABLE IF NOT EXISTS `mgr_client_list` (\n\t\t`zmd5` VARCHAR(90) NOT NULL PRIMARY KEY,\n\t\t`ipaddr` VARCHAR(90),\n\t\t`uid` VARCHAR(90),\n\t\t`CUR_CNX` BIGINT UNSIGNED,\n\t\t`RQS` BIGINT UNSIGNED,\n\t\t`TAG_NONE` BIGINT UNSIGNED,\n\t\t`TCP_HIT` BIGINT UNSIGNED,\n\t\t`TCP_MISS` BIGINT UNSIGNED,\n\t\t`TCP_REDIRECT`BIGINT UNSIGNED,\n\t\t`TCP_TUNNEL` BIGINT UNSIGNED,\n\t\tKEY `ipaddr` (`ipaddr`),\n\t\tKEY `uid` (`uid`),\n\t\tKEY `RQS` (`RQS`),\n\t\tKEY `TAG_NONE` (`TAG_NONE`),\n\t\tKEY `TCP_HIT` (`TCP_HIT`),\n\t\tKEY `TCP_REDIRECT` (`TCP_REDIRECT`),\n\t\tKEY `TCP_MISS` (`TCP_MISS`),\n\t\tKEY `CUR_CNX` (`CUR_CNX`)\n\t\t) ENGINE=MYISAM;";
$q->QUERY_SQL($sql);
$q->QUERY_SQL("TRUNCATE TABLE `mgr_client_list`");
$prefix = "INSERT IGNORE INTO `mgr_client_list` (`zmd5`,`ipaddr`,CUR_CNX,RQS,TAG_NONE,TCP_HIT,TCP_MISS,TCP_REDIRECT,TCP_TUNNEL,uid) VALUES ";
while (list($ipaddr, $array) = each($MAIN)) {
    $uid = $array["uid"];
    $md5 = md5($ipaddr . $array["uid"]);
    $CUR_CNX = intval($array["CUR_CNX"]);
    $RQS = intval($array["RQS"]);
    $TAG_NONE = intval($array["TAG_NONE"]);
    $TCP_HIT = intval($array["TCP_HIT"]);
    $TCP_MISS = intval($array["TCP_MISS"]);
    $TCP_REDIRECT = intval($array["TCP_REDIRECT"]);
    $TCP_TUNNEL = intval($array["TCP_TUNNEL"]);
    $uid = mysql_escape_string2($uid);
    $line = "('{$md5}','{$ipaddr}','{$CUR_CNX}','{$RQS}','{$TAG_NONE}','{$TCP_HIT}','{$TCP_MISS}','{$TCP_REDIRECT}','{$TCP_TUNNEL}','{$uid}')";
    echo $line . "\n";
    $T[] = $line;
}
$q->QUERY_SQL($prefix . @implode(",", $T));
?>
	
function graph1_1()
{
    $q = new mysql_squid_builder();
    $page = CurrentPageName();
    $tpl = new templates();
    $t = $_GET["t"];
    $ff = time();
    $tablename = date("Ymd", $_GET["xtime"]) . "_hour";
    $category = mysql_escape_string2($_GET["category"]);
    if ($_GET["category"] == "unknown") {
        $_GET["category"] = null;
    }
    $sql = "SELECT SUM( hits ) AS size,zDate, category FROM generic_categories GROUP BY category,zDate\n\tHAVING category='{$_GET["category"]}' ORDER BY zDate";
    $results = $q->QUERY_SQL($sql);
    $c = 0;
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        senderror("{$q->mysql_error}<br>{$sql}");
    }
    if (mysql_num_rows($results) > 0) {
        $nb_events = mysql_num_rows($results);
        while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
            $xdata[] = $ligne["zDate"];
            $ydata[] = $ligne["size"];
            $c++;
        }
    }
    $highcharts = new highcharts();
    $highcharts->container = $_GET["container"];
    $highcharts->xAxis = $xdata;
    $highcharts->Title = "{$category}: {hits}/{day}";
    $highcharts->yAxisTtitle = "{hits}";
    $highcharts->xAxisTtitle = "{days}";
    $highcharts->datas = array("{hits}" => $ydata);
    echo $highcharts->BuildChart();
}
Example #22
0
function profile_save()
{
    $_POST["rulename"] = mysql_escape_string2(url_decode_special_tool($_POST["rulename"]));
    $ID = $_POST["ID"];
    if ($ID < 0) {
        $sql = "INSERT INTO cicap_profiles (rulename,enabled) VALUES ('{$_POST["rulename"]}','{$_POST["enabled"]}')";
    } else {
        $sql = "UPDATE cicap_profiles SET `rulename`='{$_POST["rulename"]}',`enabled`='{$_POST["enabled"]}'\n\t\tWHERE ID={$ID}";
    }
    $q = new mysql_squid_builder();
    $q->QUERY_SQL($sql);
    if (!$q->ok) {
        echo $q->mysql_error . "\n{$sql}\n";
    }
}
Example #23
0
function proxy_pac()
{
    $SessionCache = 0;
    if (!$GLOBALS["VERBOSE"]) {
        header("content-type: application/x-ns-proxy-autoconfig");
    }
    header("Date: " . gmdate('D, d M Y H:i:s \\G\\M\\T', time()));
    header("Last-Modified: " . gmdate('D, d M Y H:i:s \\G\\M\\T', time()));
    header("Expires: " . gmdate('D, d M Y H:i:s \\G\\M\\T', time() + 60 * 30));
    header('Content-Transfer-Encoding: binary');
    if (!$GLOBALS["VERBOSE"]) {
        header("Content-Disposition: attachment; filename=\"proxy.pac\"");
    }
    if ($GLOBALS["VERBOSE"]) {
        unset($_SESSION["PROXY_PAC_CACHE"]);
    }
    if (!isset($_SESSION["PROXY_PAC_CACHE"])) {
        if (!class_exists("sockets")) {
            LoadIncludes();
        }
        $sock = new sockets();
        $SessionCache = intval($sock->GET_INFO("ProxyPacCacheTime"));
        $ProxyPacLockScript = intval($sock->GET_INFO("ProxyPacLockScript"));
        if ($SessionCache == 0) {
            $SessionCache = 10;
        }
        $_SESSION["PROXY_PAC_CACHE"] = $SessionCache;
        $_SESSION["PROXY_PAC_LOCK"] = $ProxyPacLockScript;
    } else {
        $SessionCache = intval($_SESSION["PROXY_PAC_CACHE"]);
        $ProxyPacLockScript = intval($_SESSION["PROXY_PAC_LOCK"]);
    }
    if ($ProxyPacLockScript == 1) {
        $ProxyPacLockScriptContent = @file_get_contents("/etc/artica-postfix/settings/Daemons/ProxyPacLockScriptContent");
        header("Content-Length: " . filesize($ProxyPacLockScriptContent));
        echo $ProxyPacLockScriptContent . "\n";
        return;
    }
    if (intval($SessionCache == 0)) {
        $SessionCache = 10;
    }
    if (!is_numeric($GLOBALS["PROXY_PAC_DEBUG"])) {
        $GLOBALS["PROXY_PAC_DEBUG"] = 0;
    }
    $IPADDR = GET_REMOTE_ADDR();
    $HTTP_USER_AGENT = trim($GLOBALS["HTTP_USER_AGENT"]);
    if (strpos($IPADDR, ",") > 0) {
        $FR = explode(",", $IPADDR);
        $IPADDR = trim($FR[0]);
    }
    $KEYMd5 = md5($HTTP_USER_AGENT . $IPADDR);
    $CACHE_FILE = dirname(__FILE__) . "/ressources/logs/proxy.pacs/{$KEYMd5}";
    if (!$GLOBALS["VERBOSE"]) {
        if (is_file($CACHE_FILE)) {
            packsyslog("connection FROM {$IPADDR} [{$HTTP_USER_AGENT}] (cached)");
            $time = pac_file_time_min($CACHE_FILE);
            if ($time < $SessionCache) {
                header("Content-Length: " . filesize($CACHE_FILE));
                @readfile($CACHE_FILE);
                return;
            }
            @unlink($CACHE_FILE);
        }
    }
    if (!class_exists("sockets")) {
        LoadIncludes();
    }
    $sock = new sockets();
    $ClassiP = new IP();
    if (!$GLOBALS["VERBOSE"]) {
        $GLOBALS["PROXY_PAC_DEBUG"] = $sock->GET_INFO("ProxyPacDynamicDebug");
    }
    $q = new mysql_squid_builder();
    if (!$ClassiP->isIPAddress($IPADDR)) {
        $GLOBALS["HOSTNAME"] = $IPADDR;
        $IPADDR = gethostbyname($IPADDR);
    } else {
        $GLOBALS["HOSTNAME"] = gethostbyaddr($IPADDR);
    }
    $GLOBALS["IPADDR"] = $IPADDR;
    //srcdomain
    pack_debug("Connection FROM: {$IPADDR} [ {$HTTP_USER_AGENT} ] ", __FUNCTION__, __LINE__);
    $sql = "SELECT * FROM wpad_rules ORDER BY zorder";
    $results = $q->QUERY_SQL($sql);
    if (mysql_num_rows($results) == 0) {
        die;
    }
    $date = date("Y-m-d H:i:s");
    $md5 = md5("{$date}{$IPADDR}{$HTTP_USER_AGENT}");
    $HTTP_USER_AGENT = mysql_escape_string2($HTTP_USER_AGENT);
    $DenyDnsResolve = intval($sock->GET_INFO("DenyDnsResolve"));
    while ($ligne = mysql_fetch_assoc($results)) {
        $rulename = $ligne["rulename"];
        $ID = $ligne["ID"];
        pack_debug("Parsing rule: \"{$rulename}\" ID:{$ID}", __FUNCTION__, __LINE__);
        if (!client_matches($ID)) {
            pack_debug("client_matches() resturn false,No source match rule {$rulename} ID {$ID}, check other rule", __FUNCTION__, __LINE__);
            continue;
        }
        pack_debug("{$rulename} matches source {$GLOBALS["IPADDR"]} building script..", __FUNCTION__, __LINE__);
        $f = array();
        $f[] = "function FindProxyForURL(url, host) {";
        $f[] = "\turl = url.toLowerCase();";
        $f[] = "\thost = host.toLowerCase();";
        if ($DenyDnsResolve == 0) {
            $f[] = "\tvar hostIP = dnsResolve(host);";
        } else {
            $f[] = "\tvar hostIP = host;";
        }
        $f[] = "\tvar myip=myIpAddress();";
        $f[] = "\tvar DestPort=GetPort(url);";
        $f[] = "\tvar PROTO='';";
        $f[] = "\tif (url.substring(0, 5) == 'http:' ){ PROTO='HTTP'; }";
        $f[] = "\tif (url.substring(0, 6) == 'https:' ){ PROTO='HTTPS'; }";
        $f[] = "\tif (url.substring(0, 4) == 'ftp:' ){ PROTO='FTP'; }";
        pack_debug("{$rulename}/{$ID} building build_whitelist({$ID})", __FUNCTION__, __LINE__);
        $f[] = build_whitelist($ID);
        pack_debug("{$rulename}/{$ID} building build_subrules({$ID})", __FUNCTION__, __LINE__);
        $f[] = build_subrules($ID);
        pack_debug("{$rulename}/{$ID} building build_proxies({$ID})", __FUNCTION__, __LINE__);
        $f[] = build_proxies($ID);
        $f[] = "}\r\n";
        $f[] = "function GetPort(TestURL){";
        $f[] = "\tTestURLRegex = /^[^:]*\\:\\/\\/([^\\/]*).*/;";
        $f[] = "\tTestURLMatch = TestURL.replace(TestURLRegex, \"\$1\");";
        $f[] = "\tTestURLLower = TestURLMatch.toLowerCase();";
        $f[] = "\tTestURLLowerRegex = /^([^\\.]*)[^\\:]*(.*)/;";
        $f[] = "\tNewPort=TestURLLower.replace(TestURLLowerRegex, \"\$2\");";
        $f[] = "\tif (NewPort == \"\"){";
        $f[] = "\t\tNewPort=\":80\";";
        $f[] = "\t}";
        $f[] = "\treturn NewPort;";
        $f[] = "}";
        $f[] = "\r\n\r\n";
        $script = @implode("\r\n", $f);
        pack_debug("SUCCESS {$rulename} sends script " . strlen($script) . " bytes to client", __FUNCTION__, __LINE__);
        if ($GLOBALS["VERBOSE"]) {
            echo "<textarea style='width:100%;height:450px'>{$script}</textarea>";
            return;
        }
        header("Content-Length: " . strlen($script));
        echo $script;
        packsyslog("Connection FROM: {$IPADDR} [ {$HTTP_USER_AGENT} ] sends script " . strlen($script), __FUNCTION__, __LINE__);
        @mkdir(dirname($CACHE_FILE), 0755, true);
        file_put_contents($CACHE_FILE, $script);
        if (!is_file($CACHE_FILE)) {
            packsyslog("FAILED {$CACHE_FILE}, permission denied");
            pack_error("FAILED {$CACHE_FILE}, permission denied", __FUNCTION__, __LINE__);
        }
        $script = mysql_escape_string2(base64_encode($script));
        $q->QUERY_SQL("INSERT IGNORE INTO `wpad_events` (`zmd5`,`zDate`,`ruleid`,`ipaddr`,`browser`,`script`,`hostname`) VALUES('{$md5}','{$date}','{$ID}','{$IPADDR}','{$HTTP_USER_AGENT}','{$script}','{$GLOBALS["HOSTNAME"]}')");
        if (!$q->ok) {
            writelogs("{$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__);
        }
        $q->QUERY_SQL("DELETE FROM `wpad_events` WHERE zDate<DATE_SUB(NOW(),INTERVAL 7 DAY)");
        if (!$q->ok) {
            writelogs("{$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__);
        }
        return;
    }
    $q->QUERY_SQL("INSERT IGNORE INTO `wpad_events` (`zmd5`,`zDate`,`ruleid`,`ipaddr`,`browser`,`hostname`) VALUES('{$md5}','{$date}','0','{$IPADDR}','{$HTTP_USER_AGENT}','{$GLOBALS["HOSTNAME"]}')");
    if (!$q->ok) {
        writelogs("{$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__);
    }
}
function group_defaults($ID)
{
    $f[] = "union.*select.*\\(";
    $f[] = "union.*all.*select.*";
    $f[] = "concat.*\\(";
    $f[] = "[a-zA-Z0-9_]=http://";
    $f[] = "[a-zA-Z0-9_]=(\\.\\.//?)+";
    $f[] = "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+";
    $f[] = "(<|%3C).*script.*(>|%3E)";
    $f[] = "GLOBALS(=|\\[|\\%[0-9A-Z]{0,2)";
    $f[] = "_REQUEST(=|\\[|\\%[0-9A-Z]{0,2)";
    $f[] = "proc/self/environ";
    $f[] = "mosConfig_[a-zA-Z_]{1,21(=|\\%3D)";
    $f[] = "base64_(en|de)code\\(.*\\)";
    $f[] = "\\b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\\b";
    $f[] = "\\b(erections|hoodia|huronriveracres|impotence|levitra|libido)\\b";
    $f[] = "\\b(ambien|blue\\spill|cialis|cocaine|e*********n|erectile)\\b";
    $f[] = "\\b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\\b";
    $prefix = "INSERT IGNORE INTO nginx_exploits_items (`groupid`,`enabled`,`pattern`,`token`) VALUES";
    while (list($head, $pattern) = each($f)) {
        $n[] = "({$ID},1,'" . mysql_escape_string2($pattern) . "','query_string')";
    }
    $f = array();
    $f[] = "Wget";
    $f[] = "Indy Library";
    $f[] = "libwww-perl";
    $f[] = "GetRight";
    $f[] = "GetWeb!";
    $f[] = "Go!Zilla";
    $f[] = "Download Demon";
    $f[] = "Go-Ahead-Got-It";
    $f[] = "TurnitinBot";
    $f[] = "GrabNet";
    $f[] = "Nmap";
    $f[] = "(SBIder/Nutch-1.0-dev|Purebot/1.1|spbot/2.0.2|Toata|Python-urllib)";
    $q = new mysql_squid_builder();
    if (!$q->TABLE_EXISTS("nginx_exploits_items")) {
        $sql = "CREATE TABLE IF NOT EXISTS `nginx_exploits_items` (\n\t\t\t  `ID` INT NOT NULL AUTO_INCREMENT,\n\t\t\t  `groupid` INT NOT NULL DEFAULT '0',\n\t\t\t  `enabled` smallint(1)  NOT NULL,\n\t\t\t  `pattern` TEXT,\n\t\t\t  `token` CHAR(20)  NOT NULL,\n\t\t\t  PRIMARY KEY (`ID`),\n\t\t\t  KEY `groupid` (`groupid`),\n\t\t\t  KEY `enabled` (`enabled`),\n\t\t\t  KEY `token` (`token`)\n\t\t\t)  ENGINE = MYISAM;";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            echo $q->mysql_error;
        }
    }
    while (list($head, $pattern) = each($f)) {
        $n[] = "({$ID},1,'" . mysql_escape_string2($pattern) . "','http_user_agent')";
    }
    $q->QUERY_SQL($prefix . @implode(",", $n));
    if (!$q->ok) {
        echo $q->mysql_error;
    }
}
function network_bridge_save(){
	$ID=$_POST["ID"];
	unset($_POST["ID"]);
	unset($_POST["Create"]);
	$q=new mysql();
	if(!isset($_POST["STP"])){$_POST["STP"]=1;}
	if(!$q->FIELD_EXISTS("nics_bridge", "STP", "artica_backup")){
		$q->QUERY_SQL("ALTER TABLE nics_bridge ADD STP smallint(1) DEFAULT 1","artica_backup");
		if(!$q->ok){echo "ALTER TABLE STP failed\n$q->mysql_error\n";return;}
	}

	if($_POST["netmask"]=='___.___.___.___'){$_POST["netmask"]="0.0.0.0";}
	if($_POST["gateway"]=='___.___.___.___'){$_POST["gateway"]="0.0.0.0";}
	if($_POST["ipaddr"]=='___.___.___.___'){$_POST["ipaddr"]="0.0.0.0";}


	while (list ($key, $value) = each ($_POST) ){
		$fields[]="`$key`";
		$values[]="'".mysql_escape_string2($value)."'";
		$edit[]="`$key`='".mysql_escape_string2($value)."'";

	}

	if($ID>0){
		$sql="UPDATE nics_bridge SET ".@implode(",", $edit)." WHERE ID=$ID";
	}else{
		$sql="INSERT IGNORE INTO nics_bridge (".@implode(",", $fields).") VALUES (".@implode(",", $values).")";

	}

	$q=new mysql();
	$q->QUERY_SQL($sql,"artica_backup");
	if(!$q->ok){echo $q->mysql_error;return;}
	
}
function Replicate_policy_to_group($gpid, $content)
{
    $q = new mysql_meta();
    $sql = "SELECT uuid FROM metagroups_link WHERE gpid='{$gpid}'";
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        meta_admin_mysql(0, "Fatal error: Mysql Error", $q->mysql_error . "\n{$sql}", __FILE__, __LINE__);
        return;
    }
    $md5Content = md5($content);
    $content = mysql_escape_string2($content);
    if (mysql_num_rows($results) == 0) {
        return;
    }
    while ($ligne = mysql_fetch_assoc($results)) {
        $uuid = $ligne["uuid"];
        $md5 = md5("{$md5Content}{$uuid}");
        $q->QUERY_SQL("DELETE FROM `policies_storage` WHERE `zmd5`='{$md5}'");
        $sql = "INSERT IGNORE INTO `policies_storage` (zmd5,uuid,policy_content) VALUES ('{$md5}','{$uuid}','{$content}')";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            meta_admin_mysql(0, "Fatal error: Mysql Error", $q->mysql_error . "\n{$sql}", __FILE__, __LINE__);
            continue;
        }
        $q->CreateOrder($uuid, "POLICY", array("VALUE" => $md5));
    }
}
Example #27
0
function import_bulk()
{
    $q = new mysql_squid_builder();
    $nginxSources = new nginx_sources();
    $nginx = new nginx();
    $filename = "/usr/share/artica-postfix/ressources/logs/web/nginx.importbulk";
    if (!is_file($filename)) {
        echo "{$filename} no such file\n";
        return;
    }
    $CONF = unserialize(@file_get_contents($filename));
    if ($CONF["RemoveOldImports"] == 1) {
        // on supprime les anciennes entrées:
        $results = $q->QUERY_SQL("SELECT ID FROM reverse_sources WHERE `Imported`=1");
        while ($ligne = mysql_fetch_assoc($results)) {
            $nginxSources->DeleteSource($ligne["ID"]);
        }
        $results = $q->QUERY_SQL("SELECT servername FROM reverse_www WHERE `Imported`=1");
        while ($ligne = mysql_fetch_assoc($results)) {
            $nginx->Delete_website($ligne["servername"], true);
        }
    }
    $randomArray[1] = "a";
    $randomArray[2] = "b";
    $randomArray[3] = "c";
    $randomArray[4] = "d";
    $randomArray[5] = "e";
    $randomArray[6] = "f";
    $randomArray[7] = "g";
    $randomArray[8] = "h";
    $randomArray[9] = "i";
    $randomArray[10] = "j";
    $randomArray[11] = "k";
    $randomArray[12] = "l";
    $randomArray[13] = "m";
    $randomArray[14] = "n";
    $randomArray[15] = "o";
    $randomArray[16] = "p";
    $randomArray[17] = "q";
    $randomArray[18] = "r";
    $randomArray[19] = "s";
    $randomArray[20] = "t";
    $randomArray[21] = "u";
    $randomArray[22] = "v";
    $randomArray[23] = "x";
    $randomArray[24] = "y";
    $randomArray[25] = "z";
    $RandomText = $CONF["RandomText"];
    $digitAdd = 0;
    $webauth = null;
    $authentication_id = $CONF["authentication"];
    if (!is_numeric($authentication_id)) {
        $authentication_id = 0;
    }
    if ($authentication_id > 0) {
        $AUTHENTICATOR["USE_AUTHENTICATOR"] = 1;
        $AUTHENTICATOR["AUTHENTICATOR_RULEID"] = $authentication_id;
        $webauth = mysql_escape_string2(base64_encode(serialize($AUTHENTICATOR)));
    }
    if (preg_match("#\\%sx([0-9]+)#", $RandomText, $re)) {
        $digitAdd = intval($re[1]);
        $RandomText = str_replace("%sx{$re[1]}", "%s", $RandomText);
    }
    echo "Random: {$RandomText}\n";
    // on parse le fichier en première passe pour le cleaner
    $f = explode("\n", $CONF["import"]);
    while (list($index, $line) = each($f)) {
        $line = trim(strtolower($line));
        if ($line == null) {
            continue;
        }
        if (preg_match("#^http.*?:\\/#", $line)) {
            // c'est une URI, on la décompose
            $URZ = parse_url($line);
            if (!isset($URZ["host"])) {
                echo "{$line} -> Unable to determine HOST, skipping\n";
            }
            $MAIN[$URZ["host"]] = $URZ["scheme"];
            continue;
        }
        $MAIN[$line] = "http";
    }
    ksort($MAIN);
    $i = 1;
    $Letter = 1;
    $IpClass = new IP();
    $SUCCESS = 0;
    $FAILED = 0;
    while (list($servername, $proto) = each($MAIN)) {
        $LetterText = $randomArray[$Letter];
        $iText = $i;
        $ssl = 0;
        if ($digitAdd > 0) {
            $iText = sprintf("%1\$0{$digitAdd}d", $i);
        }
        $SourceWeb = $RandomText;
        if ($SourceWeb != null) {
            $SourceWeb = str_replace("%a", $LetterText, $SourceWeb);
            $SourceWeb = str_replace("%s", $iText, $SourceWeb);
        } else {
            $SourceWeb = $servername;
        }
        $sourceserver = "{$proto}://{$servername}";
        echo "{$proto}://{$servername}\n";
        if ($proto == "http") {
            $sourceserver_port = 80;
        }
        if ($proto == "https") {
            $sourceserver_port = 443;
            $ssl = 1;
        }
        if (preg_match("#(.+?):([0-9]+)#", $servername, $re)) {
            $sourceserver_port = $re[1];
        }
        //existe-t-il ?
        $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT ID FROM reverse_sources WHERE ipaddr='{$sourceserver}' AND `port`='{$sourceserver_port}'"));
        $IDS = intval($ligne["ID"]);
        if ($IDS == 0) {
            //non -> Ajout de l'entrée...
            $sql = "INSERT IGNORE INTO `reverse_sources` \n\t\t\t(`servername`,`ipaddr`,`port`,`ssl`,`enabled`,`forceddomain`,`Imported`)\n\t\t\tVALUES ('{$servername}','{$sourceserver}','{$sourceserver_port}','{$ssl}',1,'{$servername}',1)";
            $q->QUERY_SQL($sql);
            $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT ID FROM reverse_sources WHERE ipaddr='{$sourceserver}' AND `port`='{$sourceserver_port}'"));
            $IDS = intval($ligne["ID"]);
        }
        if ($IDS == 0) {
            echo "Failed to add {$sourceserver}/{$sourceserver_port}/{$servername}\n";
            $FAILED++;
            continue;
        }
        // On attaque  le site web:
        $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT servername,cache_peer_id FROM reverse_www WHERE servername='{$SourceWeb}'"));
        if (trim($ligne["servername"] != null)) {
            echo "{$SourceWeb} already exists on cache ID : {$ligne["cache_peer_id"]}/{$IDS}\n";
            if ($ligne["cache_peer_id"] != $IDS) {
                $q->QUERY_SQL("UPDATE reverse_www SET `cache_peer_id`={$IDS} WHERE  servername='{$SourceWeb}'");
            }
            $SUCCESS++;
            continue;
        }
        $sql = "INSERT IGNORE INTO `reverse_www` (`servername`,`cache_peer_id`,`port`,`ssl`,`Imported`,`webauth`) VALUES\n\t\t('{$SourceWeb}','{$IDS}','{$sourceserver_port}','{$ssl}',1,'{$webauth}')";
        $q->QUERY_SQL($sql);
        if (!$q->ok) {
            echo $q->mysql_error;
            $FAILED++;
            continue;
        }
        $SUCCESS++;
        $i++;
        $Letter++;
        if ($Letter > 25) {
            $Letter = 1;
        }
    }
    echo "{$SUCCESS} Imported sites, {$FAILED} failed\n";
}
Example #28
0
function report_new_save()
{
    $q = new mysql_squid_builder();
    $q->CheckTables(null, true);
    $zmd5 = md5(time());
    $_POST["report_new"] = mysql_escape_string2($_POST["report_new"]);
    $q->QUERY_SQL("INSERT IGNORE INTO squid_reports (report_name,zmd5) VALUES ('{$_POST["report_new"]}','{$zmd5}')");
    if (!$q->ok) {
        echo $q->mysql_error;
    }
}
function _xprocess_table($tablename, $nopid = false)
{
    if ($GLOBALS["VERBOSE"]) {
        echo "Loading...\n";
    }
    $unix = new unix();
    if ($GLOBALS["VERBOSE"]) {
        echo "Loading done...\n";
    }
    if (!$nopid) {
        $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
        $timefile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
        $pid = @file_get_contents($pidfile);
        if (!$GLOBALS["FORCE"]) {
            if ($pid < 100) {
                $pid = null;
            }
            $unix = new unix();
            if ($unix->process_exists($pid, basename(__FILE__))) {
                events_tail("{$tablename}:: Already executed pid {$pid}");
                if ($GLOBALS["VERBOSE"]) {
                    echo "Already executed pid {$pid}\n";
                }
                return;
            }
            $timeexec = $unix->file_time_min($timefile);
            if ($timeexec < 120) {
                categorize_tables_events("{$tablename}:: {$timeexec}mn, need 120mn...", "pid: " . getmypid(), $tablename);
                events_tail("{$tablename}:: {$timeexec}mn, need 120mn...");
                return;
            }
            $mypid = getmypid();
            @file_put_contents($pidfile, $mypid);
        }
    }
    $sql = "SELECT COUNT(`sitename`) as tcount FROM {$tablename} WHERE LENGTH(`category`)=0";
    if ($GLOBALS["VERBOSE"]) {
        echo $sql . "\n";
    }
    $ligne = mysql_fetch_array($GLOBALS["Q"]->QUERY_SQL($sql));
    $max = $ligne["tcount"];
    $filePath = "/usr/share/artica-postfix/ressources/logs/categorize-tables/{$tablename}";
    $ARRAY = unserialize(@file_get_contents($filePath));
    if ($max > 10000) {
        $LIMIT_MAX = 3000;
        $LIMIT_MIN = 0;
        if (isset($ARRAY["CURRENT"])) {
            if ($ARRAY["CURRENT"] < $max - 3000) {
                $LIMIT_MIN = $ARRAY["CURRENT"];
            }
        }
        $LIMIT_SQL = " LIMIT {$LIMIT_MIN},{$LIMIT_MAX}";
    }
    $sql = "SELECT `sitename`,`familysite` FROM {$tablename} WHERE LENGTH(`category`)=0 ORDER BY familysite {$LIMIT_SQL}";
    $results = $GLOBALS["Q"]->QUERY_SQL($sql);
    if (!$GLOBALS["Q"]->ok) {
        events_tail("{$tablename}:: MySQL error", "{$GLOBALS["Q"]->mysql_error}");
        categorize_tables_events("MySQL error", "{$GLOBALS["Q"]->mysql_error}<br>{$sql}", $tablename);
        return;
    }
    $catz = 0;
    if (mysql_num_rows($results) > 0) {
        categorize_tables_events("{$tablename}: Processing {$max} ({$LIMIT_SQL}) not categorized websites", "pid: " . getmypid(), $tablename);
    }
    if (mysql_num_rows($results) == 0) {
        if ($GLOBALS["VERBOSE"]) {
            echo "O, nothing, return...\n";
        }
        @unlink($filePath);
        return;
    }
    $c = 0;
    $d = 0;
    $t = time();
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $sitename = $ligne["sitename"];
        $sitenameToScan = $sitename;
        $familysite = $ligne["familysite"];
        if ($sitename == null) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Null value for {$sitename},{$familysite} aborting\n";
            }
            $GLOBALS["Q"]->QUERY_SQL("DELETE FROM {$tablename} WHERE `sitename`='{$ligne["sitename"]}'");
            continue;
        }
        if ($sitename == '.') {
            if ($GLOBALS["VERBOSE"]) {
                echo "'.' value for {$sitename},{$familysite} aborting\n";
            }
            $GLOBALS["Q"]->QUERY_SQL("DELETE FROM {$tablename} WHERE `sitename`='{$ligne["sitename"]}'");
            continue;
        }
        if (strpos($sitename, ',') > 0) {
            $sitename = str_replace(",", "", $sitename);
            $sitenameToScan = $sitename;
            $GLOBALS["Q"]->QUERY_SQL("UPDATE {$tablename} SET `sitename`='{$sitename}' WHERE `sitename`='{$ligne["sitename"]}'");
        }
        if (is_numeric($sitename)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Numeric value for {$sitename},{$familysite} aborting\n";
            }
            $GLOBALS["Q"]->QUERY_SQL("DELETE FROM {$tablename} WHERE `sitename`='{$ligne["sitename"]}'");
            continue;
        }
        if (strpos($sitename, ".") == 0) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Seems to be a local domain for {$sitename},{$familysite} aborting\n";
            }
            $GLOBALS["Q"]->QUERY_SQL("UPDATE {$tablename} SET `category`='internal' WHERE `sitename`='{$ligne["sitename"]}'");
            continue;
        }
        if (!isset($GLOBALS[$tablename][$sitename])) {
            if (preg_match("#^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\$#", $sitenameToScan)) {
                $sitename = gethostbyaddr($sitename);
                if ($GLOBALS["VERBOSE"]) {
                    echo "IP:{$sitenameToScan} -> `{$sitename}`\n";
                }
                if (preg_match("#^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+\$#", $sitename)) {
                    $GLOBALS[$tablename][$sitename] = "ipaddr";
                    $GLOBALS["Q"]->categorize($sitename, "ipaddr");
                    $category = "ipaddr";
                }
            }
        }
        if (!isset($GLOBALS[$tablename][$sitename])) {
            $GLOBALS[$tablename][$sitename] = mysql_escape_string2($GLOBALS["Q"]->GET_CATEGORIES($sitename));
        }
        $c++;
        $category = $GLOBALS[$tablename][$sitename];
        writelogs_squid("{$sitename} -> `{$category}`");
        if (!$GLOBALS["VERBOSE"]) {
            if (SquidStatisticsTasksOverTime()) {
                stats_admin_events(1, "Statistics overtime... Aborting", null, __FILE__, __LINE__);
                return;
            }
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "{$sitename} -> `{$category}`\n";
        }
        $c++;
        $d++;
        if ($category == null) {
            continue;
        }
        if (!isset($UPDATED[$sitenameToScan])) {
            $GLOBALS["Q"]->categorize_temp($sitenameToScan, $category);
            $sqltmp = "UPDATE `{$tablename}` SET `category`='{$category}' WHERE `sitename`='{$sitenameToScan}'";
            $GLOBALS["Q"]->QUERY_SQL($sqltmp);
            if (!$GLOBALS["Q"]->ok) {
                categorize_tables_events("MySQL error (after {$d} rows)", "{$GLOBALS["Q"]->mysql_error}<br>{$sqltmp}", $tablename);
                return;
            }
            $UPDATED[$sitenameToScan] = true;
        }
        if ($c > 500) {
            WriteStatus($d, $max, $tablename);
            if (SquidStatisticsTasksOverTime()) {
                stats_admin_events(1, "Statistics overtime... Aborting", null, __FILE__, __LINE__);
                return;
            }
            $c = 0;
        }
    }
    if ($catz > 0) {
        $took = $unix->distanceOfTimeInWords($t, time());
        events_tail("{$catz}/{$d}/{$max} websites categorized for {$tablename}, took: {$took}");
        stats_admin_events(2, "{$catz}/{$d} websites categorized took: {$took}", $tablename, null, __FILE__, __LINE__);
    }
}
Example #30
0
function SaveItemID()
{
    $items = url_decode_special_tool($_POST["item"]);
    $items = mysql_escape_string2($items);
    $q = new mysql();
    $q->QUERY_SQL("UPDATE spamasssin_escrap SET pattern='{$items}' WHERE ID='{$_POST["ID"]}'", "artica_backup");
    if (!$q->ok) {
        echo $q->mysql_error;
        return;
    }
}