function restore($filename)
{
    $unix = new unix();
    $sock = new sockets();
    $TMP = $unix->FILE_TEMP();
    $filenameBase = basename($filename);
    if (!is_file($filename)) {
        echo "{$filename} no such file\n";
        build_progress("{failed}", 110);
    }
    $tmpf = $unix->FILE_TEMP();
    build_progress("{uncompress} {$filenameBase}", 10);
    if (!$unix->uncompress($filename, $tmpf)) {
        @unlink($filename);
        build_progress("{uncompress} {$filenameBase} {failed}", 110);
        return;
    }
    @unlink($filename);
    build_progress("{importing} {$tmpf}", 50);
    $q = new mysql_squid_builder();
    $nice = $unix->EXEC_NICE();
    $mysql = $unix->find_program("mysql");
    $gzip = $unix->find_program("gzip");
    $nohup = $unix->find_program("nohup");
    $echo = $unix->find_program("echo");
    $rm = $unix->find_program("rm");
    $php = $unix->LOCATE_PHP5_BIN();
    $sh[] = "#!/bin/sh";
    $sh[] = "{$echo} \"{$mysql} -> {$filenameBase}\"";
    $sh[] = "{$nice} {$mysql} {$q->MYSQL_CMDLINES} -f squidlogs < {$tmpf}";
    $sh[] = "{$rm} {$TMP}.sh";
    $sh[] = "\n";
    @file_put_contents("{$TMP}.sh", @implode("\n", $sh));
    @chmod("{$TMP}.sh", 0755);
    build_progress(10, "Starting restore {$filenameBase} - " . basename("{$TMP}.sh") . " ");
    system("{$nohup} {$TMP}.sh >{$TMP}.txt 2>&1 &");
    sleep(1);
    $PID = $unix->PIDOF_PATTERN("{$TMP}.sh");
    echo "Running PID {$PID}\n";
    while ($unix->process_exists($PID)) {
        build_progress(50, "Starting restoring {$filenameBase}");
        sleep(3);
        $PID = $unix->PIDOF_PATTERN("{$TMP}.sh");
        echo "Running PID {$PID}\n";
    }
    echo @file_get_contents("{$TMP}.txt") . "\n";
    @unlink("{$TMP}.sh");
    @unlink("{$TMP}.txt");
    build_progress(50, "{restore} {done} {$filenameBase}");
    build_progress(50, "{restore} Analyze Hourly tables");
    system("{$php} /usr/share/artica-postfix/exec.squid.stats.hours.php --force --verbose");
    build_progress(60, "{restore} Repair Hourly tables");
    system("{$php} /usr/share/artica-postfix/exec.squid.stats.hours.php --repair --force --verbose");
    build_progress(70, "{restore} Repair Table days");
    system("{$php} /usr/share/artica-postfix/exec.squid.stats.repair.php --tables-day --repair --force --verbose");
    build_progress(80, "{restore} Repair sums");
    system("{$php} /usr/share/artica-postfix/exec.squid.stats.totals.php --repair --force --verbose");
    build_progress(100, "{restore} Done");
}
Example #2
0
function import_acls($filename)
{
    if (!is_file($filename)) {
        echo "{$filename} no such file\n";
        return;
    }
    $unix = new unix();
    $ext = Get_extension($filename);
    if ($ext == "acl") {
        import_acls_extacl($filename, null, 0);
        return;
    }
    $destinationfile = $unix->FILE_TEMP();
    if (!$unix->uncompress($filename, $destinationfile)) {
        echo "{$filename} corrupted GZ file...\n";
        return;
    }
    $mysqlbin = $unix->find_program("mysql");
    $q = new mysql_squid_builder();
    $password = null;
    $localdatabase = "squidlogs";
    $q = new mysql_squid_builder();
    $cmdline = "{$mysqlbin} --batch --force {$q->MYSQL_CMDLINES}";
    $cmd = "{$cmdline} --database={$localdatabase} <{$destinationfile} 2>&1";
    if ($GLOBALS["VERBOSE"]) {
        echo $cmd . "\n";
    }
    shell_exec($cmd);
}
Example #3
0
function UpdateDB($uri, $filenameExtracted, $rootpath)
{
    if ($GLOBALS["VERBOSE"]) {
        echo "***** \n\n {$uri} \n*****\n\n";
    }
    $curl = new ccurl($uri);
    $unix = new unix();
    $curl->NoHTTP_POST = true;
    $h = parse_url($uri);
    $targetFileName = basename($h["path"]);
    @unlink("/tmp/{$targetFileName}");
    if (!$curl->GetFile("/tmp/{$targetFileName}")) {
        system_admin_events("Geoip Failed to retreive {$targetFileName} with error {$curl->error}", __FUNCTION__, __FILE__, __LINE__, "geoip");
        @unlink("/tmp/{$targetFileName}");
        return false;
    }
    if (!$unix->uncompress("/tmp/{$targetFileName}", "{$rootpath}/{$filenameExtracted}")) {
        system_admin_events("Geoip Failed to extract /tmp/{$targetFileName} to {$rootpath}/{$filenameExtracted}", __FUNCTION__, __FILE__, __LINE__, "geoip");
        @unlink("/tmp/{$targetFileName}");
        return false;
    }
    return true;
}
function analyze_single_file($filename)
{
    $sock = new sockets();
    $unix = new unix();
    if (!isset($GLOBALS["squidtail"])) {
        $GLOBALS["squidtail"] = new squid_tail();
    }
    if ($GLOBALS["VERBOSE"]) {
        echo $filename . " -> '/' = " . strpos($filename, '/') . " pos\n";
    }
    if (!is_file($filename)) {
        if ($GLOBALS["VERBOSE"]) {
            echo $filename . " no such file\n";
        }
        if (!tests_nas()) {
            return;
        }
        $SquidOldLogsNAS = unserialize(base64_decode($sock->GET_INFO("SquidOldLogsNAS")));
        $mountPoint = "/mnt/SquidImportLogs";
        $NasFolder = $SquidOldLogsNAS["folder"];
        $NasFolder = str_replace('\\', '/', $NasFolder);
        $NasFolder = str_replace('//', '/', $NasFolder);
        if (strpos($NasFolder, "/") > 0) {
            $f = explode("/", $NasFolder);
            unset($f[0]);
            $NasFolder = @implode("/", $f);
        }
        $targetFile = "{$mountPoint}/{$NasFolder}/{$filename}";
        $targetFile = str_replace("//", "/", $targetFile);
    } else {
        $targetFile = $filename;
    }
    $REMOVE = false;
    $ext = $unix->file_ext($targetFile);
    if ($GLOBALS["SIMULATE"]) {
        echo "Simulate enabled, no MySQL events will be injected\n";
    }
    if (!$GLOBALS["SIMULATE"]) {
        $zmd5 = md5_file($targetFile);
    }
    @mkdir("/home/squid/wkdir", 0755, true);
    if ($ext == "gz") {
        $basename = $filename;
        if (count(explode('/', $basename)) > 0) {
            $basename = basename($basename);
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "Uncompress {$targetFile}\n";
        }
        $unix->uncompress($targetFile, "/home/squid/wkdir/{$basename}");
        $targetFile = "/home/squid/wkdir/{$basename}";
        $REMOVE = TRUE;
    } else {
        $basename = $targetFile;
        if (count(explode('/', $basename)) > 0) {
            $basename = basename($basename);
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "Copy {$targetFile} -> /home/squid/wkdir/{$basename}\n";
        }
        if (!@copy($targetFile, "/home/squid/wkdir/{$basename}")) {
            events("Unable to copy {$targetFile} to /home/squid/wkdir/{$basename}");
            return false;
        }
        $targetFile = "/home/squid/wkdir/{$basename}";
        $REMOVE = TRUE;
    }
    events("_analyze_file - {$targetFile}");
    if (_analyze_file($targetFile, $zmd5)) {
        if ($REMOVE) {
            @unlink($targetFile);
        }
    }
    killNas();
}
Example #5
0
function BACKUP_RESTORE($filename)
{
    $unix = new unix();
    build_progress_restore("{restore} {$filename}", 5);
    $content_dir = dirname(__FILE__) . "/ressources/conf/upload/";
    $filesource = "{$content_dir}{$filename}";
    $filedest = $unix->FILE_TEMP();
    if (!is_file($filesource)) {
        @unlink($filesource);
        echo "{$filesource} no such file\n";
        build_progress_backup("{restore} {failed}", 110);
        return;
    }
    build_progress_restore("{restore} {$filename} {uncompress}", 50);
    if (!$unix->uncompress($filesource, $filedest)) {
        @unlink($filesource);
        @unlink($filedest);
        echo "{$filesource} unable to uncompress\n";
        build_progress_backup("{restore} {failed}", 110);
        return;
    }
    @unlink($filesource);
    build_progress_restore("{restore} {$filename} {injecting}", 90);
    $q = new mysql_squid_builder();
    $cmdline = $q->MYSQL_CMDLINES;
    $mysql = $unix->find_program("mysql");
    $cmdline = "{$mysql} {$cmdline} --force squidlogs < {$filedest}";
    echo $cmdline . "\n";
    system($cmdline);
    sleep(5);
    @unlink($filedest);
    build_progress_restore("{restore} {done}", 100);
}
function Rule3($MAIN, $mirror)
{
    $unix = new unix();
    $sock = new sockets();
    $temppath = $unix->TEMP_DIR();
    $TargetFile = "/etc/spamassassin/ArticaTechRules3.cf";
    $TIME = $MAIN["SPAMASS_3"]["TIME"];
    $MD5 = $MAIN["SPAMASS_3"]["MD5"];
    $SourceGZ = "spamassassin-rules4.gz";
    $TempSource = "{$temppath}/" . basename($TargetFile);
    $KeyTime = "SpamassassinPattern3Time";
    $MyTime = $sock->GET_INFO($KeyTime);
    if (!is_file($TargetFile)) {
        $MyTime = 0;
    }
    if ($TIME == $MyTime) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$KeyTime}: {$TIME}=={$MyTime} No new update\n";
        }
        return;
    }
    $curl = new ccurl("{$mirror}/{$SourceGZ}");
    $curl->NoHTTP_POST = true;
    if (!$curl->GetFile("{$temppath}/{$SourceGZ}")) {
        postfix_admin_mysql(0, "Unable to get {$SourceGZ}", $curl->error, __FILE__, __LINE__);
        return;
    }
    $md5f = md5_file("{$temppath}/{$SourceGZ}");
    if ($md5f != $MD5) {
        @unlink("{$temppath}/{$SourceGZ}");
        postfix_admin_mysql(0, "Unable to get {$SourceGZ} (corrupted)", $curl->error, __FILE__, __LINE__);
        return;
    }
    if (!$unix->uncompress("{$temppath}/{$SourceGZ}", $TempSource)) {
        @unlink("{$temppath}/{$SourceGZ}");
        postfix_admin_mysql(0, "Unable to extract {$SourceGZ} (corrupted)", null, __FILE__, __LINE__);
        return;
    }
    @unlink("{$temppath}/{$SourceGZ}");
    @unlink($TargetFile);
    @copy($TempSource, $TargetFile);
    @unlink($TempSource);
    postfix_admin_mysql(0, "Success updating {$TargetFile} database version {$TIME}", null, __FILE__, __LINE__);
    $sock->SET_INFO($KeyTime, $TIME);
    return true;
}
function restore($targetFilename)
{
    build_progress_idb("{restore_database}", 20);
    $unix = new unix();
    if (is_file("/tmp/postgressql-restore.running")) {
        $pid = $unix->PIDOF("/usr/local/ArticaStats/bin/psql");
        if ($unix->process_exists($pid)) {
            $timepid = $unix->PROCCESS_TIME_MIN($pid);
            echo "Already running {$pid} since {$timepid}mn\n";
            return;
        }
        @unlink("/tmp/postgressql-restore.running");
    }
    if (is_file("/tmp/postgressql-restore.running")) {
        return;
    }
    if (!is_file($targetFilename)) {
        echo "targetFilename: {$targetFilename} no such file\n";
        build_progress_idb("{restore_database} {failed}", 110);
        return;
    }
    $basename = basename($targetFilename);
    if (!preg_match("#\\.gz\$#", $basename)) {
        echo "targetFilename: {$basename} do in gzip format\n";
        build_progress_idb("{restore_database} {failed}", 110);
        return;
    }
    $UnCompressFileName = $targetFilename . ".sql";
    $su = $unix->find_program("su");
    $gunzip = $unix->find_program("gunzip");
    build_progress_idb("{restore_database} {uncompress}", 50);
    if (!$unix->uncompress($targetFilename, $UnCompressFileName)) {
        echo "Unable to uncompress {$targetFilename}\n";
        build_progress_idb("{restore_database} {failed}", 110);
        return;
    }
    $psql = "/usr/local/ArticaStats/bin/psql -f {$UnCompressFileName}  -h /var/run/ArticaStats -U ArticaStats -w proxydb";
    $f[] = "#!/bin/sh";
    $f[] = ". /lib/init/vars.sh";
    $f[] = ". /lib/lsb/init-functions";
    $f[] = "LANG=en_US.UTF-8";
    $f[] = "HOME=/home/ArticaStats";
    $f[] = "PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games";
    $f[] = "rm /tmp/postgressql-restore.sh";
    $f[] = "if [ -f \"/tmp/postgressql-restore.running\" ]; then";
    $f[] = "exit";
    $f[] = "fi";
    $f[] = "touch /tmp/postgressql-restore.running\n";
    $cmdline = "{$psql}";
    $f[] = "{$cmdline}";
    $f[] = "echo \"OK FINISH\"";
    $f[] = "rm /tmp/postgressql-restore.running";
    $f[] = "touch /tmp/postgressql-restore.OK\n";
    if (is_file("/tmp/postgressql-restore.OK")) {
        @unlink("/tmp/postgressql-restore.OK");
    }
    @file_put_contents("/tmp/postgressql-restore.sh", @implode("\n", $f));
    @chmod("/tmp/postgressql-restore.sh", 0755);
    echo $cmdline;
    build_progress_idb("{restore_database} {run}", 50);
    $text = "{please_wait}";
    $i = 0;
    $prc = 60;
    while (true) {
        $i++;
        if (is_file("/tmp/postgressql-restore.OK")) {
            break;
        }
        build_progress_idb("{restore_database} {$text} ({$i})", $prc);
        sleep(3);
        if (is_file("/tmp/postgressql-restore.running")) {
            $pid = $unix->PIDOF("/usr/local/ArticaStats/bin/psql");
            $timepid = $unix->PROCCESS_TIME_MIN($pid);
            $size = $unix->DIRSIZE_BYTES_NOCACHE("/home/ArticaStatsDB");
            $array_load = sys_getloadavg();
            $internal_load = $array_load[0];
            $text = "{running} load:{$internal_load} {$pid} {since} {$timepid}mn " . FormatBytes($size / 1024);
            $prc = 70;
        }
    }
    build_progress_idb("{restore_database} {done}", 90);
    sleep(5);
    InfluxDbSize();
    build_progress_idb("{restore_database} {success}", 100);
}
function ParseFile($tgz)
{
    $mysql = new mysql();
    if (!preg_match("#^(.+?)-[0-9]+-artica-php#", basename($tgz), $re)) {
        meta_events("Unable to find uuid in {$tgz}");
        return false;
    }
    $uuid = $re[1];
    $f = array();
    $GLOBALS["UUIDS"][$uuid] = true;
    $q = new mysql_uuid_meta($uuid);
    $tmpfile = $GLOBALS["CLASS_UNIX"]->FILE_TEMP() . ".db";
    $unix = new unix();
    if (!$unix->uncompress($tgz, $tmpfile)) {
        @unlink($tmpfile);
        meta_events("{$GLOBALS["UNCOMPRESSLOGS"]}");
        @unlink($tgz);
        return false;
    }
    $db_con = @dba_open($tmpfile, "r", "db4");
    if (!$db_con) {
        meta_events("Warning! DB open {$tmpfile} failed...");
        return false;
    }
    $mainkey = dba_firstkey($db_con);
    $c = 0;
    $n = 0;
    while ($mainkey != false) {
        $data = dba_fetch($mainkey, $db_con);
        $Array = unserialize($data);
        if (!is_array($Array)) {
            meta_events("{$mainkey} -> {$data} not an array...");
            $mainkey = dba_nextkey($db_con);
            continue;
        }
        $md5 = md5(serialize($Array));
        $date = $Array["DATE"];
        $time = strtotime($date);
        $xtime = date("Y-m-d H:i:s", $time);
        $hits = $Array["HITS"];
        $size = $Array["SIZE"];
        $mac = $Array["MAC"];
        $uid = $Array["UID"];
        $ipaddr = $Array["IPADDR"];
        $website = $Array["website"];
        $tablename = "squid_hourly_" . date("YmdH", $time);
        $f[$tablename][] = "('{$md5}','{$xtime}','{$website}','{$mac}','{$uid}','{$ipaddr}','{$hits}','{$size}')";
        if (count($f[$tablename]) > 2000) {
            meta_events("{$tablename} -> " . count($f[$tablename]));
            $prefix = "INSERT IGNORE INTO `{$tablename}` (`zdm5`,`zDate`,`sitename`,`mac`,`uid`,`ipaddr`,`hits`,`size`) VALUES ";
            if (!$q->create_squid_hourly($tablename)) {
                return false;
            }
            $q->QUERY_SQL($prefix . @implode(",", $f[$tablename]));
            if (!$q->ok) {
                meta_events($q->mysql_error);
                return false;
            }
            $f[$tablename] = array();
        }
        $mainkey = dba_nextkey($db_con);
    }
    if (count($f) > 0) {
        while (list($tablename, $rows) = each($f)) {
            meta_events("{$tablename} -> " . count($rows));
            $prefix = "INSERT IGNORE INTO `{$tablename}` (`zmd5`,`zDate`,`sitename`,`mac`,`uid`,`ipaddr`,`hits`,`size`) VALUES ";
            if (!$q->create_squid_hourly($tablename)) {
                return false;
            }
            $q->QUERY_SQL($prefix . @implode(",", $rows));
            if (!$q->ok) {
                meta_events($q->mysql_error);
                return false;
            }
        }
    }
    return true;
}
Example #9
0
function restore_tables($filename)
{
    $unix = new unix();
    $sock = new sockets();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".restore_tables." . __FUNCTION__ . ".pid";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx Already Artica task running PID {$pid} since {$time}mn\n";
        }
        return;
    }
    $filepath = dirname(__FILE__) . "/ressources/conf/upload/{$filename}";
    if (!is_file($filename)) {
        build_progress("{failed} {$filename} no such file", 110);
        return;
    }
    $tmpf = $unix->FILE_TEMP();
    build_progress("{uncompress} {$filename}", 10);
    if (!$unix->uncompress($filename, $tmpf)) {
        build_progress("{uncompress} {$filename} {failed}", 110);
        return;
    }
    @unlink($filename);
    build_progress("{importing} {$tmpf}", 50);
    $mysql = $unix->find_program("mysql");
    $q = new mysql_squid_builder();
    $cmd = "{$mysql} {$q->MYSQL_CMDLINES} -f squidlogs < {$tmpf}";
    system($cmd);
    build_progress("{done}", 100);
    @unlink($tmpf);
}
Example #10
0
function xstart()
{
    $curl = new ccurl();
    $unix = new unix();
    $Pidfile = "/etc/artica-postfix/pids/exec.abuse-ch.pid";
    $PidTime = "/etc/artica-postfix/pids/exec.abuse-ch.time";
    $pid = $unix->get_pid_from_file($Pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        if ($GLOBALS["VERBOSE"]) {
            echo "Aborting Task already running pid {$pid} " . __FUNCTION__ . "()\n";
        }
        return;
    }
    @file_put_contents($Pidfile, getmypid());
    if (!$GLOBALS["VERBOSE"]) {
        $time = $unix->file_time_min($PidTime);
        if ($time < 10) {
            echo "Only each 10mn\n";
            die;
        }
        @unlink($PidTime);
        @file_put_contents($PidTime, time());
    }
    $curl = new ccurl("http://articatech.net/WebfilterDBS/ransomwaretracker.txt");
    $tmpfile = $unix->TEMP_DIR();
    if (!$curl->GetFile("{$tmpfile}/ransomwaretracker.txt")) {
        squid_admin_mysql(0, "ransomwaretracker.txt unable to get index file", $curl->error, __FILE__, __LINE__);
        return;
    }
    $array = unserialize(@file_get_contents("{$tmpfile}/ransomwaretracker.txt"));
    $TIME = $array["TIME"];
    if (!isset($array["MD5"])) {
        squid_admin_mysql(0, "ransomwaretracker.txt corrupted file", $curl->error, __FILE__, __LINE__);
        return;
    }
    @unlink("{$tmpfile}/ransomwaretracker.txt");
    $CurrentMD5 = @file_get_contents("/etc/artica-postfix/settings/Daemons/ransomwaretrackerMD5");
    if ($CurrentMD5 == $array["MD5"]) {
        return;
    }
    $curl = new ccurl("http://articatech.net/WebfilterDBS/ransomwaretracker.gz");
    if (!$curl->GetFile("{$tmpfile}/ransomwaretracker.gz")) {
        squid_admin_mysql(0, "ransomwaretracker.gz unable to get pattern file", $curl->error, __FILE__, __LINE__);
        return;
    }
    if (!$unix->uncompress("{$tmpfile}/ransomwaretracker.gz", "{$tmpfile}/ransomwaretracker.db")) {
        squid_admin_mysql(0, "ransomwaretracker.gz unable to extract file", $curl->error, __FILE__, __LINE__);
        return;
    }
    $ARRAY = unserialize(@file_get_contents("{$tmpfile}/ransomwaretracker.db"));
    if (!isset($ARRAY["URIS"])) {
        squid_admin_mysql(0, "ransomwaretracker.db corrupted database", $curl->error, __FILE__, __LINE__);
        return;
    }
    if (is_file("/etc/squid3/ransomwaretracker.db")) {
        @unlink("/etc/squid3/ransomwaretracker.db");
    }
    @copy("{$tmpfile}/ransomwaretracker.db", "/etc/squid3/ransomwaretracker.db");
    if (!is_file("/etc/artica-postfix/settings/Daemons/RansomwareReloaded")) {
        squid_admin_mysql(1, "Reloading Proxy service for updating Ranswomware function", null, __FILE__, __LINE__);
        $squid = $unix->LOCATE_SQUID_BIN();
        shell_exec("{$squid} -f /etc/squid3/squid.conf -k reconfigure");
        @touch("/etc/artica-postfix/settings/Daemons/RansomwareReloaded");
    }
    squid_admin_mysql(2, "Success updating ranswomware database v{$TIME}", null, __FILE__, __LINE__);
}
function maillogconvert($filename)
{
    $basename = basename($filename);
    $time = filemtime($filename);
    $maillogconvert_path = "/var/log/maillogconvert/{$time}.convert";
    $unix = new unix();
    $year = date("Y");
    $compress = false;
    if (preg_match("#\\.gz\$#", $basename)) {
        if (preg_match("#^([0-9]+)-([0-9]+)-([0-9]+)\\.#", $basename, $re)) {
            $year = $re[1];
            $zdate = "{$re[1]}-{$re[2]}-{$re[3]}";
        }
        $compress = true;
    }
    $q = new postgres_sql();
    $binary = "/usr/share/artica-postfix/bin/maillogconvert.pl";
    @chmod("{$binary}", 0755);
    @mkdir("/var/log/maillogconvert");
    if ($compress) {
        $uncompressed_filename = $unix->FILE_TEMP();
        if (!$unix->uncompress($filename, $uncompressed_filename)) {
            return false;
        }
        if (is_file($maillogconvert_path)) {
            @unlink($maillogconvert_path);
        }
        echo "{$binary} standard {$year} {$uncompressed_filename} >{$maillogconvert_path}\n";
        system("{$binary} standard {$year} {$uncompressed_filename} >{$maillogconvert_path}");
        @unlink($uncompressed_filename);
        $maillogconvert_path_basename = basename($maillogconvert_path);
        if (maillogconvertparse($maillogconvert_path_basename, $zdate)) {
            $q->QUERY_SQL("INSERT INTO maillogsrc (sourcefile) VALUES ('{$basename}')");
            if (!$q->ok) {
                echo $q->mysql_error . "\n";
            }
        } else {
            echo "maillogconvert:: maillogconvertparse-> RETURN FALSE\n";
        }
        return;
    }
    if (is_file($maillogconvert_path)) {
        @unlink($maillogconvert_path);
    }
    system("{$binary} standard {$year} {$filename} >{$maillogconvert_path}");
    $maillogconvert_path_basename = basename($maillogconvert_path);
    if (maillogconvertparse($maillogconvert_path_basename)) {
        $q = new postgres_sql();
        echo "INSERT INTO maillogsrc sourcefile VALUES '{$maillogconvert_path_basename}'\n";
        $q->QUERY_SQL("INSERT INTO maillogsrc (sourcefile) VALUES ('{$basename}')");
        if (!$q->ok) {
            echo $q->mysql_error . "\n";
        }
    }
}
function start($id)
{
    $GLOBALS["CACHEFILE"] = "/usr/share/artica-postfix/ressources/logs/web/mimedefang.resend.progress.{$id}";
    $id = intval($id);
    $sock = new sockets();
    $unix = new unix();
    if ($id == 0) {
        echo "ID: {$id} not supported\n";
        build_progress(110, "{failed}");
        die;
    }
    $postgres = new postgres_sql();
    $tempfile = $unix->FILE_TEMP();
    $Dirtemp = $unix->TEMP_DIR();
    $q = new postgres_sql();
    $ligne = pg_fetch_array($q->QUERY_SQL("SELECT * FROM quarmsg WHERE id='{$id}'"));
    if (!$q->ok) {
        echo "PostgreSQL Error:" . $q->mysql_error . "\n";
        build_progress(110, "PostgreSQL {failed}");
        die;
    }
    $instance = $unix->hostname_g();
    $mailfrom = $ligne["mailfrom"];
    $mailto = $ligne["mailto"];
    $msgmd5 = $ligne["msgmd5"];
    if ($mailfrom == null) {
        $mailfrom = "root@{$instance}";
    }
    echo "From: {$mailfrom}\n";
    echo "To..: {$mailto}\n";
    echo "ID..: {$msgmd5}\n";
    build_progress(20, "{$mailfrom} {to} {$mailto} ({$msgmd5})");
    $sql = "SELECT contentid FROM quardata WHERE msgmd5='{$msgmd5}'";
    $ligne = pg_fetch_array($q->QUERY_SQL($sql));
    if (!$q->ok) {
        echo "PostgreSQL Error:" . $q->mysql_error . "\n";
        build_progress(110, "PostgreSQL {failed}");
        die;
    }
    $contentid = $ligne["contentid"];
    build_progress(30, "msg id: {$contentid}");
    @mkdir($Dirtemp, 0777, true);
    @chmod($Dirtemp, 0777);
    $sql = "select lo_export({$contentid}, '{$Dirtemp}/{$msgmd5}.gz')";
    if ($GLOBALS["VERBOSE"]) {
        echo "<hr>{$sql}<br>\n";
    }
    $q->QUERY_SQL($sql);
    if (!$q->ok) {
        echo "PostgreSQL Error:" . $q->mysql_error . "\n";
        build_progress(110, "PostgreSQL {failed}");
        die;
    }
    build_progress(40, "{uncompress}");
    if (!$unix->uncompress("{$Dirtemp}/{$msgmd5}.gz", "{$Dirtemp}/{$msgmd5}.msg")) {
        @unlink("{$Dirtemp}/{$msgmd5}.gz");
        @unlink("{$Dirtemp}/{$msgmd5}.msg");
        build_progress(110, "{uncompress} {failed}");
        die;
    }
    $smtp = new smtp();
    $TargetHostname = inet_interfaces();
    if (preg_match("#all#is", $TargetHostname)) {
        $TargetHostname = "127.0.0.1";
    }
    $params["helo"] = $instance;
    $params["debug"] = true;
    $params["host"] = $TargetHostname;
    $params["bindto"] = "127.0.0.1";
    build_progress(50, "{connecting}");
    if (!$smtp->connect($params)) {
        build_progress(110, "{connect} {failed}");
        @unlink("{$Dirtemp}/{$msgmd5}.msg");
        echo "{$smtp->error_number}: Could not connect to `{$TargetHostname}` {$smtp->error_text}\n";
        return;
    }
    $finalbody = @file_get_contents("{$Dirtemp}/{$msgmd5}.msg");
    build_progress(90, "{sending}");
    if (!$smtp->send(array("from" => $mailfrom, "recipients" => $mailto, "body" => $finalbody, "headers" => null))) {
        build_progress(110, "{sending} {failed}");
        @unlink("{$Dirtemp}/{$msgmd5}.msg");
        echo "{$smtp->error_number}: Could not connect to `{$TargetHostname}` {$smtp->error_text}\n";
        $smtp->quit();
        return;
    }
    @unlink("{$Dirtemp}/{$msgmd5}.msg");
    $smtp->quit();
    build_progress(100, "{success}");
}
function updatev2_adblock()
{
    return;
    if (isset($GLOBALS[__FUNCTION__])) {
        return;
    }
    $GLOBALS[__FUNCTION__] = true;
    $timeFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $main_artica_path = $GLOBALS["WORKDIR_LOCAL"];
    $unix = new unix();
    $users = new usersMenus();
    if (!$users->CORP_LICENSE) {
        if ($GLOBALS["VERBOSE"]) {
            echo "License error...\n";
        }
        return;
    }
    if (!$GLOBALS["FORCE"]) {
        $TimeMn = $unix->file_time_min($timeFile);
        if ($TimeMn < 60) {
            if ($GLOBALS["VERBOSE"]) {
                echo "{$TimeMn}Mn require 60mn minimal (use --force if necessary)\n";
            }
            return;
        }
    }
    @unlink($timeFile);
    @file_put_contents($timeFile, time());
    updatev2_checkversion();
    $reload = false;
    $trackergzip = "{$main_artica_path}/category_tracker/tracker_expressions.gz";
    $trackerfinal = "{$main_artica_path}/category_tracker/expressions";
    $malwaregzip = "{$main_artica_path}/category_malware/categoryuris_malware.gz";
    $malwarecsv = "{$main_artica_path}/category_malware/categoryuris_malware.csv";
    $pubgzip = "{$main_artica_path}/category_publicite/publicite_expressions.gz";
    $pubfinal = "{$main_artica_path}/category_publicite/expressions";
    $phishgzip = "{$main_artica_path}/category_phishing/categoryuris_phishing.gz";
    $phishcsv = "{$main_artica_path}/category_phishing/categoryuris_phishing.csv";
    if ($GLOBALS["MIRROR"] == null) {
        return;
    }
    @unlink("{$pubgzip}");
    $curl = new ccurl("{$GLOBALS["MIRROR"]}/publicite_expressions.gz");
    if (!$curl->GetFile($pubgzip)) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$pubgzip} failed to download {$curl->error}\n";
        }
        // ufdbguard_admin_events("UFDB::Fatal: $pubgzip failed to download $curl->error",__FUNCTION__,__FILE__,__LINE__,"ufbd-artica");
        @unlink("{$pubgzip}");
    }
    @unlink($trackergzip);
    $curl = new ccurl("{$GLOBALS["MIRROR"]}/tracker_expressions.gz");
    if (!$curl->GetFile($trackergzip)) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$trackergzip} failed to download {$curl->error}\n";
        }
        // ufdbguard_admin_events("UFDB::Fatal: $trackergzip failed to download $curl->error",__FUNCTION__,__FILE__,__LINE__,"ufbd-artica");
        @unlink($trackergzip);
    }
    @unlink($malwaregzip);
    $curl = new ccurl("{$GLOBALS["MIRROR"]}/categoryuris_malware.gz");
    if (!$curl->GetFile($malwaregzip)) {
        // ufdbguard_admin_events("UFDB::Fatal: $malwaregzip failed to download $curl->error",__FUNCTION__,__FILE__,__LINE__,"ufbd-artica");
        if ($GLOBALS["VERBOSE"]) {
            echo "{$malwaregzip} failed to download {$curl->error}\n";
        }
        @unlink($malwaregzip);
    }
    @unlink($phishgzip);
    $curl = new ccurl("{$GLOBALS["MIRROR"]}/categoryuris_phishing.gz");
    if (!$curl->GetFile($phishgzip)) {
        // ufdbguard_admin_events("UFDB::Fatal: $phishgzip failed to download $curl->error",__FUNCTION__,__FILE__,__LINE__,"ufbd-artica");
        if ($GLOBALS["VERBOSE"]) {
            echo "{$phishgzip} failed to download {$curl->error}\n";
        }
        @unlink($phishgzip);
    }
    $mdfile1 = md5_file($pubfinal);
    if ($GLOBALS["VERBOSE"]) {
        echo "{$pubfinal}({$mdfile1})\n";
    }
    if (is_file($pubgzip)) {
        $unix->uncompress($pubgzip, $pubfinal);
        $mdfile2 = md5_file($pubfinal);
        if ($GLOBALS["VERBOSE"]) {
            echo "{$pubfinal}({$mdfile2})\n";
        }
        if ($mdfile2 != $mdfile1) {
            $reload = true;
        }
    } else {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$pubgzip} no such file\n";
        }
    }
    $mdfile1 = md5_file($trackerfinal);
    if ($GLOBALS["VERBOSE"]) {
        echo "{$trackerfinal} -1- ({$mdfile1})\n";
    }
    if (is_file($trackergzip)) {
        $unix->uncompress($trackergzip, $trackerfinal);
        $mdfile2 = md5_file($trackerfinal);
        if ($GLOBALS["VERBOSE"]) {
            echo "{$trackerfinal} -2- ({$mdfile2})\n";
        }
        if ($mdfile1 != $mdfile2) {
            $reload = true;
        }
    } else {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$trackergzip} no such file\n";
        }
    }
    if (is_file($malwaregzip)) {
        $uris = array();
        $q = new mysql_squid_builder();
        $unix->uncompress($malwaregzip, $malwarecsv);
        $handle = @fopen($malwarecsv, "r");
        $q->CreateCategoryUrisTable("malware");
        if ($handle) {
            $line = @fgets($handle);
            $line = trim($line);
            if ($line == null) {
                continue;
            }
            $md5 = md5($line);
            $date = date("Y-m-d H:i:s");
            $url = mysql_escape_string2($line);
            $uris[] = "('{$md5}','{$date}','{$url}',1)";
        }
        if (count($uris) > 0) {
            $sql = "INSERT IGNORE INTO categoryuris_malware\n\t\t\t(zmd5,zDate,pattern,enabled) VALUES " . @implode(",", $uris);
            $q->QUERY_SQL($sql);
        }
    }
    if (is_file($phishgzip)) {
        $uris = array();
        $q = new mysql_squid_builder();
        $unix->uncompress($phishgzip, $phishcsv);
        $handle = @fopen($phishcsv, "r");
        $q->CreateCategoryUrisTable("phishing");
        if ($handle) {
            $line = @fgets($handle);
            $line = trim($line);
            if ($line == null) {
                continue;
            }
            $md5 = md5($line);
            $date = date("Y-m-d H:i:s");
            $url = mysql_escape_string2($line);
            $uris[] = "('{$md5}','{$date}','{$url}',1)";
        }
        if (count($uris) > 0) {
            $sql = "INSERT IGNORE INTO categoryuris_phishing\n\t\t\t(zmd5,zDate,pattern,enabled) VALUES " . @implode(",", $uris);
            $q->QUERY_SQL($sql);
        }
    }
    if ($reload) {
        squid_admin_mysql(2, "Ask to reload the Web filtering service", "");
        shell_exec("/etc/init.d/ufdb reload");
    }
}
function Scan($filepath, $md5file = null)
{
    $unix = new unix();
    if ($filepath == null) {
        echo "No path defined\n";
        return;
    }
    $pid = $unix->PIDOF_PATTERN(basename(__FILE__));
    $MyPid = getmypid();
    if ($MyPid != $pid) {
        if ($unix->process_exists($pid)) {
            $timeFile = $unix->PROCESS_TIME_INT($pid);
            $pidCmdline = @file_get_contents("/proc/{$pid}/cmdline");
            if ($timeFile < 30) {
                echo "Already PID {$pid} is running since {$timeFile}Mn\n";
                die;
            }
        }
    }
    $nextFile = null;
    if (!is_file($filepath)) {
        if ($md5file != null) {
            mysql_progress($md5file, 100, 3, "{$filepath} no such file");
        }
        echo "{$filepath} no such file";
    }
    @mkdir("/home/artica/import-temp", 0755, true);
    $basename = basename($filepath);
    if (preg_match("#\\.gz\$#", $basename)) {
        if ($md5file != null) {
            mysql_progress($md5file, 5, 0, "Uncompress {$filepath}");
        }
        echo "Uncompress {$basename}";
        $nextFile = dirname($filepath) . "/" . str_replace(".gz", "", $basename);
        echo "Uncompress {$basename} to {$nextFile}\n";
        if (is_file($nextFile)) {
            @unlink($nextFile);
        }
        if (!$unix->uncompress($filepath, $nextFile)) {
            if ($md5file != null) {
                mysql_progress($md5file, 100, 3, "Uncompress {$basename} failed");
            }
            echo "Uncompress {$basename} failed\n";
            return false;
        }
        $filepath = $nextFile;
    }
    if (!ExplodeFile($filepath, $md5file)) {
        return false;
    }
    if ($nextFile != null) {
        @unlink($nextFile);
    }
    return true;
}
Example #15
0
function range_fichier_source($filepath, $BackupMaxDaysDir, $EXTERN = false)
{
    $syslog = new mysql_storelogs();
    $unix = new unix();
    $ext = $unix->file_extension($filepath);
    $hostname = $unix->hostname_g();
    $sock = new sockets();
    $LogRotatePath = $sock->GET_INFO("LogRotatePath");
    if ($LogRotatePath == null) {
        $LogRotatePath = "/home/logrotate";
    }
    $LogRotateAccess = "{$LogRotatePath}/access";
    $LogRotateAccessFailed = "{$LogRotatePath}/failed";
    $LogRotateAccessMerged = "{$LogRotatePath}/merged";
    $SquidRotateMergeFiles = $sock->GET_INFO("SquidRotateMergeFiles");
    if (!is_numeric($SquidRotateMergeFiles)) {
        $SquidRotateMergeFiles = 1;
    }
    $LogsRotateDeleteSize = intval($sock->GET_INFO("LogsRotateDeleteSize"));
    if ($LogsRotateDeleteSize == 0) {
        $LogsRotateDeleteSize = 5000;
    }
    $basename = basename($filepath);
    if ($basename == "access.merged.log") {
        return;
    }
    $syslog->events("Analyze {$filepath} [{$ext}] ", __FUNCTION__, __LINE__);
    if ($ext == "gz") {
        if (preg_match("#\\.tar\\.gz\$#", $basename)) {
            $syslog->events("{$filepath} is a tarball!", __FUNCTION__, __LINE__);
            return;
        }
        $syslog->events("Extract {$filepath}", __FUNCTION__, __LINE__);
        $ExtractedFile = "{$LogRotateAccess}/{$basename}.log";
        if (!$unix->uncompress($filepath, $ExtractedFile)) {
            @unlink($ExtractedFile);
            $syslog->events("Unable to extract {$filepath} to {$ExtractedFile}", __FUNCTION__, __LINE__);
            return;
        }
        $syslog->events("Removing {$filepath} [{$ext}] ", __FUNCTION__, __LINE__);
        @unlink($filepath);
        $filepath = $ExtractedFile;
    }
    $unix = new unix();
    $ztimes = access_logs_getdates($filepath);
    if (!$ztimes) {
        $syslog->events("Failed to parse {$filepath}", __FUNCTION__, __LINE__);
        @mkdir($LogRotateAccessFailed, 0755, true);
        if (@copy($filepath, "{$LogRotateAccessFailed}/{$basename}")) {
            @unlink($filepath);
        }
        return false;
    }
    $xdatefrom = $ztimes[0];
    $xdateTo = $ztimes[1];
    $dateFrom = date("Y-m-d_H-i-s", $xdatefrom);
    $dateTo = date("Y-m-d_H-i-s", $xdateTo);
    $NewFileName = filename_from_arraydates($ztimes);
    if ($SquidRotateMergeFiles == 1) {
        @mkdir($LogRotateAccessMerged, 0755, true);
        if (!is_dir($LogRotateAccessMerged)) {
            $syslog->events("Unable to create Merged directory {$LogRotateAccessMerged}", __FUNCTION__, __LINE__);
        } else {
            if (!@copy($filepath, "{$LogRotateAccessMerged}/{$basename}")) {
                @unlink("{$LogRotateAccessMerged}/{$basename}");
                $syslog->events("Unable to copy {$filepath} -> {$LogRotateAccessMerged}/{$basename}", __FUNCTION__, __LINE__);
            }
        }
    }
    $FinalDirectory = "{$BackupMaxDaysDir}/proxy/" . date("Y", $xdatefrom) . "/" . date("m", $xdatefrom) . "/" . date("d", $xdatefrom);
    @mkdir($FinalDirectory, 0755, true);
    if (!is_dir($FinalDirectory)) {
        $syslog->events("Unable to create {$FinalDirectory} directory permission denied", __FUNCTION__, __LINE__);
        return;
    }
    if (!$unix->compress($filepath, "{$FinalDirectory}/{$NewFileName}")) {
        @unlink("{$FinalDirectory}/{$NewFileName}");
        $syslog->events("Unable to compress {$FinalDirectory}/{$NewFileName} permission denied", __FUNCTION__, __LINE__);
        return;
    }
    $syslog->events("Success to create {$FinalDirectory}/{$NewFileName}", __FUNCTION__, __LINE__);
    $syslog->events("Removing source file {$filepath}", __FUNCTION__, __LINE__);
    @unlink($filepath);
}
function Scan($filepath, $md5file = null)
{
    $unix = new unix();
    if ($filepath == null) {
        echo "No path defined\n";
        return;
    }
    $nextFile = null;
    if (!is_file($filepath)) {
        if ($md5file != null) {
            mysql_progress($md5file, 100, 3, "{$filepath} no such file");
        }
        echo "{$filepath} no such file";
    }
    @mkdir("/home/artica/import-temp", 0755, true);
    $basename = basename($filepath);
    if (preg_match("#\\.gz\$#", $basename)) {
        if ($md5file != null) {
            mysql_progress($md5file, 5, 0, "Uncompress {$filepath}");
        }
        echo "Uncompress {$basename}";
        $nextFile = dirname($filepath) . "/" . str_replace(".gz", "", $basename);
        echo "Uncompress {$basename} to {$nextFile}\n";
        if (is_file($nextFile)) {
            @unlink($nextFile);
        }
        if (!$unix->uncompress($filepath, $nextFile)) {
            if ($md5file != null) {
                mysql_progress($md5file, 100, 3, "Uncompress {$basename} failed");
            }
            echo "Uncompress {$basename} failed\n";
            return false;
        }
        $filepath = $nextFile;
    }
    if (!ExplodeFile($filepath, $md5file)) {
        return false;
    }
    if ($nextFile != null) {
        @unlink($nextFile);
    }
    return true;
}
function psaux_client($uuid)
{
    $unix = new unix();
    $workingfile = "/usr/share/artica-postfix/ressources/conf/meta/hosts/uploaded/{$uuid}/PSAUX.gz";
    if (!is_file($workingfile)) {
        return;
    }
    $tmpfile = $unix->FILE_TEMP();
    $unix->uncompress($workingfile, $tmpfile);
    $data = explode("\n", @file_get_contents($tmpfile));
    $q = new mysql_meta();
    $sql = "CREATE TABLE IF NOT EXISTS `psaux` (\n\t\t\t\t\tuuid VARCHAR( 90 ) NOT NULL,\n\t\t\t\t\tuser VARCHAR( 40 ) NOT NULL,\n\t\t\t\t\tpid INT( 10 ) NOT NULL,\n\t\t\t\t\tCPU FLOAT NOT NULL,\n\t\t\t\t\tMEM FLOAT NOT NULL,\n\t\t\t\t\tVSZ INT(100) NOT NULL,\n\t\t\t\t\tRSS INT(100) NOT NULL,\n\t\t\t\t\tpTIME VARCHAR( 40 ) NOT NULL,\n\t\t\t\t\tpcmd VARCHAR( 255 ) NOT NULL,\n\t\t\t\t\tKEY `user` (`user`),\n\t\t\t\t\tKEY `CPU` (`CPU`),\n\t\t\t\t\tKEY `uuid` (`uuid`),\n\t\t\t\t\tKEY `MEM` (`MEM`),\n\t\t\t\t\tKEY `VSZ` (`VSZ`),\n\t\t\t\t\tKEY `RSS` (`RSS`)\n\t\t\t\t\t) ENGINE=MYISAM;";
    $q->QUERY_SQL($sql);
    $prefix = "INSERT INTO `psaux` (uuid,user,pid,CPU,MEM,VSZ,RSS,pTIME,pcmd) VALUES ";
    $TR = array();
    while (list($index, $line) = each($data)) {
        if (!preg_match("#(.*?)\\s+([0-9]+)\\s+([0-9\\.]+)\\s+([0-9\\.]+)\\s+([0-9]+)\\s+([0-9]+)\\s+(.*?)\\s+(.*?)\\s+(.+?)\\s+([0-9\\:]+)\\s+(.*)#", $line, $re)) {
            continue;
        }
        $re[11] = mysql_escape_string2($re[11]);
        $TR[] = "('{$uuid}','{$re[1]}','{$re[2]}','{$re[3]}','{$re[4]}','{$re[5]}','{$re[6]}','{$re[10]}','{$re[11]}')";
    }
    if (count($TR) > 0) {
        if ($GLOBALS["VERBOSE"]) {
            echo "Adding " . count($TR) . " rows\n";
        }
        $q->QUERY_SQL("DELETE FROM `psaux` WHERE uuid='{$uuid}'");
        $q->QUERY_SQL($prefix . @implode(",", $TR));
    }
    @unlink($workingfile);
}
function replic_host($servername)
{
    $t = time();
    $unix = new unix();
    $free = new freeweb($servername);
    $instanceid = $free->mysql_instance_id;
    $localdatabase = $free->mysql_database;
    if (!isset($free->Params["ROUNDCUBE"]["ENABLE_REPLIC"])) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$servername}: ROUNDCUBE/ENABLE_REPLIC no set\n";
        }
        return null;
    }
    if ($free->Params["ROUNDCUBE"]["ENABLE_REPLIC"] == 0) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$servername}: ROUNDCUBE/ENABLE_REPLIC set to disabled\n";
        }
        return null;
    }
    $ARTICA_PORT = $free->Params["ROUNDCUBE"]["ARTICA_PORT"];
    $ARTICA_ADMIN = $free->Params["ROUNDCUBE"]["ARTICA_ADMIN"];
    $ARTICA_PASSWORD = $free->Params["ROUNDCUBE"]["ARTICA_PASSWORD"];
    $ARTICA_HOST = $free->Params["ROUNDCUBE"]["ARTICA_HOST"];
    $ARTICA_RMWEB = $free->Params["ROUNDCUBE"]["ARTICA_RMWEB"];
    if ($GLOBALS["VERBOSE"]) {
        echo "Send order to get database dump {$ARTICA_HOST}:{$ARTICA_PORT}\n";
    }
    $auth = array("username" => $ARTICA_ADMIN, "password" => md5($ARTICA_PASSWORD));
    $auth = base64_encode(serialize($auth));
    $curl = new ccurl("https://{$ARTICA_HOST}:{$ARTICA_PORT}/exec.gluster.php");
    $curl->noproxyload = true;
    $curl->parms["AUTH"] = $auth;
    $curl->parms["RDCUBE-REPLIC"] = $ARTICA_RMWEB;
    if (!$curl->get()) {
        if ($GLOBALS["VERBOSE"]) {
            echo "Error replicate roundcube to {$ARTICA_HOST}:{$ARTICA_PORT} with error {$curl->error}\n";
        }
        system_admin_events("Error replicate roundcube to {$ARTICA_HOST}:{$ARTICA_PORT} with error {$curl->error}", __FUNCTION__, __FILE__, __LINE__, "roundcube");
        return;
    }
    preg_match("#<INFOS>(.*?)</INFOS>#is", $curl->data, $re);
    if ($GLOBALS["VERBOSE"]) {
        echo "{$curl->data}\n";
    }
    if (!preg_match("#<FILENAME>(.*?)</FILENAME>#is", $curl->data, $re)) {
        preg_match("#<ERROR>(.*?)</ERROR>#is", $curl->data, $re);
        if ($GLOBALS["VERBOSE"]) {
            echo "Error replicate roundcube to {$ARTICA_HOST}:{$ARTICA_PORT} with error {$re[1]}\n";
        }
        system_admin_events("Error replicate roundcube to {$ARTICA_HOST}:{$ARTICA_PORT} with error {$re[1]}", __FUNCTION__, __FILE__, __LINE__, "roundcube");
        return;
    }
    $filepath = $re[1];
    $filename = basename($filepath);
    $curl = new ccurl("https://{$ARTICA_HOST}:{$ARTICA_PORT}/{$filepath}");
    if (!$curl->GetFile("/tmp/{$filename}")) {
        if ($GLOBALS["VERBOSE"]) {
            echo "Error get  roundcube database from {$filepath} with error {$curl->error}\n";
        }
        system_admin_events("Error get  roundcube database from {$filepath} with error {$curl->error}", __FUNCTION__, __FILE__, __LINE__, "roundcube");
        return;
    }
    $filesize = $unix->file_size("/tmp/{$filename}");
    if ($GLOBALS["VERBOSE"]) {
        echo "Downloading {$filename} done with {$filesize} bytes\n";
    }
    if (!$unix->uncompress("/tmp/{$filename}", "/tmp/{$filename}.sql")) {
        @unlink("/tmp/{$filename}");
        if ($GLOBALS["VERBOSE"]) {
            echo "Error uncompress {$filepath}\n";
        }
        system_admin_events("Error uncompress {$filepath}", __FUNCTION__, __FILE__, __LINE__, "roundcube");
        return;
    }
    @unlink("/tmp/{$filename}");
    $mysqlbin = $unix->find_program("mysql");
    if ($instanceid > 0) {
        $q = new mysql_multi($instance_id);
        if ($q->mysql_password != null) {
            $password = "******";
        }
        $cmdline = "{$mysqlbin} --batch --force --user={$q->mysql_admin}{$password} --socket={$q->SocketPath} --database={$localdatabase} </tmp/{$filename}.sql 2>&1";
    } else {
        $q = new mysql();
        if ($q->mysql_server == "127.0.0.1") {
            $servcmd = " --socket=/var/run/mysqld/mysqld.sock ";
        } else {
            $servcmd = " --host={$q->mysql_server} --port={$q->mysql_port} ";
        }
        if ($q->mysql_password != null) {
            $password = "******";
        }
        $cmdline = "{$mysqlbin} --batch --force --user={$q->mysql_admin}{$password} {$servcmd} --database={$localdatabase} </tmp/{$filename}.sql 2>&1";
    }
    if ($GLOBALS["VERBOSE"]) {
        echo $cmdline . "\n";
    }
    shell_exec($cmdline);
    $took = $unix->distanceOfTimeInWords($t, time(), true);
    system_admin_events("Success import from {$filename} to {$localdatabase} took {$took}", __FUNCTION__, __FILE__, __LINE__, "roundcube");
    @unlink("/tmp/{$filename}.sql");
}
Example #19
0
<?php

if (posix_getuid() != 0) {
    die("Cannot be used in web server mode\n\n");
}
include_once dirname(__FILE__) . '/ressources/class.templates.inc';
include_once dirname(__FILE__) . '/ressources/class.ccurl.inc';
include_once dirname(__FILE__) . '/ressources/class.mysql.squid.builder.php';
include_once dirname(__FILE__) . '/framework/class.unix.inc';
include_once dirname(__FILE__) . '/framework/frame.class.inc';
include_once dirname(__FILE__) . '/ressources/class.mysql.services.inc';
$unix = new unix();
$dirs = $unix->DirFiles($argv[1]);
while (list($num, $ligne) = each($dirs)) {
    $unix->uncompress($argv[1] . "/{$num}", $argv[1] . "/{$num}.log");
}
function update_milter_regex()
{
    $unix = new unix();
    $mirror = "http://mirror.articatech.net/webfilters-databases";
    if ($GLOBALS["VERBOSE"]) {
        echo "Downloading {$mirror}/milter-regex-database.gz\n";
    }
    $curl = new ccurl("{$mirror}/milter-regex-database.gz");
    $curl->NoHTTP_POST = true;
    $temppath = $unix->TEMP_DIR();
    if (!$curl->GetFile("{$temppath}/milter-regex-database.gz")) {
        postfix_admin_mysql(0, "Unable to get Milter-Regex database file", $curl->error);
        return;
    }
    if (!is_file("{$temppath}/milter-regex-database.gz")) {
        postfix_admin_mysql(0, "Unable to get Milter-Regex database file (no such file)", $curl->error);
        return;
    }
    if (!$unix->uncompress("{$temppath}/milter-regex-database.gz", "{$temppath}/milter-regex-database.sql")) {
        @unlink("{$temppath}/milter-regex-database.gz");
        postfix_admin_mysql(0, "Unable to extract milter-regex-database.gz (corrupted)", null, __FILE__, __LINE__);
        return;
    }
    @unlink("{$temppath}/milter-regex-database.gz");
    $MAIN = unserialize(@file_get_contents("{$temppath}/milter-regex-database.sql"));
    if (!is_array($MAIN)) {
        @unlink("{$temppath}/milter-regex-database.sql");
        postfix_admin_mysql(0, "Unable to understand milter-regex-database (Array corrupted)", null, __FILE__, __LINE__);
        return;
    }
    $Time = intval($MAIN["PATTERN"]["TIME"]);
    if ($Time == 0) {
        @unlink("{$temppath}/milter-regex-database.sql");
        postfix_admin_mysql(0, "Unable to understand milter-regex-database (Time corrupted)", null, __FILE__, __LINE__);
        return;
    }
    $sock = new sockets();
    $MyTime = $sock->GET_INFO("MilterRegexPatternTime");
    if ($MyTime == $Time) {
        return;
    }
    $q = new mysql();
    $RULES = $q->COUNT_ROWS("milterregex_acls", "artica_backup");
    @unlink("{$temppath}/milter-regex-database.sql");
    while (list($num, $ligne) = each($MAIN["DATAS"])) {
        while (list($a, $b) = each($ligne)) {
            $ligne[$a] = mysql_escape_string2($b);
        }
        $description = $ligne["description"];
        $pattern = $ligne["pattern"];
        $method = $ligne["method"];
        $zmd5 = $ligne["zmd5"];
        $instance = $ligne["instance"];
        $method = $ligne["method"];
        $type = $ligne["type"];
        $enabled = $ligne["enabled"];
        $reverse = $ligne["reverse"];
        $extended = $ligne["extended"];
        $zDate = $ligne["zDate"];
        $sql = "INSERT INTO `milterregex_acls`\n\t\t(`zmd5`,`zDate`,`instance`,`method`,`type`,`pattern`,`description`,`enabled`,`reverse`,`extended`) VALUES\n\t\t('{$zmd5}','{$zDate}','{$instance}','{$method}','{$type}','{$pattern}','{$description}',{$enabled},{$reverse},{$extended});";
        $q->QUERY_SQL($sql, "artica_backup");
        if (!$q->ok) {
            return;
        }
    }
    $sock->SET_INFO("MilterRegexPatternTime", $MAIN["PATTERN"]["TIME"]);
    $RULES2 = $q->COUNT_ROWS("milterregex_acls", "artica_backup");
    $SUM = $RULES2 - $RULES;
    if ($SUM > 0) {
        postfix_admin_mysql(1, "Restarting Milter-regex service", null, __FILE__, __LINE__);
        shell_exec("/etc/init.d/milter-regex restart");
        postfix_admin_mysql(2, "{$SUM} rules updated for Milter-regex ACls", null, __FILE__, __LINE__);
    }
    $chown = $unix->find_program("chown");
    shell_exec("{$chown} postfix:postfix /var/run/milter-greylist/milter-greylist.sock >/dev/null 2>&1");
}