function STREAM_LINE()
{
    $sock = new sockets();
    $EnableWebProxyStatsAppliance = $sock->GET_INFO("EnableWebProxyStatsAppliance");
    if (!is_numeric($EnableWebProxyStatsAppliance)) {
        $EnableWebProxyStatsAppliance = 0;
    }
    if ($EnableWebProxyStatsAppliance == 0) {
        writelogs("EnableWebProxyStatsAppliance={$EnableWebProxyStatsAppliance} from " . $_SERVER["REMOTE_ADDR"] . " (aborting)", __FUNCTION__, __FILE__, __LINE__);
        die;
    }
    $q = new mysql();
    $sql = base64_decode($_POST["STREAM_LINE"]);
    $q->BuildTables();
    $hostname = $_POST["HOSTNAME"];
    $q->QUERY_SQL("DELETE FROM youtubecache WHERE proxyname='{$hostname}'", "artica_events");
    $q->QUERY_SQL($sql, "artica_events");
    if ($sql == null) {
        return;
    }
    if (!$q->QUERY_SQL($sql, "artica_events")) {
        writelogs("Received " . strlen($sql) . " bytes from " . $_SERVER["REMOTE_ADDR"] . " ({$_POST["HOSTNAME"]}) (failed)", __FUNCTION__, __FILE__, __LINE__);
        writelogs("Mysql error: `{$q->mysql_error}`", __FUNCTION__, __FILE__, __LINE__);
        writelogs("Mysql error: -------------------", __FUNCTION__, __FILE__, __LINE__);
        writelogs("{$sql}", __FUNCTION__, __FILE__, __LINE__);
        writelogs("Mysql error: -------------------", __FUNCTION__, __FILE__, __LINE__);
        echo "{$q->mysql_error}\n";
        die;
    }
    writelogs("Received " . strlen($sql) . " bytes from " . $_SERVER["REMOTE_ADDR"] . " (success)", __FUNCTION__, __FILE__, __LINE__);
    echo "<ANSWER>OK</ANSWER>\n";
}
Esempio n. 2
0
function SingleDebug($ID)
{
    $q = new mysql();
    $q->BuildTables();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".{$ID}.pid";
    $unix = new unix();
    $pid = $unix->get_pid_from_file($pidfile);
    $fetchmail = $unix->find_program("fetchmail");
    if ($unix->process_exists($pid)) {
        SingleDebugEvents("Task aborted", "This task is aborted, it already running PID {$pid}, please wait before executing a new task", $ID);
        return;
    }
    @file_put_contents($pidfile, getmypid());
    SingleDebugEvents("Task executed", "Starting rule number {$ID}\nThis task is executed please wait before executing a new task", $ID);
    $fetch = new fetchmail();
    $output = array();
    $fetch = new fetchmail();
    $l[] = "set logfile /var/log/fetchmail-rule-{$ID}.log";
    $l[] = "set daemon {$fetch->FetchmailPoolingTime}";
    $l[] = "set postmaster \"{$fetch->FetchmailDaemonPostmaster}\"";
    $l[] = "set idfile \"/var/log/fetchmail.{$ID}.id\"";
    $l[] = "";
    $GLOBALS["SINGLE_DEBUG"] = true;
    BuildRules();
    $pattern = $GLOBALS["FETCHMAIL_RULES_ID"][$ID];
    $l[] = $pattern;
    @file_put_contents("/tmp/fetchmailrc.{$ID}", @implode("\n", $l));
    shell_exec("/bin/chmod 600 /tmp/fetchmailrc.{$ID}");
    $cmd = "{$fetchmail} -v -N -f /tmp/fetchmailrc.{$ID} --pidfile /tmp/fetcmailrc.{$ID}.pid 2>&1";
    exec($cmd, $output);
    SingleDebugEvents("Task finish with " . count($output) . " event(s)", @implode("\n", $output), $ID);
}
function BuildDayTable()
{
    $q = new mysql();
    $q->BuildTables();
    if (!$q->TABLE_EXISTS('smtp_logs_day', 'artica_events')) {
        send_email_events("Mysql error on smtp_logs_day table", "Artica was unable to create or detect smtp_logs_day table...", "system");
        return false;
    }
    $today = date('Y-m-d');
    $sql = "SELECT COUNT(id) as tcount,delivery_domain,DATE_FORMAT(time_stamp,'%Y-%m-%d') as tdate,bounce_error FROM \n\tsmtp_logs \n\tGROUP BY delivery_domain,tdate,bounce_error HAVING tdate<'{$today}' ORDER BY tdate DESC";
    $q = new mysql();
    $results = $q->QUERY_SQL($sql, "artica_events");
    if (!$q->ok) {
        echo "Wrong sql query {$q->mysql_error}\n";
        write_syslog("Wrong sql query {$q->mysql_error}", __FILE__);
        return false;
    }
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        $count = $count + 1;
        $emails = $ligne["tcount"];
        $delivery_domain = $ligne["delivery_domain"];
        $date = $ligne["tdate"];
        $bounce_error = $ligne["bounce_error"];
        $md5 = md5($delivery_domain . $date . $bounce_error . $emails);
        $sql = "INSERT INTO smtp_logs_day (`key`,`day`,`delivery_domain`,`bounce_error`,`emails`)\n\t\tVALUES('{$md5}','{$date}','{$delivery_domain}','{$bounce_error}','{$emails}')";
        $q->QUERY_SQL($sql, "artica_events");
        if (!$q->ok) {
            echo "Wrong sql query {$q->mysql_error}\n";
            write_syslog("Wrong sql query \"{$sql}\" {$q->mysql_error}", __FILE__);
            return false;
        }
    }
    return true;
}
Esempio n. 4
0
function rsync_server_queue(){
	$q=new mysql();
	$q->BuildTables();
	foreach (glob("/var/log/artica-postfix/rsync/*") as $filename) {
		ScanRsyncServer($filename);
	}
}
Esempio n. 5
0
function rebuild_imapsync(){
	$q=new mysql();
	writelogs("DELETE imapsync table...",__FUNCTION__,__FILE__,__LINE__);
	$sql="DROP TABLE `imapsync`";
	$q->QUERY_SQL($sql,"artica_backup");
	if(!$q->ok){echo "$sql:: $q->mysql_error\n";}
	writelogs("Rebuild tables",__FUNCTION__,__FILE__,__LINE__);
	$q->BuildTables();
	}
function clean_events()
{
    $q = new mysql();
    $q->QUERY_SQL("DROP TABLE kav4proxy_updates", "artica_events");
    $q->BuildTables();
    if (!$q->ok) {
        echo $q->mysql_error;
    }
}
function reconstruct()
{
    $database = $_POST["reconstruct"];
    $tpl = new templates();
    if ($database == "squidlogs") {
        $q = new mysql_squid_builder();
        $q->CheckTables();
        echo $tpl->javascript_parse_text("{success}");
        return;
    }
    $q = new mysql();
    $q->BuildTables();
    echo $tpl->javascript_parse_text("{success}");
}
function popup()
{
    $uid = $_GET["uid"];
    $t = $_GET["t"];
    $sql = "SELECT script_code FROM logon_scriptsusers WHERE uid='{$uid}'";
    $q = new mysql();
    if (!$q->TABLE_EXISTS("logon_scriptsusers", "artica_backup")) {
        $q->BuildTables();
    }
    $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
    $ligne["script_code"] = base64_decode($ligne["script_code"]);
    $_POST["script_data"] = str_replace("\n\n", "\n", $_POST["script_data"]);
    $html = "\n\t<div style='font-size:13px' class=explain>{LOGON_SCRIPT_TEXT}<br>\n\t{LOGON_SCRIPT_PUT}</div>\n\t<div style='float:right;margin-bottom:8px;'>" . imgtootltip("delete-32.png", "{delete}", "LOGON_SCRIPT_DEL{$t}()") . "</div>\n\t<textarea id='script_code{$t}' style='width:100%;height:350px;overflow:auto; font-family: \"Courier New\", Courier, monospace;padding:3px'>" . $ligne["script_code"] . "</textarea>\n\t<div style='text-align:right'><hr>" . button("{apply}", "LOGON_SCRIPT_SAVE{$t}()", "18px") . "</div>";
    $tpl = new templates();
    echo $tpl->_ENGINE_parse_body($html);
}
Esempio n. 9
0
function optimize()
{
    $sock = new sockets();
    $unix = new unix();
    $q = new mysql();
    $basename = basename(__FILE__);
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".MAIN.pid";
    $pid = @file_get_contents($pidfile);
    if ($unix->process_exists($pid, $basename)) {
        mysql_admin_events("Already running pid {$pid}, aborting", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    $t = 0;
    if ($GLOBALS["VERBOSE"]) {
        echo "Start ok ->CheckTables() \n";
    }
    $q->BuildTables();
    $EnableMysqlOptimize = $sock->GET_INFO("EnableMysqlOptimize");
    if (!is_numeric($EnableMysqlOptimize)) {
        $EnableMysqlOptimize = 0;
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "EnableMysqlOptimize= {$EnableMysqlOptimize} \n";
    }
    if ($EnableMysqlOptimize == 0) {
        return;
    }
    $t1 = time();
    $ARRAY = unserialize(base64_decode($sock->GET_INFO("MysqlOptimizeDBS")));
    if ($GLOBALS["VERBOSE"]) {
        echo "MysqlOptimizeDBS= " . count($ARRAY) . " \n";
    }
    mysql_admin_events("Starting optimize " . count($ARRAY) . " databases ", __FUNCTION__, __FILE__, __LINE__, "defrag");
    $c = 0;
    while (list($database, $enabled) = each($ARRAY)) {
        if (!is_numeric($enabled)) {
            continue;
        }
        if ($enabled == 1) {
            $c++;
            optimize_tables($database);
        }
    }
    $time = $unix->distanceOfTimeInWords($t1, time(), true);
    mysql_admin_events("{$c} Database(s) checked {$time}", __FUNCTION__, __FILE__, __LINE__, "defrag");
}
function folders_list()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $users = new usersMenus();
    $search = $_GET["search"];
    $search = "*{$search}*";
    $search = str_replace("***", "*", $search);
    $search = str_replace("**", "*", $search);
    $search_sql = str_replace("*", "%", $search);
    $search_sql = str_replace("%%", "%", $search_sql);
    $search_regex = str_replace(".", "\\.", $search);
    $search_regex = str_replace("*", ".*?", $search);
    $sure_delete_smb_vrt = $tpl->javascript_parse_text("{sure_delete_smb_vrt}");
    $add = imgtootltip("plus-24.png", "{add}", "SambaVirtalServerEditShare(0,'')");
    $html = "<center>\n<table cellspacing='0' cellpadding='0' border='0' class='tableView' style='width:100%'>\n<thead class='thead'>\n\t<tr>\n\t\t<th width=1%>{$add}</th>\n\t\t<th colspan=2>{shared_folders}&nbsp;|&nbsp;{$search_regex}&nbsp;|&nbsp;{$search_sql}</th>\n\t</tr>\n</thead>\n<tbody class='tbody'>";
    $q = new mysql();
    $sql = "SELECT ID,share_name FROM samba_hosts_share WHERE hostname='{$_GET["hostname"]}' AND share_name LIKE '{$search_sql}' ORDER BY share_name";
    writelogs("{$sql}", __FUNCTION__, __FILE__, __LINE__);
    $results = $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        if (strpos($q->mysql_error, "doesn't exist") > 0) {
            $q->BuildTables();
            $results = $q->QUERY_SQL($sql, "artica_backup");
        }
    }
    if (!$q->ok) {
        echo "<H2>{$q->mysql_error}</H2>";
    }
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        if ($classtr == "oddRow") {
            $classtr = null;
        } else {
            $classtr = "oddRow";
        }
        $select = imgtootltip("folder-granted-properties-32.png", "{apply}", "SambaVirtalServerEditShare('{$ligne["ID"]}','{$ligne["share_name"]}')");
        $delete = imgtootltip("delete-32.png", "{delete}", "SambaVirtalServerDeleteShare('{$ligne["ID"]}')");
        $color = "black";
        $html = $html . "\n\t\t\t\t<tr class={$classtr}>\n\t\t\t\t\t<td width=1%>{$select}</td>\n\t\t\t\t\t<td style='font-size:14px;font-weight:bold;color:{$color}'>{$ligne["share_name"]}</a></td>\n\t\t\t\t\t<td width=1%>{$delete}</td>\n\t\t\t\t</tr>\n\t\t\t\t";
    }
    $html = $html . "\n\t</table>\n\t<script>\n\t\tfunction SambaVirtalServerEditShare(ID,s){\n\t\t\tif(!s){s='New';}\n\t\t\tYahooWin4('485','{$page}?folder-id='+ID+'&hostname={$_GET["hostname"]}',s);\n\t\t}\n\t\t\n\tvar x_SambaVirtalServerDeleteShare=function (obj) {\n\t\t\ttempvalue=obj.responseText;\n\t\t\tif(tempvalue.length>2){alert(tempvalue);return;}\n\t\t\tBrowseSambaFSearch();\n\t\t\t\n\t}\t\t\n\t\t\n\tfunction SambaVirtalServerDeleteShare(ID){\n\t\tvar XHR = new XHRConnection();\n\t\tXHR.appendData('hostname','{$_GET["hostname"]}');\n\t\tXHR.appendData('folder-id',ID);\n\t\tXHR.appendData('share_delete','yes');\n\t\tXHR.sendAndLoad('{$page}', 'POST',x_SambaVirtalServerDeleteShare);\t\t\n\t}\n\t\t\n\t</script>\n\t\n\t\n\t";
    echo $tpl->_ENGINE_parse_body($html);
}
function main_table()
{
    $t = time();
    $page = CurrentPageName();
    $tpl = new templates();
    $users = new usersMenus();
    $sock = new sockets();
    $q = new mysql();
    if (!$q->TABLE_EXISTS("sender_dependent_relay_host", "artica_backup")) {
        $q->BuildTables();
    }
    if ($_GET["hostname"] == null) {
        $_GET["hostname"] = "master";
    }
    $t = time();
    $domain = $tpl->_ENGINE_parse_body("{sender_domain_email}");
    $are_you_sure_to_delete = $tpl->javascript_parse_text("{are_you_sure_to_delete}");
    $relay = $tpl->javascript_parse_text("{relay}");
    $MX_lookups = $tpl->javascript_parse_text("{MX_lookups}");
    $delete = $tpl->javascript_parse_text("{delete}");
    $InternetDomainsAsOnlySubdomains = $sock->GET_INFO("InternetDomainsAsOnlySubdomains");
    if (!is_numeric($InternetDomainsAsOnlySubdomains)) {
        $InternetDomainsAsOnlySubdomains = 0;
    }
    $add_local_domain_form_text = $tpl->javascript_parse_text("{add_local_domain_form}");
    $add_local_domain = $tpl->_ENGINE_parse_body("{add_local_domain}");
    $sender_dependent_relayhost_maps_title = $tpl->_ENGINE_parse_body("{sender_dependent_relayhost_maps_title}");
    $ouescape = urlencode($ou);
    $networks = $tpl->javascript_parse_text("{networks}");
    $hostname = $_GET["hostname"];
    $apply = $tpl->javascript_parse_text("{apply}");
    $about2 = $tpl->javascript_parse_text("{about2}");
    $title = $tpl->javascript_parse_text("{smtpd_sasl_exceptions_networks_text}");
    $add_sender_routing_rule = $tpl->_ENGINE_parse_body("{add_new_network}");
    $explain = $tpl->javascript_parse_text("{smtpd_sasl_exceptions_networks_explain}");
    $give_the_new_network = $tpl->javascript_parse_text("{give the new network}");
    $buttons = "\n\tbuttons : [\n\t{name: '{$add_sender_routing_rule}', bclass: 'add', onpress : newrule{$t}},\n\t{name: '{$apply}', bclass: 'recycle', onpress : apply{$t}},\n\t{name: '{$about2}', bclass: 'help', onpress : Help{$t}},\n\t],";
    $html = "\n\t<input type='hidden' id='ou' value='{$ou}'>\n\t<table class='SMTP_SASL_EXCEPT_TABLE' style='display: none' id='SMTP_SASL_EXCEPT_TABLE' style='width:100%'></table>\n\t<script>\n\t\$(document).ready(function(){\n\t\$('#SMTP_SASL_EXCEPT_TABLE').flexigrid({\n\turl: '{$page}?list=yes&hostname={$hostname}&t={$t}',\n\tdataType: 'json',\n\tcolModel : [\n\t{display: '{$networks}', name : 'domain', width : 749, sortable : true, align: 'left'},\n\t{display: '{$delete};', name : 'delete', width : 90, sortable : false, align: 'center'},\n\t],\n\t{$buttons}\n\tsearchitems : [\n\t{display: '{$domain}', name : 'domain'},\n\t],\n\tsortname: 'domain',\n\tsortorder: 'asc',\n\tusepager: true,\n\ttitle: '<span style=font-size:16px>{$title}</span>',\n\tuseRp: true,\n\trp: 50,\n\tshowTableToggleBtn: false,\n\twidth: '99%',\n\theight: '550',\n\tsingleSelect: true,\n\trpOptions: [10, 20, 30, 50,100,200]\n\n});\n});\n\nfunction  Help{$t}(){\nalert('{$explain}');\n}\n\nvar xnewrule{$t}= function (obj) {\n\t\$('#SMTP_SASL_EXCEPT_TABLE').flexReload();\n\n}\n\t\t\n\n\nfunction newrule{$t}(){\n\tvar a=prompt('{$give_the_new_network}');\n\tif(!a){\n\t\treturn;\n\t}\n\tvar XHR = new XHRConnection();\n\tXHR.appendData('smtpd_sasl_exceptions_networks_add',a);\n\tXHR.sendAndLoad('{$page}', 'GET',xnewrule{$t});\n}\n\t\nfunction  apply{$t}(){\n\tLoadjs('postfix.sasl.progress.php');\n}\n\nfunction smtpd_sasl_exceptions_delete(id_encrypted){\n\tvar XHR = new XHRConnection();\n\tXHR.appendData('smtpd_sasl_exceptions_networks_del',id_encrypted);\n\tXHR.sendAndLoad('{$page}', 'GET', xnewrule{$t});\n}\n\n</script>\n";
    echo $html;
}
function popup()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $q = new mysql();
    $q->BuildTables();
    $servicename = $tpl->_ENGINE_parse_body("{servicename}");
    $interface = $tpl->_ENGINE_parse_body("{interface}");
    $backends = $tpl->_ENGINE_parse_body("{backends}");
    $enabled = $tpl->_ENGINE_parse_body("{enable}");
    $weight = $tpl->_ENGINE_parse_body("{weight}");
    $select = $tpl->_ENGINE_parse_body("{select}");
    $delete_rule_ask = $tpl->javascript_parse_text("{delete_rule_ask}");
    $new_backend = $tpl->_ENGINE_parse_body("{new_backend}");
    $delete_service = $tpl->javascript_parse_text("{delete_this_service}");
    $delete_backend = $tpl->javascript_parse_text("{delete_backend}");
    $CallBack = $_GET["CallBack"];
    $servicename = $_GET["servicename"];
    $tt = $_GET["tt"];
    $t = time();
    $html = "\n\t<table class='HAPROXY_BACKENDS_BROWSE' style='display: none' id='HAPROXY_BACKENDS_BROWSE' style='width:99%'></table>\n\t<script>\n\tvar tmp{$t}='';\n\t\$(document).ready(function(){\n\t\$('#HAPROXY_BACKENDS_BROWSE').flexigrid({\n\turl: '{$page}?balancer-backends-list=yes&t={$t}&servicename={$servicename}',\n\tdataType: 'json',\n\tcolModel : [\n\t{display: '<span style=font-size:16px>{$backends}</span>', name : 'backendname', width : 192, sortable : true, align: 'left'},\n\t{display: '<span style=font-size:16px>{$interface}</span>', name : 'listen_ip', width : 172, sortable : false, align: 'left'},\n\t{display: '<span style=font-size:16px>{$weight}</span>', name : 'bweight', width : 52, sortable : true, align: 'center'},\n\t{display: '<span style=font-size:16px>{$select}</span>', name : 'delete', width : 119, sortable : false, align: 'center'},\n\n\t],\n\tsearchitems : [\n\t{display: '{$backends}', name : 'backendname'},\n\t{display: '{$interface}', name : 'listen_ip'},\n\t],\n\tsortname: 'bweight',\n\tsortorder: 'asc',\n\tusepager: true,\n\ttitle: '<span style=font-size:22px>{$servicename}</span>',\n\tuseRp: true,\n\trp: 15,\n\tshowTableToggleBtn: false,\n\twidth: '99%',\n\theight: 350,\n\tsingleSelect: true\n\n});\n});\nfunction BackendCallBack(ID) {\n\tYahooWin6Hide();\n\t{$CallBack}(ID);\n\t\n\n}\n\n\n\n\nvar x_DeleteSquidAclGroup= function (obj) {\nvar res=obj.responseText;\nif(res.length>3){alert(res);return;}\nif(document.getElementById('main_filter_rule_edit')){RefreshTab('main_filter_rule_edit');}\nif(document.getElementById('main_dansguardian_tabs')){RefreshTab('main_dansguardian_tabs');}\n\$('#rowtime'+TimeRuleIDTemp).remove();\n}\n\n\n\nvar x_EnableDisableBackendSilent= function (obj) {\nvar res=obj.responseText;\nif(res.length>3){alert(res);return;}\n\n}\n\nvar x_BackendDelete= function (obj) {\nvar res=obj.responseText;\nif(res.length>3){alert(res);return;}\n\$('#rowTF'+tmp{$t}).remove();\n\$('#HAPROXY_BACKENDS_TABLE').flexReload();\n\$('#MAIN_HAPROXY_BALANCERS_TABLE').flexReload();\n}\n\n\nfunction BackendDelete(backendname,servicename,md){\ntmp{$t}=md;\nif(confirm('{$delete_backend} :{$servicename}/'+backendname+' ?')){\nvar XHR = new XHRConnection();\nXHR.appendData('backends-delete', backendname);\nXHR.appendData('servicename', '{$servicename}');\nXHR.sendAndLoad('{$page}', 'POST',x_BackendDelete);\n}\n}\n\n\n\nfunction EnableDisableBackend(backendname){\nvar XHR = new XHRConnection();\nXHR.appendData('backends-enable', backendname);\nXHR.appendData('servicename', '{$servicename}');\nif(document.getElementById('HaProxBckDisable_'+backendname).checked){XHR.appendData('enable', '1');}else{XHR.appendData('enable', '0');}\nXHR.sendAndLoad('{$page}', 'POST',x_EnableDisableBackendSilent);\n}\n\n\n\n\n</script>";
    echo $html;
}
Esempio n. 13
0
function ip_list()
{
    $page = CurrentPageName();
    $tpl = new templates();
    $sock = new sockets();
    $EnableAmavisInMasterCF = $sock->GET_INFO("EnableAmavisInMasterCF");
    $html = "<table cellspacing='0' cellpadding='0' border='0' class='tableView' style='width:100%'>\n<thead class='thead'>\n\t<tr>\n\t\t<th>{ip_addr}</th>\n\t\t<th>&nbsp;</th>\n\t</tr>\n</thead>\n<tbody class='tbody'>";
    $sql = "SELECT * FROM amavisd_bypass ORDER BY ip_addr";
    $q = new mysql();
    $results = $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        if (preg_match("#doesn't exist#", $q->mysql_error)) {
            $q->BuildTables();
            $results = $q->QUERY_SQL($sql, "artica_backup");
        }
        if (!$q->ok) {
            echo $q->mysql_error;
            return;
        }
    }
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        if ($classtr == "oddRow") {
            $classtr = null;
        } else {
            $classtr = "oddRow";
        }
        $delete = imgtootltip("delete-32.png", "{delete}", "DeleteAmavisBypass('{$ligne["ip_addr"]}')");
        $color = "black";
        if ($EnableAmavisInMasterCF != 1) {
            $color = "#CCCCCC";
        }
        $html = $html . "\n\t\t<tr  class={$classtr}>\n\t\t<td width=99% style='font-size:16px;color:{$color}' nowrap>{$ligne["ip_addr"]}</td>\n\t\t<td width=1%>{$delete}</td>\n\t\t</tr>";
    }
    $html = $html . "</table>";
    echo $tpl->_ENGINE_parse_body($html);
}
Esempio n. 14
0
function items()
{
    $tpl = new templates();
    $MyPage = CurrentPageName();
    $q = new mysql();
    $t = $_GET["tt"];
    $search = '%';
    $table = "texttoldap";
    $page = 1;
    $FORCE_FILTER = null;
    $total = 0;
    if (!$q->TABLE_EXISTS("texttoldap", "artica_backup")) {
        $q->BuildTables();
    }
    if (isset($_POST["sortname"])) {
        if ($_POST["sortname"] != null) {
            $ORDER = "ORDER BY {$_POST["sortname"]} {$_POST["sortorder"]}";
        }
    }
    if (isset($_POST['page'])) {
        $page = $_POST['page'];
    }
    $searchstring = string_to_flexquery();
    if ($searchstring != null) {
        $sql = "SELECT COUNT(*) as TCOUNT FROM {$table} WHERE 1 {$FORCE_FILTER} {$searchstring}";
        $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
        $total = $ligne["TCOUNT"];
    } else {
        $total = $q->COUNT_ROWS("texttoldap", "artica_backup");
    }
    if (isset($_POST['rp'])) {
        $rp = $_POST['rp'];
    }
    $pageStart = ($page - 1) * $rp;
    if (is_numeric($rp)) {
        $limitSql = "LIMIT {$pageStart}, {$rp}";
    }
    $sql = "SELECT *  FROM {$table} WHERE 1 {$searchstring} {$FORCE_FILTER} {$ORDER} {$limitSql}";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    $no_rule = $tpl->_ENGINE_parse_body("{no_rule}");
    $data = array();
    $data['page'] = $page;
    $data['total'] = $total;
    $data['rows'] = array();
    if (!$q->ok) {
        json_error_show($q->mysql_error . "<br>{$sql}");
    }
    if (mysql_num_rows($results) == 0) {
        json_error_show("no data {$sql}");
    }
    $fontsize = "14";
    while ($ligne = mysql_fetch_assoc($results)) {
        $color = "black";
        $NICNAME = null;
        $delete = imgsimple("delete-32.png", null, "Loadjs('{$MyPage}?remove-connection-js={$ligne["ID"]}&t={$_GET["t"]}&t-rule={$_GET["t-rule"]}&tt={$_GET["tt"]}')");
        $editjs = "<a href=\"javascript:blur();\"\n\t\tOnClick=\"javascript:Loadjs('{$MyPage}?js=yes&connection-id={$ligne['ID']}&t={$_GET["t"]}',true);\"\n\t\tstyle='font-size:{$fontsize}px;font-weight:bold;color:{$color};text-decoration:underline'>";
        $connection = $ligne["connection"];
        $folder = $ligne["folder"];
        $hostname = $ligne["hostname"];
        $filename = $ligne["filename"];
        $ldap_group = $ligne["ldapgroup"];
        $ldap_group_text = "-";
        if ($ligne["ldapgroup"] > 0) {
            $gp = new groups($ligne["ldapgroup"]);
            $ldap_group_text = $gp->groupName;
        }
        $data['rows'][] = array('id' => $ligne['ID'], 'cell' => array("<span style='font-size:{$fontsize}px;font-weight:bold;color:{$color}'>{$editjs}{$connection}</span>", "<span style='font-size:{$fontsize}px;font-weight:bold;color:{$color}'>{$editjs}{$folder}</a></span>", "<span style='font-size:{$fontsize}px;font-weight:normal;color:{$color}'>{$hostname}</span>", "<span style='font-size:{$fontsize}px;font-weight:normal;color:{$color}'>{$filename}</span>", "<span style='font-size:{$fontsize}px;font-weight:normal;color:{$color}'>{$ldap_group_text}</span>", "<span style='font-size:{$fontsize}px;font-weight:normal;color:{$color}'>{$delete}</span>"));
    }
    echo json_encode($data);
}
Esempio n. 15
0
function backup($ID)
{
    $date_start = time();
    $sock = new sockets();
    $q = new mysql();
    $unix = new unix();
    $users = new usersMenus();
    $GLOBALS["RESOURCE_MOUNTED"] = true;
    $sql = "SELECT * FROM backup_schedules WHERE ID='{$ID}'";
    if ($GLOBALS["VERBOSE"]) {
        backup_events($ID, "initialization", "{$sql}", __LINE__);
    }
    $mount_path = "/opt/artica/mounts/backup/{$ID}";
    if (!$q->TABLE_EXISTS("backup_storages", "artica_backup", true)) {
        $q->BuildTables();
        if (!$q->TABLE_EXISTS("backup_storages", "artica_backup", true)) {
            backup_events($ID, "initialization", "ERROR, backup_storages, no such table", __LINE__);
            return;
        }
    }
    $servername = $users->fqdn;
    $servername = str_replace('.(none)', "", $servername);
    $servername = str_replace(')', "", $servername);
    $servername = str_replace('(', "", $servername);
    $GLOBALS["MYSERVERNAME"] = $servername;
    $ExecBackupDeadAfterH = $sock->GET_INFO("ExecBackupDeadAfterH");
    if (!is_numeric($ExecBackupDeadAfterH)) {
        $ExecBackupDeadAfterH = 2;
    }
    if ($ExecBackupDeadAfterH < 2) {
        $ExecBackupDeadAfterH = 2;
    }
    $ExecBackupDeadAfterH = $ExecBackupDeadAfterH * 60;
    $ligne = @mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
    if (!$q->ok) {
        send_email_events("Backup Task {$ID}:: Mysql database error !", "Aborting backup\n{$q->mysql_error}", "backup");
        backup_events($ID, "initialization", "ERROR, Mysql database error\n{$q->mysql_error}", __LINE__);
        return false;
    }
    if (!$GLOBALS["ONNLY_MOUNT"]) {
        $pid = $ligne["pid"];
        if ($unix->process_exists($pid)) {
            $time = $unix->PROCCESS_TIME_MIN($pid);
            if ($time > $ExecBackupDeadAfterH) {
                send_email_events("Backup Task {$ID}:: Already instance {$pid} running since {$time}Mn", "The old process was killed and a new backup task will be performed\nstatus:\n\n{$unix->proc_status}", "backup");
            } else {
                send_email_events("Backup Task {$ID}:: Already instance {$pid} running since {$time}Mn", "Aborting backup\n{$unix->proc_status}", "backup");
                backup_events($ID, "initialization", "ERROR, Already instance {$pid} running since {$time}Mn", $unix->proc_status);
                return false;
            }
        }
    }
    $sql = "UPDATE backup_schedules set pid='" . getmypid() . "' WHERE ID='{$ID}'";
    $q->QUERY_SQL($sql, "artica_backup");
    $ressources = unserialize(base64_decode($ligne["datasbackup"]));
    if (count($ressources) == 0) {
        backup_events($ID, "initialization", "ERROR,No source specified");
        send_email_events("Backup Task {$ID}::  No source specified", "Aborting backup", "backup");
        return false;
    }
    if ($ressources["OPTIONS"]["STOP_IMAP"] == 1) {
        $GLOBALS["NO_STOP_CYRUS"] = " --no-cyrus-stop";
    }
    $backup = new backup_protocols();
    $resource_type = $ligne["resource_type"];
    $pattern = $ligne["pattern"];
    $first_ressource = $backup->extractFirsRessource($ligne["pattern"]);
    $container = $ligne["container"];
    backup_events($ID, "initialization", "resource: {$resource_type} -> {$first_ressource}", __LINE__);
    if ($resource_type == null) {
        backup_events($ID, "initialization", "ERROR,No resource specified");
        send_email_events("Backup Task {$ID}:: No resource specified !", "Aborting backup", "backup");
        return false;
    }
    if ($resource_type == "smb") {
        $GLOBALS["CAN_CLEAN_CONTAINERS"] = true;
        $mounted_path_sep = "/";
        if (!mount_smb($pattern, $ID, true)) {
            backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_smb()", __LINE__);
            send_email_events("Backup Task {$ID}::  resource: {$first_ressource} unable to mount", "Aborting backup", "backup");
            return false;
        }
        $GLOBALS["PCOPY"] = true;
    }
    if ($resource_type == "ssh") {
        $GLOBALS["CAN_CLEAN_CONTAINERS"] = true;
        $mounted_path_sep = "/";
        if (!mount_ssh($pattern, $ID, true)) {
            backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_ssh()", __LINE__);
            send_email_events("Backup Task {$ID}::  resource: {$first_ressource} unable to mount to remote ssh service", "Aborting backup", "backup");
            return false;
        }
        $GLOBALS["PCOPY"] = true;
    }
    if ($resource_type == "usb") {
        $GLOBALS["CAN_CLEAN_CONTAINERS"] = true;
        $mounted_path_sep = "/";
        if (!mount_usb($pattern, $ID, true)) {
            backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to mount mount_usb()", __LINE__);
            send_email_events("Backup Task {$ID}::  resource: {$first_ressource} unable to mount", "Aborting backup", "backup");
            return false;
        }
        backup_events($ID, "initialization", "INFO, using external device trough USB", __LINE__);
        $GLOBALS["PCOPY"] = true;
    }
    if ($resource_type == "rsync") {
        $mounted_path_sep = null;
        $mount_path = null;
        $GLOBALS["RESOURCE_MOUNTED"] = false;
        $GLOBALS["USE_RSYNC"] = true;
        $GLOBALS["NO_UMOUNT"] = true;
        $GLOBALS["CAN_CLEAN_CONTAINERS"] = false;
        if (!mount_rsync($pattern, $ID, true)) {
            backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to connect");
            send_email_events("Backup Task {$ID}::  resource: {$first_ressource} unable to connect", "Aborting backup", "backup");
            return false;
        } else {
            backup_events($ID, "initialization", "INFO,{$first_ressource} connect success");
        }
    }
    if ($resource_type == "automount") {
        $mounted_path_sep = "/";
        $mount_path = $first_ressource;
        $GLOBALS["RESOURCE_MOUNTED"] = false;
        $GLOBALS["USE_RSYNC"] = true;
        $GLOBALS["NO_UMOUNT"] = true;
        $GLOBALS["CAN_CLEAN_CONTAINERS"] = true;
        $GLOBALS["MOUNTED_PATH_FINAL"] = $first_ressource;
        CheckCommandLineCopy();
        if (!mount_automount($pattern, $ID, true)) {
            backup_events($ID, "initialization", "ERROR,{$first_ressource} unable to connect");
            send_email_events("Backup Task {$ID}::  resource: {$first_ressource} unable to connect", "Aborting backup", "backup");
            return false;
        }
        backup_events($ID, "initialization", "INFO,{$first_ressource} connect success");
        $GLOBALS["PCOPY"] = true;
    }
    if ($resource_type == "local") {
        $mounted_path_sep = "/";
        $mount_path = $first_ressource;
        $GLOBALS["RESOURCE_MOUNTED"] = false;
        $GLOBALS["CAN_CLEAN_CONTAINERS"] = true;
        $GLOBALS["USE_RSYNC"] = true;
        $GLOBALS["NO_UMOUNT"] = true;
        $GLOBALS["MOUNTED_PATH_FINAL"] = $first_ressource;
        CheckCommandLineCopy();
        if (!is_dir($first_ressource)) {
            backup_events($ID, "initialization", "{$first_ressource} directory doesn't exsits, create it..", __LINE__);
            @mkdir($first_ressource, 0755, true);
        }
        if (!is_dir($first_ressource)) {
            backup_events($ID, "initialization", "{$first_ressource} no such directory permission denied", __LINE__);
            send_email_events("Backup Task {$ID}::  resource: {$first_ressource} no such directory", "Aborting backup", "backup");
            return false;
        }
        backup_events($ID, "initialization", "INFO,{$first_ressource} success");
        $GLOBALS["PCOPY"] = true;
    }
    if ($GLOBALS["ONLY_TESTS"]) {
        if ($GLOBALS["RESOURCE_MOUNTED"]) {
            writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path}", __FUNCTION__, __FILE__, __LINE__);
            exec("umount -l {$mount_path}");
        }
        writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: terminated...", __FUNCTION__, __FILE__, __LINE__);
        return;
    }
    if ($GLOBALS["ONNLY_MOUNT"]) {
        return $mount_path;
    }
    if ($container == "daily") {
        backup_events($ID, "initialization", "INFO, Daily container", __LINE__);
        $DirectoryContainer = "backup." . date('Y-m-d') . "/{$servername}";
        $GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"] = $DirectoryContainer;
        $mount_path_final = $mount_path . $mounted_path_sep . $DirectoryContainer;
    } else {
        backup_events($ID, "initialization", "INFO, Weekly container", __LINE__);
        $DirectoryContainer = "backup." . date('Y-W') . "/{$servername}";
        $GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"] = $DirectoryContainer;
        $mount_path_final = $mount_path . $mounted_path_sep . $DirectoryContainer;
    }
    if ($GLOBALS["DEBUG"]) {
        $cmd_verb = " --verbose";
        writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: Verbose mode detected", __FUNCTION__, __FILE__, __LINE__);
    }
    @mkdir($mount_path_final, 0755, true);
    if (!$GLOBALS["NO_STANDARD_BACKUP"]) {
        $GLOBALS["MOUNTED_PATH_FINAL"] = $mount_path_final;
        $WhatToBackup_ar = null;
        $BACKUP_WWW_ALREADY_DONE = array();
        $BACKUP_WEBGET_ALREADY_DONE = array();
        $BACKUP_INSTANCES_ALREADY_DONE = array();
        while (list($num, $WhatToBackup) = each($ressources)) {
            if (is_array($WhatToBackup)) {
                $WhatToBackup_ar = implode(",", $WhatToBackup);
                backup_events($ID, "initialization", "INFO, WhatToBackup Array = {$WhatToBackup_ar}", __LINE__);
                continue;
            }
            if ($WhatToBackup == "all") {
                backup_events($ID, "initialization", "INFO, Backup starting Running macro all cyrus, mysql, LDAP, Artica...", __LINE__);
                send_email_events("Backup Task {$ID}:: Backup starting Running macro all ", "Backup is running", "backup");
                if ($users->cyrus_imapd_installed) {
                    backup_events($ID, "initialization", "INFO, cyrus-imapd mailboxes processing");
                    backup_cyrus($ID);
                }
                backup_events($ID, "initialization", "INFO, LDAP Database processing", __LINE__);
                backup_ldap($ID);
                backup_events($ID, "initialization", "INFO, MySQL Database processing", __LINE__);
                backup_mysql($ID, 0);
                backup_events($ID, "initialization", "INFO, Restarting MySQL service...", __LINE__);
                mysql_admin_mysql(0, "Restarting mysql service.", null, __FILE__, __LINE__);
                shell_exec("/etc/init.d/mysql restart");
                backup_events($ID, "initialization", "INFO, Artica settings processing", __LINE__);
                backup_artica($ID);
                if ($users->ZARAFA_INSTALLED) {
                    if ($sock->GET_INFO("ZarafaStoreOutside") == 1) {
                        backup_events($ID, "initialization", "INFO, Zarafa external attachments processing...");
                        backup_ZarafaOutside($ID);
                    }
                }
                backup_events($ID, "initialization", "continue to next process", __LINE__);
                continue;
            }
            if (preg_match("#MYSQLINSTANCE:([0-9]+)#", $WhatToBackup, $re)) {
                $instance_id = $re[1];
                backup_events($ID, "initialization", "INFO, Backup starting backup MySQL instance Number:{$instance_id}", __LINE__);
                if ($instance_id > 0) {
                    if (!isset($BACKUP_INSTANCES_ALREADY_DONE[$instance_id])) {
                        backup_mysql($ID, $instance_id);
                        $BACKUP_INSTANCES_ALREADY_DONE[$instance_id] = true;
                    }
                }
                continue;
            }
            if (preg_match("#FREEWEB:(.+)#", $WhatToBackup, $re)) {
                $sitename = $re[1];
                backup_events($ID, "initialization", "INFO, Backup starting backup Website  {$sitename}", __LINE__);
                if (!isset($BACKUP_WWW_ALREADY_DONE[$sitename])) {
                    backup_freewebs($ID, $sitename);
                    $BACKUP_INSTANCES_ALREADY_DONE[$sitename] = true;
                }
                continue;
            }
            if (preg_match("#WEBGET:(.+)#", $WhatToBackup, $re)) {
                if (!isset($BACKUP_WEBGET_ALREADY_DONE[$re[1]])) {
                    $arr = unserialize(base64_decode($re[1]));
                    if (!is_array($arr)) {
                        backup_events($ID, "initialization", "ERROR, WEBGET `{$re[1]}` is not an array...", __LINE__);
                        continue;
                    }
                    backup_events($ID, "initialization", "INFO, Backup remote Artica FreeWebs Website {$arr["RemoteArticaSite"]} from source {$arr["RemoteArticaServer"]}", __LINE__);
                    backup_webget($ID, $arr);
                }
                continue;
            }
            backup_events($ID, "initialization", "INFO, `{$WhatToBackup}` could not understood", __LINE__);
        }
    }
    $sql = "SELECT * FROM backup_folders WHERE taskid={$ID}";
    $results = $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        if (strpos($q->mysql_error, "gone away")) {
            backup_events($ID, "personal", "ERROR, mysql {$q->mysql_error} Restarting MySQL server (Patch p.20130807)", __LINE__);
            mysql_admin_mysql(0, "Restarting mysql service.", $q->mysql_error, __FILE__, __LINE__);
            shell_exec("/etc/init.d/mysql restart");
            $q = new mysql();
            $results = $q->QUERY_SQL($sql, "artica_backup");
        }
    }
    if (!$q->ok) {
        backup_events($ID, "personal", "ERROR, mysql {$q->mysql_error}", __LINE__);
        return;
    }
    while ($ligne = @mysql_fetch_array($results, MYSQL_ASSOC)) {
        $dd1 = time();
        if ($ligne["recursive"] == 1) {
            $recursive = " --recursive";
        } else {
            $recursive = null;
        }
        $path = trim(base64_decode($ligne["path"]));
        if (!is_dir($path)) {
            backup_events($ID, "personal", "ERROR, [{$path}] no such file or directory", __LINE__);
            continue;
        }
        backup_events($ID, "personal", "INFO, Backup starting for {$path}", __LINE__);
        send_email_events("Backup Task {$ID}:: Backup starting {$path}", "Backup is running for path {$path}", "backup");
        backup_mkdir($path);
        $results = backup_copy($path, $path, $ID);
        $calculate = distanceOfTimeInWords($dd1, time());
        backup_events($ID, "personal", "INFO, Backup finish for {$path}\n{$results} {$calculate}", __LINE__);
    }
    writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]: Calculate directory size on {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__);
    $du = $unix->find_program("du");
    $dut1 = time();
    $nice = $unix->EXEC_NICE();
    $cmd = "{$nice}{$du} -s {$mount_path_final}";
    exec($cmd, $du_results);
    $calculate = distanceOfTimeInWords($dut1, time());
    $BackupSize = 0;
    if (preg_match("#^([0-9]+)\\s+#", @implode("", $du_results), $re)) {
        $BackupSize = $re[1];
        backup_events($ID, "initialization", "INFO, backup size {$BackupSize} bytes time:{$calculate}", __LINE__);
    }
    if ($GLOBALS["CAN_CLEAN_CONTAINERS"]) {
        backup_events($ID, "initialization", "INFO, cleaning containers....", __LINE__);
        CleanContainers($ID, $mount_path_final);
    } else {
        backup_events($ID, "initialization", "INFO, cannot clean containers, check protocols....", __LINE__);
    }
    $GLOBAL["BACKUP_MEMORY_SQL"]["mount_path_final"] = $mount_path_final;
    $zmd5 = md5("{$GLOBAL["BACKUP_MEMORY_SQL"]["CONTAINER"]}{$GLOBALS["MYSERVERNAME"]}");
    $cnx_params = addslashes(base64_encode(serialize($GLOBAL["BACKUP_MEMORY_SQL"])));
    $sql = "INSERT IGNORE INTO backup_storages (`taskid`,`size`,`cnx_params`,`zmd5`) VALUES('{$ID}','{$BackupSize}','{$cnx_params}','{$zmd5}')";
    $q->QUERY_SQL($sql, "artica_backup");
    $sql = "UPDATE backup_storages SET `size`='{$BackupSize}' WHERE `zmd5`='{$zmd5}'";
    $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        backup_events($ID, "initialization", "ERROR, {$q->mysql_error}", __LINE__);
    }
    if (!$GLOBALS["NO_UMOUNT"]) {
        writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__);
        if (preg_match("#^\\/opt\\/artica\\/mounts\\/backup\\/[0-9]+(.+)#", $mount_path_final, $re)) {
            $mount_path_final = str_replace($re[1], "", $mount_path_final);
            writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:translated to {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__);
        }
        backup_events($ID, "initialization", "INFO, umount {$mount_path_final}", __LINE__);
        writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount {$mount_path_final}", __FUNCTION__, __FILE__, __LINE__);
        exec("umount -l {$mount_path_final} 2>&1", $resultsUmount);
        if (count($resultsUmount) > 0) {
            writelogs(date('m-d H:i:s') . " " . "[TASK {$ID}]:umount : ----- \n" . @implode("\n", $resultsUmount) . "\n", __FUNCTION__, __FILE__, __LINE__);
        }
    }
    $date_end = time();
    $calculate = distanceOfTimeInWords($date_start, $date_end);
    backup_events($ID, "TIME", "INFO, Time: {$calculate} ({$mount_path_final})", __LINE__);
    backup_events($ID, "initialization", "INFO, Backup task terminated", __LINE__);
    send_email_events("Backup Task {$ID}:: Backup stopping", "Backup is stopped", "backup");
    shell_exec(LOCATE_PHP5_BIN2() . " " . dirname(__FILE__) . "/exec.cleanfiles.php");
}
Esempio n. 16
0
function testsMysql(){
	$_GET["mysqlpass"]=trim(base64_decode($_GET["mysqlpass"]));
	
	writelogs("testing {$_GET["mysqlserver"]}:3306 with user {$_GET["mysql_account"]} and password \"{$_GET["mysqlpass"]}\"",__FUNCTION__,__FILE__,__LINE__);
	
	$bd=@mysql_connect("{$_GET["mysqlserver"]}:3306",$_GET["mysql_account"],$_GET["mysqlpass"]);
	$database=md5('Y-m-d H:i:s');
	$tpl=new templates();
	if(!$bd){
			$errnum=mysql_errno();
    		$des=mysql_error();
    		echo "<div style='font-size:12px;color:red;font-weight:bold'>
    				<p>{connection}:ERR N.$errnum</p> $des
    			</div>";
    		exit;
			}
			
	$results=@mysql_query("CREATE DATABASE $database");
	if(!$bd){
		$errnum=mysql_errno();
    		$des=mysql_error();
    		echo RoundedLightWhite("<div style='font-size:12px;color:red;font-weight:bold'>
    				<p>{privileges}:ERR N.$errnum</p> $des
    			</div>");
    		exit;
	}
	$results=@mysql_query("DROP DATABASE $database");
	
	$artica=new artica_general();
	$artica->MysqlAdminAccount="{$_GET["mysql_account"]}:{$_GET["mysqlpass"]}";
	$artica->MysqlServerName=$_GET["mysqlserver"];
	$artica->SaveMysqlSettings();
	$mysql=new mysql();
	$mysql->mysql_server=$_GET["mysqlserver"];
	$mysql->mysql_admin=$_GET["mysql_account"];
	$mysql->mysql_password=$_GET["mysqlpass"];
	$mysql->hostname=$_GET["mysqlserver"];
	$mysql->BuildTables();
	
	
	$tpl=new templates();
	echo RoundedLightWhite($tpl->_ENGINE_parse_body('<div>{success} {edit} {mysql_account}</div>'));

	
	
	
	
}
Esempio n. 17
0
function testsMysql()
{
    $sock = new sockets();
    while (list($num, $ligne) = each($_POST)) {
        $_POST[$num] = url_decode_special_tool($ligne);
    }
    $method = "";
    writelogs("testing {$_POST["mysqlserver"]}:3306 with user {$_POST["mysqlroot"]} and password \"{$_POST["mysqlpass"]}\"", __FUNCTION__, __FILE__, __LINE__);
    //$bd=@mysql_connect("{$_GET["mysqlserver"]}:3306",$_GET["mysql_account"],$_GET["mysqlpass"]);
    if ($_POST["mysqlserver"] == "localhost" or $_POST["mysqlserver"] == "127.0.0.1") {
        $method = ":/var/run/mysqld/mysqld.sock";
        $bd = @mysql_connect(":/var/run/mysqld/mysqld.sock", $_POST["mysqlroot"], $_POST["mysqlpass"]);
    } else {
        $method = "{$_GET["mysqlserver"]}:3306";
        $bd = @mysql_connect("{$_POST["mysqlserver"]}:3306", $_POST["mysqlroot"], $_POST["mysqlpass"]);
    }
    $database = md5('Y-m-d H:i:s');
    $tpl = new templates();
    if (!$bd) {
        $errnum = mysql_errno();
        $des = mysql_error();
        echo "ERR N.{$errnum}\n{$des}\n{$method}";
        exit;
    }
    $results = @mysql_query("CREATE DATABASE {$database}");
    if (!$bd) {
        $errnum = mysql_errno();
        $des = mysql_error();
        echo "CREATE DATABASE {$database}\nERR N.{$errnum}\n{$des}\n{$method}";
        exit;
    }
    $results = @mysql_query("DROP DATABASE {$database}");
    $arrayMysqlinfos = array("USER" => $_POST["mysqlroot"], "PASSWORD" => $_POST["mysqlpass"], "SERVER" => $_POST["mysqlserver"]);
    $cmd = base64_encode(serialize($arrayMysqlinfos));
    $sock->getFrameWork("cmd.php?change-mysql-params={$cmd}");
    unset($_SESSION["MYSQL_PARAMETERS"]);
    unset($GLOBALS["MYSQL_PARAMETERS"]);
    $mysql = new mysql();
    $mysql->mysql_server = $_POST["mysqlserver"];
    $mysql->mysql_admin = $_POST["mysql_account"];
    $mysql->mysql_password = $_POST["mysqlpass"];
    $mysql->hostname = $_POST["mysqlserver"];
    $mysql->BuildTables();
    $tpl = new templates();
    echo $tpl->javascript_parse_text("{success}: {apply} {mysql_account}");
}
function group_save()
{
    $_POST["objectname"] = trim($_POST["objectname"]);
    if ($_POST["objectname"] == null) {
        $_POST["objectname"] = "New " . $_POST["type"];
    }
    $_POST["objectname"] = mysql_escape_string2($_POST["objectname"]);
    $sql = "INSERT INTO miltergreylist_objects (`instance`,`type`,`enabled`,`objectname`) \n\tVALUES ('{$_POST["hostname"]}','{$_POST["type"]}','1','{$_POST["objectname"]}')";
    if ($_POST["ID"] > 0) {
        $sql = "UPDATE miltergreylist_objects SET objectname='{$_POST["objectname"]}' WHERE ID='{$_POST["ID"]}'";
    }
    $q = new mysql();
    $q->BuildTables();
    $q->QUERY_SQL($sql, "artica_backup");
    if (!$q->ok) {
        echo $q->mysql_error;
        return;
    }
}
Esempio n. 19
0
function rows_table()
{
    $tpl = new templates();
    $MyPage = CurrentPageName();
    $q = new mysql();
    $q->BuildTables();
    $database = "artica_events";
    $search = '%';
    $table = "ipband";
    $page = 1;
    $ORDER = null;
    $total = 0;
    if ($q->COUNT_ROWS($table, $database) == 0) {
        json_error_show("no data");
    }
    if (isset($_POST["sortname"])) {
        if ($_POST["sortname"] != null) {
            $ORDER = "ORDER BY {$_POST["sortname"]} {$_POST["sortorder"]}";
        }
    }
    if (isset($_POST['page'])) {
        $page = $_POST['page'];
    }
    if ($_POST["query"] != null) {
        $_POST["query"] = "*" . $_POST["query"] . "*";
        $_POST["query"] = str_replace("**", "*", $_POST["query"]);
        $_POST["query"] = str_replace("**", "*", $_POST["query"]);
        $_POST["query"] = str_replace("*", "%", $_POST["query"]);
        $search = $_POST["query"];
        if (strpos("  {$_POST["query"]}", "%") > 0) {
            $searchstring = "AND `{$_POST["qtype"]}` LIKE '{$search}'";
        } else {
            $searchstring = "AND `{$_POST["qtype"]}` = '{$search}'";
        }
        $sql = "SELECT COUNT(*) as TCOUNT FROM `{$table}` WHERE 1 {$searchstring}";
        $ligne = mysql_fetch_array($q->QUERY_SQL($sql, $database));
        $total = $ligne["TCOUNT"];
    } else {
        $total = $q->COUNT_ROWS($table, $database);
    }
    if (isset($_POST['rp'])) {
        $rp = $_POST['rp'];
    }
    $pageStart = ($page - 1) * $rp;
    $limitSql = "LIMIT {$pageStart}, {$rp}";
    $sql = "SELECT AVG(size) as tsize,IP_FROM,IP_TO,`IP_TO_HOST`,`IP_FROM_HOST` FROM `{$table}` GROUP BY IP_FROM,IP_TO_HOST,IP_FROM_HOST,IP_TO HAVING 1 {$searchstring} {$ORDER} {$limitSql}";
    writelogs($sql, __FUNCTION__, __FILE__, __LINE__);
    $results = $q->QUERY_SQL($sql, $database);
    if (!$q->ok) {
        json_error_show($q->mysql_error);
    }
    $data = array();
    $data['page'] = $page;
    $data['total'] = $total;
    $data['rows'] = array();
    if (mysql_num_rows($results) == 0) {
        json_error_show("no data");
    }
    while ($ligne = mysql_fetch_assoc($results)) {
        $md5 = md5(serialize($ligne));
        $ipfrom = $ligne["IP_FROM"];
        $ipto = $ligne["IP_TO"];
        $ipfrom_host = $ligne["IP_FROM_HOST"];
        $ipto_host = $ligne["IP_TO_HOST"];
        if ($ipfrom_host == null) {
            $ipfrom_host = resolveHost($ipfrom);
            $q->QUERY_SQL("UPDATE ipband SET IP_FROM_HOST='{$ipfrom_host}' WHERE IP_FROM='{$ipfrom}'", "artica_events");
        }
        if ($ipto_host == null) {
            $ipto_host = resolveHost($ipto);
            $q->QUERY_SQL("UPDATE ipband SET IP_TO_HOST='{$ipto_host}' WHERE IP_TO='{$ipto}'", "artica_events");
        }
        if ($ipfrom == $ipfrom_host) {
            $ipfrom_host = null;
        }
        if ($ipto == $ipto_host) {
            $ipto_host = null;
        }
        $size = FormatBytes($ligne["tsize"] / 1024);
        $ahrefFrom = "<a href=\"javascript:blur();\"\n\t\tOnClick=\"javascript:Loadjs('{$MyPage}?details-js=yes&field=IP_FROM&value={$ipfrom}')\"\n\t\tstyle='font-size:13px;text-decoration:underline'>";
        $ahrefto = "<a href=\"javascript:blur();\" \n\t\tOnClick=\"javascript:Loadjs('{$MyPage}?details-js=yes&field=IP_TO&value={$ipto}')\"\n\t\tstyle='font-size:13px;text-decoration:underline'>";
        $data['rows'][] = array('id' => $md5, 'cell' => array("<span style='font-size:13px'>{$ahrefFrom}{$ipfrom}</a> ({$ipfrom_host})</span>", "<span style='font-size:13px'>{$ahrefto}{$ipto}</a> ({$ipto_host})</span>", "<span style='font-size:13px'>{$size}/s</span>"));
    }
    echo json_encode($data);
}
Esempio n. 20
0
function start()
{
    $sock = new sockets();
    $ZarafaAdbksWhiteTask = $sock->GET_INFO("ZarafaAdbksWhiteTask");
    $ZarafaWhiteSentItems = $sock->GET_INFO("ZarafaWhiteSentItems");
    $ZarafaJunkItems = $sock->GET_INFO("ZarafaJunkItems");
    if (!is_numeric($ZarafaAdbksWhiteTask)) {
        $ZarafaAdbksWhiteTask = 0;
    }
    if (!is_numeric($ZarafaWhiteSentItems)) {
        $ZarafaWhiteSentItems = 1;
    }
    if (!is_numeric($ZarafaJunkItems)) {
        $ZarafaJunkItems = 0;
    }
    if ($ZarafaAdbksWhiteTask == 0) {
        return;
    }
    $q = new mysql();
    $q->BuildTables();
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    if ($unix->process_exists($unix->get_pid_from_file($pidfile))) {
        system_admin_events("Already exists in memory, aborting task", __FUNCTION__, __FILE__, __LINE__, "zarafa");
        return;
    }
    @file_put_contents($pidfile, getmypid());
    $ZarafaServerListenIP = $sock->GET_INFO("ZarafaServerListenIP");
    if ($ZarafaServerListenIP == null) {
        $ZarafaServerListenIP = "127.0.0.1";
    }
    if ($ZarafaServerListenIP == "0.0.0.0") {
        $ZarafaServerListenIP = "127.0.0.1";
    }
    $TimeFile = $unix->file_time_min($pidtime);
    if ($TimeFile < 240) {
        return;
    }
    @unlink($pidtime);
    @file_put_contents($pidtime, time());
    $ldap = new clladp();
    $ous = $ldap->hash_get_ou(true);
    $countDeOu = count($ous);
    system_admin_events("Parsing {$countDeOu} organization(s)", __FUNCTION__, __FILE__, __LINE__, "zarafa");
    $GLOBALS["ITEMSC"] = 0;
    while (list($ou, $none) = each($ous)) {
        $users = $ldap->hash_users_ou($ou);
        $CountDeUsers = count($users);
        system_admin_events("{$ou} {$CountDeUsers} users", __FUNCTION__, __FILE__, __LINE__, "zarafa");
        if (!is_array($users)) {
            continue;
        }
        if (count($users) == 0) {
            continue;
        }
        while (list($uid, $none2) = each($users)) {
            if (trim($uid) == null) {
                continue;
            }
            import_contacts($uid, $ZarafaServerListenIP);
            if ($ZarafaWhiteSentItems == 1) {
                import_sentitems($uid);
            }
            if ($ZarafaJunkItems == 1) {
                inject_blacklists($uid);
            }
        }
    }
    system_admin_events("Adding {$GLOBALS["ITEMSC"]} contacts in white list", __FUNCTION__, __FILE__, __LINE__, "zarafa");
    $EnableAmavisDaemon = $sock->GET_INFO("EnableAmavisDaemon");
    if (!is_numeric($EnableAmavisDaemon)) {
        $EnableAmavisDaemon = 0;
    }
    $php5 = $unix->LOCATE_PHP5_BIN();
    $users = new usersMenus();
    if ($users->AMAVIS_INSTALLED) {
        if ($EnableAmavisDaemon == 1) {
            shell_exec("{$php5} " . dirname(__FILE__) . "/exec.amavis.php >/dev/null 2>&1");
            shell_exec("/etc/init.d/amavis reload");
        }
    }
    if ($users->MILTERGREYLIST_INSTALLED) {
        shell_exec("{$php5} " . dirname(__FILE__) . "/exec.milter-greylist.php >/dev/null 2>&1");
    }
}
Esempio n. 21
0
function LoadAvgClean()
{
    $q = new mysql();
    $q->DELETE_TABLE("loadavg", "artica_events");
    $q->BuildTables();
}
Esempio n. 22
0
function runProc($norestart = false)
{
    $unix = new unix();
    $sock = new sockets();
    $t = time();
    $timeFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    $timePID = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $EnableBandwithCalculation = $sock->GET_INFO("EnableBandwithCalculation");
    if (!is_numeric($EnableBandwithCalculation)) {
        $EnableBandwithCalculation = 1;
    }
    $GetInstances = GetInstances();
    if ($GetInstances > 0) {
        system_admin_events("{$GetInstances} instance(s) already running.. aborting...", __FUNCTION__, __FILE__, __LINE__, "testspeed");
        return;
    }
    if ($EnableBandwithCalculation == 0) {
        system_admin_events("Feature disabled trough the Interface (EnableBandwithCalculation) you have to disable the schedule too...", __FUNCTION__, __FILE__, __LINE__, "testspeed");
        return;
    }
    if (!$GLOBALS["FORCE"]) {
        $pid = $unix->get_pid_from_file($timePID);
        if ($unix->process_exists($pid, basename(__FILE__))) {
            $timexec = $unix->PROCCESS_TIME_MIN($pid);
            if ($timexec < 30) {
                system_admin_events("Already instance executed pid {$pid} since {$timexec}Mn", __FUNCTION__, __FILE__, __LINE__, "testspeed");
                return;
            } else {
                $kill = $unix->find_program("kill");
                unix_system_kill_force($pid);
                system_admin_events("Instance pid {$pid} since {$timexec}Mn was killed", __FUNCTION__, __FILE__, __LINE__, "testspeed");
            }
        }
        $ExecTimefile = $unix->file_time_min($timeFile);
        if ($ExecTimefile < 30) {
            system_admin_events("Must run minimal 30mn ({$ExecTimefile}Mn), aborting", __FUNCTION__, __FILE__, __LINE__, "testspeed");
            return;
        }
        @unlink($timeFile);
        @file_put_contents($timeFile, time());
        @file_put_contents($timePID, getmypid());
    }
    $python = $unix->find_program("python");
    if (!is_file($python)) {
        system_admin_events("python, no such binary", __FUNCTION__, __FILE__, __LINE__, "testspeed");
        return;
    }
    $speedDNum = 0;
    $speedYNum = 0;
    $IP = null;
    $ISP = null;
    if (!is_file("/usr/lib/pyshared/python2.7/lxml/etree.so")) {
        $unix->DEBIAN_INSTALL_PACKAGE("python-lxml");
    }
    @chdir("/usr/share/artica-postfix/bin");
    exec("{$python} /usr/share/artica-postfix/bin/tespeed.py -dt 1 -ut 1 2>&1", $results);
    @chdir("/root");
    while (list($index, $line) = each($results)) {
        if ($GLOBALS["VERBOSE"]) {
            echo "{$line}\n";
        }
        if (preg_match("#IP:\\s+(.+?);.*?ISP:\\s+(.+?)\$#", $line, $re)) {
            $IP = trim($re[1]);
            $ISP = trim($re[2]);
        }
        if (preg_match("#No module named lxml#", $line)) {
            system_admin_events("Error,{$line}", __FUNCTION__, __FILE__, __LINE__, "testspeed");
            if (!$norestart) {
                install_lxml();
            }
            return;
        }
        if (preg_match("#No module named argparse#", $line)) {
            system_admin_events("Error,{$line}", __FUNCTION__, __FILE__, __LINE__, "testspeed");
            if (!$norestart) {
                install_argparse();
            }
            return;
        }
        if (preg_match("#Download speed:\\s+([0-9\\.]+)\\s+Mbit#", $line, $re)) {
            $speedDNum = $re[1];
            $speedDNum = $speedDNum * 1024;
        }
        if (preg_match("#Upload speed:\\s+([0-9\\.]+)\\s+Mbit#", $line, $re)) {
            $speedUNum = $re[1];
            $speedYNum = $speedUNum * 1024;
        }
    }
    $took = $unix->distanceOfTimeInWords($t, time(), true);
    if ($GLOBALS["VERBOSE"]) {
        echo "ISP:{$ISP} , IP:{$IP} Download: {$speedDNum} Kbi/s upload {$speedYNum} Kbi/s\n";
    }
    if ($speedDNum == 0) {
        return;
    }
    if ($speedYNum == 0) {
        return;
    }
    system_admin_events("ISP:{$ISP} , IP:{$IP} Download: {$speedDNum} Kbi/s upload {$speedYNum} Kbi/s took {$took}", __FUNCTION__, __FILE__, __LINE__, "testspeed");
    $array["ISP"] = $ISP;
    $array["PUBLIC_IP"] = $IP;
    $array["DOWNLOAD"] = $speedDNum;
    $array["UPLOAD"] = $speedYNum;
    $array["DATE"] = time();
    @mkdir("/usr/share/artica-postfix/ressources/web/cache1", 0777, true);
    @file_put_contents("/usr/share/artica-postfix/ressources/web/cache1/bandwith.stats", serialize($array));
    if (strlen($speedDNum) > 2) {
        $q = new mysql();
        $q->BuildTables();
        $q->QUERY_SQL("INSERT INTO speedtests (zDate,ISP,download,upload) VALUES (NOW(),'{$ISP}','{$speedDNum}','{$speedYNum}')", "artica_events");
        if (!$q->ok) {
            system_admin_events("Fatal error, {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__, "testspeed");
        }
    }
    $q->QUERY_SQL("DELETE FROM speedtests WHERE zDate<DATE_SUB(NOW(),INTERVAL 35 DAY)", "artica_events");
}
Esempio n. 23
0
function virtuals_add(){
	$sock=new sockets();
	$tpl=new templates();
	$ERROR_NO_PRIVS=$tpl->javascript_parse_text("{ERROR_NO_PRIVS}");
	$DisableNetworksManagement=$sock->GET_INFO("DisableNetworksManagement");
	if($DisableNetworksManagement==null){$DisableNetworksManagement=0;}		
	if($DisableNetworksManagement==1){echo $ERROR_NO_PRIVS;return;}	

	
	if($_GET["nic"]==null){echo $tpl->_ENGINE_parse_body("{nic}=null");exit;}
	$PING=trim($sock->getFrameWork("cmd.php?ping=".urlencode($_GET["virt-ipaddr"])));
	
	if($PING=="TRUE"){
		echo $tpl->javascript_parse_text("{$_GET["virt-ipaddr"]}:\n{ip_already_exists_in_the_network}");
		return;
	}
	
	if($_GET["failover"]==1){
		$_GET["gateway"]=$_GET["virt-ipaddr"];
		$_GET["netmask"]="255.255.255.255";
		$_GET["ForceGateway"]=0;
		
	}
	
	if($_GET["metric"]==0){$_GET["metric"]=lastmetric();}
	
	$NoGatewayForVirtualNetWork=$sock->GET_INFO("NoGatewayForVirtualNetWork");
	if(!is_numeric($NoGatewayForVirtualNetWork)){$NoGatewayForVirtualNetWork=0;}	
	
	if($NoGatewayForVirtualNetWork==1){$_GET["gateway"]=null;}
	$q=new mysql();
	if(!$q->FIELD_EXISTS("nics_virtuals","ForceGateway","artica_backup")){$sql="ALTER TABLE `nics_virtuals` ADD `ForceGateway` TINYINT( 1 ) NOT NULL";$q->QUERY_SQL($sql,'artica_backup');if(!$q->ok){echo $q->mysql_error."\n$sql\n";return;}}		
	if(!$q->FIELD_EXISTS("nics_virtuals","failover","artica_backup")){$sql="ALTER TABLE `nics_virtuals` ADD `failover` TINYINT( 1 ) NOT NULL,ADD INDEX ( `failover` )";$q->QUERY_SQL($sql,'artica_backup');if(!$q->ok){echo $q->mysql_error."\n$sql\n\n";return;}}
	
	$sql="INSERT INTO nics_virtuals (nic,org,ipaddr,netmask,cdir,gateway,ForceGateway,failover,metric)
	VALUES('{$_GET["nic"]}','{$_GET["org"]}','{$_GET["virt-ipaddr"]}','{$_GET["netmask"]}',
	'{$_GET["cdir"]}','{$_GET["gateway"]}',{$_GET["ForceGateway"]},{$_GET["failover"]},{$_GET["metric"]});
	";
	
	if($_GET["ID"]>0){
		$sql="UPDATE nics_virtuals SET nic='{$_GET["nic"]}',
		org='{$_GET["org"]}',
		ipaddr='{$_GET["virt-ipaddr"]}',
		netmask='{$_GET["netmask"]}',
		cdir='{$_GET["cdir"]}',
		gateway='{$_GET["gateway"]}',
		ForceGateway='{$_GET["ForceGateway"]}',
		failover='{$_GET["failover"]}',
		metric='{$_GET["metric"]}'
		WHERE ID={$_GET["ID"]}";
	}
	writelogs("$sql",__FUNCTION__,__FILE__,__LINE__);
	
	$q->QUERY_SQL($sql,"artica_backup");
	if(!$q->ok){if(preg_match("#Unknown col#i", $q->mysql_error)){$q->BuildTables();$q->QUERY_SQL($sql,"artica_backup");}}
	if(!$q->ok){echo $q->mysql_error."\n$sql\n";}
	
}
Esempio n. 24
0
function ipblocks(){
	if(system_is_overloaded()){return;}
	include_once(dirname(__FILE__) . '/ressources/class.mysql.inc');
	$unix=new unix();
	$php=$unix->LOCATE_PHP5_BIN();
	$nogup=$unix->find_program("nohup");
	$pidfile="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
	$pidtime="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".time";
	$pid=@file_get_contents($pidfile);
	if($unix->process_exists($pid)){echo "Already running pid $pid\n";return;}	
	$q=new mysql();
	if(!$q->TABLE_EXISTS('ipblocks_db','artica_backup')){$q->BuildTables();}
	if(!is_file($pidtime)){
		$count=$q->COUNT_ROWS("ipblocks_db", "artica_backup");
		if($count==0){shell_exec(trim("$nogup /usr/share/artica-postfix/bin/artica-update --ipblocks >/dev/null 2>&1 &"));}
		sleep(5);
		@file_put_contents($pidtime, time());
	}
	
	if($unix->file_time_min($pidtime)>480){
		shell_exec(trim("$nogup /usr/share/artica-postfix/bin/artica-update --ipblocks >/dev/null 2>&1 &"));
		sleep(5);
		@unlink($pidtime);
		@file_put_contents($pidtime, time());
		$unix->THREAD_COMMAND_SET("$php /usr/share/artica-postfix/exec.postfix.iptables.php --ipdeny");
	}
	
	@file_put_contents($pidfile, getmypid());
	
	foreach (glob("/var/log/artica-postfix/ipblocks/*.zone") as $filename) {
		$basename=basename($filename);
		if(!preg_match("#(.+?)\.zone#", $basename,$re)){continue;}
		$country=$re[1];
		$datas=explode("\n", @file_get_contents($filename));
		$f=true;
		
		while (list ($index, $line) = each ($datas) ){
			$line=trim($line);if($line==null){continue;}if($country==null){continue;}
			$sql="INSERT IGNORE INTO ipblocks_db (cdir,country) VALUES('$line','$country')";
			$q->QUERY_SQL($sql,"artica_backup");
			if(!$q->ok){events("ipblocks:: $q->mysql_error line:".__LINE__);$f=false;break;}
		}
		if(!$f){continue;}
		@unlink($filename);
	}
	
	$file_time="/etc/artica-postfix/pids/". basename(__FILE__).".".__FUNCTION__.".time";
	if($unix->file_time_min($file_time)>300){
		$sql="DELETE FROM loadavg WHERE stime < DATE_SUB( NOW( ) , INTERVAL 7 DAY )";
		$q->QUERY_SQL($sql,"artica_events");
		@unlink($file_time);
		@file_put_contents($file_time, time());
	}
	
	
}
Esempio n. 25
0
function lists()
{
    $search = $_GET["search"];
    $page = CurrentPageName();
    $users = new usersMenus();
    $where = null;
    if (strlen($search) > 1) {
        $search = "*{$search}*";
        $search = str_replace("*", "%", $search);
        $search = str_replace("%%", "%", $search);
        $whereOU = "AND ProxyPass LIKE '{$search}'";
    }
    $tpl = new templates();
    $sock = new sockets();
    $delete_freeweb_text = $tpl->javascript_parse_text("{delete_freeweb_text}");
    $sql = "SELECT * FROM freewebs_proxy WHERE servername='{$_GET["servername"]}' {$whereOU} ORDER BY ProxyPass";
    $q = new mysql();
    $q->BuildTables();
    $results = $q->QUERY_SQL($sql, 'artica_backup');
    if (!$q->ok) {
        echo "<H2>{$q->mysql_error}</H2><code>{$sql}</code>";
    }
    $html = "\n<table cellspacing='0' cellpadding='0' border='0' class='tableView' style='width:100%'>\n<thead class='thead'>\n\t<tr>\n\t<th>" . imgtootltip("plus-24.png", "{add}", "Loadjs('{$page}?zmd5-js=&servername={$_GET["servername"]}')") . "</th>\n\t<th>{request_from}</th>\n\t<th>&nbsp;</th>\n\t<th>{redirect_to}</th>\n\t<th>&nbsp;</th>\n\t</tr>\n</thead>\n<tbody class='tbody'>";
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        if ($classtr == "oddRow") {
            $classtr = null;
        } else {
            $classtr = "oddRow";
        }
        $request_from = null;
        $redirect_to = null;
        if (preg_match("#(.+?)\\s+(.+)#", $ligne["ProxyPass"], $re)) {
            $request_from = $re[1];
            $redirect_to = $re[2];
        }
        $html = $html . "\n\t\t\t<tr class={$classtr}>\n\t\t\t<td width=1%>" . imgtootltip("Firewall-Move-Right-32.png", "{edit}", "Loadjs('{$page}?zmd5-js={$ligne["zmd5"]}&servername={$_GET["servername"]}')") . "</td>\n\t\t\t<td nowrap><strong style='font-size:14px'>{$request_from}</strong></td>\n\t\t\t<td width=1%><img src='img/fleche-20-right.png'></td>\n\t\t\t<td nowrap><strong style='font-size:14px'>{$redirect_to}</strong></td>\n\t\t\t<td width=1%>" . imgtootltip("delete-24.png", "{delete}", "ProxyPassDelete('{$ligne["zmd5"]}')") . "</td>\n\t\t\t</tr>\n\t\t\t";
    }
    $html = $html . "\n\t</tbody>\n\t</table>\n\t<script>\n\tvar x_ProxyPassDelete=function (obj) {\n\t\t\tvar results=obj.responseText;\n\t\t\tif(results.length>10){alert(results);}\t\n\t\t\tReversProxySearch();\n\t\t\tYahooWin4Hide();\n\t\t\tif(document.getElementById('main_config_freeweb')){\tRefreshTab('main_config_freeweb');}\n\t\t\tif(document.getElementById('container-www-tabs')){\tRefreshTab('container-www-tabs');}\n\t\t}\t\n\t\t\n\t\tfunction ProxyPassDelete(server){\n\t\t\tif(confirm('{$delete_freeweb_text}')){\n\t\t\t\tvar XHR = new XHRConnection();\n\t\t\t\tXHR.appendData('ProxyPassDelete',server);\n\t\t\t\tAnimateDiv('ProxyPassList');\n    \t\t\tXHR.sendAndLoad('{$page}', 'POST',x_ProxyPassDelete);\n\t\t\t}\n\t\t}\t\n\t</script>\t\n\t\n\t";
    echo $tpl->_ENGINE_parse_body($html);
}
function popup_db_list()
{
    $page = CurrentPageName();
    $tpl = new templates();
    if ($_GET["search"] != null) {
        $_GET["search"] = str_replace("*", "%", $_GET["search"]);
        $filter = "AND ((mailfrom LIKE '{$_GET["search"]}') OR (mailto LIKE '{$_GET["search"]}') OR (ip_addr LIKE '{$_GET["search"]}'))";
    }
    $html = "<center>\n<table cellspacing='0' cellpadding='0' border='0' class='tableView' style='width:100%'>\n<thead class='thead'>\n\t<tr>\n\t\t<th width=1%>{time}</th>\n\t\t<th width=25%>{ipaddr}</th>\n\t\t<th width=25%>{from}</th>\n\t\t<th width=25%>{to}</th>\n\t</tr>\n</thead>\n<tbody class='tbody'>";
    $maxlen = 30;
    $sql = "SELECT * FROM greylist_turples WHERE hostname='{$_GET["hostname"]}' {$filter} LIMIT 0,150";
    $q = new mysql();
    writelogs("{$sql}", __FUNCTION__, __FILE__, __LINE__);
    $results = $q->QUERY_SQL($sql, "artica_events");
    if (!$q->ok) {
        if (preg_match("#doesn.+?t exist#", $q->mysql_error)) {
            $q->BuildTables();
            $q->ok = true;
            $results = $q->QUERY_SQL($sql, "artica_events");
        }
    }
    if (!$q->ok) {
        echo "<H2>{$q->mysql_error}</H2>";
    }
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        if ($ligne["mailfrom"] == "Summary:") {
            continue;
        }
        if (trim($ligne["ip_addr"]) == "#") {
            continue;
        }
        $time = date("Y-m-d H:i:s", $ligne["stime"]);
        if ($classtr == "oddRow") {
            $classtr = null;
        } else {
            $classtr = "oddRow";
        }
        $len = strlen($ligne["mailfrom"]);
        if ($len > $maxlen) {
            $ligne["mailfrom"] = substr($ligne["mailfrom"], 0, $maxlen - 3) . "...";
        }
        $len = strlen($ligne["mailto"]);
        if ($len > $maxlen) {
            $ligne["mailto"] = substr($ligne["mailto"], 0, $maxlen - 3) . "...";
        }
        $color = "black";
        $html = $html . "\n\t\t<tr class={$classtr}>\n\t\t\t<td style='font-size:12px;font-weight:bold;color:{$color}' nowrap>{$time}</td>\n\t\t\t<td style='font-size:12px;font-weight:bold;color:{$color}' width=1% nowrap>{$ligne["ip_addr"]}</a></td>\n\t\t\t<td style='font-size:12px;font-weight:bold;color:{$color}' width=50%>{$ligne["mailfrom"]}</a></td>\n\t\t\t<td style='font-size:12px;font-weight:bold;color:{$color}' width=50>{$ligne["mailto"]}</a></td>\n\t\t</tr>\n\t\t";
    }
    $html = $html . "</table></center>";
    echo $tpl->_ENGINE_parse_body($html);
}
Esempio n. 27
0
function wakeup_server_mode(){
	$unix=new unix();
	$pidpath="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".pid";
	$pidtime="/etc/artica-postfix/pids/".basename(__FILE__).".".__FUNCTION__.".time";
	$oldpid=@file_get_contents($pidpath);
	if($unix->process_exists($oldpid)){writelogs("OpenVPN Already instance executed pid $oldpid",__FUNCTION__,__FILE__,__LINE__);return;}
	@file_put_contents($pidpath, posix_getpid());
	$time=$unix->file_time_min($pidtime);
	
	if($time<2){return;}
	writelogs("OpenVPN $pidtime -> {$time}Mn",__FUNCTION__,__FILE__,__LINE__);
	@unlink($pidtime);
	@file_put_contents($pidtime, time());
	
	
	$sql="SELECT ID,sitename,wakeupip,wakeupok FROM vpnclient WHERE connexion_type=1";
	$q=new mysql();
	$results=$q->QUERY_SQL($sql,"artica_backup");
	if(!$q->ok){
		writelogs("Fatal,$q->mysql_error",__FUNCTION__,__FILE__,__LINE__);
		if(preg_match("#Unknown column", $q->mysql_error)){$q->BuildTables();}
		return;
		}
	$ping=$unix->find_program("ping");
	if(!is_file($ping)){writelogs("Fatal,ping, no such binary",__FUNCTION__,__FILE__,__LINE__);return;}
	
	$tcp=new ip();
	while($ligne=mysql_fetch_array($results,MYSQL_ASSOC)){
		if(!$tcp->isValid($ligne["wakeupip"])){
			writelogs("OpenVPN {$ligne["sitename"]} \"{$ligne["wakeupip"]}\" is not a valid ip address",__FUNCTION__,__FILE__,__LINE__);
			continue;
		}
		$wakeupok=$ligne["wakeupok"];
		$resultsPing=array();
		exec("$ping -c2 -i0.2 {$ligne["wakeupip"]} 2>&1",$resultsPing);
		writelogs("OpenVPN {$ligne["sitename"]} \"{$ligne["wakeupip"]}\" ".count($resultsPing)." rows",__FUNCTION__,__FILE__,__LINE__);
		$text=date("Y-m-d H:i:s")."\n".@implode("\n", $resultsPing);
		$note=0;
		while (list ($nimber, $l) = each ($resultsPing) ){
			if(preg_match("#,\s+([0-9]+)\%\s+#", $l,$re)){
				writelogs("OpenVPN {$ligne["sitename"]} \"{$re[1]}%\" Packets lost",__FUNCTION__,__FILE__,__LINE__);
				if($re[1]==100){
					$note=-1;
					writelogs("OpenVPN {$ligne["sitename"]} Ping failed",__FUNCTION__,__FILE__,__LINE__);
					$unix->send_email_events("[VPN]: {$ligne["sitename"]} wake up failed {$ligne["wakeupip"]}" , "It seems that this remote site did not respond\n$text", "vpn");
				}else{
					$note=1;
					if($wakeupok<>1){$unix->send_email_events("[VPN]: {$ligne["sitename"]} wake up success {$ligne["wakeupip"]}" , "It seems that the connection to this remote site is established\n$text", "vpn");}
				}
			break;}
		}
		
		$sql="UPDATE vpnclient SET wakeup_results='$text' ,wakeupok='$note' WHERE ID='{$ligne["ID"]}'";
		$q->QUERY_SQL($sql,"artica_backup");
	}
}
Esempio n. 28
0
if($time<10080){die();}


$f=@file_get_contents($file);

$md5=md5($f);
$oldMd5=md5(trim(@file_get_contents("/etc/artica-postfix/UserAgents.cache")));
writelogs("$md5 == $oldMd5","MAIN",__FILE__,__LINE__);
if($md5==$oldMd5){
	writelogs("No changes","MAIN",__FILE__,__LINE__);
	die();
}
@file_put_contents("/etc/artica-postfix/UserAgents.cache","$md5");

$q=new mysql();
$q->BuildTables();
$datas=explode("\n",$f);
writelogs(count($f)." Lines to parse","MAIN",__FILE__,__LINE__);


while (list ($index, $line) = each ($datas) ){
	if(trim($line)==null){continue;}
	if(strpos($line,'*')==0){
	if(preg_match("#^([A-Za-z0-9\s\.]+)#",$line,$re)){
		$key=$re[1];
		echo $key."\n";
		continue;
	}}
	
	if(preg_match("#\s+\*(.+)#",$line,$re)){
		$array[$key][md5($re[1])]=$re[1];
function main_table()
{
    $t = time();
    $page = CurrentPageName();
    $tpl = new templates();
    $users = new usersMenus();
    $sock = new sockets();
    $q = new mysql();
    if (!$q->TABLE_EXISTS("sender_dependent_relay_host", "artica_backup")) {
        $q->BuildTables();
    }
    $t = time();
    $domain = $tpl->_ENGINE_parse_body("{sender_domain_email}");
    $are_you_sure_to_delete = $tpl->javascript_parse_text("{are_you_sure_to_delete}");
    $relay = $tpl->javascript_parse_text("{relay}");
    $MX_lookups = $tpl->javascript_parse_text("{MX_lookups}");
    $delete = $tpl->javascript_parse_text("{delete}");
    $InternetDomainsAsOnlySubdomains = $sock->GET_INFO("InternetDomainsAsOnlySubdomains");
    if (!is_numeric($InternetDomainsAsOnlySubdomains)) {
        $InternetDomainsAsOnlySubdomains = 0;
    }
    $add_local_domain_form_text = $tpl->javascript_parse_text("{add_local_domain_form}");
    $add_local_domain = $tpl->_ENGINE_parse_body("{add_local_domain}");
    $sender_dependent_relayhost_maps_title = $tpl->_ENGINE_parse_body("{sender_dependent_relayhost_maps_title}");
    $ouescape = urlencode($ou);
    $destination = $tpl->javascript_parse_text("{destination}");
    $hostname = $_GET["hostname"];
    $apply = $tpl->javascript_parse_text("{apply}");
    $about2 = $tpl->javascript_parse_text("{about2}");
    $add_sender_routing_rule = $tpl->_ENGINE_parse_body("{add_sender_routing_rule}");
    $add_remote_domain = Paragraphe("64-remotedomain-add.png", '{add_relay_domain}', '{add_relay_domain_text}', "javascript:AddRemoteDomain_form(\"{$ou}\",\"new domain\")", "add_relay_domain", 210);
    $buttons = "\n\tbuttons : [\n\t{name: '{$add_sender_routing_rule}', bclass: 'add', onpress : add_sender_routing_rule{$t}},\n\t{name: '{$apply}', bclass: 'apply', onpress : apply_sender_routing_rule{$t}},\n\t{name: '{$about2}', bclass: 'help', onpress : Help{$t}},\n\t],";
    $explain = $tpl->javascript_parse_text("{postfix_transport_senders_explain}");
    $html = "\n\t<input type='hidden' id='ou' value='{$ou}'>\n\t<table class='SENDER_DEPENDENT_RELAY_HOST' style='display: none' id='SENDER_DEPENDENT_RELAY_HOST' style='width:100%'></table>\n\t<script>\n\t\$(document).ready(function(){\n\t\$('#SENDER_DEPENDENT_RELAY_HOST').flexigrid({\n\turl: '{$page}?relay-sender-table-list=yes&hostname={$hostname}&t={$t}',\n\tdataType: 'json',\n\tcolModel : [\n\t{display: '{$domain}', name : 'domain', width : 428, sortable : true, align: 'left'},\n\t{display: '{$relay}', name : 'relay', width :260, sortable : true, align: 'left'},\n\t{display: 'AUTH', name : 'zOrders', width : 50, sortable : false, align: 'center'},\n\t{display: 'UP', name : 'zOrders', width : 50, sortable : true, align: 'center'},\n\t{display: 'DOWN', name : 'zOrders', width : 50, sortable : true, align: 'center'},\n\t{display: '{$delete};', name : 'delete', width : 75, sortable : false, align: 'center'},\n\t],\n\t{$buttons}\n\tsearchitems : [\n\t{display: '{$domain}', name : 'domain'},\n\t{display: '{$relay}', name : 'relay'},\n\t],\n\tsortname: 'zOrders',\n\tsortorder: 'asc',\n\tusepager: true,\n\ttitle: '',\n\tuseRp: true,\n\trp: 50,\n\tshowTableToggleBtn: false,\n\twidth: '99%',\n\theight: '550',\n\tsingleSelect: true,\n\trpOptions: [10, 20, 30, 50,100,200]\n\n});\n});\n\nfunction  Help{$t}(){\nalert('{$explain}');\n}\n\nvar RefreshTable{$t}= function (obj) {\n\tvar results=obj.responseText;\n\tif (results.length>0){alert(results);return;}\n\t\$('#SENDER_DEPENDENT_RELAY_HOST').flexReload();\n}\n\nfunction MoveSubRuleLinks{$t}(mkey,direction){\n\tvar XHR = new XHRConnection();\n\tXHR.appendData('item-move', mkey);\n\tXHR.appendData('direction', direction);\n\tXHR.appendData('hostname', '{$hostname}');\n\tXHR.sendAndLoad('{$page}', 'POST',RefreshTable{$t});\t\n}\n\nfunction add_sender_routing_rule{$t}(){\n\tLoadjs('{$page}?item-js=yes&zmd5=&hostname={$hostname}');\n}\n\nfunction sender_routing_ruleED{$t}(domainName){\n\tYahooWin3(552,'postfix.routing.table.php?SenderTable=yes&domainName='+domainName+'&t={$t}','{$sender_dependent_relayhost_maps_title}::'+domainName);\n}\n\n\nfunction apply_sender_routing_rule{$t}(){\n\tLoadjs('postfix.sender.routing.progress.php?hostname={$hostname}');\n\n}\n\n</script>\n";
    echo $html;
}
Esempio n. 30
0
function items_list()
{
    $tpl = new templates();
    $MyPage = CurrentPageName();
    $q = new mysql();
    if (!$q->TABLE_EXISTS("phpmyadminsecu", "artica_backup")) {
        $q->BuildTables();
    }
    $t = $_GET["t"];
    $search = '%';
    $table = "phpmyadminsecu";
    $database = "artica_backup";
    $page = 1;
    $ORDER = null;
    $FORCE_FILTER = null;
    if ($q->COUNT_ROWS($table, $database) == 0) {
        $data['page'] = $page;
        $data['total'] = $total;
        $data['rows'] = array();
        echo json_encode($data);
        return;
    }
    if (isset($_POST["sortname"])) {
        if ($_POST["sortname"] != null) {
            $ORDER = "ORDER BY {$_POST["sortname"]} {$_POST["sortorder"]}";
        }
    }
    if (isset($_POST['page'])) {
        $page = $_POST['page'];
    }
    if ($_POST["query"] != null) {
        $_POST["query"] = str_replace("*", "%", $_POST["query"]);
        $search = $_POST["query"];
        $searchstring = "AND (`{$_POST["qtype"]}` LIKE '{$search}')";
        $sql = "SELECT COUNT(*) as TCOUNT FROM `{$table}` WHERE 1 {$FORCE_FILTER} {$searchstring}";
        $ligne = mysql_fetch_array($q->QUERY_SQL($sql, "artica_backup"));
        $total = $ligne["TCOUNT"];
    } else {
        $total = $q->COUNT_ROWS($table, $database);
    }
    if (isset($_POST['rp'])) {
        $rp = $_POST['rp'];
    }
    $pageStart = ($page - 1) * $rp;
    $limitSql = "LIMIT {$pageStart}, {$rp}";
    if ($OnlyEnabled) {
        $limitSql = null;
    }
    $sql = "SELECT *  FROM `{$table}` WHERE 1 {$FORCE_FILTER} {$searchstring} {$ORDER} {$limitSql}";
    writelogs($sql, __FUNCTION__, __FILE__, __LINE__);
    $results = $q->QUERY_SQL($sql, $database);
    $data = array();
    $data['page'] = $page;
    $data['total'] = $total;
    $data['rows'] = array();
    if (mysql_num_rows($results) == 0) {
        $data['rows'][] = array('id' => $ligne[time()], 'cell' => array($sql, "", "", ""));
    }
    $typeA[0] = "{ip_address}";
    $typeA[1] = "{hostname}";
    while ($ligne = mysql_fetch_assoc($results)) {
        $color = "black";
        $md5 = md5($ligne["ID"] . $ligne["pattern"]);
        $js = "<a href=\"javascript:blur();\" OnClick=\"javascript:Loadjs('{$MyPage}?item-js=yes&table={$t}&ID={$ligne["ID"]}');\"\n\t\tstyle='font-size:16px;color:{$color};text-decoration:underline'>";
        $delete = imgtootltip("delete-24.png", "{delete}", "DeletedMysqlItemDen('{$ligne["ID"]}','{$md5}')");
        $enable = Field_checkbox($md5, 1, $ligne["enabled"], "MysqlEnableItem('{$md5}','{$ligne["ID"]}')");
        $data['rows'][] = array('id' => $md5, 'cell' => array("{$js}{$ligne["pattern"]}</a>", $tpl->_ENGINE_parse_body("<span style='font-size:14px;color:{$color}'>{$js}{$typeA[$ligne["type"]]}</a></span>"), "<div style='margin-top:5px'>{$enable}</div>", $delete));
    }
    echo json_encode($data);
}