Парсер логов SmartGuard AdvExt

Demort

Прославленный
Местный
Победитель в номинации 2023
Победитель в номинации 2020
Знаток Lineage2
Web разработчик
Любитель реакций
Старожил I степени
За заслуги перед форумом
За веру и верность форуму
Сообщения
300
Розыгрыши
1
Репутация
548
Реакции
432
Баллы
1 433
Всем привет, с толкнулся с проблемой клиента что хвиды на смарте не пишутся в базу пришлось писать парсер.
Так как повелось в основном работать с вагантом то и не стал изобретать велосипед а взял его структуру хранения хвидов и банов

BannedHardwareId
Код:
USE [lin2world]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[BannedHardwareId](
    [hardware_id] [varchar](48) NOT NULL,
    [account] [nvarchar](25) NOT NULL,
    [gm] [nvarchar](25) NOT NULL,
    [timeout] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[BannedHardwareId] ADD  DEFAULT (N'00000000000000000000000000000000') FOR [hardware_id]
GO
ALTER TABLE [dbo].[BannedHardwareId] ADD  DEFAULT (N'') FOR [account]
GO
ALTER TABLE [dbo].[BannedHardwareId] ADD  DEFAULT (N'') FOR [gm]
GO
ALTER TABLE [dbo].[BannedHardwareId] ADD  DEFAULT ((0)) FOR [timeout]
GO

В табличке user_data добавляем поле long_hardware_id varchar(43)

Сам пхп скрипт писал на коленке не ругать=)
Код:
<?php


class LogD{

    public $debug = 0; #    0 = no debug message

    #type log
    public $bans = true;
    public $hwidlist = true;
    public $system = false;
    #config bd
    public $host = 'localhost';
    public $dbname = 'lin2world';
    public $user = 'sa';
    public $pass = 'Pass';
    # how mach requests agregate in one request to SQL db ( set smallest = long insert time, but no db overload)
    public $pack_req = 1000;
    #folder dir
    public $root_dir = 'C:\server\AdvExt64\SmartGuard\\';
    public $log_dir = 'log\\';
    public $insert_dir = 'insert\\';

    public $temp_file = 'temp_settings.txt';
    public $settings = array();

    public $temp_bans = array();

    #settings system



    public $temp_dir_log = array();
    public $temp_file_log = array();
    public $temp_connect_bd = null;
    public $temp_log_f = null;

    public function __construct(){
       
       
        function array_diff_assoc_recursive($array1, $array2) {
           
            if(!is_array($array1)) 
                $array1 = array();
            elseif(!is_array($array2))
                $array2 = array();
           
                foreach ($array1 as $key => $value) {
                    if (is_array($value)) {
                        if (!isset($array2[$key])) {
                            $difference[$key] = $value;
                        } elseif (!is_array($array2[$key])) {
                            $difference[$key] = $value;
                        } else {
                            $new_diff = array_diff_assoc_recursive($value, $array2[$key]);
                            if ($new_diff != FALSE) {
                                $difference[$key] = $new_diff;
                            }
                        }
                    } elseif (!isset($array2[$key]) || $array2[$key] != $value) {
                        $difference[$key] = $value;
                    }
                }
                return !isset($difference) ? 0 : $difference;

        }
       
       
        $this->settings = $this->config();

        if($this->bans)
            $this->temp_dir_log['bans'] = $this->root_dir . 'bans.xml';

        if($this->hwidlist)
            $this->temp_dir_log['hwidlist'] = $this->root_dir . $this->log_dir . 'hwidlist\\';

        if($this->system)
            $this->temp_dir_log['system'] = $this->root_dir . $this->log_dir . 'system\\';

    }

    public function config(){
        return json_decode(file_get_contents($this->temp_file) , true);
    }

    public function write_config($data){

        file_put_contents($this->temp_file , json_encode($data));
        return true;
    }

    public function database(){
        return new PDO("sqlsrv:server=" . $this->host . ";database=" . $this->dbname, $this->user, $this->pass);
        return 0;
    }

    public function scanDir($type , $from){

        $logs = scandir($from);

        foreach ($logs as $file) {
            if($file != "." && $file != "..")
            {
                if(strripos($file, ".log") !== false){
                    $this->temp_file_log[$type][] = $file;
                }

            }
        }

    }

    public function parseLog(){

        $this->temp_connect_bd = $this->database();

        #serch logs file => to arr
        foreach($this->temp_dir_log as $type => $dir){

            if($type == 'bans')
                continue;

            $this->scanDir( $type, $dir );
        }

        if(is_array($this->temp_file_log)){

            foreach($this->temp_file_log as $type => $arr_file){

                if(!is_array($arr_file))
                    continue;

                foreach($arr_file as $file) {

                    $f_size = filesize($this->temp_dir_log[$type] . $file);


                    print $type . ' file -' . $file . ' size-' . $f_size . "b \n";

                    if ($f_size < 20) {#empty file
                        if ($this->debug)
                            print $this->temp_dir_log[$type] . $file . " - empty\n";

                        if (!rename($this->temp_dir_log[$type] . $file, $this->temp_dir_log[$type] . $this->insert_dir . $file)) {
                            print "File error move! " . $file . "\n";
                        }

                        continue;
                    }

                    if ($this->debug)
                        print "\t\t" . " Process file: $file (" . $f_size . "b)\n";


                    $this->temp_log_f = file($this->temp_dir_log[$type] . $file);
                    $insert = "";
                    $n = 0;

                    foreach ($this->temp_log_f as $str) {
                        $n++; #file line num


                        if($this->settings[$type]['file'] == $file AND $this->settings[$type]['line'] > $n){
                            continue;
                        }

                        if (strlen($str) < 20) #string to small to be log record
                            continue;


                        $data = explode(' ', $str);

                        $data[1] = str_replace(",", "", $data[1]);

                       
               
                        foreach ($data as $key => $value) {
                            if (strlen($data[$key]) == 0)
                                $data[$key] = 'NULL';
                            else
                                $data[$key] = $this->temp_connect_bd->quote(trim($data[$key]));

                        }


                        if ($type == "hwidlist") {
                            $insert .= "  UPDATE dbo.user_data SET long_hardware_id = {$data[2]} WHERE account_name = {$data[3]};\n";
                        }

                    }

                    $this->temp_log_f = null;

                    if (strlen($insert) > 20) {#have some logs
                        #1) insert data
                        if ($this->debug)
                            print "Insert data:\n" . $insert . "\n\n";

                        $jj = $nn = 0;

                        $ins_t = explode('\n', $insert);
                        unset($insert);


                        $flag = true;
                        foreach ($ins_t as $ins) {
                            $jj++;
                            $nn++;

                            if($flag){
                                $flag = !$this->temp_connect_bd->beginTransaction();
                            }

                            $this->temp_connect_bd->exec($ins);

                            if ($jj == $this->pack_req) {
                                #2) insert preceed rows

                                $flag = true;

                                if(!$this->temp_connect_bd->commit())
                                {
                                    print 'error insert 255';
                                    exit;
                                }

                                $jj = 0;

                            }
                        }

                        #2a) insert preceed rows
                        if($flag == false){


                            if(!$this->temp_connect_bd->commit())
                            {
                                print 'error insert 255';
                                exit;
                            }
                            $flag = true;

                            unset($ins_t);
                        }

                       
                        if (!rename($this->temp_dir_log[$type] . $file, $this->temp_dir_log[$type] . $this->insert_dir . $file)) {

                           
                            $this->settings[$type]['file'] = $file;
                            $this->settings[$type]['line'] = $n;

                            $this->write_config($this->settings);

                            print "File error move! " . $file . "\n";
                        }else{

                            unset($this->settings[$type]['file']);
                            unset($this->settings[$type]['line']);
                            $this->write_config($this->settings);
                        }

                    }


                }
            }

            $this->unsetTemp();

        }else
            print "Empty logs \n";

        $this->temp_connect_bd = NULL;
    }



    public function parseBans(){
        $this->temp_connect_bd = $this->database();

        #conv array
        $bans_log_temp = json_decode( json_encode( simplexml_load_file($this->temp_dir_log['bans']) ) ,true );
        $bans_log = array();

        foreach($bans_log_temp["ban"] as $id => $attributes){
            $hwid = $attributes["@attributes"]['hwid'];
            $bans_log[$hwid][0] = $hwid;
            $bans_log[$hwid][1] = $attributes['accounts']['account'];
            $bans_log[$hwid][2] = $attributes["comment"];
            $bans_log[$hwid][3] = $attributes["@attributes"]['time'];

            $hwid = null;
        }
       
        if($bans_log){
           
           
            $insert = "";
            $n = 0;

            print "Ban list update \n";
           
            $result = $bans_log;
           
            if(count($result) > 0){
               
                $insert .= " TRUNCATE TABLE lin2world.dbo.BannedHardwareId \n";
               
                foreach($result as $id => $value){
                    $n++;
                    $data = $value;
                   
                   
                    foreach ($data as $key => $val) {
                       
                        if(is_array($data[$key]))
                            $data[$key] = $this->temp_connect_bd->quote(trim($data[$key][0]));
                        elseif (strlen($data[$key]) == 0)
                            $data[$key] = 'NULL';
                        else
                            $data[$key] = $this->temp_connect_bd->quote(trim($data[$key]));
           
                    }

                    #insert
                   
                    $insert .= "insert into dbo.BannedHardwareId (hardware_id, account, gm, timeout) values ";
                    $insert .= "(" . (implode(',', $data)) . ");\n";
                   
                    unset($data);
                }

            }


            if (strlen($insert) > 20) {#have some logs
                #1) insert data
                if ($this->debug)
                    print "Insert data:\n" . $insert . "\n\n";

                $jj = $nn = 0;
               
           
                $ins_t = explode('\n', $insert);
                unset($insert);
               

                $flag = true;
                foreach ($ins_t as $ins) {
                    $jj++;
                    $nn++;

                    if($flag){
                        $flag = !$this->temp_connect_bd->beginTransaction();
                    }

                    $this->temp_connect_bd->exec($ins);

                    if ($jj == $this->pack_req) {
                        #2) insert preceed rows

                        $flag = true;

                        if(!$this->temp_connect_bd->commit())
                        {
                            print 'error insert 255';
                            exit;
                        }

                        $jj = 0;

                    }
                }

                #2a) insert preceed rows
                if($flag == false){


                    if(!$this->temp_connect_bd->commit())
                    {
                        print 'error insert 255';
                        exit;
                    }
                    $flag = true;

                    unset($ins_t);
                }

            }

            print "Ban list update \n";
        }else
            print "Ban list has not changed \n";

        $this->temp_connect_bd = NULL;
    }



    public function unsetTemp(){

        unset($this->temp_log_f,$this->temp_file_log);

    }

    public function getParslog(array $logs){

    }

}


while(true)
{
    $LogD = new LogD();
    $LogD->parseLog();
    $LogD->parseBans();
    unset($LogD);
    sleep(60);

}
?>

Ниже подцеплю весь билд в месте с пхп
 

Или можно сделать так
14508535_1303948202963055_437077114_n.jpg
 
Назад
Сверху Снизу