<?php

//基于位的截取支持utf8
function bite_str($string, $start, $len, $byte = 3) {
    $str = "";
    $count = 0;
    $str_len = strlen($string);
    for ($i = 0; $i < $str_len; $i++) {
        if (($count + 1 - $start) > $len) {
            $str .= "..."; //省略号 之前是3个 现在删除
            break;
        } elseif ((ord(substr($string, $i, 1)) <= 128) && ($count < $start)) {
            $count++;
        } elseif ((ord(substr($string, $i, 1)) > 128) && ($count < $start)) {
            $count = $count + 2;
            $i = $i + $byte - 1;
        } elseif ((ord(substr($string, $i, 1)) <= 128) && ($count >= $start)) {
            $str .= substr($string, $i, 1);
            $count++;
        } elseif ((ord(substr($string, $i, 1)) > 128) && ($count >= $start)) {
            $str .= substr($string, $i, $byte);
            $count = $count + 2;
            $i = $i + $byte - 1;
        }
    }
    return $str;
}

//剔除html代码
function SpHtml2Text($str) {
    $str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU", "", $str);
    $alltext = "";
    $start = 1;
    for ($i = 0; $i < strlen($str); $i++) {
        if ($start == 0 && $str[$i] == ">") {
            $start = 1;
        } else if ($start == 1) {
            if ($str[$i] == "<") {
                $start = 0;
                $alltext .= " ";
            } else if (ord($str[$i]) > 31) {
                $alltext .= $str[$i];
            }
        }
    }
    $alltext = str_replace("　", " ", $alltext);
    $alltext = preg_replace("/&([^;&]*)(;|&)/", "", $alltext);
    $alltext = preg_replace("/[ ]+/s", " ", $alltext);
    return $alltext;
}

function strLength($str, $charset = 'utf-8') {
    if ($charset == 'utf-8')
        $str = iconv('utf-8', 'gb2312//ignore', $str);
    $num = strlen($str);
    $cnNum = 0;
    for ($i = 0; $i < $num; $i++) {
        if (ord(substr($str, $i + 1, 1)) > 127) {
            $cnNum++;
            $i++;
        }
    }
    $enNum = $num - ($cnNum * 2);
    //$number = ($enNum / 2) + $cnNum;//英文2个算一个字符
    $number = $enNum + $cnNum;
    return ceil($number);
}

//php发送post
function php_post($url, $fields) {
    extract($_POST);
    $fields_string = "";
    foreach ($fields as $key => $value) {
        $fields_string .= $key . '=' . $value . '&';
    }
    $fields_string = rtrim($fields_string, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    //die("xxxxx".$data);
    return $data;
}

//对象转换成数组
function object2array($obj) {
    if (is_object($obj)) {
        $obj = (array) $obj;
        $obj = object2array($obj);
    } elseif (is_array($obj)) {
        foreach ($obj as $key => $value) {
            $obj[$key] = object2array($value);
        }
    }
    return $obj;
}

function isMobile() {
    require_once(APPPATH . 'third_party/Mobile_Detect.php');
    $detect = new Mobile_Detect;
    return $detect->isMobile();
}

function getConfigFile() {
    $myfile = 'config.txt';
    $file_pointer = fopen($myfile, "r");
    $config = unserialize(base64_decode(fread($file_pointer, filesize($myfile))));
    fclose($file_pointer);
    return $config;
}

//将IP转换为数字
function IpToNumber($ip) {
    $ipstr = "";
    $ip_arr = explode('.', $ip); //分隔ip段
    foreach ($ip_arr as $value) {
        $iphex = dechex($value); //将每段ip转换成16进制
        if (strlen($iphex) < 2) {//255的16进制表示是ff，所以每段ip的16进制长度不会超过2
            $iphex = '0' . $iphex; //如果转换后的16进制数长度小于2，在其前面加一个0
            //没有长度为2，且第一位是0的16进制表示，这是为了在将数字转换成ip时，好处理
        }
        $ipstr .= $iphex; //将四段IP的16进制数连接起来，得到一个16进制字符串，长度为8
    }
    return hexdec($ipstr); //将16进制字符串转换成10进制，得到ip的数字表示
}

//将数字转换为IP，进行上面函数的逆向过程
function NumberToIp($n) {
    $iphex = dechex($n); //将10进制数字转换成16进制
    $len = strlen($iphex); //得到16进制字符串的长度
    echo $iphex . "<br />";
    if (strlen($iphex) < 8) {
        $iphex = '0' . $iphex; //如果长度小于8，在最前面加0
        $len = strlen($iphex); //重新得到16进制字符串的长度
    }
    //这是因为ipton函数得到的16进制字符串，如果第一位为0，在转换成数字后，是不会显示的
    //所以，如果长度小于8，肯定要把第一位的0加上去
    //为什么一定是第一位的0呢，因为在ipton函数中，后面各段加的'0'都在中间，转换成数字后，不会消失
    for ($i = 0, $j = 0; $j < $len; $i = $i + 1, $j = $j + 2) {//循环截取16进制字符串，每次截取2个长度
        $ippart = substr($iphex, $j, 2); //得到每段IP所对应的16进制数
        $fipart = substr($ippart, 0, 1); //截取16进制数的第一位
        if ($fipart == '0') {//如果第一位为0，说明原数只有1位
            $ippart = substr($ippart, 1, 1); //将0截取掉
        }
        $ip[] = hexdec($ippart); //将每段16进制数转换成对应的10进制数，即IP各段的值
    }
    //$ip = array_reverse($ip);

    return implode('.', $ip); //连接各段，返回原IP值
}

function validateServer() {
    $ip = gethostbyname($_SERVER["SERVER_NAME"]);
    if ($ip != '42.51.155.104' && $ip != '127.0.0.1') {
        return false;
    }
    return true;
}

function msgbox($msg, $url) {
    if (strlen($url) == 0) {
        echo "<script>alert('" . $msg . "');history.go(-1);</script>";
        die();
    } else {
        echo "<script>alert('" . $msg . "');window.location='" . $url . "';</script>";
        die();
    }
}

function hideMiddleString($str) {
    $newstr = "";
    if (strlen($str) == 11) {//mobile
        $temp = StringToArray(trim($str));
        for ($i = 0; $i < count($temp); $i++) {
            if ($i < 3) {
                $newstr .= $temp[$i];
            } else if ($i > 2 && $i < 7) {
                $newstr .= "*";
            } else {
                $newstr .= $temp[$i];
            }
        }
    } else {//email or other
        $arr = explode("@", $str);
        $temp = StringToArray(trim($arr[0]));
        for ($i = 0; $i < count($temp); $i++) {
            if ($i < 3) {
                $newstr .= $temp[$i];
            } else if ($i > 2 && $i < 7) {
                $newstr .= "*";
            } else {
                $newstr .= $temp[$i];
            }
        }
    }
    return $newstr;
}

//字符转换成数组
function StringToArray($str) {
    $result = array();
    $len = strlen($str);
    $i = 0;
    while ($i < $len) {
        $chr = ord($str[$i]);
        if ($chr == 9 || $chr == 10 || (32 <= $chr && $chr <= 126)) {
            $result[] = substr($str, $i, 1);
            $i += 1;
        } elseif (192 <= $chr && $chr <= 223) {
            $result[] = substr($str, $i, 2);
            $i += 2;
        } elseif (224 <= $chr && $chr <= 239) {
            $result[] = substr($str, $i, 3);
            $i += 3;
        } elseif (240 <= $chr && $chr <= 247) {
            $result[] = substr($str, $i, 4);
            $i += 4;
        } elseif (248 <= $chr && $chr <= 251) {
            $result[] = substr($str, $i, 5);
            $i += 5;
        } elseif (252 <= $chr && $chr <= 253) {
            $result[] = substr($str, $i, 6);
            $i += 6;
        }
    }
    return $result;
}

function csrf_hidden() {
    $ci = &get_instance();
    $name = $ci->security->get_csrf_token_name();
    $val = $ci->security->get_csrf_hash();
    echo "<input type=\"hidden\" name=\"$name\" value=\"$val\" />";
}

//第一个是原串,第二个是 部份串
function startWith($str, $needle) {
    return strpos($str, $needle) === 0;
}

//第一个是原串,第二个是 部份串
function endWith($haystack, $needle) {
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }
    return (substr($haystack, -$length) === $needle);
}

function writeFile($path, $content, $mode = 'w+') {
    $fp = fopen($path, $mode);
    flock($fp, LOCK_EX | LOCK_NB);
    fwrite($fp, $content);
    flock($fp, LOCK_UN);
    fclose($fp);
}

/**
 * 获取密码安全等级
 * @param string $password 密码
 * @return int 1:低,2:中,3:高
 */
function password_level($password) {
    if (preg_match('/^([0-9]{6,16})$/', $password)) {
        return 1;
    } else if (preg_match('/^[0-9 a-z]{6,16}$/', $password)) {
        return 2;
    } else if (preg_match('/^[0-9 a-z A-Z !@#$%^&*]{6,16}$/', $password)) {
        return 3;
    }
    return 0;
}

//构建json数据
function buildJSON($cb, $code, $msg, $data, $ext = null) {
    if (strlen($cb) == 0) {
        echo json_encode(array("code" => $code, "msg" => $msg, "data" => $data, "ext" => $ext));
    } else {
        echo $cb . "(" . json_encode(array("code" => $code, "msg" => $msg, "data" => $data, "ext" => $ext)) . ")";
    }
    die();
}

/**
 * 求两个日期之间相差的天数
 * (针对1970年1月1日之后，求之前可以采用泰勒公式)
 * @param string $day1
 * @param string $day2
 * @return number
 */
function diffBetweenTwoDays($day1, $day2) {
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}
