예제 #1
0
function PushToRepo($filepath)
{
    $curl = "/usr/bin/curl";
    $unix = new unix();
    $ftpass5 = trim(@file_get_contents("/root/ftp-password5"));
    $uri = "ftp://mirror.articatech.net/www.artica.fr/WebfilterDBS";
    $size = round(filesize($filepath) / 1024);
    $ftpass5 = $unix->shellEscapeChars($ftpass5);
    echo "Push {$filepath} ( {$size} KB ) to {$uri}\n";
    system("{$curl} -T {$filepath} {$uri}/ --user {$ftpass5}");
}
예제 #2
0
파일: zarafa.php 프로젝트: rsd/artica-1.5
function DbAttachConverter(){
	$unix=new unix();
	$nohup=$unix->find_program("nohup");
	$perl=$unix->find_program("perl");
	$sqladm=base64_decode($_GET["sqladm"]);
	$sqlpass=base64_decode($_GET["mysqlpass"]);
	$sqlpass=$unix->shellEscapeChars($sqlpass);
	$path=$_GET["path"];
	if(!is_dir($path)){@mkdir($path,644,true);}
	$cmd="$nohup $perl /usr/share/doc/zarafa/db-convert-attachments-to-files $sqladm $sqlpass zarafa $path delete >/dev/null 2>&1 &";	
	writelogs_framework($cmd,__FUNCTION__,__FILE__,__LINE__);
	shell_exec($cmd);	
}
예제 #3
0
function test_auth()
{
    $unix = new unix();
    $username = base64_decode($_GET["username"]);
    $password = base64_decode($_GET["password"]);
    $radtest = $unix->find_program("radtest");
    $username = $unix->shellEscapeChars($username);
    $password = $unix->shellEscapeChars($password);
    $resultsA = "\t\t*********************************\n\t\t*********** FAILED *******************\n\t\t*********************************\n";
    $mainpassword = @file_get_contents("/etc/artica-postfix/ldap_settings/password");
    $mainpassword = $unix->shellEscapeChars($mainpassword);
    $cmdline = "{$radtest} {$username} {$password} localhost 0 {$mainpassword} 2>&1";
    writelogs_framework("{$cmdline}", __FUNCTION__, __FILE__, __LINE__);
    exec($cmdline, $results);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#User-Password#", $ligne, $re)) {
        }
        if (preg_match("#Access-Accept#", $ligne)) {
            $resultsA = "\t\t*********************************\n\t\t*********** SUCCESS ******************\n\t\t*********************************\n";
        }
    }
    $resultsA = str_replace("*", " * ", $resultsA);
    echo "<articadatascgi>" . base64_encode($resultsA . @implode("\n", $results)) . "</articadatascgi>";
}
예제 #4
0
function ChangeRootPassword()
{
    $unix = new unix();
    echo "Give the root password:\n";
    $answer = trim(fgets(STDIN));
    if ($answer == null) {
        echo "No password set\n";
        echo "Type Enter key to exit.\n";
        $answer = trim(strtolower(fgets(STDIN)));
        menu();
        return;
    }
    $password = $unix->shellEscapeChars($answer);
    $cmd = "/usr/share/artica-postfix/bin/artica-install --change-mysqlroot --inline \"root\" \"{$password}\"";
    echo "Running {$cmd}\n";
    system($cmd);
    echo "Refresh settings...\n";
    system("/usr/share/artica-postfix/bin/process1 --force");
    echo "\n\nType Enter key to exit.\n";
    $answer = trim(strtolower(fgets(STDIN)));
}
예제 #5
0
function databasesize($force = false)
{
    $unix = new unix();
    $sock = new sockets();
    $arrayfile = "/usr/share/artica-postfix/ressources/logs/web/{$GLOBALS["SERV_NAME"]}.size.db";
    $pidfile = "/etc/artica-postfix/pids/{$GLOBALS["SERV_NAME"]}-databasesize.pid";
    if (!$force) {
        $pid = $unix->get_pid_from_file($pidfile);
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            return;
        }
        @file_put_contents($pidfile, getmypid());
        $time = $unix->file_time_min($arrayfile);
        if ($time < 20) {
            return;
        }
    }
    $ArticaDBPath = "/home/artica/categories_databases";
    $GLOBALS["WORKDIR"] = $ArticaDBPath;
    $dir = $GLOBALS["WORKDIR"];
    if (is_link($dir)) {
        $dir = readlink($dir);
    }
    $unix = new unix();
    $sizbytes = $unix->DIRSIZE_BYTES($dir);
    $dir = $unix->shellEscapeChars($dir);
    $df = $unix->find_program("df");
    $array["DBSIZE"] = $sizbytes / 1024;
    exec("{$df} -B K {$dir} 2>&1", $results);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#^.*?\\s+([0-9A-Z\\.]+)K\\s+([0-9A-Z\\.]+)K\\s+([0-9A-Z\\.]+)K\\s+([0-9\\.]+)%\\s+(.+)#", $ligne, $re)) {
            $array["SIZE"] = $re[1];
            $array["USED"] = $re[2];
            $array["AIVA"] = $re[3];
            $array["POURC"] = $re[4];
            $array["MOUNTED"] = $re[5];
            break;
        }
    }
    $results = array();
    exec("{$df} -i {$dir} 2>&1", $results);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#^.*?\\s+([0-9A-Z\\.]+)\\s+([0-9A-Z\\.]+)\\s+([0-9A-Z\\.]+)\\s+([0-9\\.]+)%\\s+(.+)#", $ligne, $re)) {
            $array["ISIZE"] = $re[1];
            $array["IUSED"] = $re[2];
            $array["IAIVA"] = $re[3];
            $array["IPOURC"] = $re[4];
            break;
        }
    }
    if ($GLOBALS["VERBOSE"]) {
        print_r($array);
    }
    @unlink($arrayfile);
    @file_put_contents($arrayfile, serialize($array));
    if ($GLOBALS["VERBOSE"]) {
        echo "Saving {$arrayfile}...\n";
    }
    @chmod($arrayfile, 0755);
}
    $T[] = $ligne;
}
@file_put_contents("/root/milter-greylist-database.txt", @implode("\n", $T));
$unix = new unix();
if (!$unix->compress("/root/milter-greylist-database.txt", "/root/milter-greylist-database.gz")) {
    die;
}
@unlink("/root/milter-greylist-database.txt");
$md5 = md5_file("/root/milter-greylist-database.gz");
$MAIN["PATTERN"]["TIME"] = time();
$MAIN["PATTERN"]["MD5"] = $md5;
@file_put_contents("/root/milter-greylist-database.txt", serialize($MAIN));
$ftp_serv = @file_get_contents("/root/ftp-hostname");
$ftp_passw = @file_get_contents("/root/ftp-password");
$curl = $unix->find_program("curl");
$ftp_passw = $unix->shellEscapeChars($ftp_passw);
echo "\n ************** FTP WWWW **************\n";
echo "Push to ftp://mirror.articatech.net/www.artica.fr/WebfilterDBS/\n";
$cmdline = "{$curl} -T /root/milter-greylist-database.txt ftp://mirror.articatech.net/www.artica.fr/WebfilterDBS/ --user {$ftp_passw}\n";
echo $cmdline . "\n";
shell_exec("{$curl} -T /root/milter-greylist-database.txt ftp://mirror.articatech.net/www.artica.fr/WebfilterDBS/ --user {$ftp_passw}");
shell_exec("{$curl} -T /root/milter-greylist-database.gz ftp://mirror.articatech.net/www.artica.fr/WebfilterDBS/ --user {$ftp_passw}");
echo "*****************************************************\n";
$q = new mysql();
$sql = "SELECT description,pattern FROM miltergreylist_acls WHERE `method`='blacklist' AND `type`='domain'";
$results = $q->QUERY_SQL($sql, "artica_backup");
while ($ligne = mysql_fetch_assoc($results)) {
    $domain = $ligne["pattern"];
    if (preg_match("#regex:\\s+#", $domain)) {
        continue;
    }
예제 #7
0
function changeRootPasswd()
{
    $unix = new unix();
    $echo = $unix->find_program("echo");
    $passwd = base64_decode($_GET["pass"]);
    $chpasswd = $unix->find_program("chpasswd");
    $pass = $unix->shellEscapeChars($pass);
    $cmd = "{$echo} \"root:{$passwd}\" | {$chpasswd} 2>&1";
    exec("{$cmd}", $results);
    writelogs_framework("{$cmd} " . count($results) . " rows", __FUNCTION__, __FILE__, __LINE__);
    while (list($num, $line) = each($results)) {
        writelogs_framework("{$line}", __FUNCTION__, __FILE__, __LINE__);
    }
}
예제 #8
0
function restore_squidlogs($sourceDir)
{
    if (!($handle = opendir("{$sourceDir}/squidlogs"))) {
        echo "Failed open {$sourceDir}/squidlogs\n";
        return;
    }
    $password = null;
    $unix = new unix();
    if (!$unix->is_socket("/var/run/mysqld/squid-db.sock")) {
        system_admin_events("Error,/var/run/mysqld/squid-db.sock no such socket", __FUNCTION__, __FILE__, __LINE__);
        return false;
    }
    $sock = new sockets();
    $gunzip = $unix->find_program("gunzip");
    $mysql = $unix->find_program("mysql");
    $BLACKLIST = array();
    $nice = $unix->EXEC_NICE();
    $q = new mysql_squid_builder();
    $sock = new sockets();
    $BackupArticaRestoreNetwork = intval($sock->GET_INFO("BackupArticaRestoreNetwork"));
    if ($GLOBALS["NOT_RESTORE_NETWORK"]) {
        $BackupArticaRestoreNetwork = 0;
    }
    if ($BackupArticaRestoreNetwork == 0) {
        $BLACKLIST["dns_servers.gz"] = true;
        $BLACKLIST["dnsmasq_records.gz"] = true;
    }
    if ($q->mysql_password != null) {
        $password = "******" . $unix->shellEscapeChars($q->mysql_password);
    }
    $prefix = trim("{$mysql} --force -S /var/run/mysqld/squid-db.sock -u {$q->mysql_admin}{$password} squidlogs");
    while (false !== ($filename = readdir($handle))) {
        if ($filename == ".") {
            continue;
        }
        if ($filename == "..") {
            continue;
        }
        if (isset($BLACKLIST[$filename])) {
            continue;
        }
        $SourceFile = "{$sourceDir}/squidlogs/{$filename}";
        if (is_dir($SourceFile)) {
            continue;
        }
        echo "Restoring Proxy database/{$filename}\n";
        $cmd = trim("{$nice} {$gunzip} -c {$SourceFile} |{$prefix}");
        system($cmd);
    }
}
예제 #9
0
function disconnect()
{
    $unix = new unix();
    $user = new settings_inc();
    $netbin = $unix->LOCATE_NET_BIN_PATH();
    $kdestroy = $unix->find_program("kdestroy");
    $sock = new sockets();
    $nohup = $unix->find_program("nohup");
    $array = unserialize(base64_decode($sock->GET_INFO("KerbAuthInfos")));
    if (!isset($array["USE_AUTORID"])) {
        $array["USE_AUTORID"] = 1;
    }
    if (!is_numeric($array["USE_AUTORID"])) {
        $array["USE_AUTORID"] = 1;
    }
    $domainUp = strtoupper($array["WINDOWS_DNS_SUFFIX"]);
    $domain_lower = strtolower($array["WINDOWS_DNS_SUFFIX"]);
    $adminpassword = $array["WINDOWS_SERVER_PASS"];
    $adminpassword = $unix->shellEscapeChars($adminpassword);
    $adminpassword = str_replace("'", "", $adminpassword);
    $adminname = $array["WINDOWS_SERVER_ADMIN"];
    $ad_server = $array["WINDOWS_SERVER_NETBIOSNAME"];
    $kdb5_util = $unix->find_program("kdb5_util");
    $function = __FUNCTION__;
    if (!is_file($netbin)) {
        progress_logs(100, "{join_activedirectory_domain}", " net, no such binary");
        return;
    }
    if (!$user->SAMBA_INSTALLED) {
        progress_logs(100, "{join_activedirectory_domain}", " Samba, no such software");
        return;
    }
    build_progress_disconnect("Flush Keytab...", 5);
    exec("{$netbin} ads keytab flush 2>&1", $results);
    build_progress_disconnect("Leave Active Directory...", 10);
    exec("{$netbin} ads leave -U {$adminname}%{$adminpassword} 2>&1", $results);
    build_progress_disconnect("Destroy Kerberos ticket", 10);
    exec("{$kdestroy} 2>&1", $results);
    build_progress_disconnect("Destroy Kerberos ticket", 15);
    system("{$kdb5_util} -r {$domainUp}  -P {$adminpassword} destroy -f");
    build_progress_disconnect("Destroy Kerberos ticket", 20);
    @unlink("/etc/squid3/PROXY.keytab");
    squid_admin_mysql(0, "Active directory disconnected", "An order as been sent to disconnect Active Directory", __FILE__, __LINE__);
    build_progress_disconnect("Stamp to not use Active Directory", 50);
    $sock->SET_INFO("EnableKerbAuth", 0);
    @unlink("/etc/cron.d/artica-ads-watchdog");
    @unlink("/etc/cron.daily/msktutil");
    build_progress_disconnect("Remove the system from Active Directory", 70);
    exec("/usr/share/artica-postfix/bin/artica-install --nsswitch 2>&1", $results);
    build_progress_disconnect("Restarting SMB Engine", 70);
    exec("/etc/init.d/artica-postfix restart samba 2>&1", $results);
    while (list($num, $ligne) = each($results)) {
        echo "Leave......: {$ligne}\n";
        progress_logs(90, "{join_activedirectory_domain}", "Leave......: {$ligne}");
    }
    build_progress_disconnect("{reconfiguring_proxy_service}", 80);
    $php5 = $unix->LOCATE_PHP5_BIN();
    system("{$php5} /usr/share/artica-postfix/exec.squid.php --build --force");
    build_progress_disconnect("{done}", 100);
}
예제 #10
0
function activedirectory_ping(){
	$sock=new sockets();
	$unix=new unix();
	$filetime="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".time";
	$EnableSambaActiveDirectory=$sock->GET_INFO("EnableSambaActiveDirectory");
	if(!is_numeric($EnableSambaActiveDirectory)){return;}
	if($EnableSambaActiveDirectory<>1){return;}
	$ping_dc=false;
	$time=$unix->file_time_min($filetime);
	if($time<120){
		if(!$GLOBALS["VERBOSE"]){return;}
		echo "$filetime ({$time}Mn)\n";
	}
	
	$kinit=$unix->find_program("kinit");
	$echo=$unix->find_program("echo");
	$net=$unix->LOCATE_NET_BIN_PATH();
	$wbinfo=$unix->find_program("wbinfo");
	$config=unserialize(base64_decode($sock->GET_INFO("SambaAdInfos")));
	$domain=strtoupper($config["ADDOMAIN"]);
	$domain_lower=strtolower($config["ADDOMAIN"]);

	$ADSERVER_IP=$config["ADSERVER_IP"];	
	$ad_server=strtolower($config["ADSERVER"]);
	$kinitpassword=$config["PASSWORD"];
	$kinitpassword=$unix->shellEscapeChars($kinitpassword);
	
	$clock_explain="The clock on you system (Linux/UNIX) is too far off from the correct time.\nYour machine needs to be within 5 minutes of the Kerberos servers in order to get any tickets.\nYou will need to run ntp, or a similar service to keep your clock within the five minute window";
	
	
	$cmd="$echo $kinitpassword|$kinit {$config["ADADMIN"]}@$domain 2>&1";
	echo "$cmd\n";
	exec("$cmd",$kinit_results);
	while (list ($num, $ligne) = each ($kinit_results) ){
		if(preg_match("#Clock skew too great while getting initial credentials#", $ligne)){$unix->send_email_events("Active Directory connection clock issue", "kinit program claim\n$ligne\n$clock_explain", "system");}
		if($GLOBALS["VERBOSE"]){echo "kinit: $ligne\n";}
	}	
	

	exec("$wbinfo --ping-dc 2>&1",$ping_dc_results);
	
	while (list ($num, $ligne) = each ($ping_dc_results) ){
		if($GLOBALS["VERBOSE"]){echo "ping-dc: $ligne\n";}
		if(preg_match("#succeeded#", $ligne)){$ping_dc=true;}
	}
	
	@unlink($filetime);
	@file_put_contents($filetime, time());
	
	
}
예제 #11
0
파일: mysql.php 프로젝트: BillTheBest/1.6.x
function backuptable()
{
    $PARAMS = unserialize(base64_decode($_GET["backuptable"]));
    $unix = new unix();
    $mysqldump = $unix->find_program("mysqldump");
    if (!is_file($mysqldump)) {
        echo "<articadatascgi>" . base64_encode("ERROR: mysqldump no such binary") . "</articadatascgi>";
        return;
    }
    $t = time();
    $tfile = "{$PARAMS["PATH"]}/{$PARAMS["DB"]}.{$PARAMS["TABLE"]}.{$t}.sql";
    if (!is_numeric($PARAMS["PORT"])) {
        $PARAMS["PORT"] = 3306;
    }
    $PARAMS["PASS"] = $unix->shellEscapeChars($PARAMS["PASS"]);
    @mkdir($PARAMS["PATH"], 0755, true);
    $cmd = "{$mysqldump} --user={$PARAMS["ROOT"]} --password={$PARAMS["PASS"]} --port={$PARAMS["PORT"]} --host={$PARAMS["HOST"]} {$PARAMS["DB"]} {$PARAMS["TABLE"]} > {$tfile} 2>&1";
    writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__);
    exec($cmd, $results);
    if (!is_file($tfile)) {
        echo "<articadatascgi>" . base64_encode("ERROR: mysqldump {$tfile} no such file") . "</articadatascgi>";
        return;
    }
    $filesize = $unix->file_size($tfile);
    $filesize = round($filesize / 1024);
    echo "<articadatascgi>" . base64_encode("{$tfile} ({$filesize} K) done\n" . @implode("\n", $results)) . "</articadatascgi>";
}
예제 #12
0
function databasesize($force = false)
{
    $sock = new sockets();
    $unix = new unix();
    $arrayfile = $GLOBALS["DBCACHE_PATH"];
    if (!$force) {
        $pidfile = $GLOBALS["DATABASE_STATS_PID"];
        $pid = $unix->get_pid_from_file($pidfile);
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            return;
        }
        @file_put_contents($pidfile, getmypid());
        $time = $unix->file_time_min($arrayfile);
        if ($time < 20) {
            return;
        }
    }
    $WORKDIR = $sock->GET_INFO($GLOBALS["WORK_DIR_TOKEN"]);
    if ($WORKDIR == null) {
        $WORKDIR = $GLOBALS["WORK_DIR_DEFAULT"];
    }
    $dir = $WORKDIR;
    if (is_link($dir)) {
        $dir = readlink($dir);
    }
    $unix = new unix();
    $sizbytes = $unix->DIRSIZE_BYTES($dir);
    $dir = $unix->shellEscapeChars($dir);
    $df = $unix->find_program("df");
    $array["DBSIZE"] = $sizbytes / 1024;
    exec("{$df} -B K {$dir} 2>&1", $results);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#^.*?\\s+([0-9A-Z\\.]+)K\\s+([0-9A-Z\\.]+)K\\s+([0-9A-Z\\.]+)K\\s+([0-9\\.]+)%\\s+(.+)#", $ligne, $re)) {
            $array["SIZE"] = $re[1];
            $array["USED"] = $re[2];
            $array["AIVA"] = $re[3];
            $array["POURC"] = $re[4];
            $array["MOUNTED"] = $re[5];
            break;
        }
    }
    $results = array();
    exec("{$df} -i {$dir} 2>&1", $results);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#^.*?\\s+([0-9A-Z\\.]+)\\s+([0-9A-Z\\.]+)\\s+([0-9A-Z\\.]+)\\s+([0-9\\.]+)%\\s+(.+)#", $ligne, $re)) {
            $array["ISIZE"] = $re[1];
            $array["IUSED"] = $re[2];
            $array["IAIVA"] = $re[3];
            $array["IPOURC"] = $re[4];
            break;
        }
    }
    if ($GLOBALS["VERBOSE"]) {
        print_r($array);
    }
    @unlink($arrayfile);
    @file_put_contents($arrayfile, serialize($array));
    if ($GLOBALS["VERBOSE"]) {
        echo "Saving {$arrayfile}...\n";
    }
    @chmod($arrayfile, 0755);
}
예제 #13
0
function recycles_restore()
{
    $sql = "SELECT * FROM samba_recycle_bin_list WHERE restore=1";
    $q = new mysql();
    $unix = new unix();
    $mv = $unix->find_program("mv");
    $results = $q->QUERY_SQL($sql, "artica_backup");
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        $path = $ligne["path"];
        $path_org = $path;
        echo "{$path}\n";
        $uid = $ligne["uid"];
        $pathToRestore = str_replace("/.RecycleBin\$/{$uid}", "", $path);
        $pathToRestoreorg = $pathToRestore;
        if (!is_file($path)) {
            echo "FAILED {$path} no such file\n";
            $sql = "DELETE FROM samba_recycle_bin_list WHERE path='{$path_org}'";
            $q->QUERY_SQL($sql, "artica_backup");
            continue;
        }
        $path = $unix->shellEscapeChars($path);
        $dirname = dirname($pathToRestore);
        $pathToRestore = $unix->shellEscapeChars($pathToRestore);
        echo "restore to \"{$dirname}\"\n";
        recycles_privileges($path_org, $uid);
        if (!is_dir($dirname)) {
            echo "FAILED ! {$dirname} no such directory\n";
            $sql = "UPDATE samba_recycle_bin_list SET restore=0 WHERE path='{$path_org}'";
            $q->QUERY_SQL($sql, "artica_backup");
            continue;
        }
        $cmd = "{$mv} -b {$path} {$pathToRestore}";
        $ras = shell_exec($cmd);
        if (!is_file($pathToRestoreorg)) {
            echo "FAILED ! mv {$path} {$pathToRestore} {$ras}\n";
            $sql = "UPDATE samba_recycle_bin_list SET restore=0 WHERE path='{$path_org}'";
            $q->QUERY_SQL($sql, "artica_backup");
            continue;
        } else {
            $sql = "DELETE FROM samba_recycle_bin_list WHERE path='{$path_org}'";
            $q->QUERY_SQL($sql, "artica_backup");
        }
    }
}
예제 #14
0
function CheckGroup($groupname)
{
    $unix = new unix();
    $wbinfo = $unix->find_program("wbinfo");
    $net = $unix->find_program("net");
    $groupanecmd = $unix->shellEscapeChars($groupname);
    $cmd = "{$net} cache flush";
    if ($GLOBALS["VERBOSE"]) {
        echo "{$cmd}\n";
    }
    shell_exec($cmd);
    $cmd = "{$wbinfo} --group-info={$groupanecmd} 2>&1";
    if ($GLOBALS["VERBOSE"]) {
        echo "{$cmd}\n";
    }
    exec($cmd, $results);
    $line = trim(@implode(" ", $results));
    if (preg_match("#Could not get info for group#", $line, $re)) {
        ufdbguard_admin_events("Failed to lookup users, {$groupname}: {$line}", __FUNCTION__, __FILE__, __LINE__, "activedirectory");
        return;
    }
    if (!preg_match("#^.+?:x:([0-9]+):(.*)#", $line, $re)) {
        ufdbguard_admin_events("Failed to lookup users, {$groupname}: {$line}", __FUNCTION__, __FILE__, __LINE__, "activedirectory");
        return;
    }
    $gpid = $re[1];
    $userslist = $re[2];
    $sql = "DELETE FROM adgroups WHERE gpid={$gpid}";
    $q = new mysql();
    $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        ufdbguard_admin_events("Failed to manage, {$groupname}: {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "activedirectory");
        return;
    }
    $groupname = utf8_encode($groupname);
    $groupname = addslashes($groupname);
    $q->QUERY_SQL("INSERT IGNORE INTO adgroups (gpid,groupname) VALUES ('{$gpid}','{$groupname}')", "artica_backup");
    if (!$q->ok) {
        ufdbguard_admin_events("Failed to manage, {$groupname}: {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "activedirectory");
        return;
    }
    $q->QUERY_SQL("DELETE FROM adusers WHERE gpid={$gpid}", "artica_backup");
    $c = 0;
    $f = array();
    $usersTR = explode(",", $userslist);
    while (list($num, $line) = each($usersTR)) {
        if (trim($line) == null) {
            continue;
        }
        $line = utf8_encode($line);
        $line = addslashes($line);
        $f[] = "('{$gpid}','{$line}')";
        $c++;
    }
    if (count($f) > 0) {
        $sql = "INSERT IGNORE INTO adusers(`gpid`,`uid`) VALUES " . @implode(",", $f);
        $q->QUERY_SQL($sql, "artica_backup");
        if (!$q->ok) {
            ufdbguard_admin_events("Failed to import users on {$groupname}: {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "activedirectory");
            return;
        }
    }
    $GLOBALS["xxxCOUNT"] = $GLOBALS["xxxCOUNT"] + $c;
}
예제 #15
0
function loadavg_notif()
{
    $array_load = sys_getloadavg();
    $internal_load = $array_load[0];
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "/pids/" . __FUNCTION__ . ".pid";
    $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "/pids/" . __FUNCTION__ . ".time";
    $pid = @file_get_contents($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        writelogs("Already process {$pid} exists", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $time = $unix->file_time_min($pidTime);
    if ($time < 5) {
        writelogs("Max 1 report each 5 minutes (current {$time}Mn)", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    @file_put_contents($pidTime, time());
    $ps = $unix->find_program("ps");
    $tail = $unix->find_program("tail");
    $lsof = $unix->find_program("lsof");
    $wc = $unix->find_program("wc");
    $awk = $unix->find_program("awk");
    $grep = $unix->find_program("grep");
    $iostat = $unix->find_program("iostat");
    exec("{$lsof}|{$wc} -l 2>&1", $locfa);
    $lsof_text = "Number of opened files: " . @implode("", $locfa);
    exec("{$ps} -elf | {$awk} '{print \$2}' | {$grep} ^Z | {$wc} -l 2>&1", $locfa2);
    $zombies_text = "Number of zombies processes: " . @implode("", $locfa2);
    if (is_file($iostat)) {
        exec("{$iostat} -tmdx 2>&1", $iostata);
        $iostata[] = "\nCpu:\n------------------------------\n";
        exec("{$iostat} -tmcx 2>&1", $iostata);
        $iostat_text = "\n\nIostat report:\n--------------------------\n" . @implode("\n", $iostata);
    }
    exec("{$ps} aux --sort %cpu|{$tail} -n 20 2>&1", $psaux);
    krsort($psaux);
    $mysql = new mysql();
    $mysqladmin = $unix->find_program("mysqladmin");
    if (is_file($mysqladmin)) {
        if ($mysql->mysql_server == "localhost" or $mysql->mysql_server == "127.0.0.1") {
            $serv = " --socket=/var/run/mysqld/mysqld.sock";
            $servtext = "Local";
        } else {
            $serv = " --host={$mysql->mysql_server} --port={$mysql->mysql_port}";
            $servtext = "{$mysql->mysql_server}:{$mysql->mysql_port}";
        }
        if ($mysql->mysql_password != null) {
            $password = "******" . $unix->shellEscapeChars($mysql->mysql_password);
        }
        exec("{$mysqladmin}{$serv} --user={$mysql->mysql_admin}{$password} processlist 2>&1", $mysqladmin_results);
        $mysqladmin_text = "Mysql ({$servtext}) processes report:\n---------------------------\n" . @implode("\n", $mysqladmin_results);
    }
    $text[] = "This is a report that provide system informations about a suspicous system load ({$internal_load})";
    $text[] = $lsof_text;
    $text[] = "Processes that consume CPU:";
    $text[] = "---------------------------";
    $text[] = @implode("\n", $psaux);
    $text[] = $iostat_text;
    $text[] = $mysqladmin_text;
    $textfinal = @implode("\n", $text);
    $subject = "System notification: Load exceed rule: [{$internal_load}]";
    if ($GLOBALS["VERBOSE"]) {
        echo "{$subject}\n{$textfinal}\n";
        return;
    }
    $unix->send_email_events($subject, $textfinal, "system");
}
예제 #16
0
function importActivedirectoryusers()
{
    $sock = new sockets();
    $EnableKerbAuth = $sock->GET_INFO("EnableKerbAuth");
    if (!is_numeric($EnableKerbAuth)) {
        $EnableKerbAuth = 0;
    }
    if ($EnableKerbAuth == 0) {
        return;
    }
    $unix = new unix();
    $user = new settings_inc();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $pidTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    $pid = $unix->get_pid_from_file($pidfile);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        WriteMyLogs("Process {$pid} already exists", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    if (system_is_overloaded(basename(__FILE__))) {
        WriteMyLogs("Overloaded system, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $TImeStamp = $unix->file_time_min($pidTime);
    if (!$GLOBALS["FORCE"]) {
        if ($TImeStamp < 20) {
            WriteMyLogs("Need 20mn, current={$TImeStamp}Mn executed by:{$GLOBALS["EXECUTOR"]} Params:{$GLOBALS["PARAMS"]}", __FUNCTION__, __FILE__, __LINE__);
            return;
        }
    }
    @unlink($pidTime);
    @file_put_contents($pidTime, time());
    $netbin = $unix->LOCATE_NET_BIN_PATH();
    $usermod = $unix->find_program("usermod");
    $chmod = $unix->find_program("chmod");
    if (!is_file($netbin)) {
        WriteMyLogs("net no such binary, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    if (is_dir("/var/run/samba/winbindd_privileged")) {
        shell_exec("{$usermod} -G winbindd_priv squid >/dev/null 2>&1");
        shell_exec("{$chmod} 0750 /var/run/samba/winbindd_privileged/ >/dev/null 2>&1");
    }
    $array = unserialize(base64_decode($sock->GET_INFO("KerbAuthInfos")));
    $domainUp = strtoupper($array["WINDOWS_DNS_SUFFIX"]);
    $domain_lower = strtolower($array["WINDOWS_DNS_SUFFIX"]);
    $adminpassword = $array["WINDOWS_SERVER_PASS"];
    $adminpassword = $unix->shellEscapeChars($adminpassword);
    $adminname = $array["WINDOWS_SERVER_ADMIN"];
    $ad_server = $array["WINDOWS_SERVER_NETBIOSNAME"];
    $GLOBALS["AUTHCMD"] = " -U {$adminname}%{$adminpassword}";
    getNetInfos();
    if (!isset($GLOBALS["LDAP_HOST"])) {
        WriteMyLogs("Unable to get ldap infos, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    GetUsersArray();
}
예제 #17
0
function RestoreFromBackup($backuppath)
{
    $unix = new unix();
    $PidRestore = "/etc/artica-postfix/pids/zarafaRestore.pid";
    $rm = $unix->find_program("rm");
    $pid = $unix->get_pid_from_file($PidRestore);
    if ($unix->process_exists($pid, basename(__FILE__))) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Restore Task Already running PID {$pid} since {$time}mn\n";
        }
        return;
    }
    $pid = $unix->PIDOF_PATTERN("exec.zarafa-db.php --restorefrom");
    if ($pid != getmypid()) {
        if ($unix->process_exists($pid)) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " [INIT]: Restore Task Already running PID {$pid} since {$time}mn\n";
            }
            return;
        }
    }
    $mysql = $unix->find_program("mysql");
    $pid = $unix->PIDOF_PATTERN("{$mysql}\\s+.*?--socket=/var/run/mysqld/zarafa-db.sock.*?database=zarafa");
    if ($unix->process_exists($pid)) {
        $time = $unix->PROCCESS_TIME_MIN($pid);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Restore Task Already running PID {$pid} since {$time}mn\n";
        }
        return;
    }
    @file_put_contents($PidRestore, getmypid());
    $sock = new sockets();
    $SourceDir = dirname($backuppath);
    $WORKDIR = $sock->GET_INFO("ZarafaDedicateMySQLWorkDir");
    if ($WORKDIR == null) {
        $WORKDIR = "/home/zarafa-db";
    }
    if (is_file("{$SourceDir}/ldap.ldif")) {
        RestoreFromBackup_progress("{restore_ldap_database}", 10);
        RestoreFromBackup_ldap("{$SourceDir}/ldap.ldif");
    }
    $unix = new unix();
    if (!is_file($backuppath)) {
        echo "Action: `{$backuppath}` no such file: ABORT!\n";
        RestoreFromBackup_progress("{failed}", 100);
        return;
    }
    echo "Action: Removing Zarafa Database MySQL client `{$mysql}`....\n";
    RestoreFromBackup_progress("Removing Zarafa Database", 30);
    $cmd = "{$mysql} --socket=/var/run/mysqld/zarafa-db.sock --protocol=socket --user=root --batch --debug-info --database=zarafa --execute=\"DROP DATABASE zarafa\" 2>&1";
    $results = array();
    exec("{$cmd}", $results);
    while (list($num, $ligne) = each($results)) {
        echo "MySQL: (Delete Database) {$ligne}\n";
    }
    RestoreFromBackup_progress("Removing all content", 32);
    if (is_dir("{$WORKDIR}/data/zarafa")) {
        recursive_remove_directory("{$WORKDIR}");
    }
    RestoreFromBackup_progress("Restarting MySQL service (recovery)", 40);
    echo "Action: Restarting MySQL service...\n";
    echo "Action: Stopping MySQL service...\n";
    stop(true);
    echo "Action: Starting MySQL service (InnoDB recovery mode)...\n";
    start(true, true);
    while (list($num, $ligne) = each($results)) {
        echo "Service: {$ligne}\n";
    }
    sleep(5);
    $ZARAFADB_PID = ZARAFADB_PID();
    if (!$unix->process_exists($ZARAFADB_PID)) {
        RestoreFromBackup_progress("Failed to restart dedicated MySQL", 100);
        return;
    }
    RestoreFromBackup_progress("Stopping Zarafa server", 43);
    @unlink("/tmp/zarafa-upgrade-lock");
    shell_exec("/etc/init.d/zarafa-server stop --force");
    $pid = XZARAFA_SERVER_PID();
    if ($unix->process_exists($pid)) {
        $kill = $unix->find_program("kill");
        unix_system_kill_force($pid);
    }
    RestoreFromBackup_progress("Restarting MySQL service (normal)", 45);
    echo "Action: Restarting MySQL service...\n";
    echo "Action: Stopping MySQL service...\n";
    stop(true);
    echo "Action: Starting MySQL service (InnoDB normal mode)...\n";
    start(true, false);
    while (list($num, $ligne) = each($results)) {
        echo "Service: {$ligne}\n";
    }
    sleep(2);
    $ZARAFADB_PID = ZARAFADB_PID();
    if (!$unix->process_exists($ZARAFADB_PID)) {
        RestoreFromBackup_progress("Failed to restart dedicated MySQL", 100);
        return;
    }
    if (!$unix->is_socket("/var/run/mysqld/zarafa-db.sock")) {
        echo "Action: /var/run/mysqld/zarafa-db.sock waiting socket\n";
        for ($i = 0; $i < 5; $i++) {
            if ($unix->is_socket("/var/run/mysqld/zarafa-db.sock")) {
                break;
            }
            echo "Action: Waiting zarafa-db.sock {$i}/4\n";
            sleep(1);
        }
    }
    if (!$unix->is_socket("/var/run/mysqld/zarafa-db.sock")) {
        echo "Action: /var/run/mysqld/zarafa-db.sock no such socket\n";
        RestoreFromBackup_progress("zarafa-db.sock no such socket", 100);
        return;
    }
    echo "Action: /var/run/mysqld/zarafa-db.sock OK\n";
    echo "Action: create a freshed Zarafa database\n";
    $ZarafaIndexPath = $sock->GET_INFO("ZarafaIndexPath");
    if ($ZarafaIndexPath == null) {
        $ZarafaIndexPath = "/var/lib/zarafa/index";
    }
    RestoreFromBackup_progress("Cleaning/Stopping Zarafa search DBs", 50);
    if (is_dir($ZarafaIndexPath)) {
        recursive_remove_directory("{$ZarafaIndexPath}");
        shell_exec("/etc/init.d/zarafa-search stop");
    }
    RestoreFromBackup_progress("Create a freshed Zarafa database", 50);
    $results = array();
    $cmd = "{$mysql} --socket=/var/run/mysqld/zarafa-db.sock --protocol=socket --user=root --batch --debug-info --execute=\"CREATE DATABASE zarafa\" 2>&1";
    $results = array();
    exec("{$cmd}", $results);
    while (list($num, $ligne) = each($results)) {
        echo "MySQL: (Create Database) {$ligne}\n";
    }
    RestoreFromBackup_progress("Testing Database...", 51);
    if (!is_dir("{$WORKDIR}/data/zarafa")) {
        echo "Action: FAILED TO create a freshed Zarafa database: ABORT!!\n";
        echo "Action: {$WORKDIR}/data/zarafa no such directory\n";
        RestoreFromBackup_progress("FAILED to create a freshed Zarafa database", 100);
        return;
    }
    RestoreFromBackup_progress("Checks Database size", 53);
    databasesize(true);
    $gunzip = $unix->find_program("gunzip");
    $SourceFileBase = basename($backuppath);
    $file_ext = $unix->file_ext($SourceFileBase);
    $tStart = time();
    $nohup = $unix->find_program("nohup");
    $backuppath1 = $unix->shellEscapeChars($backuppath);
    $cmd = "{$nohup} {$mysql} --show-warnings --socket=/var/run/mysqld/zarafa-db.sock --protocol=socket --user=root --batch --debug-info --database=zarafa < {$backuppath1} >/root/mysqllog.txt 2>&1 &";
    echo "Action: {$SourceFileBase} extension {$file_ext}\n";
    echo "Action: Restoring From {$backuppath1}\n";
    if ($file_ext == "gz") {
        echo "Action: Restoring From {$backuppath1} with uncompress..\n";
        $cmd = "{$nohup} {$gunzip} -c {$backuppath1} |{$mysql} --show-warnings --socket=/var/run/mysqld/zarafa-db.sock --protocol=socket --user=root --batch --debug-info --database=zarafa >/root/mysqllog.txt 2>&1 &";
    }
    $size = @filesize($backuppath);
    $size = FormatBytes($size / 1024);
    echo "Action: Please wait, it should take time...\nAction: Do not shutdown the computer or restart the MySQL service!\n";
    $results = array();
    RestoreFromBackup_progress("{restoring_data} {$size} {please_wait} !", 70);
    $lastmd5 = null;
    $continue = true;
    shell_exec($cmd);
    $ALRDLO = array();
    while ($continue) {
        $fileMD5 = @md5_file("/root/mysqllog.txt");
        if ($fileMD5 != $lastmd5) {
            $LOGS = explode("\n", @file_get_contents("/root/mysqllog.txt"));
            while (list($num, $ligne) = each($LOGS)) {
                if (trim($ligne) == null) {
                    continue;
                }
                if (isset($ALRDLO[md5($ligne)])) {
                    continue;
                }
                $ALRDLO[md5($ligne)] = true;
                if (preg_match("#ERROR\\s+([0-9]+)\\s+\\(#", $ligne, $re)) {
                    echo date("Y-m-d H:i:s") . " MySQL: FAILED !!! {$ligne}\n";
                    RestoreFromBackup_progress("{failed} {error} {$re[1]} ", 100);
                    return;
                }
                echo date("Y-m-d H:i:s") . " MySQL: {$ligne}\n";
            }
            $lastmd5 = $fileMD5;
        }
        $pid = $unix->PIDOF_PATTERN("{$mysql}\\s+.*?--socket=/var/run/mysqld/zarafa-db.sock.*?database=zarafa");
        echo "Action: PID: {$pid}\n";
        if (!$unix->process_exists($pid)) {
            echo "Action: injection stopped running since " . $unix->distanceOfTimeInWords($tStart, time(), true) . "\n";
            $continue = false;
            break;
        }
        echo "Action: PID {$pid} running since " . $unix->distanceOfTimeInWords($tStart, time(), true) . ", please wait...\n";
        RestoreFromBackup_progress($unix->distanceOfTimeInWords($tStart, time(), true) . " {please_wait} !", 71);
        $continue = true;
        sleep(30);
        continue;
    }
    echo "Action: Done, took: " . $unix->distanceOfTimeInWords($tStart, time(), true) . "\n";
    echo "Action: Please wait, Checks Database size\n";
    RestoreFromBackup_progress("Checks Database size", 75);
    databasesize(true);
    RestoreFromBackup_progress("{restoring_data} {success}", 80);
    echo "Action: restart_services\n";
    RestoreFromBackup_progress("{restart_services}", 90);
    $unix->THREAD_COMMAND_SET("/etc/init.d/zarafa-server restart");
    echo "Action: Restore task done...\n";
    echo "Action: You can close the windows now...\n";
    RestoreFromBackup_progress("{done}", 100);
    die;
}
예제 #18
0
function unix_file_size($path)
{
    $unix = new unix();
    if ($GLOBALS["stat"] == null) {
        $GLOBALS["stat"] = $unix->find_program("stat");
    }
    $path = $unix->shellEscapeChars($path);
    exec("{$GLOBALS["stat"]} {$path} ", $results);
    while (list($num, $line) = each($results)) {
        if (preg_match("#Size:\\s+([0-9]+)\\s+Blocks#", $line, $re)) {
            $res = $re[1];
            break;
        }
    }
    if (!is_numeric($res)) {
        $res = 0;
    }
    return $res;
}
예제 #19
0
function zarafadb_restore()
{
    $unix = new unix();
    $logfile = "/usr/share/artica-postfix/ressources/logs/web/zarafa_restore_task.log";
    $dir = base64_decode($_GET["zarafadb-restore"]);
    $nohup = $unix->find_program("nohup");
    $php = $unix->LOCATE_PHP5_BIN();
    $dir = $unix->shellEscapeChars($dir);
    $pid = $unix->PIDOF_PATTERN("exec.zarafa-db.php --restorefrom");
    if ($unix->process_exists($pid)) {
        return;
    }
    @unlink($logfile);
    @file_put_contents($logfile, "Please, wait, task will running...\n");
    @chmod("{$logfile}", 0775);
    $cmd = "{$nohup} {$php} /usr/share/artica-postfix/exec.zarafa-db.php --restorefrom {$dir} >>{$logfile} 2>&1 &";
    writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__);
    shell_exec($cmd);
}
예제 #20
0
function AddUnixUser()
{
    $unix = new unix();
    $user = $_GET["AddUnixUser"];
    writelogs_framework("Add unix user -> {$user}", __FUNCTION__, __FILE__, __LINE__);
    $password = base64_decode($_GET["password"]);
    $useradd = $unix->find_program("useradd");
    $echo = $unix->find_program("echo");
    $cmd = "{$useradd} \"{$user}\" 2>&1";
    writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__);
    exec($cmd, $results);
    $chpasswd = $unix->find_program("chpasswd");
    $password = $unix->shellEscapeChars($password);
    $cmd = "{$echo} \"{$user}:{$password}\" | {$chpasswd} 2>&1";
    writelogs_framework("{$cmd}", __FUNCTION__, __FILE__, __LINE__);
    exec($cmd, $results);
    echo "<articadatascgi>" . base64_encode(serialize($results)) . "</articadatascgi>";
}
예제 #21
0
function build()
{
    $sock = new sockets();
    $unix = new unix();
    $clamdscan = $unix->find_program("clamdscan");
    $FreshClamCheckDay = intval($sock->GET_INFO("FreshClamCheckDay"));
    $FreshClamMaxAttempts = intval($sock->GET_INFO("FreshClamMaxAttempts"));
    if ($FreshClamCheckDay == 0) {
        $FreshClamCheckDay = 16;
    }
    if ($FreshClamMaxAttempts == 0) {
        $FreshClamMaxAttempts = 16;
    }
    $ClamUser = $unix->ClamUser();
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} clamdscan = {$clamdscan}\n";
    }
    $f[] = "DatabaseOwner {$ClamUser}";
    $f[] = "UpdateLogFile /var/log/clamav/freshclam.log";
    $f[] = "LogVerbose false";
    $f[] = "LogSyslog true";
    $f[] = "LogFacility LOG_LOCAL6";
    $f[] = "LogFileMaxSize 0";
    $f[] = "LogTime true";
    $f[] = "Foreground false";
    $f[] = "Debug false";
    $f[] = "MaxAttempts {$FreshClamMaxAttempts}";
    $f[] = "DatabaseDirectory /var/lib/clamav";
    $f[] = "AllowSupplementaryGroups true";
    $f[] = "NotifyClamd /etc/clamav/clamd.conf";
    $f[] = "PidFile /var/run/clamav/freshclam.pid";
    $f[] = "ConnectTimeout 30";
    $f[] = "ReceiveTimeout 30";
    $f[] = "TestDatabases yes";
    $f[] = "ScriptedUpdates yes";
    $f[] = "CompressLocalDatabase no";
    $f[] = "Bytecode true";
    $f[] = "# Check for new database {$FreshClamCheckDay} times a day";
    $f[] = "Checks {$FreshClamCheckDay}";
    $f[] = "DNSDatabaseInfo current.cvd.clamav.net";
    $f[] = "DatabaseMirror db.local.clamav.net";
    $f[] = "DatabaseMirror database.clamav.net";
    $f[] = "OnUpdateExecute " . __FILE__ . " --updated";
    $HTTPProxyServer = $unix->GET_HTTP_PROXY_STRING();
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Proxy:{$HTTPProxyServer}\n";
    }
    if ($HTTPProxyServer != null) {
        if (preg_match("#\\/\\/(.+?):([0-9]+)#", $HTTPProxyServer, $re)) {
            $f[] = "HTTPProxyServer {$re[1]}";
            $f[] = "HTTPProxyPort {$re[2]}";
        } else {
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Proxy:{$HTTPProxyServer} no match\n";
            }
        }
    }
    @mkdir("/etc/clamav", 0755, true);
    $SecuriteInfoCode = $sock->GET_INFO("SecuriteInfoCode");
    $EnableClamavUnofficial = intval($sock->GET_INFO("EnableClamavUnofficial"));
    if ($SecuriteInfoCode != null) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Enabled: securiteinfo\n";
        }
        $f[] = "DatabaseCustomURL http://www.securiteinfo.com/get/signatures/{$SecuriteInfoCode}/securiteinfo.hdb";
        $f[] = "DatabaseCustomURL http://www.securiteinfo.com/get/signatures/{$SecuriteInfoCode}/securiteinfo.ign2";
        $f[] = "DatabaseCustomURL http://www.securiteinfo.com/get/signatures/{$SecuriteInfoCode}/javascript.ndb";
        $f[] = "DatabaseCustomURL http://www.securiteinfo.com/get/signatures/{$SecuriteInfoCode}/spam_marketing.ndb";
        $f[] = "DatabaseCustomURL http://www.securiteinfo.com/get/signatures/{$SecuriteInfoCode}/securiteinfohtml.hdb";
        $f[] = "DatabaseCustomURL http://www.securiteinfo.com/get/signatures/{$SecuriteInfoCode}/securiteinfoascii.hdb";
    }
    $f[] = "";
    $f[] = "";
    @file_put_contents("/etc/clamav/freshclam.conf", @implode("\n", $f));
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Unofficial databases:{$EnableClamavUnofficial}\n";
    }
    if ($EnableClamavUnofficial == 1) {
        if (!is_file("/etc/cron.d/clamav-unofficial-sigs-cron")) {
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Building /etc/cron.d/clamav-unofficial-sigs-cron\n";
            }
            $CRON[] = "MAILTO=\"\"";
            $CRON[] = "45 * * * * root /usr/share/artica-postfix/bin/clamav-unofficial-sigs.sh -c /etc/clamav-unofficial-sigs.conf >/dev/null 2>&1";
            $CRON[] = "";
            file_put_contents("/etc/cron.d/clamav-unofficial-sigs-cron", @implode("\n", $CRON));
            $CRON = array();
            chmod("/etc/cron.d/clamav-unofficial-sigs-cron", 0640);
            chown("/etc/cron.d/clamav-unofficial-sigs-cron", "root");
            system("/etc/init.d/cron reload");
        }
    } else {
        if (is_file("/etc/cron.d/clamav-unofficial-sigs-cron")) {
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Removing /etc/cron.d/clamav-unofficial-sigs-cron\n";
            }
            @unlink("/etc/cron.d/clamav-unofficial-sigs-cron");
            system("/etc/init.d/cron reload");
        }
    }
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} freshclam.conf done\n";
    }
    $unix = new unix();
    $sock = new sockets();
    $CurlProxy = null;
    $squidbin = $unix->LOCATE_SQUID_BIN();
    if (is_file($squidbin)) {
        $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
        if (!is_numeric($SQUIDEnable)) {
            $SQUIDEnable = 1;
        }
        if ($SQUIDEnable == 1) {
            $port = $unix->squid_internal_port();
            $CurlProxy = "-x 127.0.0.1:{$port}";
        }
    }
    if ($CurlProxy == null) {
        $ini = new Bs_IniHandler();
        $sock = new sockets();
        $datas = $sock->GET_INFO("ArticaProxySettings");
        if (trim($datas) != null) {
            $ini->loadString($datas);
            $ArticaProxyServerEnabled = $ini->_params["PROXY"]["ArticaProxyServerEnabled"];
            $ArticaProxyServerName = $ini->_params["PROXY"]["ArticaProxyServerName"];
            $ArticaProxyServerPort = $ini->_params["PROXY"]["ArticaProxyServerPort"];
            $ArticaProxyServerUsername = trim($ini->_params["PROXY"]["ArticaProxyServerUsername"]);
            $ArticaProxyServerUserPassword = $ini->_params["PROXY"]["ArticaProxyServerUserPassword"];
            if ($ArticaProxyServerEnabled == 1) {
                $ArticaProxyServerEnabled = "yes";
            }
        }
        if ($ArticaProxyServerEnabled == "yes") {
            $CurlProxy = "-x {$ArticaProxyServerName}:{$ArticaProxyServerPort}";
            if ($ArticaProxyServerUsername != null) {
                $ArticaProxyServerUserPassword = $unix->shellEscapeChars($ArticaProxyServerUserPassword);
                $CurlProxy = $CurlProxy . " -U {$ArticaProxyServerUsername}:{$ArticaProxyServerUserPassword}";
            }
        }
    }
    @mkdir("/var/log/clamav-unofficial-sigs", 0755, true);
    @chmod("/usr/share/artica-postfix/exec.freshclam.updated.php", 0755);
    @chmod("/usr/share/artica-postfix/exec.freshclam.sansecurity.updated.php", 0755);
    @chmod("/usr/share/artica-postfix/bin/clamav-unofficial-sigs.sh", 0755);
    $SecuriteInfoCode = $sock->GET_INFO("SecuriteInfoCode");
    $MalwarePatrolCode = $sock->GET_INFO("MalwarePatrolCode");
    $f = array();
    $f[] = "# This file contains user configuration settings for clamav-unofficial-sigs.sh";
    $f[] = "###################";
    $f[] = "# This is property of eXtremeSHOK.com";
    $f[] = "# You are free to use, modify and distribute, however you may not remove this notice.";
    $f[] = "# Copyright (c) Adrian Jon Kriel :: admin@extremeshok.com";
    $f[] = "##################";
    $f[] = "#";
    $f[] = "# Script updates can be found at: https://github.com/extremeshok/clamav-unofficial-sigs";
    $f[] = "# ";
    $f[] = "# Originially based on: ";
    $f[] = "# Script provide by Bill Landry (unofficialsigs@gmail.com).";
    $f[] = "#";
    $f[] = "# License: BSD (Berkeley Software Distribution)";
    $f[] = "#";
    $f[] = "##################";
    $f[] = "#";
    $f[] = "# NOT COMPATIBLE WITH VERSION 3.XX CONFIG ";
    $f[] = "#";
    $f[] = "################################################################################";
    $f[] = "";
    $f[] = "# Edit the quoted variables below to meet your own particular needs";
    $f[] = "# and requirements, but do not remove the \"quote\" marks.";
    $f[] = "";
    $f[] = "# Set the appropriate ClamD user and group accounts for your system.";
    $f[] = "# If you do not want the script to set user and group permissions on";
    $f[] = "# files and directories, comment the next two variables.";
    $f[] = "clam_user=\"{$ClamUser}\"";
    $f[] = "clam_group=\"{$ClamUser}\"";
    $f[] = "clam_dbs=\"/var/lib/clamav\"";
    $f[] = "clamd_pid=\"/var/run/clamav/clamd.pid\"";
    $f[] = "#reload_dbs=\"yes\"";
    $f[] = "#reload_opt=\"{$clamdscan} --reload\"  # Default";
    $f[] = "# owner: read, write";
    $f[] = "# group: read";
    $f[] = "# world: read";
    $f[] = "#";
    $f[] = "# as defined in the \"clam_dbs\" path variable below, then set the following";
    $f[] = "# \"setmode\" variable to \"no\".";
    $f[] = "setmode=\"yes\"";
    $f[] = "";
    $f[] = "# Set path to ClamAV database files location.  If unsure, check";
    $f[] = "# your clamd.conf file for the \"DatabaseDirectory\" path setting.";
    $f[] = "clam_dbs=\"/var/lib/clamav\"";
    $f[] = "";
    $f[] = "# Set path to clamd.pid file (see clamd.conf for path location).";
    $f[] = "clamd_pid=\"/var/run/clamav/clamd.pid\"";
    $f[] = "#clamd_pid=\"/var/run/clamd.pid\"";
    $f[] = "";
    $f[] = "# To enable \"ham\" (non-spam) directory scanning and removal of";
    $f[] = "# signatures that trigger on ham messages, uncomment the following";
    $f[] = "# variable and set it to the appropriate ham message directory.";
    $f[] = "#ham_dir=\"/var/lib/clamav-unofficial-sigs/ham-test\"";
    $f[] = "";
    $f[] = "# If you would like to reload the clamd databases after an update,";
    $f[] = "# change the following variable to \"yes\".";
    $f[] = "reload_dbs=\"yes\"";
    $f[] = "";
    $f[] = "# Top level working directory, script will attempt to create them.";
    $f[] = "work_dir=\"/var/lib/clamav-unofficial-sigs\"   #Top level working directory";
    $f[] = "";
    $f[] = "# Log update information to '\$log_file_path/\$log_file_name'.";
    $f[] = "enable_logging=\"yes\"";
    $f[] = "log_file_path=\"/var/log/clamav-unofficial-sigs\"";
    $f[] = "log_file_name=\"clamav-unofficial-sigs.log\"";
    $f[] = "";
    $f[] = "";
    $f[] = "# =========================";
    $f[] = "# MalwarePatrol : https://www.malwarepatrol.net";
    $f[] = "# MalwarePatrol 2015 free clamav signatures";
    $f[] = "#";
    $f[] = "# 1. Sign up for a free account : https://www.malwarepatrol.net/signup-free.shtml";
    $f[] = "# 2. You will recieve an email containing your password/receipt number";
    $f[] = "# 3. Enter the receipt number into the config: replacing YOUR-RECEIPT-NUMBER with your receipt number from the email";
    $f[] = "";
    $f[] = "malwarepatrol_receipt_code=\"{$MalwarePatrolCode}\"";
    $f[] = "# Set to no to enable the commercial subscription url.";
    $f[] = "malwarepatrol_free=\"yes\"";
    $f[] = "";
    $f[] = "# =========================";
    $f[] = "# SecuriteInfo : https://www.SecuriteInfo.com";
    $f[] = "# SecuriteInfo 2015 free clamav signatures";
    $f[] = "#";
    $f[] = "#Usage of SecuriteInfo 2015 free clamav signatures : https://www.securiteinfo.com";
    $f[] = "# - 1. Sign up for a free account : https://www.securiteinfo.com/clients/customers/signup";
    $f[] = "# - 2. You will recieve an email to activate your account and then a followup email with your login name";
    $f[] = "# - 3. Login and navigate to your customer account : https://www.securiteinfo.com/clients/customers/account";
    $f[] = "# - 4. Click on the Setup tab";
    $f[] = "# - 5. You will need to get your unique identifier from one of the download links, they are individual for every user";
    $f[] = "# - 5.1. The 128 character string is after the http://www.securiteinfo.com/get/signatures/ ";
    $f[] = "# - 5.2. Example https://www.securiteinfo.com/get/signatures/your_unique_and_very_long_random_string_of_characters/securiteinfo.hdb";
    $f[] = "#   Your 128 character authorisation signature would be : your_unique_and_very_long_random_string_of_characters";
    $f[] = "# - 6. Enter the authorisation signature into the config securiteinfo_authorisation_signature: replacing YOUR-SIGNATURE-NUMBER with your authorisation signature from the link";
    $f[] = "";
    $f[] = "securiteinfo_authorisation_signature=\"{$SecuriteInfoCode}\"";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# Database provider update time";
    $f[] = "# ========================";
    $f[] = "# Since the database files are dynamically created, non default values can cause banning, change with caution";
    $f[] = "";
    $f[] = "securiteinfo_update_hours=\"4\"   # Default is 4 hours (6 downloads daily).";
    $f[] = "linuxmalwaredetect_update_hours=\"6\"   # Default is 6 hours (4 downloads daily).";
    $f[] = "malwarepatrol_update_hours=\"24\"   # Default is 24 hours (1 downloads daily).";
    $f[] = "yararules_update_hours=\"24\"   # Default is 24 hours (1 downloads daily).";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# Enabled Databases";
    $f[] = "# ========================";
    $f[] = "# Set to no to disable an entire database.";
    if ($SecuriteInfoCode != null) {
        $f[] = "securiteinfo_enabled=\"yes\"   # SecuriteInfo ";
    } else {
        $f[] = "securiteinfo_enabled=\"no\"   # SecuriteInfo ";
    }
    $f[] = "sanesecurity_enabled=\"yes\"   # Sanesecurity";
    $f[] = "linuxmalwaredetect_enabled=\"yes\"   # Linux Malware Detect";
    if ($MalwarePatrolCode != null) {
        $f[] = "malwarepatrol_enabled=\"yes\"   # Malware Patrol";
    } else {
        $f[] = "malwarepatrol_enabled=\"no\"   # Malware Patrol";
    }
    $f[] = "yararules_enabled=\"no\"   # Yara-Rule Project, requires clamAV 0.99+";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# Sanesecurity Database(s)";
    $f[] = "# ========================";
    $f[] = "# Add or remove database file names between quote marks as needed.  To";
    $f[] = "# disable usage of any of the Sanesecurity distributed database files";
    $f[] = "# shown, remove the database file name from the quoted section below.";
    $f[] = "# Only databases defined as \"low\" risk have been enabled by default ";
    $f[] = "# for additional information about the database ratings, see: ";
    $f[] = "# http://www.sanesecurity.com/clamav/databases.htm";
    $f[] = "# Only add signature databases here that are \"distributed\" by Sanesecuirty";
    $f[] = "# as defined at the URL shown above.  Database distributed by others sources";
    $f[] = "# (e.g., SecuriteInfo & MalewarePatrol, can be added to other sections of";
    $f[] = "# this config file below).  Finally, make sure that the database names are";
    $f[] = "# spelled correctly or you will experience issues when the script runs";
    $f[] = "# (hint: all rsync servers will fail to download signature updates).";
    $f[] = "";
    $f[] = "sanesecurity_dbs=\" # BEGIN SANESECURITY DATABASE";
    $f[] = "### SANESECURITY http://sanesecurity.com/usage/signatures/";
    $f[] = "## REQUIRED, Do NOT disable";
    $f[] = "sanesecurity.ftm  #REQUIRED Message file types, for best performance";
    $f[] = "sigwhitelist.ign2 #REQUIRED Fast update file to whitelist any problem signatures";
    $f[] = "## LOW";
    $f[] = "junk.ndb  #LOW  General high hitting junk, containing spam/phishing/lottery/jobs/419s etc ";
    $f[] = "jurlbl.ndb #LOW Junk Url based";
    $f[] = "phish.ndb #LOW Phishing";
    $f[] = "rogue.hdb  #LOW Malware, Rogue anti-virus software and Fake codecs etc.  Updated hourly to cover the latest malware threats  ";
    $f[] = "scam.ndb #LOW Spam/scams  ";
    $f[] = "spamimg.hdb #LOW Spam images ";
    $f[] = "spamattach.hdb #LOW Spam Spammed attachments such as pdf/doc/rtf/zip ";
    $f[] = "blurl.ndb  #LOW Blacklisted full urls over the last 7 days, covering malware/spam/phishing. URLs added only when main signatures have failed to detect but are known to be \"bad\"  ";
    $f[] = "## MED";
    $f[] = "spear.ndb  #MED Spear phishing email addresses (autogenerated from data here)";
    $f[] = "lott.ndb  #MED Lottery  ";
    $f[] = "spam.ldb  #MED Spam detected using the new Logical Signature type";
    $f[] = "spearl.ndb  #MED Spear phishing urls (autogenerated from data here)   ";
    $f[] = "jurlbla.ndb #MED Junk Url based autogenerated from various feeds";
    $f[] = "badmacro.ndb #MED Detect dangerous macros";
    $f[] = "";
    $f[] = "### FOXHOLE http://sanesecurity.com/foxhole-databases/";
    $f[] = "## LOW";
    $f[] = "malwarehash.hsb  #LOW Malware hashes without known Size";
    $f[] = "## MED";
    $f[] = "#foxhole_generic.cdb #MED See Foxhole page for more details";
    $f[] = "#foxhole_filename.cdb #MED See Foxhole page for more details";
    $f[] = "## HIGH";
    $f[] = "#foxhole_all.cdb  #HIGH See Foxhole page for more details  ";
    $f[] = "";
    $f[] = "### OITC http://www.oitc.com/winnow/clamsigs/index.html";
    $f[] = "### Note: the two databases winnow_phish_complete.ndb and winnow_phish_complete_url.ndb should NOT be used together.  ";
    $f[] = "# LOW";
    $f[] = "winnow.attachments.hdb  #LOW Spammed attachments such as pdf/doc/rtf/zip";
    $f[] = "winnow_malware.hdb  #LOW Current virus, trojan and other malware not yet detected by ClamAV.";
    $f[] = "winnow_malware_links.ndb #LOW Links to malware";
    $f[] = "winnow_extended_malware.hdb  #LOW contain hand generated signatures for malware ";
    $f[] = "winnow_bad_cw.hdb #LOW md5 hashes of malware attachments acquired directly from a group of botnets";
    $f[] = "# MED";
    $f[] = "#winnow_phish_complete_url.ndb #Med Similar to winnow_phish_complete.ndb except that entire urls are used  ";
    $f[] = "#winnow.complex.patterns.ldb  #MED contain hand generated signatures for malware and some egregious fraud  ";
    $f[] = "#winnow_extended_malware_links.ndb #MED contain hand generated signatures for malware links ";
    $f[] = "#winnow_spam_complete.ndb  #MED Signatures to detect fraud and other malicious spam";
    $f[] = "# HIGH";
    $f[] = "#winnow_phish_complete.ndb #HIGH Phishing and other malicious urls and compromised hosts **DO NOT USE WITH winnow_phish_complete_url**";
    $f[] = "";
    $f[] = "### SCAMNAILER http://www.scamnailer.info/";
    $f[] = "# MED";
    $f[] = "#scamnailer.ndb  #MED Spear phishing and other phishing emails";
    $f[] = "";
    $f[] = "### BOFHLAND http://clamav.bofhland.org/";
    $f[] = "# LOW";
    $f[] = "bofhland_cracked_URL.ndb  #LOW Spam URLs  ";
    $f[] = "bofhland_malware_URL.ndb  #LOW Malware URLs ";
    $f[] = "bofhland_phishing_URL.ndb #LOW Phishing URLs";
    $f[] = "bofhland_malware_attach.hdb #LOW Malware Hashes";
    $f[] = "";
    $f[] = "###  RockSecurity http://rooksecurity.com/";
    $f[] = "#LOW";
    $f[] = "hackingteam.hsb #LOW Hacking Team hashes";
    $f[] = "";
    $f[] = "### CRDF https://threatcenter.crdf.fr/";
    $f[] = "# LOW";
    $f[] = "crdfam.clamav.hdb #LOW List of new threats detected by CRDF Anti Malware  ";
    $f[] = "";
    $f[] = "### Porcupine";
    $f[] = "# LOW";
    $f[] = "porcupine.ndb  #LOW Brazilian e-mail phishing and malware signatures ";
    $f[] = "phishtank.ndb  #LOW Online and valid phishing urls from phishtank.com data feed ";
    $f[] = "";
    $f[] = "### Sanesecurity YARA Format rules";
    $f[] = "### Note: Yara signatures require ClamAV 0.99 or newer to work";
    $f[] = "#Sanesecurity_sigtest.yara #LOW Sanesecurity test signatures ";
    $f[] = "#Sanesecurity_spam.yara #LOW detect spam ";
    $f[] = "";
    $f[] = "\" # END SANESECURITY DATABASES";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# SecuriteInfo Database(s)";
    $f[] = "# ========================";
    $f[] = "# Only active when you set your securiteinfo_authorisation_signature";
    $f[] = "# Add or remove database file names between quote marks as needed.  To";
    $f[] = "# disable any SecuriteInfo database downloads, remove the appropriate";
    $f[] = "# lines below.";
    $f[] = "securiteinfo_dbs=\"";
    $f[] = "### Securiteinfo https://www.securiteinfo.com/services/improve-detection-rate-of-zero-day-malwares-for-clamav.shtml";
    $f[] = "## REQUIRED, Do NOT disable";
    $f[] = "securiteinfo.ign2";
    $f[] = "# LOW";
    $f[] = "securiteinfo.hdb #LOW Malwares in the Wild";
    $f[] = "javascript.ndb  #LOW Malwares Javascript ";
    $f[] = "securiteinfohtml.hdb  #LOW Malwares HTML ";
    $f[] = "securiteinfoascii.hdb  #LOW Text file malwares (Perl or shell scripts, bat files, exploits, ...)";
    $f[] = "securiteinfopdf.hdb #LOW Malwares PDF ";
    $f[] = "# HIGH";
    $f[] = "#spam_marketing.ndb #HIGH Spam Marketing /  spammer blacklist";
    $f[] = "\" #END SECURITEINFO DATABASES";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# Linux Malware Detect Database(s)";
    $f[] = "# ========================";
    $f[] = "# Add or remove database file names between quote marks as needed.  To";
    $f[] = "# disable any SecuriteInfo database downloads, remove the appropriate";
    $f[] = "# lines below.";
    $f[] = "linuxmalwaredetect_dbs=\"";
    $f[] = "### Linux Malware Detect https://www.rfxn.com/projects/linux-malware-detect/";
    $f[] = "# LOW";
    $f[] = "rfxn.ndb #LOW HEX Malware detection signatures";
    $f[] = "rfxn.hdb  #LOW MD5 malware detection signatures";
    $f[] = "\" #END LINUXMALWAREDETECT DATABASES";
    $f[] = "";
    $f[] = "# =========================";
    $f[] = "# MalwarePatrol Database ";
    $f[] = "# =========================";
    $f[] = "# Only active when you set your malwarepatrol_receipt_code";
    $f[] = "## REQUIRED, Do NOT disable";
    $f[] = "malwarepatrol_db=\"malwarepatrol.db\" #LOW URLs containing of Viruses, Trojans, Worms, or Malware  ";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# Yara Rules Project Database(s)";
    $f[] = "# ========================";
    $f[] = "# Add or remove database file names between quote marks as needed.  To";
    $f[] = "# disable any Yara Rule database downloads, remove the appropriate";
    $f[] = "# lines below.";
    $f[] = "yararules_dbs=\"";
    $f[] = "### Yara Rules https://github.com/Yara-Rules/rules";
    $f[] = "# LOW";
    $f[] = "antidebug.yar #LOW anti debug and anti virtualization techniques used by malware ";
    $f[] = "malicious_document.yar #LOW documents with malicious code";
    $f[] = "# MED";
    $f[] = "#packer.yar #MED well-known sofware packers";
    $f[] = "# HIGH";
    $f[] = "#crypto.yar #HIGH detect the existence of cryptographic algoritms";
    $f[] = "\" #END YARARULES DATABASES";
    $f[] = "";
    $f[] = "";
    $f[] = "# =========================";
    $f[] = "# Additional signature databases";
    $f[] = "# =========================";
    $f[] = "# Additional signature databases can be specified here in the following";
    $f[] = "# format: PROTOCOL://URL-or-IP/PATH/TO/FILE-NAME (use a trailing \"/\" in";
    $f[] = "# place of the \"FILE-NAME\" to download all files from specified location,";
    $f[] = "# but this *ONLY* works for files downloaded via rsync).  For non-rsync";
    $f[] = "# downloads, curl is used.  For download protocols supported by curl, see";
    $f[] = "# \"man curl\".  This also works well for locations that have many ClamAV";
    $f[] = "# servers that use 3rd party signature databases, as only one server need";
    $f[] = "# download the remote databases, and all others can update from the local";
    $f[] = "# mirrors copy.  See format examples below.  To use, remove the comments";
    $f[] = "# and examples shown and add your own sites between the quote marks.";
    $f[] = "#add_dbs=\"";
    $f[] = "#   rsync://192.168.1.50/new-db/sigs.hdb";
    $f[] = "#   rsync://rsync.example.com/all-dbs/";
    $f[] = "#   ftp://ftp.example.net/pub/sigs.ndb";
    $f[] = "#   http://www.example.org/sigs.ldb";
    $f[] = "#\" #END ADDITIONAL DATABASES";
    $f[] = "";
    $f[] = "";
    $f[] = "";
    $f[] = "";
    $f[] = "# ==================================================";
    $f[] = "# ==================================================";
    $f[] = "# A D V A N C E D   O P T I O N S";
    $f[] = "# ==================================================";
    $f[] = "# ==================================================";
    $f[] = "";
    $f[] = "# Enable or disable download time randomization.  This allows the script to";
    $f[] = "# be executed via cron, but the actual database file checking will pause";
    $f[] = "# for a random number of seconds between the \"min\" and \"max\" time settings";
    $f[] = "# specified below.  This helps to more evenly distribute load on the host";
    $f[] = "# download sites.  To disable, set the following variable to \"no\".";
    $f[] = "enable_random=\"yes\"";
    $f[] = "";
    $f[] = "# If download time randomization is enabled above (enable_random=\"yes\"),";
    $f[] = "# then set the min and max radomization time intervals (in seconds).";
    $f[] = "min_sleep_time=\"60\"    # Default minimum is 60 seconds (1 minute).";
    $f[] = "max_sleep_time=\"600\"   # Default maximum is 600 seconds (10 minutes).";
    $f[] = "";
    $f[] = "# Set the clamd_restart_opt if the \"reload_dbs\" variable above is set";
    $f[] = "# Command to do a full clamd service stop/start";
    $f[] = "clamd_restart_opt=\"/etc/init.d/clamd restart\"";
    $f[] = "";
    $f[] = "# If running clamd in \"LocalSocket\" mode (*NOT* in TCP/IP mode), and";
    $f[] = "# either \"SOcket Cat\" (socat) or the \"IO::Socket::UNIX\" perl module";
    $f[] = "# are installed on the system, and you want to report whether clamd";
    $f[] = "# is running or not, uncomment the \"clamd_socket\" variable below (you";
    $f[] = "# will be warned if neither socat nor IO::Socket::UNIX are found, but";
    $f[] = "# the script will still run).  You will also need to set the correct";
    $f[] = "# path to your clamd socket file (if unsure of the path, check the";
    $f[] = "# \"LocalSocket\" setting in your clamd.conf file for socket location).";
    $f[] = "#clamd_socket=\"/tmp/clamd.socket\"";
    $f[] = "#clamd_socket=\"/var/run/clamd.socket\"";
    $f[] = "";
    $f[] = "# If you would like to attempt to restart ClamD if detected not running,";
    $f[] = "# uncomment the next 2 lines.  Enter the clamd service stop and  start command";
    $f[] = "# for your particular distro for the \"start_clamd\" \"stop_clamd\" variables";
    $f[] = "# (the sample start command shown below should work for most linux distros).";
    $f[] = "# NOTE: these 2 variables are dependant on the \"clamd_socket\" variable";
    $f[] = "# shown above - if not enabled, then the following 2 variables will be";
    $f[] = "# ignored, whether enabled or not.";
    $f[] = "#clamd_start=\"service clamd start\"";
    $f[] = "#clamd_stop=\"service clamd stop\"";
    $f[] = "";
    $f[] = "# Set rsync connection and data transfer timeout limits in seconds.";
    $f[] = "# The defaults settings here are reasonable, only change if you are";
    $f[] = "# experiencing timeout issues.";
    $f[] = "rsync_connect_timeout=\"30\"";
    $f[] = "rsync_max_time=\"90\"";
    $f[] = "";
    $f[] = "# Set curl connection and data transfer timeout limits in seconds.";
    $f[] = "# The defaults settings here are reasonable, only change if you are";
    $f[] = "# experiencing timeout issues.";
    $f[] = "curl_connect_timeout=\"30\"";
    $f[] = "curl_max_time=\"90\"";
    $f[] = "";
    $f[] = "# Set working directory paths (edit to meet your own needs). If these";
    $f[] = "# directories do not exist, the script will attempt to create them.";
    $f[] = "# Sub-directory names:";
    $f[] = "sanesecurity_dir=\"\$work_dir/dbs-ss\"        # Sanesecurity sub-directory";
    $f[] = "securiteinfo_dir=\"\$work_dir/dbs-si\"        # SecuriteInfo sub-directory ";
    $f[] = "linuxmalwaredetect_dir=\"\$work_dir/dbs-lmd\"      # Linux Malware Detect sub-directory ";
    $f[] = "malwarepatrol_dir=\"\$work_dir/dbs-mbl\"      # MalwarePatrol sub-directory ";
    $f[] = "yararules_dir=\"\$work_dir/dbs-yara\"      # Yara-Rules sub-directory ";
    $f[] = "config_dir=\"\$work_dir/configs\"   # Script configs sub-directory";
    $f[] = "gpg_dir=\"\$work_dir/gpg-key\"      # Sanesecurity GPG Key sub-directory";
    $f[] = "add_dir=\"\$work_dir/dbs-add\"      # User defined databases sub-directory";
    $f[] = "";
    $f[] = "# If you would like to make a backup copy of the current running database";
    $f[] = "# file before updating, leave the following variable set to \"yes\" and a";
    $f[] = "# backup copy of the file will be created in the production directory";
    $f[] = "# with -bak appended to the file name.";
    $f[] = "keep_db_backup=\"no\"";
    $f[] = "";
    $f[] = "# If you want to silence the information reported by curl, rsync, gpg";
    $f[] = "# or the general script comments, change the following variables to";
    $f[] = "# \"yes\".  If all variables are set to \"yes\", the script will output";
    $f[] = "# nothing except error conditions.";
    $f[] = "silence_ssl=\"yes\" # Default is \"yes\" ignore ssl errors and warnings";
    $f[] = "curl_silence=\"no\"      # Default is \"no\" to report curl statistics";
    $f[] = "rsync_silence=\"no\"     # Default is \"no\" to report rsync statistics";
    $f[] = "gpg_silence=\"no\"       # Default is \"no\" to report gpg signature status";
    $f[] = "comment_silence=\"no\"   # Default is \"no\" to report script comments";
    $f[] = "";
    $f[] = "# If necessary to proxy database downloads, define the rsync and/or curl";
    $f[] = "# proxy settings here.  For rsync, the proxy must support connections to";
    $f[] = "# port 873.  Both curl and rsync proxy setting need to be defined in the";
    $f[] = "# format of \"hostname:port\".  For curl, also note the -x and -U flags,";
    $f[] = "# which must be set as \"-x hostname:port\" and \"-U username:password\".";
    $f[] = "rsync_proxy=\"\"";
    $f[] = "curl_proxy=\"{$CurlProxy}\"";
    $f[] = "user_configuration_complete=\"yes\"";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# Database provider URLs, do not edit.";
    $f[] = "sanesecurity_url=\"rsync.sanesecurity.net\"";
    $f[] = "sanesecurity_gpg_url=\"http://www.sanesecurity.net/publickey.gpg\"";
    $f[] = "securiteinfo_url=\"https://www.securiteinfo.com/get/signatures/\"";
    $f[] = "linuxmalwaredetect_url=\"http://cdn.rfxn.com/downloads/\"";
    $f[] = "malwarepatrol_free_url=\"https://lists.malwarepatrol.net/cgi/getfile?product=8&list=clamav_basic\"";
    $f[] = "malwarepatrol_subscription_url=\"https://lists.malwarepatrol.net/cgi/getfile?product=15&list=clamav_basic\"";
    $f[] = "yararules_url=\"https://raw.githubusercontent.com/Yara-Rules/rules/master/\"";
    $f[] = "";
    $f[] = "# ========================";
    $f[] = "# do not edit";
    $f[] = "config_version=\"53\"";
    $f[] = "";
    @file_put_contents("/etc/clamav-unofficial-sigs.conf", @implode("\n", $f));
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} clamav-unofficial-sigs.conf done\n";
    }
    $f = array();
}
function CopyToFrom($orgdir, $destdir)
{
    $orgdir = trim($orgdir);
    $destdir = trim($destdir);
    if ($orgdir == null) {
        echo "CopyToFrom: Orginal dir is null\n";
        return false;
    }
    if ($destdir == null) {
        echo "CopyToFrom: Destdir dir is null\n";
        return false;
    }
    $unix = new unix();
    $cp = $unix->find_program("cp");
    $orgdir = $unix->shellEscapeChars($orgdir);
    $destdir = $unix->shellEscapeChars($destdir);
    exec("{$cp} -rfp {$orgdir}/* {$destdir}/ 2>&1", $results);
    while (list($a, $b) = each($results)) {
        if (preg_match("#(No space|failed to|error|missing)#i", $b)) {
            echo $b;
            return false;
        }
    }
    return true;
}
예제 #23
0
파일: cmd.php 프로젝트: brucewu16899/artica
function shellEscapeChars($path)
{
    $unix = new unix();
    return $unix->shellEscapeChars($path);
}
예제 #24
0
function SERVICE_STOP($aspid = false)
{
    $unix = new unix();
    $sock = new sockets();
    $socket = "/var/run/mysqld/mysqld.sock";
    $mysqlbin = $unix->LOCATE_mysqld_bin();
    $php5 = $unix->LOCATE_PHP5_BIN();
    $nohup = $unix->find_program("nohup");
    $mysqladmin = $unix->find_program("mysqladmin");
    $kill = $unix->find_program("kill");
    $pgrep = $unix->find_program("pgrep");
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pid = @file_get_contents($pidfile);
    $kill = $unix->find_program("kill");
    if (!$aspid) {
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            echo "Stopping MySQL...............: This script is already executed PID: {$pid} since {$time}Mn\n";
            if ($time < 5) {
                if (!$GLOBALS["FORCE"]) {
                    return;
                }
            }
            unix_system_kill_force($pid);
        }
        @file_put_contents($pidfile, getmypid());
    }
    $pid = PID_NUM();
    if ($GLOBALS["VERBOSE"]) {
        echo "DEBUG:: PID RETURNED {$pid}\n";
    }
    $unix->ToSyslog("MySQL: Stopping MySQL server");
    if (!$unix->process_exists($pid, $mysqlbin)) {
        echo "Stopping MySQL...............: Already stopped\n";
        return;
    }
    $q = new mysql();
    $q2 = new mysql_squid_builder();
    $q2->MEMORY_TABLES_DUMP();
    if (is_file($mysqladmin)) {
        if (is_file($socket)) {
            $cmds[] = "nohup";
            $cmds[] = $mysqladmin;
            $cmds[] = "--user={$q->mysql_admin}";
            if ($q->mysql_password != null) {
                $password = $q->mysql_password;
                $password = $unix->shellEscapeChars($password);
                $cmds[] = "--password={$password}";
            }
            $cmds[] = "--socket={$socket}";
            $cmds[] = "shutdown";
            $cmd = @implode(" ", $cmds);
            $cmd = $cmd . " >/dev/null 2>&1 &";
            echo "Stopping MySQL...............: Stopping smoothly mysqld pid:{$pid}\n";
            if ($GLOBALS["VERBOSE"]) {
                echo "[VERBOSE]: {$cmd}\n";
            }
            for ($i = 0; $i < 10; $i++) {
                sleep(1);
                $pid = PID_NUM();
                if (!$unix->process_exists($pid, $mysqlbin)) {
                    break;
                }
                echo "Stopping MySQL...............: Stopping, please wait {$i}/10\n";
            }
        }
    }
    $pid = PID_NUM();
    if (!$unix->process_exists($pid, $mysqlbin)) {
        echo "Stopping MySQL...............: Stopped\n";
        system_admin_events("Success to STOP MySQL server", __FUNCTION__, __FILE__, __LINE__, "services");
        return;
    }
    mysql_admin_mysql(0, "Stopping MySQL service PID {$pid}", null, __FILE__, __LINE__);
    echo "Stopping MySQL...............: killing smoothly PID {$pid}\n";
    unix_system_kill($pid);
    for ($i = 0; $i < 5; $i++) {
        sleep(1);
        $pid = PID_NUM();
        if (!$unix->process_exists($pid, $mysqlbin)) {
            break;
        }
    }
    if (!$unix->process_exists($pid, $mysqlbin)) {
        echo "Stopping MySQL...............: Stopped\n";
        system_admin_events("Success to STOP MySQL server", __FUNCTION__, __FILE__, __LINE__, "services");
        return;
    }
    echo "Stopping MySQL...............: Force killing PID {$pid}\n";
    unix_system_kill_force($pid);
    for ($i = 0; $i < 5; $i++) {
        sleep(1);
        $pid = PID_NUM();
        if (!$unix->process_exists($pid, $mysqlbin)) {
            break;
        }
    }
    if (!$unix->process_exists($pid, $mysqlbin)) {
        echo "Stopping MySQL...............: Stopped\n";
        system_admin_events("Success to STOP MySQL server", __FUNCTION__, __FILE__, __LINE__, "services");
        return;
    }
    echo "Stopping MySQL...............: failed\n";
}
예제 #25
0
function DeleteRules($aspid = false)
{
    $unix = new unix();
    $sock = new sockets();
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    if (!$aspid) {
        $TimeExec = $unix->file_time_min($pidtime);
        if ($TimeExec < 240) {
            return;
        }
    }
    @unlink($pidtime);
    @file_put_contents($pidtime, time());
    if (!isset($GLOBALS["HyperCacheStoragePath"])) {
        $GLOBALS["HyperCacheStoragePath"] = $sock->GET_INFO("HyperCacheStoragePath");
        if ($GLOBALS["HyperCacheStoragePath"] == null) {
            $GLOBALS["HyperCacheStoragePath"] = "/home/artica/proxy-cache";
        }
    }
    $rm = $unix->find_program("rm");
    $q = new mysql_squid_builder();
    $RootPath = $GLOBALS["HyperCacheStoragePath"];
    $results = $q->QUERY_SQL("SELECT * FROM artica_caches_mirror WHERE ToDelete=1");
    while ($ligne = mysql_fetch_assoc($results)) {
        $ID = $ligne["ID"];
        $Directory = $unix->shellEscapeChars("{$RootPath}/mirror/{$ligne["sitename"]}");
        if (is_dir($Directory)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Remove {$Directory}\n";
            }
            shell_exec("{$rm} -rf {$Directory}");
        }
        $q->QUERY_SQL("DELETE FROM artica_caches_mirror WHERE ID={$ID}");
    }
    $results = $q->QUERY_SQL("SELECT ID FROM artica_caches WHERE MarkToDelete=1");
    while ($ligne = mysql_fetch_assoc($results)) {
        $ID = $ligne["ID"];
        $Directory = "{$RootPath}/{$ID}";
        if (is_dir($Directory)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Remove {$Directory}\n";
            }
            shell_exec("{$rm} -rf {$Directory}");
        }
        $DirFiles = $unix->DirFiles("/usr/share/squid3", "HyperCacheQueue-.*?-{$ID}\\.db\$");
        while (list($database, $none) = each($DirFiles)) {
            if ($GLOBALS["VERBOSE"]) {
                echo "Remove {$database}\n";
            }
            @unlink($database);
        }
        $q->QUERY_SQL("DELETE FROM artica_caches WHERE ID={$ID}");
    }
    HyperCacheMD5File_clean();
    HyperCacheRetranslation_scan();
}
예제 #26
0
function ping_kdc()
{
    $sock = new sockets();
    $unix = new unix();
    $filetime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $EnableKerbAuth = $sock->GET_INFO("EnableKerbAuth");
    if (!is_numeric("{$EnableKerbAuth}")) {
        $EnableKerbAuth = 0;
    }
    if ($EnableKerbAuth == 0) {
        echo "Starting......: [PING]: Kerberos, disabled\n";
        return;
    }
    if (!checkParams()) {
        echo "Starting......: [PING]: Kerberos, misconfiguration failed\n";
        return;
    }
    $array = unserialize(base64_decode($sock->GET_INFO("KerbAuthInfos")));
    $time = $unix->file_time_min($filetime);
    if ($time < 120) {
        if (!$GLOBALS["VERBOSE"]) {
            return;
        }
        echo "{$filetime} ({$time}Mn)\n";
    }
    $kinit = $unix->find_program("kinit");
    $echo = $unix->find_program("echo");
    $net = $unix->LOCATE_NET_BIN_PATH();
    $wbinfo = $unix->find_program("wbinfo");
    $domain = strtoupper($array["WINDOWS_DNS_SUFFIX"]);
    $domain_lower = strtolower($array["WINDOWS_DNS_SUFFIX"]);
    $ad_server = strtolower($config["WINDOWS_SERVER_NETBIOSNAME"]);
    $kinitpassword = $array["WINDOWS_SERVER_PASS"];
    $kinitpassword = $unix->shellEscapeChars($kinitpassword);
    $clock_explain = "The clock on you system (Linux/UNIX) is too far off from the correct time.\nYour machine needs to be within 5 minutes of the Kerberos servers in order to get any tickets.\nYou will need to run ntp, or a similar service to keep your clock within the five minute window";
    $cmd = "{$echo} {$kinitpassword}|{$kinit} {$array["WINDOWS_SERVER_ADMIN"]}@{$domain} -V 2>&1";
    echo "{$cmd}\n";
    exec("{$cmd}", $kinit_results);
    while (list($num, $ligne) = each($kinit_results)) {
        if (preg_match("#Clock skew too great while getting initial credentials#", $ligne)) {
            $unix->send_email_events("Active Directory connection clock issue", "kinit program claim\n{$ligne}\n{$clock_explain}", "system");
        }
        if (preg_match("#Client not found in Kerberos database while getting initial credentials#", $ligne)) {
            $unix->send_email_events("Active Directory authentification issue", "kinit program claim\n{$ligne}\n", "system");
        }
        if (preg_match("#Authenticated to Kerberos#", $ligne)) {
            echo "starting......: [PING]: Kerberos, Success\n";
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "kinit: {$ligne}\n";
        }
    }
    @unlink($filetime);
    @file_put_contents($filetime, time());
}
예제 #27
0
function ApplySingleAcls($directory)
{
    $unix = new unix();
    $chmod_bin = $unix->find_program("chmod");
    $setfacl_bin = $unix->find_program("setfacl");
    $recursive = null;
    $chmod = null;
    $q = new mysql();
    $dir = $unix->shellEscapeChars($directory);
    if (!is_dir($directory)) {
        echo "Starting......: acls {$directory} no such directory\n";
        $q->QUERY_SQL("DELETE FROM acl_directories WHERE `directory`='{$directory}'");
        if (!$q->ok) {
            echo $q->mysql_error . "\n";
        }
        return;
    }
    $acls = new aclsdirs($directory);
    echo "Starting......: acls \"{$dir}\" directory\n";
    if (!is_numeric($acls->chmod_octal)) {
        $events[] = "octal is not a numeric value...";
    }
    if (is_numeric($acls->chmod_octal)) {
        $events[] = "octal \"{$acls->chmod_octal}\"";
        if (chmod_recursive == 1) {
            $events[] = "Recursive mode";
            $recursive = " -R ";
        }
        $chmod = " " . $acls->chmod_octal;
    }
    if ($chmod != null) {
        $cmd = "{$chmod_bin}{$recursive}{$chmod} {$dir}";
        $events[] = "{$cmd}";
        exec("{$chmod_bin}{$recursive}{$chmod} {$dir} 2>&1", $events);
    }
    if (strlen($setfacl_bin) < 3) {
        $events[] = "ERROR: setfacl no such binary file";
        $events_text = @implode("\n", $events);
        if ($GLOBALS["VERBOSE"]) {
            echo $events_text . "\n";
        }
        $sql = "UPDATE acl_directories SET events='" . addslashes($events_text) . "' WHERE `md5`='{$acls->md5}'";
        if ($GLOBALS["VERBOSE"]) {
            echo $sql . "\n";
        }
        $q->QUERY_SQL($sql, "artica_backup");
        if (!$q->ok) {
            echo "{$q->mysql_error}\n";
        }
        return;
    }
    $cmd = "{$setfacl_bin} -b {$dir} 2>&1";
    $events[] = $cmd;
    exec("{$cmd}", $events);
    if ($GLOBALS["VERBOSE"]) {
        if (!is_array($acls->acls_array)) {
            echo "acls_array not an Array\n";
        }
    }
    print_r($acls->acls_array);
    $gp = new groups();
    if (is_array($acls->acls_array["GROUPS"])) {
        while (list($groupname, $array) = each($acls->acls_array["GROUPS"])) {
            $perms = array();
            $perms_strings = null;
            $recurs = null;
            if ($array["r"] == 1) {
                $perms[] = "r";
            }
            if ($array["w"] == 1) {
                $perms[] = "w";
            }
            if ($array["x"] == 1) {
                $perms[] = "x";
            }
            $perms_strings = @implode("", $perms);
            if ($perms_strings == null) {
                $events[] = "No permissions set for {$groupname}";
                continue;
            }
            if ($acls->acls_array["recursive"] == 1) {
                $recurs = "-R ";
            }
            $gpid = $gp->GroupIDFromGetEnt($groupname);
            $groupname = utf8_encode($groupname);
            if ($GLOBALS["VERBOSE"]) {
                echo "`{$groupname}` as gidNumber `{$gpid}`\n";
            }
            if (is_numeric($gpid)) {
                if ($gpid > 0) {
                    $groupname = $gpid;
                }
            }
            $cmd = "{$setfacl_bin} {$recurs}-m g:\"{$groupname}\":{$perms_strings} {$dir} 2>&1";
            $events[] = $cmd;
            exec("{$cmd}", $events);
            if ($acls->acls_array["default"] == 1) {
                $groupname = utf8_encode($groupname);
                $cmd = "{$setfacl_bin} {$recurs}-m d:g:\"{$groupname}\":{$perms_strings} {$dir} 2>&1";
                $events[] = $cmd;
                exec("{$cmd}", $events);
            }
        }
    } else {
        $events[] = "Groups: No acls\n";
    }
    if (is_array($acls->acls_array["MEMBERS"])) {
        while (list($member, $array) = each($acls->acls_array["MEMBERS"])) {
            $perms = array();
            $perms_strings = null;
            $recurs = null;
            if ($array["r"] == 1) {
                $perms[] = "r";
            }
            if ($array["w"] == 1) {
                $perms[] = "w";
            }
            if ($array["x"] == 1) {
                $perms[] = "x";
            }
            $perms_strings = @implode("", $perms);
            if ($perms_strings == null) {
                $events[] = "No permissions set for {$member}";
                continue;
            }
            if ($acls->acls_array["recursive"] == 1) {
                $recurs = "R";
            }
            $member = utf8_encode($member);
            $cmd = "{$setfacl_bin} -m{$recurs} u:\"{$member}\":{$perms_strings} {$dir} 2>&1";
            $events[] = $cmd;
            exec("{$cmd}", $events);
            if ($acls->acls_array["default"] == 1) {
                $member = utf8_encode($member);
                $cmd = "{$setfacl_bin} -m{$recurs} d:u:\"{$member}\":{$perms_strings} {$dir} 2>&1";
                $events[] = $cmd;
                exec("{$cmd}", $events);
            }
        }
    } else {
        $events[] = "Members: No acls\n";
    }
    $events_text = @implode("\n", $events);
    if ($GLOBALS["VERBOSE"]) {
        echo $events_text . "\n";
    }
    $sql = "UPDATE acl_directories SET events='" . addslashes($events_text) . "' WHERE `md5`='{$acls->md5}'";
    $q->QUERY_SQL($sql, "artica_backup");
}
예제 #28
0
function duplicate_wordpress($servername)
{
    $unix = new unix();
    $q = new mysql();
    $free = new freeweb($servername);
    $WORKING_DIRECTORY = $free->www_dir;
    if ($free->groupware_duplicate == null) {
        build_progress("{$servername}: {duplicate} {$servername} no duplicate set...", 42);
        sleep(2);
        return false;
    }
    $free2 = new freeweb($free->groupware_duplicate);
    if ($free2->mysql_database == null) {
        echo "Fatal: {$free->groupware_duplicate} did not have any such DB set, try to find it..\n";
        $free2->mysql_database = $free2->CreateDatabaseName();
        echo "Fatal: {$free->groupware_duplicate} = {$free2->mysql_database}\n";
    }
    if (!$q->DATABASE_EXISTS($free2->mysql_database, true)) {
        build_progress("{$servername}: {duplicate} {$free->groupware_duplicate} did not have any database...", 42);
        sleep(2);
        return false;
    }
    $srcdir = $free2->www_dir;
    $Mysqlpassword = null;
    $cp = $unix->find_program("cp");
    $rm = $unix->find_program("rm");
    if (@is_link($WORKING_DIRECTORY)) {
        $WORKING_DIRECTORY = @readlink($WORKING_DIRECTORY);
    }
    if (is_dir($WORKING_DIRECTORY)) {
        build_progress("{$servername}: {removing} {$WORKING_DIRECTORY}...", 42);
        sleep(2);
        shell_exec("{$rm} -rf {$WORKING_DIRECTORY}/*");
    }
    @mkdir($WORKING_DIRECTORY, 0755, true);
    build_progress("{$servername}: {installing} {from} {$srcdir}...", 42);
    shell_exec("{$cp} -rf {$srcdir}/* {$WORKING_DIRECTORY}/");
    $wordpressDB = $free->mysql_database;
    if ($wordpressDB == null) {
        $wordpressDB = $free->CreateDatabaseName();
    }
    if ($q->DATABASE_EXISTS($wordpressDB)) {
        build_progress("{$servername}: {remove_database} {$wordpressDB}...", 42);
        sleep(2);
        if (!$q->DELETE_DATABASE($wordpressDB)) {
            build_progress("{$servername}: {remove_database} {$wordpressDB} {failed}...", 42);
            return false;
        }
        if (!$q->CREATE_DATABASE($wordpressDB, true)) {
            build_progress("{$servername}: {create_database} {$wordpressDB} {failed}...", 42);
            return false;
        }
    }
    if (!$q->DATABASE_EXISTS($wordpressDB)) {
        if (!$q->CREATE_DATABASE($wordpressDB, true)) {
            build_progress("{$servername}: {create_database} {$wordpressDB} {failed}...", 42);
            return false;
        }
    }
    build_progress("{$servername}: {backup_database} {from} {$free2->mysql_database}...", 42);
    $mysqldump = $unix->find_program("mysqldump");
    $q = new mysql();
    if ($q->mysql_password != null) {
        $Mysqlpassword = "******" . $unix->shellEscapeChars($q->mysql_password);
    }
    $t = time();
    $TMP_FILE = $unix->FILE_TEMP();
    $cmdline = trim("{$mysqldump} --add-drop-table --single-transaction --force --insert-ignore -S /var/run/mysqld/mysqld.sock -u {$q->mysql_admin}{$Mysqlpassword} {$free2->mysql_database} >{$TMP_FILE} 2>&1");
    if ($GLOBALS["VERBOSE"]) {
        echo "{$cmdline}\n";
    }
    $results = array();
    exec($cmdline, $results);
    while (list($num, $ligne) = each($results)) {
        echo "{$ligne}\n";
        if (preg_match("#ERROR\\s+([0-9]+)#", $ligne)) {
            build_progress("{$servername}: {restore_database} {to} {$wordpressDB} {failed}..", 42);
            sleep(3);
            return false;
        }
    }
    build_progress("{$servername}: {restore_database} {to} {$wordpressDB}..", 42);
    $mysqlbin = $unix->find_program("mysql");
    $cmd = "{$mysqlbin} --batch --force -S /var/run/mysqld/mysqld.sock -u {$q->mysql_admin}{$Mysqlpassword} --database={$wordpressDB} <{$TMP_FILE} 2>&1";
    if ($GLOBALS["VERBOSE"]) {
        echo "{$cmd}\n";
    }
    exec($cmd, $results);
    while (list($num, $ligne) = each($results)) {
        echo "{$ligne}\n";
        if (preg_match("#ERROR\\s+([0-9]+)#", $ligne)) {
            build_progress("{$servername}: {restore_database} {to} {$wordpressDB} {failed}..", 42);
            sleep(3);
            return false;
        }
    }
    build_progress("{$servername}: {restore_database} {to} {$wordpressDB}..{done}", 42);
    @unlink($TMP_FILE);
    if (!scan($WORKING_DIRECTORY)) {
        build_progress("{$servername}: {install} {failed}", 42);
        sleep(3);
        return false;
    }
    $proto = "http";
    if ($free->useSSL == 1) {
        $proto = "https";
    }
    $sql = "UPDATE `wp_options` SET `option_value`='{$proto}://{$servername}' WHERE `option_name`='siteurl'";
    $q->QUERY_SQL($sql, $wordpressDB);
    if (!$q->ok) {
        echo $q->mysql_error;
        build_progress("{$servername}: {install} {failed}", 42);
        sleep(3);
        return false;
    }
    $sql = "UPDATE `wp_options` SET `option_value`='{$proto}://{$servername}' WHERE `option_name`='home'";
    $q->QUERY_SQL($sql, $wordpressDB);
    if (!$q->ok) {
        echo $q->mysql_error;
        build_progress("{$servername}: {install} {failed}", 42);
        sleep(3);
        return false;
    }
    $free->groupware_duplicate = null;
    $free->CreateSite(true);
    return true;
}
예제 #29
0
function acls_delete()
{
    $unix = new unix();
    $setfacl = $unix->find_program("setfacl");
    $dir = $unix->shellEscapeChars($_GET["acls-delete"]);
    $cmd = "{$setfacl} -b {$dir} 2>&1";
    exec("{$cmd}", $events);
}
예제 #30
-1
function UpdateUtilitySize($force = false)
{
    $unix = new unix();
    $arrayfile = "/usr/share/artica-postfix/ressources/logs/web/UpdateUtilitySize.size.db";
    $pidfile = "/etc/artica-postfix/pids/UpdateUtilitySize.pid";
    if (!$force) {
        $pid = $unix->get_pid_from_file($pidfile);
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            return;
        }
        @file_put_contents($pidfile, getmypid());
        $time = $unix->file_time_min($arrayfile);
        if ($time < 20) {
            return;
        }
    }
    $sock = new sockets();
    $dir = $sock->GET_INFO("UpdateUtilityStorePath");
    if ($dir == null) {
        $dir = "/home/kaspersky/UpdateUtility";
    }
    $UpdateUtilityUseLoop = $sock->GET_INFO("UpdateUtilityUseLoop");
    if (!is_numeric($UpdateUtilityUseLoop)) {
        $UpdateUtilityUseLoop = 0;
    }
    if ($UpdateUtilityUseLoop == 1) {
        $dir = "/automounts/UpdateUtility";
    }
    if (is_link($dir)) {
        $dir = readlink($dir);
    }
    $unix = new unix();
    $sizbytes = $unix->DIRSIZE_BYTES($dir);
    $dir = $unix->shellEscapeChars($dir);
    $df = $unix->find_program("df");
    $array["DBSIZE"] = $sizbytes / 1024;
    exec("{$df} -B K {$dir} 2>&1", $results);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#^.*?\\s+([0-9A-Z\\.]+)K\\s+([0-9A-Z\\.]+)K\\s+([0-9A-Z\\.]+)K\\s+([0-9\\.]+)%\\s+(.+)#", $ligne, $re)) {
            $array["SIZE"] = $re[1];
            $array["USED"] = $re[2];
            $array["AIVA"] = $re[3];
            $array["POURC"] = $re[4];
            $array["MOUNTED"] = $re[5];
            break;
        }
    }
    $results = array();
    exec("{$df} -i {$dir} 2>&1", $results);
    while (list($num, $ligne) = each($results)) {
        if (preg_match("#^.*?\\s+([0-9A-Z\\.]+)\\s+([0-9A-Z\\.]+)\\s+([0-9A-Z\\.]+)\\s+([0-9\\.]+)%\\s+(.+)#", $ligne, $re)) {
            $array["ISIZE"] = $re[1];
            $array["IUSED"] = $re[2];
            $array["IAIVA"] = $re[3];
            $array["IPOURC"] = $re[4];
            break;
        }
    }
    if ($GLOBALS["VERBOSE"]) {
        print_r($array);
    }
    @unlink($arrayfile);
    @file_put_contents($arrayfile, serialize($array));
    if ($GLOBALS["VERBOSE"]) {
        echo "Saving {$arrayfile}...\n";
    }
    @chmod($arrayfile, 0755);
}