<?php
function get_curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $httpheader[] = "Accept: */*";
    $httpheader[] = "Accept-Encoding: gzip,deflate,sdch";
    $httpheader[] = "Accept-Language: zh-CN,zh;q=0.8";
    $httpheader[] = "Connection: close";
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
    if ($header) {
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
    }
    if ($cookie) {
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    if ($referer) {
        if ($referer == 1) {
            curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
        } else {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
    }
    if ($ua) {
        curl_setopt($ch, CURLOPT_USERAGENT, $ua);
    } else {
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36');
    }
    if ($nobaody) {
        curl_setopt($ch, CURLOPT_NOBODY, 1);
    }
    curl_setopt($ch, CURLOPT_ENCODING, "gzip");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $ret = curl_exec($ch);
    curl_close($ch);
    return $ret;
}


function key_array($key, $arr)
{
    $newArr = [];
    if (is_array($arr) && count($arr) > 0) {
        foreach ($arr as $v) {
            $newArr[] = isset($v[$key]) ? $v[$key] : '';
        }
    }
    return $newArr;
}

function key_value_column($key, $v_key, $arr)
{
    $newArr = [];
    foreach ($arr as $v) {
        $newArr[$v[$key]] = $v[$v_key];
    }
    return $newArr;
}

function real_ip()
{
    $ip = $_SERVER['REMOTE_ADDR'];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
        foreach ($matches[0] AS $xip) {
            if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                $ip = $xip;
                break;
            }
        }
    } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (isset($_SERVER['HTTP_X_REAL_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_X_REAL_IP'])) {
        $ip = $_SERVER['HTTP_X_REAL_IP'];
    }
    return $ip;
}

function get_ip_city($ip)
{
    $url = 'http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=';
    $city = get_curl($url . $ip);
    $city = mb_convert_encoding($city, "UTF-8", "GB2312");
    $city = json_decode($city, true);
    if ($city['city']) {
        $location = $city['pro'] . $city['city'];
    } else {
        $location = $city['pro'];
    }
    if ($location) {
        return $location;
    } else {
        return false;
    }
}

function daddslashes($string, $force = 0, $strip = FALSE)
{
//    !defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
//    if (!MAGIC_QUOTES_GPC || $force) {
//        if (is_array($string)) {
//            foreach ($string as $key => $val) {
//                $string[$key] = daddslashes($val, $force, $strip);
//            }
//        } else {
//            $string = addslashes($strip ? stripslashes($string) : $string);
//        }
//    }
    return $string;
}

function strexists($string, $find)
{
    return !(strpos($string, $find) === FALSE);
}

function dstrpos($string, $arr)
{
    if (empty($string)) return false;
    foreach ((array)$arr as $v) {
        if (strpos($string, $v) !== false) {
            return true;
        }
    }
    return false;
}

function checkmobile()
{
    $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $ualist = array('android', 'midp', 'nokia', 'mobile', 'iphone', 'ipod', 'blackberry', 'windows phone');
    if ((dstrpos($useragent, $ualist) || strexists($_SERVER['HTTP_ACCEPT'], "VND.WAP") || strexists($_SERVER['HTTP_VIA'], "wap"))) {
        return true;
    } else {
        return false;
    }
}

function checkEmail($value)
{
    if (preg_match("/^[\w\.\-]+@\w+([\.\-]\w+)*\.\w+$/", $value) && strlen($value) <= 60) {
        return true;
    } else {
        return false;
    }
}

/**
 * 取中间文本
 * @param unknown $str
 * @param number $leftStr
 * @param number $rightStr
 */
function getSubstr($str, $leftStr, $rightStr)
{
    $left = strpos($str, $leftStr);
    $right = strpos($str, $rightStr, $left);
    if ($left < 0 or $right < $left) return '';
    return substr($str, $left + strlen($leftStr), $right - $left - strlen($leftStr));
}

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
    $ckey_length = 4;
    $key = md5($key ? $key : '21736da67d2d77432de7e2e4300b9ee3');
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace('=', '', base64_encode($result));
    }
}

function random($length, $numeric = 0)
{
    $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
    $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
    $hash = '';
    $max = strlen($seed) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $seed{mt_rand(0, $max)};
    }
    return $hash;
}

function get_rand($proArr)
{
    $result = "";
    $proSum = array_sum($proArr);
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        }
        $proSum -= $proCur;
    }
    unset($proArr);
    return $result;
}

function showmsg($content = '未知的异常', $type = 4, $back = false)
{
    switch ($type) {
        case 1:
            $panel = "success";
            break;
        case 2:
            $panel = "info";
            break;
        case 3:
            $panel = "warning";
            break;
        case 4:
            $panel = "danger";
            break;
        default:
            $panel = 'default';
            break;
    }

    echo '<div class="panel panel-' . $panel . '"><div class="panel-heading"> <h3 class="panel-title">提示信息</h3></div><div class="panel-body">';
    echo $content;

    if ($back) {
        echo '<hr><a href="' . $back . '"><< 返回上一页</a>';
    } else {
        echo '<hr><a href="javascript:history.back(-1)"><< 返回上一页</a>';
    }

    echo '</div></div>';
    exit;
}

// 带上响应式
function showmsgAuto($content = '未知的异常', $type = 4, $back = false)
{
    switch ($type) {
        case 1:
            $panel = "success";
            break;
        case 2:
            $panel = "info";
            break;
        case 3:
            $panel = "warning";
            break;
        case 4:
            $panel = "danger";
            break;
        default:
            $panel = 'default';
            break;
    }

    echo '<div class="col-sm-12 col-md-10 col-lg-8 center-block" style="float: none;">';
    echo '<div class="panel panel-' . $panel . '"><div class="panel-heading"> <h3 class="panel-title">提示信息</h3></div><div class="panel-body">';
    echo $content;

    if ($back) {
        echo '<hr><a href="' . $back . '"><< 返回上一页</a>';
    } else {
        echo '<hr><a href="javascript:history.back(-1)"><< 返回上一页</a>';
    }

    echo '</div></div></div>';
    exit;
}

function check_china()
{
    $ip = gethostbyname('check.cccyun.cc');
    if ($ip == '192.168.0.1') {
        return true;
    } else {
        return false;
    }
}

function yile_getSign($param, $key)
{
    $signPars = "";
    ksort($param);
    foreach ($param as $k => $v) {
        if ("sign" != $k && "" != $v) {
            $signPars .= $k . "=" . $v . "&";
        }
    }
    $signPars = trim($signPars, '&');
    $signPars .= $key;
    $sign = md5($signPars);
    return $sign;
}

// 【卡商网】API签名计算
function kashangwl_getSign($param, $key)
{
    $signPars = '';
    ksort($param);
    foreach ($param as $k => $v) {
        if ('sign' != $k && '' != $v) {
            $signPars .= $k . $v;
        }
    }
    $signPars = $key . $signPars;
    $sign = md5($signPars);
    return $sign;
}

function getServerIp()
{
    $url = 'http://members.3322.org/dyndns/getip';
    $url2 = 'https://www.bt.cn/Api/getIpAddress';
    if ($data = get_curl($url2)) {
        return $data;
    } else {
        $data = get_curl($url);
        return $data;
    }
}


/**
 * @param $requestUrl
 * @param $storeID
 * @param int $page
 * @return array
 */
function kayixinGetProductList($requestUrl, $storeID, $page = 1)
{
    $productListHtml = curl($requestUrl . '/front/inter/cutPageGoodsList.htm?nowPage=' . $page, [], 'post', [
        'dirId'   => $storeID . ',0,0',
        'keyWord' => '',
        'dremId'  => ''
    ]);

    if ($productListHtml === false)
        return [false, '[卡易信] 获取商品列表失败，请重试'];

    try {
        $dom = new \htmlParser\ParserDom($productListHtml);

        $contents = $dom->find('#contextDiv>tr');

        if (count($contents) === 0)
            return [false, []];

        $tempData = [];

        foreach ($contents as $content) {
            $tdList = $content->find('td');
            if (count($tdList) != 8)
                continue;
            $tempContent = $tdList[1]->find('a')[0]->getAttr('onclick');
            preg_match('/showgoodsmessage\(\'(.+),(.+)\'\)/i', $tempContent, $pregResult);
            if (count($pregResult) !== 3)
                continue;
            $tempData[] = [
                'id'     => $tdList[0]->getPlainText(),
                'name'   => trim($tdList[1]->find('a>font')[0]->getPlainText()),
                'price'  => trim($tdList[4]->find('font>strong')[0]->getPlainText()),
                'goodID' => $pregResult[1],
                'keyID'  => $pregResult[2]
            ];
        }

        $tempDataLength = count($tempData);

        if ($tempDataLength == 20) {
            $tempPageData = kayixinGetProductList($requestUrl, $storeID, $page + 1);
            if ($tempPageData[0] && count($tempPageData[1]) > 0)
                $tempData = array_merge($tempData, $tempPageData[1]);
        }

        return [true, $tempData];
    } catch (\Exception $exception) {
        return [false, '[系统异常] ' . $exception->getMessage()];
    }
}
