<?php

//订单号 -> IP
//
//{
//    "COLI_WebCode": "JP",
//    "COLI_ID": "ZPL161028068",
//    "COLI_ApplyDate": "2016-04-15 23:17:20",
//    "COLI_SenderIP": "116.226.169.236"
//}
//
//CHT:http://www.chinahighlights.com/api/api.php?method=order.json_by_lmr&order_id=hy161104033
//国际:http://www.viaje-a-china.com/index.php/ajax/ajax_order_datas/
//
//
$order_id = isset($_GET['order_id']) ? $_GET['order_id'] : FALSE;
$order_id = isset($_POST['order_id']) ? $_POST['order_id'] : $order_id;
//$site = isset($_GET['site']) ? $_GET['site'] : FALSE;
//$site = isset($_POST['site']) ? $_POST['site'] : $site;
$ip = '255.255.255.255';
$web_code = FALSE;
$date = date('Y-m-d h:i:s');
$host = array(
    'xx' => 'xx',
    'jp' => 'JP',
    'vc' => 'FR',
    'vac' => 'ES',
    'train_vac' => 'ES',
    'ru' => 'RU',
    'train_ru' => 'RU',
    'it' => 'IT',
    'train_it' => 'IT',
    'cht' => 'CHT',
    'ct' => 'yincheng',
    'gm' => 'gm-vps',
    'ah' => 'AH',
);
$host_name = array(
    'jp' => 'http://www.arachina.com',
    'vc' => 'http://www.voyageschine.com',
    'vac' => 'http://www.viaje-a-china.com',
    'train_vac' => 'http://www.viaje-a-china.com',
    'ru' => 'http://www.chinahighlights.ru',
    'train_ru' => 'http://www.chinahighlights.ru',
    'it' => 'http://www.viaggio-in-cina.it',
    'train_it' => 'http://www.viaggio-in-cina.it',
    'cht' => 'http://www.chinahighlights.com',
    'ct' => 'http://www.chinatravel.com',
    'gm' => 'http://www.chinarundreisen.com',
    'ah' => 'http://www.asiahighlights.com',
);
$bf_date = date('m/d/Y:00:00:00', time() - 3600*24*90);
$af_date = date('m/d/Y:00:00:00', time() + 3600*24*90);
$order_txt = '';
$web_code = 'xx';
$order_date = '';

if ($order_id)
{
    //if ($site == 'ch') 
    //{
    //    $order = @file_get_contents('http://www.chinahighlights.com/api/api.php?method=order.json_by_lmr&order_id='.$order_id);
    //}
    //else
    //{
        $order = @file_get_contents('http://www.viaje-a-china.com/index.php/ajax/ajax_order_datas/'.$order_id);
    //}
   
    if ($order && $order !== 'no data')
    {
        $order = json_decode($order);
        $ip = $order->COLI_SenderIP;
        if (!$ip || $ip=='159.8.126.74' || $ip=='180.140.114.208') 
        {
            $ip = null;
        }
        $web_code = $order->COLI_WebCode;
        $order_date = $order->COLI_ApplyDate;
        $date_time = strtotime($order->COLI_ApplyDate);
        $bf_date = date('m/d/Y:00:00:00', $date_time - 3600*24*90);
        $af_date = date('m/d/Y:00:00:00', $date_time + 3600*24*90);
        $order_txt = $order->COLI_OrderDetailText;
    }
}

//连接Splunk SDK
require_once '../Splunk.php';
$connect_arguments = array(
    'scheme' => 'https',
    'host' => '192.155.250.125',
    'port' => 8089,
    'username' => 'haina',
    'password' => '383d43GZ82[Ai',
);
$service = new Splunk_Service($connect_arguments);
$service->login();

//查询IP
//[EXA] host=ES "68.180.229.232" earliest="11/1/2016:00:00:00" latest="11/2/2016:00:00:00"
$results = array();
if ($ip) 
{
    $search = 'search host='.$host[strtolower($web_code)].' "'.$ip.'" earliest="'.$bf_date.'" latest="'.$af_date.'" NOT("/ngx_pagespeed_beacon" OR "/tourprice" OR "/include" OR "/api" OR "/ajax" OR "/image" OR "/common" OR "/ckplayer" OR ".css" OR ".js" OR ".ico" OR ".gif" OR ".jpg" OR ".png" OR ".json" OR ".xml" OR ".ttf" OR ".woff" OR ".eot" OR "webhtmllog" OR "asphttp_accept_language" OR "down.asp" OR "verifyemail" OR "test")';
    //调用Spluck Search
    $job = $service->getJobs()->create($search);
    while (!$job->isDone())
    {
      $job->refresh();
    }
    $results = $job->getResults();
}


?><!DOCTYPE html>
<html lang="en">
<head>
<title>订单日志查询</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="/css/another/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script src="/js/jquery.min.js"></script>
<style type="text/css">
@media (min-width: 768px) {
    .container {width: 750px;}
    ._raw{max-width:700px;word-wrap: break-word;}
    .btn-default {max-width: 700px;}
}
@media (min-width: 992px) {
    .container {width: 970px;}
    ._raw{max-width:920px;word-wrap: break-word;}
    .btn-default {max-width: 860px;}
}
@media (min-width: 1200px) {
    .container {width: 1200px;}
    ._raw{max-width:1100px;word-wrap: break-word;}
    .btn-default {max-width: 1000px;}
}
#formbody {margin:20px 0;}
#start_date, #end_date, #fz_name, #dz_name, #train_date {width: 135px;}
#site_code {min-width: 200px}
#train_date {min-width: 152px;}
#fix_alert {padding-top: 8px;padding-bottom: 8px;}
td,th {font-size: 13px;}
.pagination {margin: 0 0 12px;}
#ui-datepicker-div {z-index: 1000!important;}
pre {margin-top: 5px;font-size: 0.8em;}
.btn-default {white-space: initial;text-align: left;word-wrap: break-word;}
.tt{color: #07c;}
._raw a.btn-sm {font-size: 14px;}
</style>
</head>
<body class="container">
    <div id="formbody">
        <form class="form-inline" action="" method="post" id="sform">
            <div class="form-group has-success">
                <label class="sr-only" for="order_id">订单号</label>
                <input type="text" name="order_id" class="form-control" id="order_id" placeholder="输入订单号" value="<?php if ($order_id) echo($order_id); ?>">
            </div>
            <button type="submit" class="btn btn-primary" data-loading-text="Loading..." id="btn6">查询</button>
        </form>
    </div>
    <div class="alert alert-info" role="alert" id="fix_alert">
    <?php 
    if ($web_code) echo(' [站点：'.$web_code.']'); 
    if ($order_date) echo(' [提交日期：'.$order_date.']'); 
    if ($order_txt) echo('<pre>'.$order_txt.'</pre>'); 
    //echo(' 【SPL：'.$search.'】'); 
    ?>
    </div>
    <!--nav>
        <ul class="pagination">
            <?php
            $page = 1;
            $page_count = 10;
            $prev_cls = '';
            if ($page == 1) $prev_cls = 'disabled';
            $next_cls = '';
            if ($page == $page_count) $next_cls = 'disabled';
            ?>
            <li class="<?php echo($prev_cls);?>">
                <a href="#" aria-label="Previous" id="prev">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <?php for ($i=1; $i<=$page_count; $i++) { 
                    $cls = '';
                    if ($i == $page) $cls = 'active';
            ?>
            <li class="<?php echo($cls);?>"><a href="javascript:;" class="page_a" data-action="/train/china-trains/search/logs/<?php echo($i);?>"><?php echo($i);?></a></li>
            <?php } ?>
            <li class="<?php echo($next_cls);?>">
                <a href="#" aria-label="Next" id="next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav-->
    <table class="table table-bordered table-hover">
        <?php
        $messages = array();
        $anyRows = FALSE;
        $columnNames = NULL;
        foreach($results as $result) 
        {
            if ($result instanceof Splunk_ResultsFieldOrder) 
            {
                //所有字段
                $columnNames = $result->getFieldNames();
                //所需字段
                $need_th = array('_serial', '_raw', '_time');
                //字段差集
                $columnNames = array_intersect($need_th, $columnNames);
                echo '<thead><tr><td colspan="3" class="tt">提示: “GET”表示正常访问；“POST”表示从表单提交访问；“标黄”表示订单相关的访问。</td></tr><tr>';
                foreach($columnNames as $columnName)
                echo '<th>'.htmlspecialchars($columnName).
                '</th>';
                echo '</tr></thead>';
                echo "\n";
            } 
            else if ($result instanceof Splunk_ResultsMessage)
            {
              $messages[] = $result;
            }
            else if (is_array($result)) 
            {
                $anyRows = TRUE;
                assert($columnNames !== NULL);
                echo '<tr>';
                foreach($columnNames as $columnName) 
                {
                    $cellValue = array_key_exists($columnName, $result) ? $result[$columnName] : NULL;
                    //nginx日志
                    if ($columnName == '_raw') 
                    {
                        echo '<td><div class="_raw">';
                        if (is_array($cellValue))
                        {
                            $log = implode('', $cellValue);
                            //116.226.169.236 - - [27/Oct/2016:07:35:39 -0500] "GET / HTTP/1.1" 200 8857 "-" "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/14A456 Safari/602.1"
                            //ip(1), visit(3), from(6), ua(7)
                            $p = '/^(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})\s-\s-\s\[(.*)\]\s\"(.*)\"\s(\d{3})\s(\d+)\s\"(.*)\"\s\"(.*)\"$/';
                            preg_match($p, $log, $matches);
                            //print_r($matches); 
                            if (isset($matches[3]))
                            {
                                $tmp_a = explode(' ', $matches[3]);
                                echo '<a href="'.$host_name[strtolower($web_code)].@$tmp_a[1].'" class="btn btn-sm btn-primary" type="button" target="_blank"><span class="badge">visit</span> '.urldecode($matches[3]).'</a> &nbsp;';
                            }
                            if (isset($matches[6]))
                            {
                                if ($matches[6]=='-') $matches[6] = '从收藏夹、历史记录或地址栏直接访问';
                                echo '<a href="'.$matches[6].'" class="btn btn-sm btn-default" type="button" target="_blank"><span class="badge">from</span> '.urldecode($matches[6]).'</a> &nbsp;';
                            }
                            if (!isset($matches[1]))
                            {
                                echo $log;
                            }
                        }
                        echo '</div></td>';
                    }
                    //日期
                    else if ($columnName == '_time') 
                    {
                        echo '<td>';
                        $time = strtotime($cellValue);
                        echo date('Y-m-d h:i:s', $time);
                        echo '</td>';
                    }
                    //splunk记录
                    else
                    {
                        echo '<td>';
                        if ($cellValue !== NULL) 
                        {
                            if (is_array($cellValue)) 
                            {
                                echo '<ul>';
                                foreach($cellValue as $value) 
                                {
                                    echo '<li>'.htmlspecialchars($value).'</li>';
                                }
                                echo '</ul>';
                            } 
                            else 
                            {
                                echo htmlspecialchars($cellValue);
                            }
                        }
                        echo '</td>';
                    }
                }
                echo '</tr>';
            }
        }
        ?>
    </table>

    <?php if (count($messages) > 0): ?>
        <ul>
        <?php
        foreach ($messages as $message)
        {
            echo '<li>[' . htmlspecialchars($message->getType()) . '] ';
            echo htmlspecialchars($message->getText()) . '</li>';
        }
        ?>
        </ul>
    <?php endif; ?>
    <?php if (!$anyRows && (count($messages) === 0)): ?>
        <p>
            没有查到相关日志
        </p>
    <?php endif; ?>

    <script type="text/javascript">
        function openwindow(url,name,iWidth,iHeight)
        {
            var url; //转向网页的地址;
            var name; //网页名称，可为空;
            var iWidth; //弹出窗口的宽度;
            var iHeight; //弹出窗口的高度;
            //window.screen.height获得屏幕的高，window.screen.width获得屏幕的宽
            var iTop = (window.screen.height-30-iHeight)/2; //获得窗口的垂直位置;
            var iLeft = (window.screen.width-10-iWidth)/2; //获得窗口的水平位置;
            window.open(url,name,'height='+iHeight+',,innerHeight='+iHeight+',width='+iWidth+',innerWidth='+iWidth+',top='+iTop+',left='+iLeft+',toolbar=no,menubar=no,scrollbars=auto,resizeable=no,location=no,status=no');
        }
        $('a.js_win').on('click', function() {
            var _sn = $(this).attr('data-sn');
            var _url = '/train/china-trains/search/log_data/'+_sn+'/';
            openwindow(_url, "SL", 809, 500);
        });
        $('.page_a').on('click', function(){
            $('#sform').attr('action', $(this).attr('data-action')).submit();
        });
        $('#prev').on('click', function() {
            if (!$(this).parent('li').hasClass('disabled')) {
                var curr = $('li.active').index();
                $('#sform').attr('action', '/train/china-trains/search/logs/'+ (curr-1)).submit();
            }
        });
        $('#next').on('click', function() {
            if (!$(this).parent('li').hasClass('disabled')) {
                var curr = $('li.active').index();
                $('#sform').attr('action', '/train/china-trains/search/logs/'+ (curr+1)).submit();
            }
        });
         $('#btn6').on('click', function () {
            $(this).html('Seraching...');
            $(this).prop('disabled', true);
            $('#sform').submit();
          })
    </script>
</body>
</html>