Example #1
0
function build()
{
    $users = new usersMenus();
    $sock = new sockets();
    $unix = new unix();
    $SystemLoadNotif = $sock->GET_INFO("SystemLoadNotif");
    if (!is_numeric($SystemLoadNotif)) {
        $SystemLoadNotif = 0;
    }
    $EnableSyslogDB = $sock->GET_INFO("EnableSyslogDB");
    if (!is_numeric($EnableSyslogDB)) {
        $EnableSyslogDB = 0;
    }
    $MySQLSyslogType = $sock->GET_INFO("MySQLSyslogType");
    if (!is_numeric($MySQLSyslogType)) {
        $MySQLSyslogType = 1;
    }
    $SquidPerformance = intval($sock->GET_INFO("SquidPerformance"));
    $EnableIntelCeleron = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableIntelCeleron"));
    $python = $unix->find_program("python");
    $nice = $unix->EXEC_NICE();
    $ps = $unix->find_program("ps");
    $sort = $unix->find_program("sort");
    $head = $unix->find_program("head");
    $echo = $unix->find_program("echo");
    $date = $unix->find_program("date");
    $mkdir = $unix->find_program("mkdir");
    $php5 = $unix->LOCATE_PHP5_BIN();
    $ZarafaDedicateMySQLServer = $sock->GET_INFO("ZarafaDedicateMySQLServer");
    if (!is_numeric($ZarafaDedicateMySQLServer)) {
        $ZarafaDedicateMySQLServer = 0;
    }
    build_progress_restart("{reconfiguring}", 22);
    $ini = new Bs_IniHandler();
    $ini->loadFile('/etc/artica-postfix/smtpnotif.conf');
    if (!is_numeric($ini->_params["SMTP"]["EnableNotifs"])) {
        $ini->_params["SMTP"]["EnableNotifs"] = 0;
    }
    if (!is_numeric($ini->_params["SMTP"]["tls_enabled"])) {
        $ini->_params["SMTP"]["tls_enabled"] = 0;
    }
    $smtp_server = trim($ini->_params["SMTP"]['smtp_server_name']);
    $smtp_server_port = $ini->_params["SMTP"]['smtp_server_port'];
    $smtp_dest = $ini->_params["SMTP"]['smtp_dest'];
    $smtp_sender = $ini->_params["SMTP"]['smtp_sender'];
    $smtp_auth_user = $ini->_params["SMTP"]['smtp_auth_user'];
    $smtp_auth_passwd = $ini->_params["SMTP"]['smtp_auth_passwd'];
    $tls_enabled = $ini->_params["SMTP"]["tls_enabled"];
    $recipientsZ = explode("\n", "/etc/artica-postfix/settings/Daemons/SmtpNotificationConfigCC");
    $recipients = array();
    while (list($index, $to) = each($recipientsZ)) {
        if (trim($to) == null) {
            continue;
        }
        $recipients[] = $to;
    }
    if ($smtp_server == null) {
        $ini->_params["SMTP"]["EnableNotifs"] = 0;
    }
    if ($smtp_dest == null) {
        if (count($recipients) == 0) {
            $ini->_params["SMTP"]["EnableNotifs"] = 0;
        }
    }
    if (!is_numeric($smtp_server_port)) {
        $smtp_server_port = 25;
    }
    $EnableNotifs = $ini->_params["SMTP"]["EnableNotifs"];
    $monit_not_on = 'instance,action';
    $f[] = 'set daemon 60 with start delay 5';
    $f[] = 'set idfile /var/run/monit/monit.id';
    $cpunum = $unix->CPU_NUMBER();
    $normal = $cpunum * 2 + 1;
    $normal2 = $cpunum * 2;
    $busy = $cpunum * 4;
    build_progress_restart("{reconfiguring}", 23);
    $EnableMONITSmtpNotif = $sock->GET_INFO("EnableMONITSmtpNotif");
    if (!is_numeric($EnableMONITSmtpNotif)) {
        $EnableMONITSmtpNotif = 1;
    }
    $MonitCPUUsage = intval($sock->GET_INFO("MonitCPUUsage"));
    $MonitCPUUsageCycles = intval($sock->GET_INFO("MonitCPUUsageCycles"));
    $MonitMemUsage = intval($sock->GET_INFO("MonitMemUsage"));
    $MonitMemUsageCycles = intval($sock->GET_INFO("MonitMemUsageCycles"));
    $MonitReportLoadVG1mn = intval($sock->GET_INFO("MonitReportLoadVG1mn"));
    $MonitReportLoadVG1mnCycles = intval($sock->GET_INFO("MonitReportLoadVG1mnCycles"));
    if ($MonitReportLoadVG1mnCycles == 0) {
        $MonitReportLoadVG1mnCycles = 5;
    }
    $MonitReportLoadVG5mn = intval($sock->GET_INFO("MonitReportLoadVG5mn"));
    $MonitReportLoadVG5mnCycles = intval($sock->GET_INFO("MonitReportLoadVG5mnCycles"));
    if ($MonitReportLoadVG5mnCycles == 0) {
        $MonitReportLoadVG5mnCycles = 15;
    }
    $MonitReportLoadVG15mn = intval($sock->GET_INFO("MonitReportLoadVG15mn"));
    $MonitReportLoadVG15mnCycles = intval($sock->GET_INFO("MonitReportLoadVG15mnCycles"));
    if ($MonitReportLoadVG15mnCycles == 0) {
        $MonitReportLoadVG15mnCycles = 60;
    }
    $MonitMemPurgeCache = intval($sock->GET_INFO("MonitMemPurgeCache"));
    $MonitMemPurgeCacheCycles = intval($sock->GET_INFO("MonitMemPurgeCacheCycles"));
    if ($MonitMemPurgeCache == 0) {
        $MonitMemPurgeCache = 70;
    }
    if ($MonitMemPurgeCacheCycles == 0) {
        $MonitMemPurgeCacheCycles = 5;
    }
    if ($MonitMemUsageCycles == 0) {
        $MonitMemUsageCycles = 5;
    }
    if ($MonitCPUUsageCycles == 0) {
        $MonitCPUUsageCycles = 15;
    }
    if ($MonitCPUUsage > 0) {
        if ($MonitCPUUsage < 50) {
            $MonitCPUUsage = 90;
        }
    }
    if ($MonitMemUsage > 0) {
        if ($MonitMemUsage < 50) {
            $MonitMemUsage = 90;
        }
    }
    build_progress_restart("{reconfiguring}", 24);
    $rmbin = $unix->find_program("rm");
    $echo = $unix->find_program("echo");
    $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
    if (!is_numeric($SQUIDEnable)) {
        $SQUIDEnable = 1;
    }
    $f[] = 'set logfile syslog facility log_daemon';
    $f[] = 'set statefile /var/run/monit/monit.state';
    $f[] = '';
    if ($EnableNotifs == 1) {
        if ($EnableMONITSmtpNotif == 1) {
            $f[] = "set mailserver {$smtp_server} PORT {$smtp_server_port}";
            if (strlen($smtp_auth_user) > 0) {
                $f[] = "\tUSERNAME \"{$smtp_auth_user}\" PASSWORD \"{$smtp_auth_passwd}\"";
            }
            if ($tls_enabled == 1) {
                $f[] = "\tusing TLSV1";
            }
            $f[] = "\tset eventqueue";
            $f[] = "\tbasedir /var/monit";
            $f[] = "\tslots 100";
            $f[] = "\tset mail-format {";
            $f[] = "\t\tfrom: {$smtp_sender}";
            $f[] = "\t\tsubject: Artica service monitor: \$SERVICE \$EVENT";
            $f[] = "\t\tmessage: Artica service monitor  \$ACTION  \$SERVICE at  \$DATE on  \$HOST:  \$DESCRIPTION";
            $f[] = "\t}";
            $f[] = "set alert {$smtp_dest} but not on {{$monit_not_on}}";
            if ($recipients > 0) {
                while (list($index, $to) = each($recipientsZ)) {
                    $f[] = "set alert {$to} but not on {{$monit_not_on}}";
                }
            }
        }
    }
    build_progress_restart("{reconfiguring}", 25);
    $allips = $unix->NETWORK_ALL_INTERFACES(true);
    $f[] = "set httpd port 2874 and use address 127.0.0.1";
    $f[] = "\tallow 127.0.0.1";
    while (list($tcpi, $to) = each($allips)) {
        $f[] = "\tallow {$tcpi}";
    }
    $top = $unix->find_program("top");
    $hostname = $unix->hostname_g();
    $TSCR = array();
    if ($MonitReportLoadVG1mn > 0) {
        $TSCR[] = "\tif loadavg (1min) > {$MonitReportLoadVG1mn} for {$MonitReportLoadVG1mnCycles} cycles then exec \"/bin/artica-system-alert.sh LOAD_1 {$MonitReportLoadVG1mn}\"";
    }
    if ($MonitReportLoadVG5mn > 0) {
        $TSCR[] = "\tif loadavg (5min) > {$MonitReportLoadVG5mn} for {$MonitReportLoadVG5mnCycles} cycles then exec \"/bin/artica-system-alert.sh LOAD_5 {$MonitReportLoadVG5mn}\"";
    }
    if ($MonitReportLoadVG15mn > 0) {
        $TSCR[] = "\tif loadavg (15min) > {$MonitReportLoadVG15mn} for {$MonitReportLoadVG15mnCycles} cycles then exec \"/bin/artica-system-alert.sh LOAD_15 {$MonitReportLoadVG15mn}\"";
    }
    if ($MonitCPUUsage > 0) {
        if ($MonitCPUUsage < 75) {
            $MonitCPUUsage = 75;
        }
        $TSCR[] = "\tif cpu usage(system) > {$MonitCPUUsage}% for {$MonitCPUUsageCycles} cycles then exec \"/bin/artica-system-alert.sh CPU_SYSTEM {$MonitCPUUsage}\"";
        $TSCR[] = "\tif cpu usage(user) > {$MonitCPUUsage}% for {$MonitCPUUsageCycles} cycles then exec \"/bin/artica-system-alert.sh CPU_USER {$MonitCPUUsage}\"";
        $TSCR[] = "\tif cpu usage(wait) > {$MonitCPUUsage}% for {$MonitCPUUsageCycles} cycles then exec \"/bin/artica-system-alert.sh CPU_WAIT {$MonitCPUUsage}\"";
    }
    if ($MonitMemUsage > 0) {
        if ($MonitMemUsage < 75) {
            $MonitMemUsage = 75;
        }
        $TSCR[] = "\tif memory > {$MonitMemUsage}% for {$MonitMemUsageCycles} cycles then exec \"/bin/artica-system-alert.sh MEM {$MonitMemUsage}\"";
    }
    if ($MonitMemPurgeCache > 5) {
        @chmod("/usr/share/artica-postfix/exec.kernel.purge.cache.php", 0755);
        $TSCR[] = "\tif memory > {$MonitMemPurgeCache}% for {$MonitMemPurgeCacheCycles} cycles then exec \"/usr/share/artica-postfix/exec.kernel.purge.cache.php\"";
    }
    if (count($TSCR) > 1) {
        $f[] = "check system " . $unix->hostname_g();
        $f[] = @implode("\n", $TSCR);
    }
    $TSCR = array();
    $SCRIPT = array();
    $SCRIPT[] = "#!/bin/sh";
    $SCRIPT[] = "CURRENT=`{$date} +%s`";
    $SCRIPT[] = "DIR=\"/home/artica/system/perf-queue/\$CURRENT\"";
    $SCRIPT[] = "{$mkdir} -p \"\$DIR\"";
    $SCRIPT[] = "{$echo} \$CURRENT >\$DIR/time.txt";
    $SCRIPT[] = "{$echo} \$1 >\$DIR/why.txt";
    $SCRIPT[] = "{$echo} \$2 >\$DIR/why2.txt";
    $iotop = $unix->find_program("iotop");
    if (is_file($iotop)) {
        $SCRIPT[] = "{$iotop} -o -a -b -q -t -n 20  >\$DIR/iotop.txt || true";
    }
    $SCRIPT[] = "{$nice} {$python} /usr/share/artica-postfix/bin/ps_mem.py >\$DIR/psmem.txt 2>&1";
    $SCRIPT[] = "{$ps} --no-heading -eo user,pid,pcpu,args|{$sort} -grbk 3|{$head} -50 >\$DIR/TOP50-CPU.txt 2>&1";
    $SCRIPT[] = "{$ps} --no-heading -eo user,pid,pmem,args|{$sort} -grbk 3|{$head} -50 >\$DIR/TOP50-MEM.txt 2>&1";
    $SCRIPT[] = "{$ps} auxww  >\$DIR/ALLPS.txt 2>&1";
    $SCRIPT[] = "";
    @file_put_contents("/bin/artica-system-alert.sh", @implode("\n", $SCRIPT));
    @chmod("/bin/artica-system-alert.sh", 0755);
    $SCRIPT = array();
    $f[] = "";
    $f[] = "check host loopback with address 127.0.0.1";
    $f[] = "\tif failed icmp type echo with timeout 1 seconds then exec \"/bin/loopbackfailed.sh\"";
    $f[] = "";
    $loopbackfailed[] = "#!/bin/sh";
    $loopbackfailed[] = "{$php5} /usr/share/artica-postfix/exec.virtuals-ip.php --loopback";
    $loopbackfailed[] = "";
    @file_put_contents("/bin/loopbackfailed.sh", @implode("\n", $loopbackfailed));
    @chmod("/bin/loopbackfailed.sh", 0755);
    $loopbackfailed = array();
    build_progress_restart("{reconfiguring}", 25);
    //********************************************************************************************************************
    $f[] = "check file php.log with path /var/log/php.log";
    $f[] = "\tif size > 100 MB then";
    $f[] = "\t\texec \"/bin/clean-phplog.sh\"";
    $f[] = "";
    $f[] = "check file usrphp.log with path /usr/share/artica-postfix/ressources/logs/php.log";
    $f[] = "      if size > 100 MB then";
    $f[] = "\t\texec \"/bin/clean-phplog.sh\"";
    $f[] = "";
    $f[] = "check file squid-logger-start.log with path /var/log/artica-postfix/squid-logger-start.log";
    $f[] = "\tif size > 100 MB then";
    $f[] = "\t\texec \"/bin/squid-logger-start.sh\"";
    $f[] = "";
    build_progress_restart("{reconfiguring}", 26);
    $f[] = "include /etc/monit/conf.d/*";
    @file_put_contents("/etc/monit/monitrc", @implode("\n", $f));
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} /etc/monit/monitrc done...\n";
    }
    $AA[] = "#!/bin/sh";
    $AA[] = "{$echo} \"#\" >/var/log/artica-postfix/squid-logger-start.log";
    $AA[] = "";
    @file_put_contents("/bin/squid-logger-start.sh", @implode("\n", $AA));
    @chmod("/bin/squid-logger-start.sh", 0755);
    $AA = array();
    $AA[] = "#!/bin/sh";
    $AA[] = "{$echo} \"#\" >/var/log/php.log";
    $AA[] = "";
    @file_put_contents("/bin/clean-phplog.sh", @implode("\n", $AA));
    @chmod("/bin/clean-phplog.sh", 0755);
    $AA = array();
    $monit = new monit();
    $monit->save();
    $INITD_PATH = $unix->SLAPD_INITD_PATH();
    $SLAPD_PID_FILE = $unix->SLAPD_PID_PATH();
    $squidbin = $unix->LOCATE_SQUID_BIN();
    @unlink("/etc/monit/conf.d/APP_OPENLDAP.monitrc");
    //********************************************************************************************************************
    $f = array();
    //********************************************************************************************************************
    build_progress_restart("{reconfiguring}", 27);
    $f = array();
    $f[] = "check process APP_FRAMEWORK";
    $f[] = "with pidfile /var/run/lighttpd/framework.pid";
    $f[] = "start program = \"/etc/init.d/artica-framework start --monit\"";
    $f[] = "stop program =  \"/etc/init.d/artica-framework stop --monit\"";
    $f[] = "if 5 restarts within 5 cycles then timeout";
    @file_put_contents("/etc/monit/conf.d/articaframework.monitrc", @implode("\n", $f));
    $f = array();
    //********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/APP_OPENSSH.monitrc");
    @unlink("/etc/monit/conf.d/APP_MYSQLD.monitrc");
    //********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring}", 28);
    $f[] = "check process APP_ARTICA_STATUS with pidfile /etc/artica-postfix/exec.status.php.pid";
    $f[] = "\tstart program = \"/etc/init.d/artica-status start --monit\"";
    $f[] = "\tstop program = \"/etc/init.d/artica-status stop --monit\"";
    $f[] = "\tif 5 restarts within 5 cycles then timeout";
    $f[] = "";
    if ($GLOBALS["OUTPUT"]) {
        echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Status...\n";
    }
    @file_put_contents("/etc/monit/conf.d/APP_ARTICASTATUS.monitrc", @implode("\n", $f));
    //********************************************************************************************************************
    $f = array();
    $EnableInflux = 1;
    if ($SquidPerformance > 2) {
        $EnableInflux = 0;
    }
    $InfluxUseRemote = intval($sock->GET_INFO("InfluxUseRemote"));
    $EnableInfluxDB = intval($sock->GET_INFO("EnableInfluxDB"));
    if ($InfluxUseRemote == 1) {
        $EnableInfluxDB = 0;
    }
    if ($EnableIntelCeleron == 1) {
        $EnableInflux = 0;
    }
    if ($EnableInfluxDB == 0) {
        $EnableInflux = 0;
    }
    if (is_file("/etc/artica-postfix/STATS_APPLIANCE")) {
        $EnableInflux = 1;
    }
    build_progress_restart("{reconfiguring}", 29);
    @unlink("/etc/monit/conf.d/APP_INFLUXDB.monitrc");
    @unlink("/etc/monit/conf.d/APP_POSTGRES.monitrc");
    if (is_file("/usr/local/ArticaStats/bin/postgres")) {
        if ($EnableInflux == 1) {
            $InfluxRestartMem = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/InfluxRestartMem"));
            $f[] = "check process APP_POSTGRES with pidfile /home/ArticaStatsDB/postmaster.pid";
            $f[] = "\tstart program = \"/etc/init.d/artica-postgres start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/artica-postgres --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            if ($InfluxRestartMem > 50) {
                $f[] = "\tif totalmem > {$InfluxRestartMem} MB for 5 cycles then restart";
            }
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Status...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_POSTGRES.monitrc", @implode("\n", $f));
            //********************************************************************************************************************
        }
    }
    $f = array();
    @unlink("/etc/monit/conf.d/squid.monitrc");
    @unlink("/etc/monit/conf.d/APP_SQUIDMAIN.monitrc");
    // ********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/APP_SQUIDDB.monitrc");
    build_progress_restart("{reconfiguring} Proxy service", 30);
    if (is_dir("/opt/squidsql/data")) {
        if ($SQUIDEnable == 1) {
            $f = array();
            $f[] = "check process APP_SQUID_DB with pidfile /var/run/squid-db.pid";
            $f[] = "\tstart program = \"/etc/init.d/squid-db start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/squid-db stop --monit\"";
            $f[] = "\tif failed unixsocket /var/run/mysqld/squid-db.sock then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Squid MySQL DB...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SQUIDDB.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring} Dnsmasq", 31);
    @unlink("/etc/monit/conf.d/APP_DNSMASQ.monitrc");
    if ($users->dnsmasq_installed) {
        $enabled = $sock->dnsmasq_enabled();
        if ($enabled == 1) {
            $f[] = "check process APP_DNSMASQ with pidfile /var/run/dnsmasq.pid";
            $f[] = "\tstart program = \"/etc/init.d/dnsmasq start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/dnsmasq stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DnsMASQ...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_DNSMASQ.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring} Proftpd", 31);
    @unlink("/etc/monit/conf.d/APP_PROFTPD.monitrc");
    $proftpd = $unix->find_program("proftpd");
    if (is_file($proftpd)) {
        $enabled = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableProFTPD"));
        if ($enabled == 1) {
            $f[] = "check process APP_PROFTPD with pidfile /var/run/proftpd.pid";
            $f[] = "\tstart program = \"/etc/init.d/proftpd start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/proftpd stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DnsMASQ...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_PROFTPD.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring} Bandwidthd", 31);
    @unlink("/etc/monit/conf.d/APP_BANDWIDTHD.monitrc");
    if (is_file("/usr/bandwidthd/bandwidthd")) {
        $enabled = $sock->Bandwidthd_enabled();
        if ($enabled == 1) {
            $f[] = "check process APP_BANDWIDTHD with pidfile /var/run/bandwidthd.pid";
            $f[] = "\tstart program = \"/etc/init.d/bandwidthd start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/bandwidthd stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DnsMASQ...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_BANDWIDTHD.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring} rsyslog", 32);
    $rsyslogd = $unix->find_program("rsyslogd");
    @unlink("/etc/monit/conf.d/APP_RSYSLOG.monitrc");
    if (is_file($rsyslogd)) {
        $SCRIPT = array();
        $SCRIPT[] = "#!/bin/sh";
        $SCRIPT[] = "{$php5} /usr/share/artica-postfix/exec.watchdog.rsyslogd.php --start";
        $SCRIPT[] = "";
        @file_put_contents("/bin/artica-rsyslog-start.sh", @implode("\n", $SCRIPT));
        @chmod("/bin/artica-rsyslog-start.sh", 0755);
        $SCRIPT = array();
        $SCRIPT[] = "#!/bin/sh";
        $SCRIPT[] = "{$php5} /usr/share/artica-postfix/exec.watchdog.rsyslogd.php --stop";
        $SCRIPT[] = "";
        @file_put_contents("/bin/artica-rsyslog-stop.sh", @implode("\n", $SCRIPT));
        @chmod("/bin/artica-rsyslog-stop.sh", 0755);
        $SCRIPT = array();
        $f[] = "check process APP_RSYSLOG with pidfile /var/run/rsyslogd.pid";
        $f[] = "\tstart program = \"/bin/artica-rsyslog-start.sh\"";
        $f[] = "\tstop program = \"/bin/artica-rsyslog-stop.sh\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring rsyslogd...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_RSYSLOG.monitrc", @implode("\n", $f));
    }
    // ********************************************************************************************************************
    build_progress_restart("{reconfiguring} Squid-tail", 32);
    $APP_ARTICA_SQUID_TAIL = $unix->SQUID_TAIL_ENABLED();
    @unlink("/etc/monit/conf.d/APP_ARTICA_SQUID_TAIL.monitrc");
    if ($APP_ARTICA_SQUID_TAIL == 1) {
        $f = array();
        $f[] = "check process APP_ARTICA_SQUID_TAIL with pidfile /etc/artica-postfix/pids/exec.logfile_daemon.php.pid";
        $f[] = "\tstart program = \"/etc/init.d/squid-tail start\"";
        $f[] = "\tstop program = \"/etc/init.d/squid-tail stop\"";
        $f[] = "\tif cpu usage > 95% for 5 cycles then restart";
        $f[] = "\tif totalmem > 550.0 MB for 5 cycles then restart";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring squid-tail...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_ARTICA_SQUID_TAIL.monitrc", @implode("\n", $f));
    }
    // ********************************************************************************************************************
    build_progress_restart("{reconfiguring} Squid-Proxy", 32);
    $APP_SQUID = $unix->SQUID_ENABLED();
    @unlink("/etc/monit/conf.d/APP_SQUID.monitrc");
    if ($APP_SQUID == 1) {
        $MonitConfig = unserialize(base64_decode(@file_get_contents("/etc/artica-postfix/settings/SquidWatchdogMonitConfig")));
        if (!isset($MonitConfig["watchdog"])) {
            $MonitConfig["watchdog"] = 1;
        }
        if (!is_numeric($MonitConfig["watchdog"])) {
            $MonitConfig["watchdog"] = 1;
        }
        $f = array();
        if ($MonitConfig["watchdog"] == 1) {
            $MonitSquidMaxRestartMem = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/MonitSquidMaxRestartMem"));
            $MonitSquidMaxCPU = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/MonitSquidMaxCPU"));
            $f[] = "check process APP_SQUID with pidfile /var/run/squid/squid.pid";
            $f[] = "\tstart program = \"/etc/init.d/squid start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/squid stop --monit\"";
            if ($MonitSquidMaxCPU > 0) {
                $f[] = "\tif cpu usage > {$MonitSquidMaxCPU}% for 5 cycles then restart";
            }
            if ($MonitSquidMaxRestartMem > 0) {
                $f[] = "\tif totalmem > {$MonitSquidMaxRestartMem}.0 MB for 5 cycles then restart";
            }
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring squid...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SQUID.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    build_progress_restart("{reconfiguring} OpenLDAP", 32);
    $EnableOpenLDAP = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableOpenLDAP"));
    $SLAPD_PID_FILE = $unix->SLAPD_PID_PATH();
    @unlink("/etc/monit/conf.d/APP_SLAPD.monitrc");
    if ($EnableOpenLDAP == 1) {
        if ($EnableIntelCeleron == 0) {
            $f = array();
            $f[] = "check process APP_SLAPD with pidfile {$SLAPD_PID_FILE}";
            $f[] = "\tstart program = \"/etc/init.d/slapd start --force --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/slapd stop --force\"";
            $f[] = "\tif cpu usage > 95% for 5 cycles then restart";
            $f[] = "\tif totalmem > 550.0 MB for 5 cycles then restart";
            $f[] = "\tif failed unixsocket /var/run/slapd/slapd.sock then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring slapd...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SLAPD.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring} Suricata", 32);
    $EnableSuricata = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableSuricata"));
    @unlink("/etc/monit/conf.d/APP_SURICATA.monitrc");
    @unlink("/etc/monit/conf.d/APP_SURICATA_TAIL.monitrc");
    $suricata = $unix->find_program("suricata");
    if (is_file($suricata)) {
        if ($EnableSuricata == 1) {
            $f[] = "check process APP_SURICATA with pidfile /var/run/suricata/suricata.pid";
            $f[] = "\tstart program = \"/etc/init.d/suricata start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/suricata stop --monit\"";
            $f[] = "\tif cpu usage > 95% for 5 cycles then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Suricata...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SURICATA.monitrc", @implode("\n", $f));
            $f = array();
            $f[] = "check process APP_SURICATA_TAIL with pidfile /etc/artica-postfix/exec.suricata-tail.php.pid";
            $f[] = "\tstart program = \"/etc/init.d/suricata-tail start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/suricata-tail stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Suricata tail...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SURICATA_TAIL.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring}", 32);
    $winbind = $unix->find_program("winbindd");
    if (is_file("/etc/monit/conf.d/winbindd.monitrc")) {
        @unlink("/etc/monit/conf.d/winbindd.monitrc");
    }
    @unlink("/etc/monit/conf.d/winbind.monitrc");
    $EnableKerbAuth = intval(@file_get_contents("/etc/artica-postfix/settings/Daemons/EnableKerbAuth"));
    if (is_file($winbind)) {
        if ($EnableKerbAuth == 1) {
            $f[] = "check process winbindd with pidfile /var/run/samba/winbindd.pid";
            $f[] = "\tstart program = \"/etc/init.d/winbind start\"";
            $f[] = "\tstop program = \"/etc/init.d/winbind stop\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring winbindd...\n";
            }
            @file_put_contents("/etc/monit/conf.d/winbind.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    build_progress_restart("{reconfiguring}", 33);
    @unlink("/etc/monit/conf.d/APP_CICAP.monitrc");
    if ($users->C_ICAP_INSTALLED) {
        if ($SQUIDEnable == 1) {
            $CicapEnabled = $sock->GET_INFO("CicapEnabled");
            if (!is_numeric($CicapEnabled)) {
                $CicapEnabled = 0;
            }
            if ($CicapEnabled == 1) {
                $f[] = "check process APP_C_ICAP with pidfile /var/run/c-icap/c-icap.pid";
                $f[] = "\tstart program = \"/etc/init.d/artica-postfix start cicap\"";
                $f[] = "\tstop program = \"/etc/init.d/artica-postfix stop cicap\"";
                $f[] = "\tif 5 restarts within 5 cycles then timeout";
                $f[] = "";
                if ($GLOBALS["OUTPUT"]) {
                    echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring C-ICAP...\n";
                }
                @file_put_contents("/etc/monit/conf.d/APP_CICAP.monitrc", @implode("\n", $f));
            }
        }
    }
    // ********************************************************************************************************************
    build_progress_restart("{reconfiguring}", 34);
    @unlink("/etc/monit/conf.d/APP_SYSLOGDB.monitrc");
    if ($EnableSyslogDB == 1) {
        if ($MySQLSyslogType == 1) {
            $f = array();
            $f[] = "check process APP_SYSLOG_DB with pidfile /var/run/syslogdb.pid";
            $f[] = "\tstart program = \"/etc/init.d/syslog-db start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/syslog-db stop --monit\"";
            $f[] = "\tif failed unixsocket /var/run/syslogdb.sock then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring syslogd...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SYSLOGDB.monitrc", @implode("\n", $f));
            $f = array();
        }
    }
    //********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/cron.monitrc");
    if (is_file("/etc/monit/templates/rootbin")) {
        $f[] = "check process crond with pidfile /var/run/crond.pid";
        $f[] = "   group system";
        $f[] = "   group crond";
        $f[] = "   start program = \"/etc/init.d/cron start\"";
        $f[] = "   stop  program = \"/etc/init.d/cron stop\"";
        $f[] = "   if 5 restarts with 5 cycles then timeout";
        $f[] = "   depend cron_bin";
        $f[] = "   depend cron_rc";
        $f[] = "   depend cron_spool";
        $f[] = "";
        $f[] = " check file cron_bin with path /usr/sbin/cron";
        $f[] = "   group crond";
        $f[] = "   include /etc/monit/templates/rootbin";
        $f[] = "";
        $f[] = " check file cron_rc with path \"/etc/init.d/cron\"";
        $f[] = "   group crond";
        $f[] = "   include /etc/monit/templates/rootbin";
        $f[] = "";
        $f[] = " check directory cron_spool with path /var/spool/cron/crontabs";
        $f[] = "   group crond";
        $f[] = "   if failed permission 1730 then unmonitor";
        $f[] = "   if failed uid root        then unmonitor";
        $f[] = "   if failed gid crontab     then unmonitor";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring cron...\n";
        }
        @file_put_contents("/etc/monit/conf.d/cron.monitrc", @implode("\n", $f));
        $f = array();
    }
    @unlink("/etc/monit/conf.d/APP_ZARAFASERVER.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFAGATEWAY.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFAAPACHE.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFAWEB.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFASPOOLER.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFADB.monitrc");
    build_progress_restart("{reconfiguring}", 35);
    if (is_file($unix->find_program("zarafa-server"))) {
        $ZarafaApacheEnable = $sock->GET_INFO("ZarafaApacheEnable");
        if (!is_numeric($ZarafaApacheEnable)) {
            $ZarafaApacheEnable = 1;
        }
        $ZarafaApachePort = $sock->GET_INFO("ZarafaApachePort");
        if (!is_numeric($ZarafaApachePort)) {
            $ZarafaApachePort = 9010;
        }
        if ($ZarafaDedicateMySQLServer == 1) {
            $f = array();
            $f[] = "check process APP_ZARAFA_DB with pidfile /var/run/zarafa-db.pid";
            $f[] = "\tstart program = \"/etc/init.d/zarafa-db start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/zarafa-db stop --monit\"";
            $f[] = "\tif failed unixsocket /var/run/mysqld/zarafa-db.sock then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Database...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_ZARAFADB.monitrc", @implode("\n", $f));
        }
        $f = array();
        $f[] = "check process APP_ZARAFA_SERVER with pidfile /var/run/zarafa-server.pid";
        $f[] = "\tstart program = \"/etc/init.d/zarafa-server start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/zarafa-server stop --monit\"";
        $f[] = "\tif failed unixsocket /var/run/zarafa then restart";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Server...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_ZARAFASERVER.monitrc", @implode("\n", $f));
        $f = array();
        $f[] = "check process APP_ZARAFA_SPOOLER with pidfile /var/run/zarafa-spooler.pid";
        $f[] = "\tstart program = \"/etc/init.d/zarafa-spooler start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/zarafa-spooler stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Spooler...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_ZARAFASPOOLER.monitrc", @implode("\n", $f));
        $f = array();
        $f[] = "check process APP_ZARAFA_GATEWAY with pidfile /var/run/zarafa-gateway.pid";
        $f[] = "\tstart program = \"/etc/init.d/zarafa-gateway start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/zarafa-gateway stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Gateway...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_ZARAFAGATEWAY.monitrc", @implode("\n", $f));
    }
    //********************************************************************************************************************
    build_progress_restart("{reconfiguring}", 36);
    $EnableClamavDaemon = $sock->GET_INFO("EnableClamavDaemon");
    $EnableClamavDaemonForced = $sock->GET_INFO("EnableClamavDaemonForced");
    $CicapEnabled = $sock->GET_INFO("CicapEnabled");
    $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
    if (!is_numeric($EnableClamavDaemon)) {
        $EnableClamavDaemon = 0;
    }
    if (!is_numeric($EnableClamavDaemonForced)) {
        $EnableClamavDaemonForced = 0;
    }
    if (!is_numeric($SQUIDEnable)) {
        $SQUIDEnable = 1;
    }
    if (!is_numeric($CicapEnabled)) {
        $CicapEnabled = 0;
    }
    if ($SQUIDEnable == 1) {
        if ($CicapEnabled == 1) {
            $EnableClamavDaemon = 1;
        }
    }
    if ($EnableClamavDaemonForced == 1) {
        $EnableClamavDaemon = 1;
    }
    //********************************************************************************************************************
    build_progress_restart("{reconfiguring}", 37);
    @unlink("/etc/monit/conf.d/APP_CLAMAV.monitrc");
    $MasterBin = $unix->find_program("clamd");
    if (is_file($MasterBin)) {
        if ($EnableClamavDaemon == 1) {
            $f = array();
            $f[] = "check process APP_CLAMAV";
            $f[] = "with pidfile /var/run/clamav/clamd.pid";
            $f[] = "start program = \"/etc/init.d/clamav-daemon start --monit\"";
            $f[] = "stop program =  \"/etc/init.d/clamav-daemon stop --monit\"";
            $f[] = "if 5 restarts within 5 cycles then timeout";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Clamd service...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_CLAMAV.monitrc", @implode("\n", $f));
            $f = array();
        }
    }
    //********************************************************************************************************************
    @unlink("/etc/monit/conf.d/ufdb.monitrc");
    @unlink("/etc/monit/conf.d/ufdbweb.monitrc");
    $ufdbbin = $unix->find_program("ufdbguardd");
    build_progress_restart("{reconfiguring}", 38);
    if (is_file($ufdbbin)) {
        $EnableUfdbGuard = intval($sock->EnableUfdbGuard());
        $UseRemoteUfdbguardService = $sock->GET_INFO('UseRemoteUfdbguardService');
        $EnableSquidGuardHTTPService = $sock->GET_INFO("EnableSquidGuardHTTPService");
        $SquidPerformance = intval($sock->GET_INFO("SquidPerformance"));
        $EnableWebProxyStatsAppliance = $sock->GET_INFO("EnableWebProxyStatsAppliance");
        $SquidGuardApachePort = $sock->GET_INFO("SquidGuardApachePort");
        $SquidGuardApacheSSLPort = $sock->GET_INFO("SquidGuardApacheSSLPort");
        if (!is_numeric($UseRemoteUfdbguardService)) {
            $UseRemoteUfdbguardService = 0;
        }
        if (!is_numeric($EnableUfdbGuard)) {
            $EnableUfdbGuard = 0;
        }
        if (!is_numeric($EnableSquidGuardHTTPService)) {
            $EnableSquidGuardHTTPService = 1;
        }
        if (!is_numeric($EnableWebProxyStatsAppliance)) {
            $EnableWebProxyStatsAppliance = 0;
        }
        if ($EnableUfdbGuard == 0) {
            $EnableSquidGuardHTTPService = 0;
        }
        if ($EnableWebProxyStatsAppliance == 1) {
            $EnableSquidGuardHTTPService = 1;
        }
        if (!is_numeric($SquidGuardApachePort)) {
            $SquidGuardApachePort = "9020";
        }
        if (!is_numeric($SquidGuardApacheSSLPort)) {
            $SquidGuardApacheSSLPort = 9025;
        }
        if ($SquidPerformance > 2) {
            $EnableSquidGuardHTTPService = 0;
        }
        if ($SQUIDEnable == 1) {
            if ($EnableSquidGuardHTTPService == 1) {
                $f = array();
                $f[] = "check process APP_SQUIDGUARD_HTTP";
                $f[] = "with pidfile /var/run/lighttpd/squidguard-lighttpd.pid";
                $f[] = "start program = \"/etc/init.d/squidguard-http start --monit\"";
                $f[] = "stop program =  \"/etc/init.d/squidguard-http stop --monit\"";
                $f[] = "if failed host 127.0.0.1 port {$SquidGuardApachePort} then restart";
                $f[] = "if 5 restarts within 5 cycles then timeout";
                if ($GLOBALS["OUTPUT"]) {
                    echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Web filtering HTTP service...\n";
                }
                @file_put_contents("/etc/monit/conf.d/ufdbweb.monitrc", @implode("\n", $f));
            }
        }
    }
    //********************************************************************************************************************
    $EnableArticaFrontEndToNGninx = $sock->GET_INFO("EnableArticaFrontEndToNGninx");
    $EnableArticaFrontEndToApache = $sock->GET_INFO("EnableArticaFrontEndToApache");
    if (!is_numeric($EnableArticaFrontEndToNGninx)) {
        $EnableArticaFrontEndToNGninx = 0;
    }
    if (!is_numeric($EnableArticaFrontEndToApache)) {
        $EnableArticaFrontEndToApache = 0;
    }
    $EnableNginx = $sock->GET_INFO("EnableNginx");
    $EnableFreeWeb = $sock->GET_INFO("EnableFreeWeb");
    if (!is_numeric($EnableFreeWeb)) {
        $EnableFreeWeb = 0;
    }
    if (!is_numeric($EnableNginx)) {
        $EnableNginx = 1;
    }
    if ($EnableNginx == 0) {
        $EnableArticaFrontEndToNGninx = 0;
    }
    $pid = null;
    build_progress_restart("{reconfiguring}", 39);
    @unlink("/etc/monit/conf.d/APP_LIGHTTPD.monitrc");
    if ($EnableArticaFrontEndToNGninx == 0) {
        $pid = "/var/run/lighttpd/lighttpd.pid";
        if ($EnableArticaFrontEndToApache == 1) {
            $pid = "/var/run/artica-apache/apache.pid";
        }
        $f = array();
        $f[] = "check process APP_ARTICAWEBCONSOLE with pidfile {$pid}";
        $f[] = "\tstart program = \"/etc/init.d/artica-webconsole start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/artica-webconsole stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Web Console...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_LIGHTTPD.monitrc", @implode("\n", $f));
    }
    //********************************************************************************************************************
    @unlink("/etc/monit/conf.d/APP_NGINX.monitrc");
    $nginx = $unix->find_program("nginx");
    if (is_file($nginx)) {
        if ($EnableNginx == 1) {
            $f = array();
            $f[] = "check process APP_NGINX with pidfile /var/run/nginx.pid";
            $f[] = "\tstart program = \"/etc/init.d/nginx start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/nginx stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring NgINX...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_NGINX.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    build_progress_restart("{reconfiguring}", 40);
    $f = array();
    if (is_file("/etc/init.d/sysklogd")) {
        $f[] = "check process APP_SYSLOGD with pidfile /var/run/syslogd.pid";
        $f[] = "\tstart program = \"/etc/init.d/sysklogd start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/sysklogd stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "\tcheck file syslogd_file with path /var/log/syslog";
        $f[] = "\tif timestamp > 10 minutes then restart";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring sysklogd...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_SYSKLOGD.monitrc", @implode("\n", $f));
    }
    //********************************************************************************************************************
    build_progress_restart("{reconfiguring}", 41);
    $binpath = $unix->DHCPD_BIN_PATH();
    @unlink("/etc/monit/conf.d/APP_DHCPD.monitrc");
    $f = array();
    if (is_file($binpath)) {
        $EnableDHCPServer = $sock->GET_INFO("EnableDHCPServer");
        if (!is_numeric($EnableDHCPServer)) {
            $EnableDHCPServer = 0;
        }
        if ($EnableDHCPServer == 1) {
            $f[] = "check process APP_DHCP with pidfile /var/run/dhcpd.pid";
            $f[] = "\tstart program = \"/etc/init.d/isc-dhcp-server start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/isc-dhcp-server stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DHCP Service...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_DHCPD.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    $binpath = $unix->find_program("rdpproxy");
    build_progress_restart("{reconfiguring}", 42);
    @unlink("/etc/monit/conf.d/APP_RDPPROXY.monitrc");
    $f = array();
    if (is_file($binpath)) {
        $EnableRDPProxy = $sock->GET_INFO("EnableRDPProxy");
        if (!is_numeric($EnableRDPProxy)) {
            $EnableRDPProxy = 0;
        }
        if ($EnableRDPProxy == 1) {
            $f[] = "check process APP_RDPPROXY with pidfile /var/run/redemption/rdpproxy.pid";
            $f[] = "\tstart program = \"/etc/init.d/rdpproxy start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/rdpproxy stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring RDP Proxy...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_RDPPROXY.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    build_progress_restart("{reconfiguring}", 43);
    @unlink("/etc/monit/conf.d/APP_DNSMASQ.monitrc");
    $f = array();
    $binpath = $unix->find_program("dnsmasq");
    if (is_file($binpath)) {
        $EnableDNSMASQ = $users->EnableDNSMASQ();
        if ($EnableDNSMASQ == 1) {
            $f[] = "check process APP_DNSMASQ with pidfile /var/run/dnsmasq.pid";
            $f[] = "\tstart program = \"/etc/init.d/dnsmasq start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/dnsmasq stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DNSMasq Service...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_DNSMASQ.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} checking syslog\n";
    }
    if (is_file("/etc/init.d/syslog")) {
        checkDebSyslog();
    }
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} configuration done\n";
    }
    shell_exec($GLOBALS["MONIT_CLASS"]->monitor_all_cmdline . " 2>&1");
    build_progress_restart("{reconfiguring}", 45);
}
Example #2
0
function build($OnlySingle = false)
{
    if (isset($GLOBALS[__FILE__ . __FUNCTION__])) {
        return;
    }
    $GLOBALS[__FILE__ . __FUNCTION__] = true;
    $unix = new unix();
    $php5 = $unix->LOCATE_PHP5_BIN();
    shell_exec("/etc/init.d/mysql start");
    build_progress("{building_main_settings}", 10);
    if ($unix->SQUID_GET_LISTEN_PORT() == 80) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Squid listen 80, ports conflicts, change it\n";
        }
        shell_exec("{$php5} /usr/share/artica-postfix/exec.squid.php --build --force");
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Restarting Squid-cache..\n";
        }
        shell_exec("/etc/init.d/squid restart --script=" . basename(__FILE__));
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: done...\n";
        }
    }
    if ($unix->SQUID_GET_LISTEN_SSL_PORT() == 443) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Squid listen 443, ports conflicts, change it\n";
        }
        shell_exec("{$php5} /usr/share/artica-postfix/exec.squid.php --build --force");
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Restarting Squid-cache..\n";
        }
        shell_exec("/etc/init.d/squid restart --script=" . basename(__FILE__));
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: done...\n";
        }
    }
    $reconfigured = false;
    if ($unix->APACHE_GET_LISTEN_PORT() == 80) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Apache listen 80, ports conflicts, change it\n";
        }
        shell_exec("{$php5} /usr/share/artica-postfix/exec.freeweb.php --build --force");
        shell_exec("{$php5} /usr/share/artica-postfix/exec.freeweb.php --stop --force");
        shell_exec("{$php5} /usr/share/artica-postfix/exec.freeweb.php --start --force");
        $reconfigured = true;
    }
    if (!$reconfigured) {
        if ($unix->APACHE_GET_LISTEN_PORT() == 443) {
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " [INIT]: Apache listen 443, ports conflicts, change it\n";
            }
            shell_exec("{$php5} /usr/share/artica-postfix/exec.freeweb.php --build --force");
        }
    }
    $APACHE_USER = $unix->APACHE_SRC_ACCOUNT();
    $APACHE_SRC_GROUP = $unix->APACHE_SRC_GROUP();
    $NginxProxyStorePath = "/home/nginx";
    @mkdir("/etc/nginx/sites-enabled", 0755, true);
    @mkdir("/etc/nginx/local-sites", 0755, true);
    @mkdir("/etc/nginx/local-sslsites", 0755, true);
    @mkdir($NginxProxyStorePath, 0755, true);
    @mkdir($NginxProxyStorePath . "/tmp", 0755, true);
    @mkdir($NginxProxyStorePath . "/disk", 0755, true);
    @mkdir("/var/lib/nginx/fastcgi", 0755, true);
    @mkdir("/home/nginx/tmp", 0755, true);
    $Tempdir = $unix->TEMP_DIR() . "/nginx";
    @mkdir($Tempdir, 0755, true);
    $unix->chown_func($APACHE_USER, $APACHE_SRC_GROUP, $NginxProxyStorePath);
    $unix->chown_func($APACHE_USER, $APACHE_SRC_GROUP, "/etc/nginx/sites-enabled");
    $unix->chown_func($APACHE_USER, $APACHE_SRC_GROUP, $NginxProxyStorePath . "/tmp");
    $unix->chown_func($APACHE_USER, $APACHE_SRC_GROUP, $NginxProxyStorePath . "/disk");
    $unix->chown_func($APACHE_USER, $APACHE_SRC_GROUP, "/var/lib/nginx/fastcgi");
    $unix->chown_func($APACHE_USER, $APACHE_SRC_GROUP, $Tempdir);
    nginx_ulimit();
    $workers = $unix->CPU_NUMBER();
    build_progress("Building configuration", 15);
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: Running {$APACHE_USER}:{$APACHE_SRC_GROUP}..\n";
    }
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: Running {$workers} worker(s)..\n";
    }
    if (is_file("/etc/nginx/sites-enabled/default")) {
        @unlink("/etc/nginx/sites-enabled/default");
    }
    if (is_link("/etc/nginx/sites-enabled/default")) {
        @unlink("/etc/nginx/sites-enabled/default");
    }
    if (is_link("/etc/nginx/conf.d/example_ssl.conf")) {
        @unlink("/etc/nginx/conf.d/example_ssl.conf");
    }
    $limit = 4096 * $workers;
    if ($limit > 65535) {
        $limit = 65535;
    }
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx, Running limit of {$limit} open files\n";
    }
    $L = explode("\n", @file_get_contents("/etc/security/limits.conf"));
    $FOUNDL = false;
    $T = array();
    while (list($index, $line) = each($L)) {
        $line = trim($line);
        if (trim($line) == null) {
            continue;
        }
        if (substr($line, 0, 1) == "#") {
            continue;
        }
        if (preg_match("#^{$APACHE_USER}#", $line)) {
            continue;
        }
        $T[] = $line;
    }
    if (!$FOUNDL) {
        $T[] = "{$APACHE_USER}       soft    nofile   {$limit}";
        $T[] = "{$APACHE_USER}       hard    nofile   {$limit}";
    }
    @file_put_contents("/etc/security/limits.conf", @implode("\n", $T) . "\n");
    $L = array();
    $T = array();
    $MEMORY = $unix->MEM_TOTAL_INSTALLEE();
    $server_names_hash_bucket_size = 128;
    $worker_connections = 8192;
    if ($MEMORY < 624288) {
        $server_names_hash_bucket_size = 64;
        $worker_connections = 1024;
        $workers = 4;
    }
    $mail_protocols = mail_protocols();
    //
    $f[] = "# Builded on " . date("Y-m-d H:i:s");
    $f[] = "user   {$APACHE_USER};";
    $f[] = "worker_processes  {$workers};";
    $nginx_version = nginx_version();
    preg_match("#^([0-9])+\\.([0-9]+)\\.#", $nginx_version, $re);
    $re[1] = intval($re[1]);
    $re[2] = intval($re[2]);
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx, Major {$re[1]} Minor:{$re[2]}\n";
    }
    $syslog = false;
    $f[] = "worker_rlimit_nofile 16384;";
    $f[] = "timer_resolution 1ms;";
    $f[] = "";
    if ($re[1] > 0) {
        if ($re[2] > 6) {
            $f[] = "error_log syslog:server=127.0.0.1,facility=daemon info;";
            $syslog = true;
        }
    }
    $syslog = false;
    if (!$syslog) {
        $f[] = "error_log  /var/log/nginx/error.log warn;";
    }
    $f[] = "pid        /var/run/nginx.pid;";
    $f[] = "";
    $f[] = "";
    $f[] = "events {";
    $f[] = "    worker_connections  {$worker_connections};";
    $f[] = "    multi_accept  on;";
    $f[] = "    use epoll;";
    $f[] = "\t  accept_mutex_delay 1ms;";
    $f[] = "}";
    $upstream = new nginx_upstream();
    $upstreams_servers = $upstream->build();
    $f[] = "";
    $f[] = "";
    $f[] = "http {";
    $f[] = "\tinclude /etc/nginx/mime.types;";
    $f[] = "\tlog_format  awc_log";
    $f[] = "\t\t'[\$server_name] \$remote_addr - \$remote_user [\$time_local] \$request '";
    $f[] = "\t\t'\"\$status\" \$body_bytes_sent \"\$http_referer\" '";
    $f[] = "\t\t'\"\$http_user_agent\" \"\$http_x_forwarded_for\" [\$upstream_cache_status]';";
    $f[] = "";
    $f[] = "\tlimit_conn_zone \$binary_remote_addr zone=LimitCnx:10m;";
    $q = new mysql_squid_builder();
    $results = $q->QUERY_SQL("SELECT LimitReqs,servername FROM reverse_www WHERE LimitReqs > 0");
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        $servername = $ligne["servername"];
        $ZoneName = str_replace(".", "", $servername);
        $ZoneName = str_replace("-", "", $servername);
        $ZoneName = str_replace("_", "", $servername);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx, limit {$servername}/{$servername} {$ligne["LimitReqs"]}r/s\n";
        }
        $f[] = "\tlimit_req_zone  \$binary_remote_addr  zone={$ZoneName}:10m   rate={$ligne["LimitReqs"]}r/s;";
    }
    $nginxClass = new nginx();
    if ($nginxClass->IsSubstitutions()) {
        //$f[]="\tsubs_filter_types text/html text/css text/xml;";
    }
    @mkdir($Tempdir, 0775, true);
    @mkdir("/home/nginx/tmp", 0755, true);
    $f[] = "\tlimit_conn_log_level info;";
    $f[] = "\tclient_body_temp_path {$Tempdir} 1 2;";
    $f[] = "\tclient_header_timeout 5s;";
    $f[] = "\tclient_body_timeout 5s;";
    $f[] = "\tsend_timeout 10m;";
    $f[] = "\tconnection_pool_size 128k;";
    $f[] = "\tclient_header_buffer_size 16k;";
    $f[] = "\tlarge_client_header_buffers 1024 128k;";
    $f[] = "\trequest_pool_size 128k;";
    $f[] = "\tkeepalive_requests 1000;";
    $f[] = "\tkeepalive_timeout 10;";
    $f[] = "\tclient_max_body_size 10g;";
    $f[] = "\tclient_body_buffer_size 1m;";
    $f[] = "\tclient_body_in_single_buffer on;";
    $f[] = "\topen_file_cache max=10000 inactive=300s;";
    $f[] = "\treset_timedout_connection on;";
    $f[] = "\ttypes_hash_max_size 8192;";
    $f[] = "\tserver_names_hash_bucket_size 128;";
    $f[] = "\tserver_names_hash_max_size 512;";
    $f[] = "\tvariables_hash_max_size 512;";
    $f[] = "\tvariables_hash_bucket_size 128;";
    $f[] = "\tfastcgi_buffers 8 16k;";
    $f[] = "\tfastcgi_buffer_size 32k;";
    $f[] = "\tfastcgi_connect_timeout 300;";
    $f[] = "\tfastcgi_send_timeout 300;";
    $f[] = "\tfastcgi_read_timeout 300;";
    $f[] = "map \$scheme \$server_https {";
    $f[] = "default off;";
    $f[] = "https on;";
    $f[] = "}\t";
    $f[] = "\tgzip on;";
    $f[] = "\tgzip_disable msie6;";
    $f[] = "\tgzip_static on;";
    $f[] = "\tgzip_min_length 1100;";
    $f[] = "\tgzip_buffers 16 8k;";
    $f[] = "\tgzip_comp_level 9;";
    $f[] = "\tgzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;";
    $f[] = "\tgzip_vary on;";
    $f[] = "\tgzip_proxied any;";
    $f[] = "\toutput_buffers 1000 128k;";
    $f[] = "\tpostpone_output 1460;";
    $f[] = "\tsendfile on;";
    $f[] = "\tsendfile_max_chunk 256k;";
    $f[] = "\ttcp_nopush on;";
    $f[] = "\ttcp_nodelay on;";
    $f[] = "\tserver_tokens off;";
    $dns = new resolv_conf();
    $sock = new sockets();
    if ($sock->dnsmasq_enabled()) {
        $resolver[] = "127.0.0.1";
    }
    if ($dns->MainArray["DNS1"] != null) {
        $resolver[] = $dns->MainArray["DNS1"];
    }
    if ($dns->MainArray["DNS2"] != null) {
        $resolver[] = $dns->MainArray["DNS2"];
    }
    if ($dns->MainArray["DNS3"] != null) {
        $resolver[] = $dns->MainArray["DNS3"];
    }
    $f[] = "\tresolver " . @implode(" ", $resolver) . ";";
    $f[] = "\tignore_invalid_headers on;";
    $f[] = "\tindex index.html;";
    $f[] = "\tadd_header X-CDN \"Served by myself\";";
    $q = new mysql_squid_builder();
    $sql = "SELECT * FROM nginx_caches  ORDER BY directory";
    $results = $q->QUERY_SQL($sql);
    while ($ligne = mysql_fetch_array($results, MYSQL_ASSOC)) {
        $directory = $ligne["directory"];
        @mkdir($directory, 0755, true);
        $unix->chown_func("www-data", "www-data", $directory);
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx, cache `{$directory}`\n";
        }
        $f[] = "\tproxy_cache_path {$directory} levels={$ligne["levels"]} keys_zone={$ligne["keys_zone"]}:{$ligne["keys_zone_size"]}m max_size={$ligne["max_size"]}G  inactive={$ligne["inactive"]} loader_files={$ligne["loader_files"]} loader_sleep={$ligne["loader_sleep"]} loader_threshold={$ligne["loader_threshold"]};";
    }
    $f[] = "\tproxy_temp_path {$NginxProxyStorePath}/tmp/ 1 2;";
    $f[] = "\tproxy_cache_valid 404 10m;";
    $f[] = "\tproxy_cache_valid 400 501 502 503 504 1m;";
    $f[] = "\tproxy_cache_valid any 4320m;";
    $f[] = "\tproxy_cache_use_stale updating invalid_header error timeout http_404 http_500 http_502 http_503 http_504;";
    $f[] = "\tproxy_next_upstream error timeout invalid_header http_404 http_500 http_502 http_503 http_504;";
    $f[] = "\tproxy_redirect off;";
    $f[] = "\tproxy_set_header Host \$http_host;";
    $f[] = "\tproxy_set_header Server Apache;";
    $f[] = "\tproxy_set_header Connection Close;";
    $f[] = "\tproxy_pass_header Set-Cookie;";
    $f[] = "\tproxy_pass_header User-Agent;";
    $f[] = "\tproxy_set_header X-Accel-Buffering on;";
    $f[] = "\tproxy_hide_header X-CDN;";
    $f[] = "\tproxy_hide_header X-Server;";
    $f[] = "\tproxy_intercept_errors off;";
    $f[] = "\tproxy_ignore_client_abort on;";
    $f[] = "\tproxy_connect_timeout 60s;";
    $f[] = "\tproxy_send_timeout 60s;";
    $f[] = "\tproxy_read_timeout 150s;";
    $f[] = "\tproxy_buffer_size 64k;";
    $f[] = "\tproxy_buffers 16384 128k;";
    $f[] = "\tproxy_busy_buffers_size 256k;";
    $f[] = "\tproxy_temp_file_write_size 128k;";
    $f[] = "\tproxy_headers_hash_bucket_size 128;";
    $f[] = "\tproxy_cache_min_uses 0;";
    $f[] = "";
    $f[] = "{$upstreams_servers}";
    $f[] = "\tinclude /etc/nginx/sites-enabled/*.conf;";
    $f[] = "\tinclude /etc/nginx/local-sites/*.conf;";
    $f[] = "\tinclude /etc/nginx/conf.d/*.conf;";
    $f[] = "\t}";
    $f[] = $mail_protocols;
    $f[] = "";
    @copy("/etc/nginx/nginx.conf", "/etc/nginx/nginx.bak");
    @file_put_contents("/etc/nginx/nginx.conf", @implode("\n", $f));
    if (!$OnlySingle) {
        if ($GLOBALS["VERBOSE"]) {
            echo __FUNCTION__ . "." . __LINE__ . ": OK...\n";
        }
        build_progress("Building default configuration", 10);
        build_default(true);
        build_localhosts();
        if ($GLOBALS["VERBOSE"]) {
            echo __FUNCTION__ . "." . __LINE__ . ": OK...\n";
        }
    } else {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx, Only single defined\n";
        }
    }
    if ($GLOBALS["RECONFIGURE"]) {
        $pid = PID_NUM();
        if (is_numeric($pid)) {
            if ($GLOBALS["OUTPUT"]) {
                echo "Starting......: " . date("H:i:s") . " [INIT]: Nginx, reload pid {$pid}\n";
            }
            $kill = $unix->find_program("kill");
            unix_system_HUP($pid);
        } else {
            start(true);
        }
    }
    build_progress("Building configuration done", 10);
}
function CHECK_DNS_SYSTEMS()
{
    $unix = new unix();
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".time";
    $pidFile = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".pid";
    $BigTime = "/etc/artica-postfix/pids/" . basename(__FILE__) . "." . __FUNCTION__ . ".week.time";
    $pid = $unix->get_pid_from_file($pidFile);
    if ($unix->process_exists($pid)) {
        if ($unix->PROCCESS_TIME_MIN($pid, 10) < 2) {
            return;
        }
    }
    if ($GLOBALS["VERBOSE"]) {
        echo "pidtime ={$pidtime}\n";
    }
    @file_put_contents($pidFile, getmypid());
    $time = $unix->file_time_min($pidtime);
    if (!$GLOBALS["FORCE"]) {
        if ($time < 5) {
            Events("{$time}mn < 5mn ( use --force to bypass)");
            if ($GLOBALS["VERBOSE"]) {
                echo "{$time}mn < 5mn ( use --force to bypass)\n";
            }
            return;
        }
    }
    @unlink($pidtime);
    @file_put_contents($pidtime, time());
    $BigTimeEx = $unix->file_time_min($BigTime);
    if ($GLOBALS["VERBOSE"]) {
        echo "{$BigTimeEx}M for {$BigTime}\n";
    }
    if ($BigTimeEx > 4320) {
        $q = new mysql();
        @unlink($BigTimeEx);
        @file_put_contents($BigTimeEx, time());
        Events("DELETE FROM dnsperfs_week WHERE zDate<DATE_SUB(NOW(),INTERVAL 8 DAY)");
        $q->QUERY_SQL("DELETE QUICK FROM dnsperfs_week WHERE zDate<DATE_SUB(NOW(),INTERVAL 8 DAY)", "artica_events");
        $q->QUERY_SQL("OPTIMIZE TABLE dnsperfs_week", "artica_events");
    }
    $resolv = new resolv_conf();
    $q = new mysql_squid_builder();
    $sock = new sockets();
    include_once dirname(__FILE__) . "/ressources/externals/Net_DNS2/DNS2.php";
    include_once dirname(__FILE__) . "/ressources/class.resolv.conf.inc";
    $sql = "SELECT *  FROM dns_servers ORDER BY zOrder";
    $results = $q->QUERY_SQL($sql);
    if (!$q->ok) {
        ToSyslog("{$q->mysql_error}");
        return;
    }
    while ($ligne = mysql_fetch_assoc($results)) {
        $DNS[] = $ligne["dnsserver"];
    }
    $sock = new sockets();
    if ($sock->dnsmasq_enabled() == 1) {
        $DNS[] = "127.0.0.1";
    }
    $q = new mysql();
    $sql = "CREATE TABLE IF NOT EXISTS `dnsperfs` (\n\t\t\t\t`dnsserver` VARCHAR(128) PRIMARY KEY,\n\t\t\t\t`performance` FLOAT(5),\n\t\t\t\t `percent` smallint(2),\n\t\t\t\t `zDate` datetime\n\t\t\t\t ) ENGINE=MyISAM;";
    $q->QUERY_SQL($sql, 'artica_events');
    $sql = "CREATE TABLE IF NOT EXISTS `dnsperfs_week` (\n\t\t\t\t`dnsserver` VARCHAR(128),\n\t\t\t\t`performance` FLOAT(5),\n\t\t\t\t `percent` smallint(2),\n\t\t\t\t `zDate` datetime,\n\t\t\t\t KEY `zDate` (`zDate`),\n\t\t\t     KEY `dnsserver` (`dnsserver`)\n\t\t\t\t ) ENGINE=MyISAM;";
    $q->QUERY_SQL($sql, 'artica_events');
    $nameserver = explode("\n", @file_get_contents("/etc/resolv.conf"));
    while (list($index, $line) = each($nameserver)) {
        $line = trim($line);
        if ($line == null) {
            continue;
        }
        if (!preg_match("#^nameserver\\s+(.+)#i", $line, $re)) {
            continue;
        }
        $COMP[trim($re[1])] = true;
    }
    $q->QUERY_SQL("TRUNCATE TABLE `dnsperfs`", 'artica_events');
    //ref=518379
    if ($resolv->MainArray["DNS1"] != null) {
        $DNS[] = $resolv->MainArray["DNS1"];
    }
    if ($resolv->MainArray["DNS2"] != null) {
        $DNS[] = $resolv->MainArray["DNS2"];
    }
    if ($resolv->MainArray["DNS3"] != null) {
        $DNS[] = $resolv->MainArray["DNS3"];
    }
    $type = "A";
    $ipClass = new IP();
    $minperf = $sock->GET_INFO("DNSPerfsPointer");
    if (!is_numeric($minperf)) {
        $minperf = 301450;
    }
    while (list($index, $dnsA) = each($DNS)) {
        $COMP[$dnsA] = true;
    }
    while (list($dnsA, $none) = each($COMP)) {
        Events("Checks DNS {$dnsA}");
        if (!$ipClass->isIPAddress($dnsA)) {
            continue;
        }
        if ($GLOBALS["VERBOSE"]) {
            echo "{$dnsA}\n";
        }
        $t['start'] = microtime(true);
        $rs = new Net_DNS2_Resolver(array('nameservers' => array($dnsA)));
        try {
            $date = date("Y-m-d H:i:s");
            $tA = rand("10000", "208460");
            $result = $rs->query("p4-cpsk2owex6nby-dwvedtapjla4ebei-{$tA}-i2-v6exp3-v4.metric.gstatic.com", "A");
            $t[$dnsA] = microtime(true);
            $time = mini_bench_to($t);
            $timeC = $time * 10000;
        } catch (Net_DNS2_Exception $e) {
            $error = $e->getMessage();
            $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','0','0','{$date}')", "artica_events");
            $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs_week` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','0','0','{$date}')", "artica_events");
            continue;
        }
        $perc = $minperf / $timeC;
        $perc = round($perc * 100);
        Events("{$dnsA} Response Time:{$time} = {$timeC}/{$minperf} {$perc}%");
        foreach ($result->answer as $record) {
            if ($ipClass->isIPAddress($record->address)) {
                if ($perc > 100) {
                    $perc = 100;
                }
                $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','{$time}','{$perc}','{$date}')", "artica_events");
                if ($GLOBALS["VERBOSE"]) {
                    echo "INSERT IGNORE INTO `dnsperfs_week` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','{$time}','{$perc}','{$date}')\n";
                }
                $q->QUERY_SQL("INSERT IGNORE INTO `dnsperfs_week` (dnsserver,performance,percent,zDate) VALUES ('{$dnsA}','{$time}','{$perc}','{$date}')", "artica_events");
                break;
            }
        }
    }
    $cacheFile = "/usr/share/artica-postfix/ressources/logs/web/dnsperformances.cache";
    $sql = "SELECT * FROM dnsperfs ORDER BY percent DESC";
    $results = $q->QUERY_SQL($sql, "artica_events");
    while ($ligne = mysql_fetch_assoc($results)) {
        $percentage = $ligne["percent"];
        $dnsserver = $ligne["dnsserver"];
        if ($percentage > 100) {
            $percentage = 100;
        }
        $TTR[] = "\n\t\t<tr>\n\t\t\t<td style='font-weight:bold;font-size:12px' align='right'>{$dnsserver}:</td>\n\t\t\t<td style='font-weight:bold;font-size:12px'><td>" . pourcentage($percentage, 10, "green") . "</td>\n\t\t</tr>\n\t\t";
    }
    if (count($TTR) > 0) {
        $data = RoundedLightGreen("<div style='min-height:147px'>\n\t\t<table style='width:100%'>\n\t\t\t\t<tr><td colspan=3><span style='font-weight:bold;font-size:12px'>{dns_performance}</span></td></tr>\n\t\t\t\t" . @implode($TTR, "\n") . "\n\t\t\t\t\n\t\t<tr>\n\t\t\t<td colspan=3 align='right'>\n\t\t\t\t<i><a href=\"javascript:blur();\" OnClick=\"javascript:Loadjs('dnsperfs.php',true)\" style='font-weight:normal;font-size:12px;text-decoration:underline'>{more_infos}</a>&nbsp;|&nbsp;\n\t\t\t\t<a href=\"javascript:blur();\" OnClick=\"javascript:Loadjs('squid.popups.php?script=dns');\" style='font-weight:normal;font-size:12px;text-decoration:underline'>{settings}</a>\n\t\t\t\t</i>\n\t\t\t</td>\n\t\t</tr>\t\t\t\t\n\t\t\t\t\n\t\t</table></div>") . "<br>";
        @file_put_contents($cacheFile, $data);
    }
}
Example #4
0
function install_service_main($G)
{
    $sock = new sockets();
    $unix = new unix();
    $php = $unix->LOCATE_PHP5_BIN();
    $INITD_PATH = "/etc/init.d/dnsmasq";
    $php5script = basename(__FILE__);
    $daemonbinLog = "DNSMasq for main";
    $daemon_path = $unix->find_program("dnsmasq");
    $EnableDNSMASQ = $sock->dnsmasq_enabled();
    $cmdline = @implode(" ", $G);
    if (count($G) < 2) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Failed NO Tokens, Build config...\n";
        }
        return;
    }
    $f[] = "#!/bin/sh";
    $f[] = "### BEGIN INIT INFO";
    $f[] = "# Provides:       dnsmasq";
    $f[] = "# Required-Start: \$network \$remote_fs \$syslog";
    $f[] = "# Required-Stop:  \$network \$remote_fs \$syslog";
    $f[] = "# Default-Start:  2 3 4 5";
    $f[] = "# Default-Stop:   0 1 6";
    $f[] = "# Description:    DHCP and DNS server";
    $f[] = "### END INIT INFO";
    $f[] = "";
    $f[] = "set +e   # Don't exit on error status";
    $f[] = "";
    $f[] = "PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin";
    $f[] = "DAEMON={$daemon_path}";
    $f[] = "NAME=dnsmasq";
    $f[] = "DESC=\"DNS forwarder and DHCP server\"";
    $f[] = "";
    $f[] = "# Most configuration options in /etc/default/dnsmasq are deprecated";
    $f[] = "# but still honoured.";
    $f[] = "ENABLED={$EnableDNSMASQ}";
    $f[] = "if [ -r /etc/default/\$NAME ]; then";
    $f[] = "\t. /etc/default/\$NAME";
    $f[] = "fi";
    $f[] = "";
    $f[] = "# Get the system locale, so that messages are in the correct language, and the ";
    $f[] = "# charset for IDN is correct";
    $f[] = "if [ -r /etc/default/locale ]; then";
    $f[] = "        . /etc/default/locale";
    $f[] = "        export LANG";
    $f[] = "fi";
    $f[] = "";
    $f[] = "test -x \$DAEMON || exit 0";
    $f[] = "";
    $f[] = "# Provide skeleton LSB log functions for backports which don't have LSB functions.";
    $f[] = "if [ -f /lib/lsb/init-functions ]; then";
    $f[] = "         . /lib/lsb/init-functions";
    $f[] = "else";
    $f[] = "         log_warning_msg () {";
    $f[] = "            echo \"\${@}.\"";
    $f[] = "         }";
    $f[] = "";
    $f[] = "         log_success_msg () {";
    $f[] = "            echo \"\${@}.\"";
    $f[] = "         }";
    $f[] = "";
    $f[] = "         log_daemon_msg () {";
    $f[] = "            echo -n \"\${1}: \$2\"";
    $f[] = "         }";
    $f[] = "";
    $f[] = "\t log_end_msg () {";
    $f[] = "            if [ \$1 -eq 0 ]; then";
    $f[] = "              echo \".\"";
    $f[] = "            elif [ \$1 -eq 255 ]; then";
    $f[] = "              /bin/echo -e \" (warning).\"";
    $f[] = "            else";
    $f[] = "              /bin/echo -e \" failed!\"";
    $f[] = "            fi";
    $f[] = "         }";
    $f[] = "fi";
    $f[] = "";
    $f[] = "# RESOLV_CONF:";
    $f[] = "# If the resolvconf package is installed then use the resolv conf file";
    $f[] = "# that it provides as the default.  Otherwise use /etc/resolv.conf as";
    $f[] = "# the default.";
    $f[] = "#";
    $f[] = "# If IGNORE_RESOLVCONF is set in /etc/default/dnsmasq or an explicit";
    $f[] = "# filename is set there then this inhibits the use of the resolvconf-provided";
    $f[] = "# information.";
    $f[] = "#";
    $f[] = "# Note that if the resolvconf package is installed it is not possible to ";
    $f[] = "# override it just by configuration in /etc/dnsmasq.conf, it is necessary";
    $f[] = "# to set IGNORE_RESOLVCONF=yes in /etc/default/dnsmasq.";
    $f[] = "";
    $f[] = "if [ ! \"\$RESOLV_CONF\" ] &&";
    $f[] = "   [ \"\$IGNORE_RESOLVCONF\" != \"yes\" ] &&";
    $f[] = "   [ -x /sbin/resolvconf ]";
    $f[] = "then";
    $f[] = "\tRESOLV_CONF=/var/run/dnsmasq/resolv.conf";
    $f[] = "fi";
    $f[] = "";
    $f[] = "for INTERFACE in \$DNSMASQ_INTERFACE; do";
    $f[] = "\tDNSMASQ_INTERFACES=\"\$DNSMASQ_INTERFACES -i \$INTERFACE\"";
    $f[] = "done";
    $f[] = "";
    $f[] = "for INTERFACE in \$DNSMASQ_EXCEPT; do";
    $f[] = "\tDNSMASQ_INTERFACES=\"\$DNSMASQ_INTERFACES -I \$INTERFACE\"";
    $f[] = "done";
    $f[] = "";
    $f[] = "if [ ! \"\$DNSMASQ_USER\" ]; then";
    $f[] = "   DNSMASQ_USER=\"root\"";
    $f[] = "fi";
    $f[] = "";
    $f[] = "start()";
    $f[] = "{";
    $f[] = "        # Return";
    $f[] = "\t#   0 if daemon has been started";
    $f[] = "\t#   1 if daemon was already running";
    $f[] = "\t#   2 if daemon could not be started";
    $f[] = "";
    $f[] = "        # /var/run may be volatile, so we need to ensure that";
    $f[] = "        # /var/run/dnsmasq exists here as well as in postinst";
    $f[] = "        if [ ! -d /var/run/dnsmasq ]; then";
    $f[] = "           mkdir /var/run/dnsmasq || return 2";
    $f[] = "        fi";
    $f[] = "";
    $f[] = "\tstart-stop-daemon --start --quiet --pidfile /var/run/dnsmasq/\$NAME.pid --exec \$DAEMON --test > /dev/null || return 1";
    $f[] = "\tstart-stop-daemon --start --quiet --pidfile /var/run/dnsmasq/\$NAME.pid --exec \$DAEMON -- {$cmdline} || return 2 ";
    $f[] = "}";
    $f[] = "";
    $f[] = "start_resolvconf()";
    $f[] = "{";
    $f[] = "# If interface \"lo\" is explicitly disabled in /etc/default/dnsmasq";
    $f[] = "# Then dnsmasq won't be providing local DNS, so don't add it to";
    $f[] = "# the resolvconf server set.";
    $f[] = "\tfor interface in \$DNSMASQ_EXCEPT";
    $f[] = "\tdo";
    $f[] = "\t\t[ \$interface = lo ] && return";
    $f[] = "\tdone";
    $f[] = "";
    $f[] = "        if [ -x /sbin/resolvconf ] ; then";
    $f[] = "\t\techo \"nameserver 127.0.0.1\" | /sbin/resolvconf -a lo.\$NAME";
    $f[] = "\tfi";
    $f[] = "\treturn 0";
    $f[] = "}";
    $f[] = "";
    $f[] = "stop()";
    $f[] = "{";
    $f[] = "\t# Return";
    $f[] = "\t#   0 if daemon has been stopped";
    $f[] = "\t#   1 if daemon was already stopped";
    $f[] = "\t#   2 if daemon could not be stopped";
    $f[] = "\t#   other if a failure occurred";
    $f[] = "\tstart-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile /var/run/dnsmasq/\$NAME.pid --name \$NAME";
    $f[] = "\tRETVAL=\"\$?\"";
    $f[] = "\t[ \"\$RETVAL\" = 2 ] && return 2";
    $f[] = "\treturn \"\$RETVAL\"";
    $f[] = "}";
    $f[] = "";
    $f[] = "stop_resolvconf()";
    $f[] = "{";
    $f[] = "\tif [ -x /sbin/resolvconf ] ; then";
    $f[] = "\t\t/sbin/resolvconf -d lo.\$NAME";
    $f[] = "\tfi";
    $f[] = "\treturn 0";
    $f[] = "}";
    $f[] = "";
    $f[] = "status()";
    $f[] = "{";
    $f[] = "\t# Return";
    $f[] = "\t#   0 if daemon is running";
    $f[] = "\t#   1 if daemon is dead and pid file exists";
    $f[] = "\t#   3 if daemon is not running";
    $f[] = "\t#   4 if daemon status is unknown";
    $f[] = "\tstart-stop-daemon --start --quiet --pidfile /var/run/dnsmasq/\$NAME.pid --exec \$DAEMON --test > /dev/null";
    $f[] = "\tcase \"\$?\" in";
    $f[] = "\t\t0) [ -e \"/var/run/dnsmasq/\$NAME.pid\" ] && return 1 ; return 3 ;;";
    $f[] = "\t\t1) return 0 ;;";
    $f[] = "\t\t*) return 4 ;;";
    $f[] = "\tesac";
    $f[] = "}";
    $f[] = "";
    $f[] = "case \"\$1\" in";
    $f[] = "  start)";
    $f[] = "\ttest \"\$ENABLED\" != \"0\" || exit 0";
    $f[] = "\tlog_daemon_msg \"Starting \$DESC\" \"\$NAME\"";
    $f[] = "\tstart";
    $f[] = "\tcase \"\$?\" in";
    $f[] = "\t\t0)";
    $f[] = "\t\t\tlog_end_msg 0";
    $f[] = "\t\t\tstart_resolvconf";
    $f[] = "\t\t\texit 0";
    $f[] = "\t\t\t;;";
    $f[] = "\t\t1)";
    $f[] = "\t\t\tlog_success_msg \"(already running)\"";
    $f[] = "\t\t\texit 0";
    $f[] = "\t\t\t;;";
    $f[] = "\t\t*)";
    $f[] = "\t\t\tlog_end_msg 1";
    $f[] = "\t\t\texit 1";
    $f[] = "\t\t\t;;";
    $f[] = "\tesac";
    $f[] = "\t;;";
    $f[] = "  stop)";
    $f[] = "  {$php} " . __FILE__ . " --stop || true";
    $f[] = "\t;;";
    $f[] = "  restart|force-reload)";
    $f[] = "\ttest \"\$ENABLED\" != \"0\" || exit 1";
    $f[] = "  {$php} " . __FILE__ . " --stop || true";
    $f[] = "  {$php} " . __FILE__ . " --start || true";
    $f[] = "\t;;";
    $f[] = "  status)";
    $f[] = "\tlog_daemon_msg \"Checking \$DESC\" \"\$NAME\"";
    $f[] = "\tstatus";
    $f[] = "\tcase \"\$?\" in";
    $f[] = "\t\t0) log_success_msg \"(running)\" ; exit 0 ;;";
    $f[] = "\t\t1) log_success_msg \"(dead, pid file exists)\" ; exit 1 ;;";
    $f[] = "\t\t3) log_success_msg \"(not running)\" ; exit 3 ;;";
    $f[] = "\t\t*) log_success_msg \"(unknown)\" ; exit 4 ;;";
    $f[] = "\tesac";
    $f[] = "\t;;";
    $f[] = "  dump-stats)";
    $f[] = "        kill -s USR1 `cat /var/run/dnsmasq/\$NAME.pid`";
    $f[] = "\t;;";
    $f[] = "  systemd-start-resolvconf)";
    $f[] = "\tstart_resolvconf";
    $f[] = "\t;;";
    $f[] = "  systemd-stop-resolvconf)";
    $f[] = "\tstop_resolvconf";
    $f[] = "\t;;";
    $f[] = "  *)";
    $f[] = "\techo \"Usage: /etc/init.d/\$NAME {start|stop|restart|force-reload|dump-stats|status}\" >&2";
    $f[] = "\texit 3";
    $f[] = "\t;;";
    $f[] = "esac";
    $f[] = "";
    $f[] = "exit 0";
    $f[] = "";
    echo "{$daemonbinLog}: [INFO] Writing {$INITD_PATH} with new config\n";
    @unlink($INITD_PATH);
    @file_put_contents($INITD_PATH, @implode("\n", $f));
    @chmod($INITD_PATH, 0755);
    if (is_file('/usr/sbin/update-rc.d')) {
        shell_exec("/usr/sbin/update-rc.d -f " . basename($INITD_PATH) . " defaults >/dev/null 2>&1");
    }
    if (is_file('/sbin/chkconfig')) {
        shell_exec("/sbin/chkconfig --add " . basename($INITD_PATH) . " >/dev/null 2>&1");
        shell_exec("/sbin/chkconfig --level 345 " . basename($INITD_PATH) . " on >/dev/null 2>&1");
    }
    return true;
}
Example #5
0
function details_tablerows()
{
    $tpl = new templates();
    $MyPage = CurrentPageName();
    $q = new mysql_squid_builder();
    $squid = new squidbee();
    $sock = new sockets();
    $t = $_GET["t"];
    $search = '%';
    $table = "dns_servers";
    if (!$q->TABLE_EXISTS($table)) {
        $q->QUERY_SQL("CREATE TABLE `squidlogs`.`dns_servers` ( `ID` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY ,\n\t\t\t\t `dnsserver` VARCHAR( 90 ) NOT NULL , \n\t\t\t\t `zOrder` SMALLINT( 2 ) NOT NULL ,\n\t\t\t\t INDEX (`zOrder`), \n\t\t\t\tUNIQUE KEY `dnsserver` (`dnsserver`) )");
    }
    $page = 1;
    $FORCE_FILTER = null;
    $total = 0;
    $enabled = 1;
    $SquidDNSUseSystem = intval($sock->GET_INFO("SquidDNSUseSystem"));
    $SquidDNSUseLocalDNSService = intval($sock->GET_INFO("SquidDNSUseLocalDNSService"));
    $LOCAL_ENABLED = 1;
    $SquidDNSUseSystem_icon = "ok-42.png";
    $SquidDNSUseSystem_color = "black";
    $SquidDNSUseLocalDNSService_icon = "ok-42.png";
    $SquidDNSUseLocalDNSService_color = "black";
    $TableMainColor = "black";
    $SquidDNSUseSystem_js = "Loadjs('{$MyPage}?SquidDNSUseSystem-js=yes')";
    $SquidDNSUseLocalDNSService_js = "Loadjs('{$MyPage}?SquidDNSUseLocalDNSService-js=yes')";
    if ($SquidDNSUseSystem == 0) {
        $SquidDNSUseSystem_icon = "danger42.png";
    }
    if ($SquidDNSUseLocalDNSService == 0) {
        $SquidDNSUseLocalDNSService_icon = "danger42.png";
        $LOCAL_ENABLED = 0;
    }
    if ($SquidDNSUseSystem == 1) {
        $TableMainColor = "#898989";
        $LOCAL_ENABLED = 0;
        $SquidDNSUseLocalDNSService_icon = "ok-42-grey.png";
        $SquidDNSUseLocalDNSService_color = "#898989";
    }
    if ($sock->dnsmasq_enabled() == 0) {
        $LOCAL_ENABLED = 0;
        $SquidDNSUseLocalDNSService_icon = "ok-42-grey.png";
        $SquidDNSUseLocalDNSService_color = "#898989";
        $SquidDNSUseLocalDNSService_js = "blur()";
    }
    if ($LOCAL_ENABLED == 1) {
        $SquidDNSUseSystem_color = "#898989";
    }
    $SquidDNSUseSystem_icon = imgsimple($SquidDNSUseSystem_icon, null, $SquidDNSUseSystem_js);
    $SquidDNSUseSystem_text = $tpl->_ENGINE_parse_body("{squid_use_local_system_dns}");
    $SquidDNSUseLocalDNSService_icon = imgsimple($SquidDNSUseLocalDNSService_icon, null, $SquidDNSUseLocalDNSService_js);
    $SquidDNSUseLocalDNSService_text = $tpl->_ENGINE_parse_body("{squid_use_local_service_dns}");
    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));
        $total = $ligne["TCOUNT"];
    } else {
        $sql = "SELECT COUNT(*) as TCOUNT FROM {$table}";
        $ligne = mysql_fetch_array($q->QUERY_SQL($sql));
        $total = $ligne["TCOUNT"];
    }
    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);
    $no_rule = $tpl->_ENGINE_parse_body("{no data}");
    $data = array();
    $data['page'] = $page;
    $data['total'] = $total + 2;
    $data['rows'] = array();
    if (!$q->ok) {
        json_error_show($q->mysql_error . "<br>{$sql}");
    }
    $data['rows'][] = array('id' => "squid-dns-A", 'cell' => array("<center style='font-size:36px;color:{$SquidDNSUseSystem_color}'>{$SquidDNSUseSystem_icon}</center>", "<a href=\"javascript:blur();\" OnClick=\"javascript:{$SquidDNSUseSystem_js}\" \n\t\t\t\t\t\tstyle='font-size:36px;color:{$SquidDNSUseSystem_color};text-decoration:underline'>{$SquidDNSUseSystem_text}</span>", "<center style='font-size:36px;color:{$SquidDNSUseSystem_color}'>-</center>", "<center style='font-size:36px;color:{$SquidDNSUseSystem_color}'>-</center>", "<center style='font-size:36px;color:{$SquidDNSUseSystem_color}'>-</center>"));
    $data['rows'][] = array('id' => "squid-dns-A", 'cell' => array("<center style='font-size:36px;color:{$SquidDNSUseLocalDNSService_color}'>{$SquidDNSUseLocalDNSService_icon}</center>", "<a href=\"javascript:blur();\" OnClick=\"javascript:{$SquidDNSUseLocalDNSService_js}\" \n\t\t\t\t\tstyle='font-size:36px;color:{$SquidDNSUseLocalDNSService_color};;text-decoration:underline'>{$SquidDNSUseLocalDNSService_text} (127.0.0.1)</span>", "<center style='font-size:36px;color:{$SquidDNSUseLocalDNSService_color}'>-</center>", "<center style='font-size:36px;color:{$SquidDNSUseLocalDNSService_color}'>-</center>", "<center style='font-size:36px;color:{$SquidDNSUseLocalDNSService_color}'>-</center>"));
    $fontsize = "16";
    while ($ligne = mysql_fetch_assoc($results)) {
        $delete = imgtootltip('delete-42.png', '{delete}', "DnsDelete{$t}('{$ligne["dnsserver"]}')");
        $up = imgsimple("arrow-up-42.png", "", "SquidDNSUpDown('{$ligne['ID']}',1)");
        $down = imgsimple("arrow-down-42.png", "", "SquidDNSUpDown('{$ligne['ID']}',0)");
        $data['rows'][] = array('id' => "squid-dns-{$ligne["ID"]}", 'cell' => array("<center style='font-size:36px;color:{$TableMainColor}'>{$ligne["zOrder"]}</center>", "<span style='font-size:36px;color:{$TableMainColor}'>{$ligne["dnsserver"]}</span>", "<center style='font-size:12.5px'>{$up}</center>", "<center style='font-size:12.5px'>{$down}</center>", "<center style='font-size:12.5px'>{$delete}</center>"));
    }
    echo json_encode($data);
}
Example #6
0
function build()
{
    $users = new usersMenus();
    $sock = new sockets();
    $unix = new unix();
    $SystemLoadNotif = $sock->GET_INFO("SystemLoadNotif");
    if (!is_numeric($SystemLoadNotif)) {
        $SystemLoadNotif = 0;
    }
    $EnableSyslogDB = $sock->GET_INFO("EnableSyslogDB");
    if (!is_numeric($EnableSyslogDB)) {
        $EnableSyslogDB = 0;
    }
    $MySQLSyslogType = $sock->GET_INFO("MySQLSyslogType");
    if (!is_numeric($MySQLSyslogType)) {
        $MySQLSyslogType = 1;
    }
    $ZarafaDedicateMySQLServer = $sock->GET_INFO("ZarafaDedicateMySQLServer");
    if (!is_numeric($ZarafaDedicateMySQLServer)) {
        $ZarafaDedicateMySQLServer = 0;
    }
    $ini = new Bs_IniHandler();
    $ini->loadFile('/etc/artica-postfix/smtpnotif.conf');
    if (!is_numeric($ini->_params["SMTP"]["EnableNotifs"])) {
        $ini->_params["SMTP"]["EnableNotifs"] = 0;
    }
    if (!is_numeric($ini->_params["SMTP"]["tls_enabled"])) {
        $ini->_params["SMTP"]["tls_enabled"] = 0;
    }
    $smtp_server = trim($ini->_params["SMTP"]['smtp_server_name']);
    $smtp_server_port = $ini->_params["SMTP"]['smtp_server_port'];
    $smtp_dest = $ini->_params["SMTP"]['smtp_dest'];
    $smtp_sender = $ini->_params["SMTP"]['smtp_sender'];
    $smtp_auth_user = $ini->_params["SMTP"]['smtp_auth_user'];
    $smtp_auth_passwd = $ini->_params["SMTP"]['smtp_auth_passwd'];
    $tls_enabled = $ini->_params["SMTP"]["tls_enabled"];
    $recipientsZ = explode("\n", "/etc/artica-postfix/settings/Daemons/SmtpNotificationConfigCC");
    $recipients = array();
    while (list($index, $to) = each($recipientsZ)) {
        if (trim($to) == null) {
            continue;
        }
        $recipients[] = $to;
    }
    if ($smtp_server == null) {
        $ini->_params["SMTP"]["EnableNotifs"] = 0;
    }
    if ($smtp_dest == null) {
        if (count($recipients) == 0) {
            $ini->_params["SMTP"]["EnableNotifs"] = 0;
        }
    }
    if (!is_numeric($smtp_server_port)) {
        $smtp_server_port = 25;
    }
    $EnableNotifs = $ini->_params["SMTP"]["EnableNotifs"];
    $monit_not_on = 'instance,action';
    $f[] = 'set daemon 60 with start delay 5';
    $f[] = 'set idfile /var/run/monit/monit.id';
    $cpunum = $unix->CPU_NUMBER();
    $normal = $cpunum * 2 + 1;
    $normal2 = $cpunum * 2;
    $busy = $cpunum * 4;
    $EnableMONITSmtpNotif = $sock->GET_INFO("EnableMONITSmtpNotif");
    if (!is_numeric($EnableMONITSmtpNotif)) {
        $EnableMONITSmtpNotif = 1;
    }
    $EnableWatchMemoryUsage = $sock->GET_INFO("EnableWatchMemoryUsage");
    if (!is_numeric($EnableWatchMemoryUsage)) {
        $EnableWatchMemoryUsage = 1;
    }
    $EnableWatchCPUsage = $sock->GET_INFO("EnableWatchCPUsage");
    if (!is_numeric($EnableWatchCPUsage)) {
        $EnableWatchCPUsage = 1;
    }
    $SystemWatchMemoryUsage = $sock->GET_INFO("SystemWatchMemoryUsage");
    if (!is_numeric($SystemWatchMemoryUsage)) {
        $SystemWatchMemoryUsage = 75;
    }
    $EnableWatchCPUsage = $sock->GET_INFO("EnableWatchCPUsage");
    if (!is_numeric($EnableWatchCPUsage)) {
        $EnableWatchCPUsage = 1;
    }
    $SystemWatchCPUUser = $sock->GET_INFO("SystemWatchCPUUser");
    if (!is_numeric($SystemWatchCPUUser)) {
        $SystemWatchCPUUser = 80;
    }
    $SystemWatchCPUSystem = $sock->GET_INFO("SystemWatchCPUSystem");
    if (!is_numeric($SystemWatchCPUSystem)) {
        $SystemWatchCPUSystem = 80;
    }
    $EnableLoadAvg1mnUser = $sock->GET_INFO("EnableLoadAvg1mnUser");
    if (!is_numeric($EnableLoadAvg1mnUser)) {
        $EnableLoadAvg1mnUser = 1;
    }
    $EnableLoadAvg5mnUser = $sock->GET_INFO("EnableLoadAvg5mnUser");
    if (!is_numeric($EnableLoadAvg5mnUser)) {
        $EnableLoadAvg5mnUser = 1;
    }
    $EnableLoadAvg15mnUser = $sock->GET_INFO("EnableLoadAvg15mnUser");
    if (!is_numeric($EnableLoadAvg15mnUser)) {
        $EnableLoadAvg15mnUser = 1;
    }
    $Load1mn = $sock->GET_INFO("Load1mn");
    if (!is_numeric($Load1mn)) {
        $Load1mn = $busy;
    }
    $Load15mn = $sock->GET_INFO("Load15mn");
    if (!is_numeric($Load15mn)) {
        $Load15mn = $normal2;
    }
    $Load5mn = $sock->GET_INFO("Load5mn");
    if (!is_numeric($Load5mn)) {
        $Load5mn = $normal;
    }
    $DoNotCheckSystem = 0;
    if ($EnableLoadAvg1mnUser == 0) {
        if ($EnableLoadAvg5mnUser == 0) {
            if ($EnableLoadAvg15mnUser == 0) {
                if ($EnableWatchMemoryUsage == 0) {
                    if ($SystemLoadNotif == 0) {
                        if ($EnableWatchCPUsage == 0) {
                            $DoNotCheckSystem = 1;
                        }
                    }
                }
            }
        }
    }
    $php5 = $unix->LOCATE_PHP5_BIN();
    $rmbin = $unix->find_program("rm");
    $echo = $unix->find_program("echo");
    if ($SystemWatchCPUSystem > 100) {
        $SystemWatchCPUSystem = 99;
    }
    if ($SystemWatchCPUUser > 100) {
        $SystemWatchCPUUser = 99;
    }
    if ($SystemWatchMemoryUsage > 10) {
        $SystemWatchMemoryUsage = 99;
    }
    if ($SystemWatchCPUSystem < 5) {
        $SystemWatchCPUSystem = 99;
    }
    if ($SystemWatchCPUUser < 5) {
        $SystemWatchCPUUser = 99;
    }
    if ($SystemWatchMemoryUsage < 5) {
        $SystemWatchMemoryUsage = 99;
    }
    $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
    if (!is_numeric($SQUIDEnable)) {
        $SQUIDEnable = 1;
    }
    $f[] = 'set logfile syslog facility log_daemon';
    $f[] = 'set statefile /var/run/monit/monit.state';
    $f[] = '';
    if ($EnableNotifs == 1) {
        if ($EnableMONITSmtpNotif == 1) {
            $f[] = "set mailserver {$smtp_server} PORT {$smtp_server_port}";
            if (strlen($smtp_auth_user) > 0) {
                $f[] = "\tUSERNAME \"{$smtp_auth_user}\" PASSWORD \"{$smtp_auth_passwd}\"";
            }
            if ($tls_enabled == 1) {
                $f[] = "\tusing TLSV1";
            }
            $f[] = "\tset eventqueue";
            $f[] = "\tbasedir /var/monit";
            $f[] = "\tslots 100";
            $f[] = "\tset mail-format {";
            $f[] = "\t\tfrom: {$smtp_sender}";
            $f[] = "\t\tsubject: Artica service monitor: \$SERVICE \$EVENT";
            $f[] = "\t\tmessage: Artica service monitor  \$ACTION  \$SERVICE at  \$DATE on  \$HOST:  \$DESCRIPTION";
            $f[] = "\t}";
            $f[] = "set alert {$smtp_dest} but not on {{$monit_not_on}}";
            if ($recipients > 0) {
                while (list($index, $to) = each($recipientsZ)) {
                    $f[] = "set alert {$to} but not on {{$monit_not_on}}";
                }
            }
        }
    }
    $allips = $unix->NETWORK_ALL_INTERFACES(true);
    $f[] = "set httpd port 2874 and use address 127.0.0.1";
    $f[] = "\tallow 127.0.0.1";
    while (list($tcpi, $to) = each($allips)) {
        $f[] = "\tallow {$tcpi}";
    }
    $top = $unix->find_program("top");
    $hostname = $unix->hostname_g();
    if ($DoNotCheckSystem == 0) {
        $f[] = "check system " . $unix->hostname_g();
        if ($SystemLoadNotif > 0) {
            $f[] = "\tif loadavg (1min) > {$SystemLoadNotif} then exec \"{$php5} /usr/share/artica-postfix/exec.watchdog.php --loadavg-notif\"";
        }
        if ($EnableLoadAvg1mnUser == 1) {
            $f[] = "\tif loadavg (1min) > {$Load1mn} for 5 cycles then alert";
        }
        if ($EnableLoadAvg5mnUser == 1) {
            $f[] = "\tif loadavg (5min) > {$Load5mn} for 5 cycles then alert";
        }
        if ($EnableLoadAvg15mnUser == 1) {
            $f[] = "\tif loadavg (15min) > {$Load15mn} for 5 cycles then alert";
        }
        if ($EnableWatchMemoryUsage == 1) {
            $f[] = "\tif memory usage > {$SystemWatchMemoryUsage}% for 5 cycles then alert";
        }
        if ($EnableWatchCPUsage == 1) {
            //$f[]="if cpu usage (user) > $SystemWatchCPUUser% for 5 cycles then exec \"/bin/bash -c '$top -b -n 1 >> /var/log/ArticaProc.log;/bin/date >> /var/log/ArticaProc.log'\"";
            //$f[]="if cpu usage (system) > $SystemWatchCPUSystem% for 5 cycles then exec \"/bin/bash -c '$top -b -n 1 >> /var/log/ArticaProc.log;/bin/date >> /var/log/ArticaProc.log'\"";
        }
    }
    $f[] = "check host loopback with address 127.0.0.1";
    $f[] = "\tif failed icmp type echo with timeout 1 seconds then exec \"/bin/loopbackfailed.sh\"";
    $f[] = "";
    $loopbackfailed[] = "#!/bin/sh";
    $loopbackfailed[] = "{$php5} /usr/share/artica-postfix/exec.virtuals-ip.php --loopback";
    $loopbackfailed[] = "";
    @file_put_contents("/bin/loopbackfailed.sh", @implode("\n", $loopbackfailed));
    @chmod("/bin/loopbackfailed.sh", 0755);
    $loopbackfailed = array();
    //********************************************************************************************************************
    $f[] = "check file php.log with path /var/log/php.log";
    $f[] = "\tif size > 100 MB then";
    $f[] = "\t\texec \"/bin/clean-phplog.sh\"";
    $f[] = "";
    $f[] = "check file usrphp.log with path /usr/share/artica-postfix/ressources/logs/php.log";
    $f[] = "      if size > 100 MB then";
    $f[] = "\t\texec \"/bin/clean-phplog.sh\"";
    $f[] = "";
    $f[] = "include /etc/monit/conf.d/*";
    @file_put_contents("/etc/monit/monitrc", @implode("\n", $f));
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} /etc/monit/monitrc done...\n";
    }
    $AA[] = "#!/bin/sh";
    $AA[] = "{$echo} \"\" >/var/log/php.log";
    $AA[] = "";
    @file_put_contents("/bin/clean-phplog.sh", @implode("\n", $AA));
    @chmod("/bin/clean-phplog.sh", 0755);
    $AA = array();
    $monit = new monit();
    $monit->save();
    $INITD_PATH = $unix->SLAPD_INITD_PATH();
    $SLAPD_PID_FILE = $unix->SLAPD_PID_PATH();
    $squidbin = $unix->LOCATE_SQUID_BIN();
    @unlink("/etc/monit/conf.d/APP_OPENLDAP.monitrc");
    //********************************************************************************************************************
    $f = array();
    //********************************************************************************************************************
    $f = array();
    $f[] = "check process APP_FRAMEWORK";
    $f[] = "with pidfile /var/run/lighttpd/framework.pid";
    $f[] = "start program = \"/etc/init.d/artica-framework start --monit\"";
    $f[] = "stop program =  \"/etc/init.d/artica-framework stop --monit\"";
    $f[] = "if 5 restarts within 5 cycles then timeout";
    @file_put_contents("/etc/monit/conf.d/articaframework.monitrc", @implode("\n", $f));
    $f = array();
    //********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/APP_OPENSSH.monitrc");
    @unlink("/etc/monit/conf.d/APP_MYSQLD.monitrc");
    //********************************************************************************************************************
    $f = array();
    $f[] = "check process APP_ARTICA_STATUS with pidfile /etc/artica-postfix/exec.status.php.pid";
    $f[] = "\tstart program = \"/etc/init.d/artica-status start --monit\"";
    $f[] = "\tstop program = \"/etc/init.d/artica-status stop --monit\"";
    $f[] = "\tif 5 restarts within 5 cycles then timeout";
    $f[] = "";
    if ($GLOBALS["OUTPUT"]) {
        echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Status...\n";
    }
    @file_put_contents("/etc/monit/conf.d/APP_ARTICASTATUS.monitrc", @implode("\n", $f));
    //********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/squid.monitrc");
    @unlink("/etc/monit/conf.d/APP_SQUIDMAIN.monitrc");
    if (is_file($squidbin)) {
        if ($SQUIDEnable == 1) {
            $MonitConfig = unserialize(base64_decode($sock->GET_INFO("SquidWatchdogMonitConfig")));
            $SquidMgrListenPort = trim($sock->GET_INFO("SquidMgrListenPort"));
            if (!is_numeric($MonitConfig["watchdog"])) {
                $MonitConfig["watchdog"] = 1;
            }
            if (!is_numeric($MonitConfig["watchdogCPU"])) {
                $MonitConfig["watchdogCPU"] = 95;
            }
            if (!is_numeric($MonitConfig["watchdogMEM"])) {
                $MonitConfig["watchdogMEM"] = 1500;
            }
            if ($MonitConfig["watchdog"] == 1) {
                if ($MonitConfig["watchdogMEM"] > 500) {
                    $AVAILABLE_MEM = $unix->MEM_TOTAL_INSTALLEE();
                    $AVAILABLE_MEM = $AVAILABLE_MEM / 1024;
                    $prc = $MonitConfig["watchdogMEM"] / $AVAILABLE_MEM;
                    $prc = round($prc * 100);
                }
                $f = array();
                $f[] = "check process APP_SQUID with pidfile /var/run/squid/squid.pid";
                $f[] = "\tstart program = \"/etc/init.d/squid start --monit\"";
                $f[] = "\tstop program = \"/etc/init.d/squid stop --monit\"";
                if ($SquidMgrListenPort > 0) {
                    $f[] = "\tif failed host 127.0.0.1 port {$SquidMgrListenPort}  then restart";
                }
                if ($MonitConfig["watchdogCPU"] > 60) {
                    $f[] = "\tif cpu usage > {$MonitConfig["watchdogCPU"]}% for 5 cycles then restart";
                }
                if ($prc > 10) {
                    $f[] = "\tif mem usage > {$prc}% for 5 cycles then restart";
                }
                $f[] = "\tif 5 restarts within 5 cycles then timeout";
                $f[] = "";
                if ($GLOBALS["OUTPUT"]) {
                    echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Squid-Cache...\n";
                }
                @file_put_contents("/etc/monit/conf.d/APP_SQUIDMAIN.monitrc", @implode("\n", $f));
            }
        }
    }
    // ********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/APP_SQUIDDB.monitrc");
    if (is_dir("/opt/squidsql/data")) {
        if ($SQUIDEnable == 1) {
            $f = array();
            $f[] = "check process APP_SQUID_DB with pidfile /var/run/squid-db.pid";
            $f[] = "\tstart program = \"/etc/init.d/squid-db start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/squid-db stop --monit\"";
            $f[] = "\tif failed unixsocket /var/run/mysqld/squid-db.sock then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Squid MySQL DB...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SQUIDDB.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/APP_DNSMASQ.monitrc");
    if ($users->dnsmasq_installed) {
        $enabled = $sock->dnsmasq_enabled();
        if ($enabled == 1) {
            $f[] = "check process APP_DNSMASQ with pidfile /var/run/dnsmasq.pid";
            $f[] = "\tstart program = \"/etc/init.d/dnsmasq start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/dnsmasq stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DnsMASQ...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_DNSMASQ.monitrc", @implode("\n", $f));
        }
    }
    // ********************************************************************************************************************
    // ********************************************************************************************************************
    $f = array();
    @unlink("/etc/monit/conf.d/APP_CICAP.monitrc");
    if ($users->C_ICAP_INSTALLED) {
        if ($SQUIDEnable == 1) {
            $CicapEnabled = $sock->GET_INFO("CicapEnabled");
            if (!is_numeric($CicapEnabled)) {
                $CicapEnabled = 0;
            }
            if ($CicapEnabled == 1) {
                $f[] = "check process APP_C_ICAP with pidfile /var/run/c-icap/c-icap.pid";
                $f[] = "\tstart program = \"/etc/init.d/artica-postfix start cicap\"";
                $f[] = "\tstop program = \"/etc/init.d/artica-postfix stop cicap\"";
                $f[] = "\tif 5 restarts within 5 cycles then timeout";
                $f[] = "";
                if ($GLOBALS["OUTPUT"]) {
                    echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring C-ICAP...\n";
                }
                @file_put_contents("/etc/monit/conf.d/APP_CICAP.monitrc", @implode("\n", $f));
            }
        }
    }
    // ********************************************************************************************************************
    @unlink("/etc/monit/conf.d/APP_SYSLOGDB.monitrc");
    if ($EnableSyslogDB == 1) {
        if ($MySQLSyslogType == 1) {
            $f = array();
            $f[] = "check process APP_SYSLOG_DB with pidfile /var/run/syslogdb.pid";
            $f[] = "\tstart program = \"/etc/init.d/syslog-db start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/syslog-db stop --monit\"";
            $f[] = "\tif failed unixsocket /var/run/syslogdb.sock then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring syslogd...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_SYSLOGDB.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    @unlink("/etc/monit/conf.d/APP_ZARAFASERVER.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFAGATEWAY.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFAAPACHE.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFAWEB.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFASPOOLER.monitrc");
    @unlink("/etc/monit/conf.d/APP_ZARAFADB.monitrc");
    if (is_file($unix->find_program("zarafa-server"))) {
        $ZarafaApacheEnable = $sock->GET_INFO("ZarafaApacheEnable");
        if (!is_numeric($ZarafaApacheEnable)) {
            $ZarafaApacheEnable = 1;
        }
        $ZarafaApachePort = $sock->GET_INFO("ZarafaApachePort");
        if (!is_numeric($ZarafaApachePort)) {
            $ZarafaApachePort = 9010;
        }
        if ($ZarafaDedicateMySQLServer == 1) {
            $f = array();
            $f[] = "check process APP_ZARAFA_DB with pidfile /var/run/zarafa-db.pid";
            $f[] = "\tstart program = \"/etc/init.d/zarafa-db start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/zarafa-db stop --monit\"";
            $f[] = "\tif failed unixsocket /var/run/mysqld/zarafa-db.sock then restart";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Database...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_ZARAFADB.monitrc", @implode("\n", $f));
        }
        $f = array();
        $f[] = "check process APP_ZARAFA_SERVER with pidfile /var/run/zarafa-server.pid";
        $f[] = "\tstart program = \"/etc/init.d/zarafa-server start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/zarafa-server stop --monit\"";
        $f[] = "\tif failed unixsocket /var/run/zarafa then restart";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Server...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_ZARAFASERVER.monitrc", @implode("\n", $f));
        $f = array();
        $f[] = "check process APP_ZARAFA_SPOOLER with pidfile /var/run/zarafa-spooler.pid";
        $f[] = "\tstart program = \"/etc/init.d/zarafa-spooler start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/zarafa-spooler stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Spooler...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_ZARAFASPOOLER.monitrc", @implode("\n", $f));
        $f = array();
        $f[] = "check process APP_ZARAFA_GATEWAY with pidfile /var/run/zarafa-gateway.pid";
        $f[] = "\tstart program = \"/etc/init.d/zarafa-gateway start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/zarafa-gateway stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Zarafa Gateway...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_ZARAFAGATEWAY.monitrc", @implode("\n", $f));
    }
    //********************************************************************************************************************
    $EnableClamavDaemon = $sock->GET_INFO("EnableClamavDaemon");
    $EnableClamavDaemonForced = $sock->GET_INFO("EnableClamavDaemonForced");
    $CicapEnabled = $sock->GET_INFO("CicapEnabled");
    $SQUIDEnable = $sock->GET_INFO("SQUIDEnable");
    if (!is_numeric($EnableClamavDaemon)) {
        $EnableClamavDaemon = 0;
    }
    if (!is_numeric($EnableClamavDaemonForced)) {
        $EnableClamavDaemonForced = 0;
    }
    if (!is_numeric($SQUIDEnable)) {
        $SQUIDEnable = 1;
    }
    if (!is_numeric($CicapEnabled)) {
        $CicapEnabled = 0;
    }
    if ($SQUIDEnable == 1) {
        if ($CicapEnabled == 1) {
            $EnableClamavDaemon = 1;
        }
    }
    if ($EnableClamavDaemonForced == 1) {
        $EnableClamavDaemon = 1;
    }
    //********************************************************************************************************************
    @unlink("/etc/monit/conf.d/APP_CLAMAV.monitrc");
    $MasterBin = $unix->find_program("clamd");
    if (is_file($MasterBin)) {
        if ($EnableClamavDaemon == 1) {
            $f = array();
            $f[] = "check process APP_CLAMAV";
            $f[] = "with pidfile /var/run/clamav/clamd.pid";
            $f[] = "start program = \"/etc/init.d/clamav-daemon start --monit\"";
            $f[] = "stop program =  \"/etc/init.d/clamav-daemon stop --monit\"";
            $f[] = "if 5 restarts within 5 cycles then timeout";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Clamd service...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_CLAMAV.monitrc", @implode("\n", $f));
            $f = array();
        }
    }
    //********************************************************************************************************************
    @unlink("/etc/monit/conf.d/ufdb.monitrc");
    @unlink("/etc/monit/conf.d/ufdbweb.monitrc");
    $ufdbbin = $unix->find_program("ufdbguardd");
    if (is_file($ufdbbin)) {
        $EnableUfdbGuard = $sock->EnableUfdbGuard();
        $UseRemoteUfdbguardService = $sock->GET_INFO('UseRemoteUfdbguardService');
        $EnableSquidGuardHTTPService = $sock->GET_INFO("EnableSquidGuardHTTPService");
        $SquidPerformance = intval($sock->GET_INFO("SquidPerformance"));
        $EnableWebProxyStatsAppliance = $sock->GET_INFO("EnableWebProxyStatsAppliance");
        $SquidGuardApachePort = $sock->GET_INFO("SquidGuardApachePort");
        $SquidGuardApacheSSLPort = $sock->GET_INFO("SquidGuardApacheSSLPort");
        if (!is_numeric($UseRemoteUfdbguardService)) {
            $UseRemoteUfdbguardService = 0;
        }
        if (!is_numeric($EnableUfdbGuard)) {
            $EnableUfdbGuard = 0;
        }
        if (!is_numeric($EnableSquidGuardHTTPService)) {
            $EnableSquidGuardHTTPService = 1;
        }
        if (!is_numeric($EnableWebProxyStatsAppliance)) {
            $EnableWebProxyStatsAppliance = 0;
        }
        if ($EnableUfdbGuard == 0) {
            $EnableSquidGuardHTTPService = 0;
        }
        if ($EnableWebProxyStatsAppliance == 1) {
            $EnableSquidGuardHTTPService = 1;
        }
        if (!is_numeric($SquidGuardApachePort)) {
            $SquidGuardApachePort = "9020";
        }
        if (!is_numeric($SquidGuardApacheSSLPort)) {
            $SquidGuardApacheSSLPort = 9025;
        }
        if ($SquidPerformance > 2) {
            $EnableSquidGuardHTTPService = 0;
        }
        if ($SQUIDEnable == 1) {
            if ($UseRemoteUfdbguardService == 0) {
                if ($EnableUfdbGuard == 1) {
                    $f = array();
                    $f[] = "check process APP_UFDBGUARD";
                    $f[] = "with pidfile /var/run/urlfilterdb/ufdbguardd.pid";
                    $f[] = "start program = \"/etc/init.d/ufdb start --monit\"";
                    $f[] = "stop program =  \"/etc/init.d/ufdb stop --monit\"";
                    $f[] = "if totalmem > 700 MB for 5 cycles then alert";
                    $f[] = "if cpu > 95% for 5 cycles then alert";
                    $f[] = "if 5 restarts within 5 cycles then timeout";
                    if ($GLOBALS["OUTPUT"]) {
                        echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Web filtering service...\n";
                    }
                    @file_put_contents("/etc/monit/conf.d/ufdb.monitrc", @implode("\n", $f));
                }
            }
            if ($EnableSquidGuardHTTPService == 1) {
                $f = array();
                $f[] = "check process APP_SQUIDGUARD_HTTP";
                $f[] = "with pidfile /var/run/lighttpd/squidguard-lighttpd.pid";
                $f[] = "start program = \"/etc/init.d/squidguard-http start --monit\"";
                $f[] = "stop program =  \"/etc/init.d/squidguard-http stop --monit\"";
                $f[] = "if failed host 127.0.0.1 port {$SquidGuardApachePort} then restart";
                $f[] = "if 5 restarts within 5 cycles then timeout";
                if ($GLOBALS["OUTPUT"]) {
                    echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Web filtering HTTP service...\n";
                }
                @file_put_contents("/etc/monit/conf.d/ufdbweb.monitrc", @implode("\n", $f));
            }
        }
    }
    //********************************************************************************************************************
    $EnableArticaFrontEndToNGninx = $sock->GET_INFO("EnableArticaFrontEndToNGninx");
    $EnableArticaFrontEndToApache = $sock->GET_INFO("EnableArticaFrontEndToApache");
    if (!is_numeric($EnableArticaFrontEndToNGninx)) {
        $EnableArticaFrontEndToNGninx = 0;
    }
    if (!is_numeric($EnableArticaFrontEndToApache)) {
        $EnableArticaFrontEndToApache = 0;
    }
    $EnableNginx = $sock->GET_INFO("EnableNginx");
    $EnableFreeWeb = $sock->GET_INFO("EnableFreeWeb");
    if (!is_numeric($EnableFreeWeb)) {
        $EnableFreeWeb = 0;
    }
    if (!is_numeric($EnableNginx)) {
        $EnableNginx = 1;
    }
    if ($EnableNginx == 0) {
        $EnableArticaFrontEndToNGninx = 0;
    }
    $pid = null;
    @unlink("/etc/monit/conf.d/APP_LIGHTTPD.monitrc");
    if ($EnableArticaFrontEndToNGninx == 0) {
        $pid = "/var/run/lighttpd/lighttpd.pid";
        if ($EnableArticaFrontEndToApache == 1) {
            $pid = "/var/run/artica-apache/apache.pid";
        }
        $f = array();
        $f[] = "check process APP_ARTICAWEBCONSOLE with pidfile {$pid}";
        $f[] = "\tstart program = \"/etc/init.d/artica-webconsole start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/artica-webconsole stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring Artica Web Console...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_LIGHTTPD.monitrc", @implode("\n", $f));
    }
    //********************************************************************************************************************
    @unlink("/etc/monit/conf.d/APP_NGINX.monitrc");
    $nginx = $unix->find_program("nginx");
    if (is_file($nginx)) {
        if ($EnableNginx == 1) {
            $f = array();
            $f[] = "check process APP_NGINX with pidfile /var/run/nginx.pid";
            $f[] = "\tstart program = \"/etc/init.d/nginx start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/nginx stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring NgINX...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_NGINX.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    $f = array();
    if (is_file("/etc/init.d/sysklogd")) {
        $f[] = "check process APP_SYSLOGD with pidfile /var/run/syslogd.pid";
        $f[] = "\tstart program = \"/etc/init.d/sysklogd start --monit\"";
        $f[] = "\tstop program = \"/etc/init.d/sysklogd stop --monit\"";
        $f[] = "\tif 5 restarts within 5 cycles then timeout";
        $f[] = "\tcheck file syslogd_file with path /var/log/syslog";
        $f[] = "\tif timestamp > 10 minutes then restart";
        $f[] = "";
        if ($GLOBALS["OUTPUT"]) {
            echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring sysklogd...\n";
        }
        @file_put_contents("/etc/monit/conf.d/APP_SYSKLOGD.monitrc", @implode("\n", $f));
    }
    //********************************************************************************************************************
    $binpath = $unix->DHCPD_BIN_PATH();
    @unlink("/etc/monit/conf.d/APP_DHCPD.monitrc");
    $f = array();
    if (is_file($binpath)) {
        $EnableDHCPServer = $sock->GET_INFO("EnableDHCPServer");
        if (!is_numeric($EnableDHCPServer)) {
            $EnableDHCPServer = 0;
        }
        if ($EnableDHCPServer == 1) {
            $f[] = "check process APP_DHCP with pidfile /var/run/dhcpd.pid";
            $f[] = "\tstart program = \"/etc/init.d/isc-dhcp-server start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/isc-dhcp-server stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DHCP Service...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_DHCPD.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    $binpath = $unix->find_program("rdpproxy");
    @unlink("/etc/monit/conf.d/APP_RDPPROXY.monitrc");
    $f = array();
    if (is_file($binpath)) {
        $EnableRDPProxy = $sock->GET_INFO("EnableRDPProxy");
        if (!is_numeric($EnableRDPProxy)) {
            $EnableRDPProxy = 0;
        }
        if ($EnableRDPProxy == 1) {
            $f[] = "check process APP_RDPPROXY with pidfile /var/run/redemption/rdpproxy.pid";
            $f[] = "\tstart program = \"/etc/init.d/rdpproxy start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/rdpproxy stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring RDP Proxy...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_RDPPROXY.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    @unlink("/etc/monit/conf.d/APP_DNSMASQ.monitrc");
    $f = array();
    $binpath = $unix->find_program("dnsmasq");
    if (is_file($binpath)) {
        $EnableDNSMASQ = $users->EnableDNSMASQ();
        if ($EnableDNSMASQ == 1) {
            $f[] = "check process APP_DNSMASQ with pidfile /var/run/dnsmasq.pid";
            $f[] = "\tstart program = \"/etc/init.d/dnsmasq start --monit\"";
            $f[] = "\tstop program = \"/etc/init.d/dnsmasq stop --monit\"";
            $f[] = "\tif 5 restarts within 5 cycles then timeout";
            $f[] = "";
            if ($GLOBALS["OUTPUT"]) {
                echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} monitoring DNSMasq Service...\n";
            }
            @file_put_contents("/etc/monit/conf.d/APP_DNSMASQ.monitrc", @implode("\n", $f));
        }
    }
    //********************************************************************************************************************
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} checking syslog\n";
    }
    if (is_file("/etc/init.d/syslog")) {
        checkDebSyslog();
    }
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} configuration done\n";
    }
    shell_exec($GLOBALS["MONIT_CLASS"]->monitor_all_cmdline . " 2>&1");
}
Example #7
0
function build($aspid = false)
{
    $unix = new unix();
    $pidfile = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".pid";
    $pidtime = "/etc/artica-postfix/pids/" . basename(__FILE__) . ".time";
    if (!$aspid) {
        if (!$GLOBALS["FORCE"]) {
            $pid = @file_get_contents($pidfile);
            if ($unix->process_exists($pid, basename(__FILE__))) {
                writelogs("Already executed pid {$pid}, aborting...", "MAIN", __FILE__, __LINE__);
                die;
            }
            $time = $unix->file_time_min($pidtime);
            if ($time < 2) {
                if ($time > 0) {
                    if ($GLOBALS["OUTPUT"]) {
                        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["SERVICE_NAME"]} Current {$time}Mn Requested 2mn, schedule this task\n";
                    }
                    writelogs("Current {$time}Mn Requested 2mn, schedule this task", "MAIN", __FILE__, __LINE__);
                    $unix->THREAD_COMMAND_SET($unix->LOCATE_PHP5_BIN() . " " . __FILE__);
                }
                die;
            }
        }
        @unlink($pidtime);
        @file_put_contents($pidtime, time());
        @file_put_contents($pidfile, getmypid());
    }
    $Masterbin = $unix->find_program("dnsmasq");
    $users = new settings_inc();
    if (!$users->dnsmasq_installed) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} is not installed, aborting\n";
        writelogs("DNSMasq is not installed, aborting", "MAIN", __FILE__, __LINE__);
        return;
    }
    $sock = new sockets();
    $EnableDNSMASQ = $sock->dnsmasq_enabled();
    $EnableRemoteStatisticsAppliance = intval($sock->GET_INFO("EnableRemoteStatisticsAppliance"));
    $DNSMasqUseStatsAppliance = intval($sock->GET_INFO("DNSMasqUseStatsAppliance"));
    $EnableWebProxyStatsAppliance = intval($sock->GET_INFO("EnableWebProxyStatsAppliance"));
    $UnlockWebStats = intval($sock->GET_INFO("UnlockWebStats"));
    if ($UnlockWebStats == 1) {
        $EnableRemoteStatisticsAppliance = 0;
    }
    if ($EnableDNSMASQ == 0) {
        if ($GLOBALS["OUTPUT"]) {
            echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} DnsMasq is disabled\n";
        }
        return;
    }
    if ($EnableRemoteStatisticsAppliance == 1) {
        if ($DNSMasqUseStatsAppliance == 1) {
            writelogs("DNSMasq -> use Web statistics Appliance...", "MAIN", __FILE__, __LINE__);
            UseStatsAppliance();
            die;
        }
    }
    $php = $unix->LOCATE_PHP5_BIN();
    shell_exec("{$php} /usr/share/artica-postfix/exec.virtuals-ip.php --hosts");
    @file_put_contents("/etc/dnsmasq.conf.empty", "");
    $DNsServers = GetDNSSservers();
    $getdomains = getdomains();
    check_squid_inside();
    $LocalDNSMASQItems = $sock->GET_INFO('LocalDNSMASQItems');
    if (!is_numeric($LocalDNSMASQItems)) {
        $LocalDNSMASQItems = 250000;
    }
    $cf = new dnsmasq();
    $G = array();
    $G[] = "{$Masterbin}";
    $G[] = "--local-ttl=3600";
    $G[] = "--conf-file=/etc/dnsmasq.conf.empty";
    $G[] = "--pid-file=/var/run/dnsmasq.pid";
    $G[] = "--strict-order";
    $G[] = "--domain-needed";
    $G[] = "--expand-hosts";
    $G[] = "--bogus-priv";
    if ($DNsServers != null) {
        $G[] = $DNsServers;
    }
    if ($getdomains != null) {
        $G[] = $getdomains;
    }
    $G[] = "--cache-size={$LocalDNSMASQItems}";
    $G[] = "--filterwin2k";
    $G[] = "--log-facility=DAEMON";
    if ($cf->main_array["log-queries"] == "yes") {
        $G[] = "--log-queries";
    }
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} CONFIGURATOR " . count($G) . " line(s) LINE:" . __LINE__ . "\n";
    }
    $G = cachednshosts_records($G);
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} CONFIGURATOR " . count($G) . " line(s) LINE:" . __LINE__ . "\n";
    }
    @mkdir("/var/run/dnsmasq", 0755, true);
    if ($GLOBALS["OUTPUT"]) {
        echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} CONFIGURATOR /etc/dnsmasq.cmdlines.array done\n";
    }
    @file_put_contents("/etc/dnsmasq.cmdlines.array", serialize($G));
    $unix->THREAD_COMMAND_SET($unix->LOCATE_PHP5_BIN() . " /usr/share/artica-postfix/exec.initslapd.php dnsmasq");
    if ($EnableWebProxyStatsAppliance == 1) {
        notify_remote_proxys_dnsmasq();
    }
}