<?php

class Common_Common {

    /**
     * @return mixed
     */
    public static function getIP() {
        if (@$_SERVER['HTTP_CLIENT_IP'] && @$_SERVER['HTTP_CLIENT_IP'] != 'unknown') {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (@$_SERVER['HTTP_X_FORWARDED_FOR'] && @$_SERVER['HTTP_X_FORWARDED_FOR'] != 'unknown') {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip ? $ip : '127.0.0.1';
    }


    /**
     * XML转数组
     * @param string $xmlString XML字符串
     * @return array XML数组
     */
    public static function simpleXmlToArray($xmlString) {
        $obj = simplexml_load_string($xmlString);
        if($obj===false){
            return false;
        }
        return json_decode(json_encode((array)$obj), true);
    }


    /**
     * 产生随机字符
     * @param $length
     * @param int $numeric
     * @return string
     */
    public static function random($length, $numeric = 0) {
        PHP_VERSION < '4.2.0' ? mt_srand((double) microtime() * 1000000) : mt_srand();
        $seed = base_convert(md5(print_r($_SERVER, 1) . microtime()), 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;
    }

    /**
     * 文件下载
     */
    public static function downloadFile($file) {
        // if (!is_file($file)) { die("<b>404 File not found!</b>"); }
        // Gather relevent info about file
        $len = filesize($file);
        $filename = basename($file);
        $file_extension = strtolower(substr(strrchr($filename, "."), 1));
        // This will set the Content-Type to the appropriate setting for the file
        switch ($file_extension) {
            case "pdf":
                $ctype = "application/pdf";
                break;
            case "exe":
                $ctype = "application/octet-stream";
                break;
            case "zip":
                $ctype = "application/zip";
                break;
            case "doc":
                $ctype = "application/msword";
                break;
            case "xls":
                $ctype = "application/vnd.ms-excel";
                break;
            case "ppt":
                $ctype = "application/vnd.ms-powerpoint";
                break;
            case "gif":
                $ctype = "image/gif";
                break;
            case "png":
                $ctype = "image/png";
                break;
            case "jpeg":
            case "jpg":
                $ctype = "image/jpg";
                break;
            case "mp3":
                $ctype = "audio/mpeg";
                break;
            case "wav":
                $ctype = "audio/x-wav";
                break;
            case "mpeg":
            case "mpg":
            case "mpe":
                $ctype = "video/mpeg";
                break;
            case "mov":
                $ctype = "video/quicktime";
                break;
            case "avi":
                $ctype = "video/x-msvideo";
                break;
            // The following are for extensions that shouldn't be downloaded (sensitive stuff, like php files)
            case "php":
            case "htm":
            case "html":
            case "txt":
                die("<b>Cannot be used for " . $file_extension . " files!</b>");
                break;
            default:
                $ctype = "application/force-download";
        }
        ob_end_clean();
        // Begin writing headers
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        // Use the switch-generated Content-Type
        header("Content-Type: $ctype");
        // Force the download
        $header = "Content-Disposition: attachment; filename=" . $filename . ";";
        header($header);
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . $len);
        @readfile($file);
        exit();
    }

    /**
     * 获取服务器IP
     * @return string
     */
    public static function getRealIp() {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
    }

    /**
     * 对象转数组
     * @param $obj
     * @return mixed
     */
    public static function objectToArray($obj) {
        $arr = [];
        $_arr = is_object($obj) ? get_object_vars($obj) : $obj;
        if (is_array($_arr)) {
            foreach ($_arr as $key => $val) {
                $val = (is_array($val) || is_object($val)) ? self::objectToArray($val) : $val;
                $arr[$key] = $val;
            }
        }
        return $arr;
    }

    /*
     * 页面延迟跳转，并提示
     */

    public static function redirect($url, $msg) {
        $second = 3;
        $millisecond = $second * 1000;
        // 用html方法实现页面延迟跳转
        echo "<html>\n";
        echo "<head>\n";
        echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
        echo "<meta http-equiv='refresh' content='{$second};url=" . $url . "'>\n";
        echo "</head>\n";
        echo "<body style='text-align:center;padding-top:100px;line-height:25px;'>\n";
        echo $msg . "</br>\n";
        echo "页面将在{$second}秒后自动跳转...</br>\n";
        echo "<a href='" . $url . "'>如果没有跳转，请点这里跳转</a>\n";
        echo "</body>\n";
        echo "</html>\n";
        exit();

        // 用js方法实现页面延迟跳转
        echo $msg . "</br>";
        echo "页面将在3秒后自动跳转...</br>";
        echo "<a href='" . $url . "'>如果没有跳转，请点这里跳转</a>";
        echo "<script language='javascript'>setTimeout(\"window.location.href='" . $url . "'\",{$millisecond})</script>";
        exit();
    }

    /**
     * 字符串截取
     * @param $str
     * @param $len
     * @return string
     */
    public static function utf_substr($str, $len) {
        for ($i = 0; $i < $len; $i++) {
            $temp_str = substr($str, 0, 1);
            if (ord($temp_str) > 127) {
                $i++;
                if ($i < $len) {
                    $new_str[] = substr($str, 0, 3);
                    $str = substr($str, 3);
                }
            } else {
                $new_str[] = substr($str, 0, 1);
                $str = substr($str, 1);
            }
        }
        return join('', $new_str);
    }

    //清除wsdl缓存文件
    public static function clearWsdlTmp() {
        $dir = ini_get('soap.wsdl_cache_dir'); // 查找跟目录下file文件夹中的文件
        if (is_dir($dir)) {
            if ($dir_handle = opendir($dir)) {
                while (false !== ($file_name = readdir($dir_handle))) {
                    if ($file_name == '.' or $file_name == '..') {
                        continue;
                    } else {
                        //     					echo $file_name."\n";
                        if (preg_match('/^(wsdl).*/', $file_name)) {

                            @unlink($dir . "/" . $file_name);
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    //清除wsdl缓存文件
    public static function clearWsdlCacheFile() {
        $dir = APPLICATION_PATH . '/../data/cache';
        if (is_dir($dir)) {
            if ($dir_handle = opendir($dir)) {
                while (false !== ($file_name = readdir($dir_handle))) {
                    if ($file_name == '.' or $file_name == '..') {
                        continue;
                    } else {
                        //     					echo $file_name."\n";
                        if (preg_match('/.*(wsdl)$/', $file_name)) {

                            @unlink($dir . "/" . $file_name);
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    //清除超时图片缓存文件
    public static function clearImageTempFile() {
        $dir = APPLICATION_PATH . '/../data/images/temp';
        if (is_dir($dir)) {
            if ($dir_handle = opendir($dir)) {
                while (false !== ($file_name = readdir($dir_handle))) {
                    if ($file_name == '.' or $file_name == '..') {
                        continue;
                    } else {
                        // echo $file_name."\n";
                        $a = fileatime($dir . "/" . $file_name);
                        if (time() - $a > 3600) {
                            @unlink($dir . "/" . $file_name);
                        }
                    }
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 判断是不是soap数组
     * @param array $input
     * @return boolean
     */
    public static function isSoapArray($input) {
        if (!is_array($input)) {
            return false;
        }
        $keys = array_keys($input);
        $isInt = true;
        foreach ($keys as $k) {
            if (!is_int($k)) {
                $isInt = false;
            }
        }
        return $isInt;
    }

    /**
     * 判断如果为一维数据转为多维
     * @param $arr
     * @return array
     */
    public static function multiArr($arr) {
        $return = array();
        $isMulti = false;
        foreach ($arr as $k => $v) {
            if (is_int($k)) {
                $isMulti = true;
            }
        }
        if (!$isMulti) {
            $return[] = $arr;
        } else {
            $return = $arr;
        }
        return $return;
    }

    /**
     * @param $url
     * @param int $timeout
     * @param array $header
     * @return mixed
     * @throws Exception
     */
    public static function http_request($url, $timeout = 300, $header = array()) {
        if (!function_exists('curl_init')) {
            throw new Exception('server not install curl');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $data = curl_exec($ch);
        list ($header, $data) = explode("\r\n\r\n", $data);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302) {
            $matches = array();
            preg_match('/Location:(.*?)\n/', $header, $matches);
            $url = trim(array_pop($matches));
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            $data = curl_exec($ch);
        }

        if ($data == false) {
            curl_close($ch);
        }
        @curl_close($ch);
        return $data;
    }
      public static function http_post($url, $timeout = 300, $post = array()) {

        $ch = curl_init();
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //支持跳转
        curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //可跳转的次数
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        if (!empty($post)) {
            curl_setopt($ch, CURLOPT_POST, true);
            if (is_scalar($post)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
            }
        }
        $data = curl_exec($ch);
        if ($data == false) {
            curl_close($ch);
        }
        @curl_close($ch);
        return $data;
    }
    

    public static function getAdapter() {
        return Service_Application::getModelInstance()->getAdapter();
    }

    //字符串解密加密
    public static function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
        $ckey_length = 6; // 随机密钥长度 取值 0-32;
        // 加入随机密钥，可以令密文无任何规律，即便是原文和密钥完全相同，加密结果也会每次不同，增大破解难度。
        // 取值越大，密文变动规律越大，密文变化 = 16 的 $ckey_length 次方
        // 当此值为 0 时，则不产生随机密钥

        $key = md5($key ? $key : 'EC');
        $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));
        }
    }

    /*
     * 创建文件路径
     *
     * @access	public
     * @param	string		($dir	路径)
     * @param	int			($mode	权限)
     * @return	boolean
     */

    public static function createPath($dir, $mode = 0777) {
        clearstatcache();
        $path = preg_replace('/(\/){2,}|(\\\){1,}/', '/', $dir);
        if (is_dir($path)) {
            return true;
        } else {
            $dirs = array();
            $dirs = explode("/", $path);
            $path = "";
            foreach ($dirs as $element) {
                $path .= $element . "/";
                if (!is_dir($path)) {
                    @mkdir($path, $mode);
                }
            }
            return is_dir($path);
        }
    }

    /**
     * 上传图片
     *
     * @access	public
     * @param	array		($files		$_FILES)
     * @param	string		($field		上传字段)
     * @param	int			($width		图片宽度)
     * @param	int			($height	图片高度)
     * @param	string		($path		保存路径)
     * @param	boolean		($piece		是否单个)
     * @return	array
     */
    public static function uploadImg($files, $field, $path, $piece = true, $width = 5000, $height = 5000) {
        $config['upload_path'] = $path;
        $config['allowed_types'] = 'gif|jpg|jpeg|jpe|png|pdf';
        $config['max_size'] = '10000';
        $config['max_width'] = $width;
        $config['max_height'] = $height;
        $config['encrypt_name'] = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload_auto($files, $field)) {
            $state = array('error' => true, 'msg' => $upload->display_errors());
        } else {
            $state = array('error' => false, 'msg' => $piece ? $upload->data() : $upload->get_datas());
        }
        return $state;
    }

    /* 数字转换为汉字 colin */

    public static function num2char($num, $mode = true) {
        $char = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
        //$char = array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖);
        $dw = array('', '十', '百', '千', '', '万', '亿', '兆');
        //$dw = array('','拾','佰','仟','','萬','億','兆');
        $dec = '点';  //$dec = '點';
        $retval = '';
        if ($mode) {
            preg_match_all('/^0*(\d*)\.?(\d*)/', $num, $ar);
        } else {
            preg_match_all('/(\d*)\.?(\d*)/', $num, $ar);
        }
        if ($ar[2][0] != '') {
            $retval = $dec . ch_num($ar[2][0], false); //如果有小数，先递归处理小数
        }
        if ($ar[1][0] != '') {
            $str = strrev($ar[1][0]);
            for ($i = 0; $i < strlen($str); $i++) {
                $out[$i] = $char[$str[$i]];
                if ($mode) {
                    $out[$i] .= $str[$i] != '0' ? $dw[$i % 4] : '';
                    if ($str[$i] + $str[$i - 1] == 0) {
                        $out[$i] = '';
                    }
                    if ($i % 4 == 0) {
                        $out[$i] .= $dw[4 + floor($i / 4)];
                    }
                }
            }
            $retval = join('', array_reverse($out)) . $retval;
        }
        return $retval;
    }

    /* 固定宽度输出colin */

    public static function fix_width_output($str, $width = 200) {

        $strlen = self::char_display_width($str);
        if ($strlen < $width) {
            $str.= str_repeat(' ', $width - $strlen);
            return $str;
        }
        return $str;
    }

    /* 显示宽度 */

    public static function char_display_width($str) {
        $strlen = (strlen($str) + mb_strlen($str, 'UTF8')) / 2;
        return $strlen;
    }

    /**
     * 去掉数组元素的空格
     *
     * @access	public

     */
    public static function trim_blank(&$args = array()) {
        if (empty($args) || !is_array($args)) {
            return;
        }
        foreach ($args as &$v) {
            if (is_array($v)) {
                self::trim_blank($v);
            } else{
                $v = trim($v);
            }
        }
        unset($v);
    }

    /**
     * 缩小图片尺寸.
     *
     * @param $PDF 待处理的二进制图片
     * @param $width 处理后图片尺寸的宽度(px)
     * @param $height 处理后图片尺寸的高度(px)
     * @param $quality 设置图像的压缩质量
     *
     * @return 处理好的二进制图片
     */
    public static function pdf2jpg($PDF, $width = 1850, $height = 1850, $quality = 100) {
        if (!extension_loaded('imagick')) {
            return false;
        }
        if (!file_exists($PDF)) {
            return false;
        }

        $imagick = new imagick();
        $imagick->setResolution(300, 300);
        $imagick->readImage($PDF);        
        foreach ($imagick as $Key => $Var) {
            $Var->setImageFormat('png');
            $Filename = $PDF . "-{$Key}.png";
            $Var->setCompressionQuality($quality);  
            $Var->setResolution(300, 300);
            $Var->scaleImage($width,$height,true);             
            if ($Var->writeImage($Filename) == true) {
                $Return[] = $Filename;
            }

        }
        $Var->clear();
        $Var->destroy();
        $imagick->clear();
        $imagick->destroy();
        return $Return;
    }

    /**
     *  function: 合成图片
     * @param  string      $output_url 图片保存路径
     * @param  string      $img_type   图片保存类型
     * @param  integral    $line_num   每行显示图片数量
     * @param  array       $logo_info  每张待合成图片的信息（要求所有尺寸统一）
     * @param  array       $img_list  待合成的图片绝对路径
     * 
     * @return void
     */
    public function generate($output_url, $img_type, $line_num, $logo_info, $img_list = array()) {

        //计算图片有多少行  
        $lines = ceil(count($img_list) / $line_num);

        $bg_width = ($logo_info['width'] + $logo_info['line_width']) * $line_num;
        $bg_height = ($logo_info['height'] + $logo_info['line_height']) * $lines;

        //构建画布  
        $canvas = null;
        $canvas = new Imagick();
        $canvas->newimage($bg_width, $bg_height, 'white');
        $canvas->setimageformat($img_type);
        $i = $j = 0;
        foreach ($img_list as $item) {
            $im = null;
            $im = new Imagick($item);
            $x = $logo_info['line_width'] * 2 + $i * $logo_info['width'];
            $y = $logo_info['line_height'] * 2 + $j * $logo_info['height'];

            // $canvas -> compositeimage($im, Imagick::COMPOSITE_OVER, $x, $y);  
            $canvas->compositeimage($im, $im->getImageCompose(), $x, $y);
            if (($i + 1) % $line_num === 0) {
                $i = 0;
                $j++;
            } else {
                $i++;
            }
            $im->clear();
            $im->destroy();
        }
        $canvas->writeimage($output_url);
        $canvas->clear();
        $canvas->destroy();
    }
    /*** 
    * 人民币大写转换函数 colin 
    */  
    public static function Chinese_RMB($money) {  
            $money = round($money, 2);    // 四舍五入  
            if ($money <= 0) {  
                    return '零元';  
            }  
            $units = array ( '', '拾', '佰', '仟', '', '万', '亿', '兆' );  
            $amount = array( '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' );  
            $arr = explode('.', $money);    // 拆分小数点  
            $money = strrev($arr[0]);        // 翻转整数  
            $length = strlen($money);        // 获取数字的长度  
            for ($i = 0; $i < $length; $i++) {  
                    $int[$i] = $amount[$money[$i]];    // 获取大写数字  
                    if (!empty($money[$i])) {  
                            $int[$i] .= $units[$i%4];    // 获取整数位  
                    }  
                    if ($i%4 == 0) {  
                            $int[$i] .= $units[4+floor($i/4)];    // 取整  
                    }  
            }  
            $con = isset($arr[1]) ? '元' . $amount[$arr[1][0]] . '角' . $amount[$arr[1][1]] . '分' : '元整';  
            $convert = implode('', array_reverse($int)) . $con;
            $convert = preg_replace(array('/[零]+$/u', '/[零]+/u', '/零万/u', '/零亿/u'), array('', '零', '万', '亿'), $convert);
            return $convert; // 整合数组为字符串  
    }  
        
    public static function ceil4bit($num){	 
        return  sprintf("%.4f", $num); 
    }

    public static function arrayMap($item){
        return current($item);
    }

    public static function charToABC($numeric = 0){
        $strABD = '';
        if($numeric > 25){
            $first = ceil($numeric / 26);
            (26 * $first == $numeric) && $first += 1;
            if($first > 26){//只能二位字母
                return false;
            }else{ 
                $strABD .=   chr($first+63);
            }
            // echo $numeric % 27;
            $strABD .= chr(($numeric % 26) + 65);
        }else{
            // echo ($numeric % 27).'-';
            $strABD .= chr(($numeric % 26) + 65);
        }
        
        return $strABD;
    }

    /*用于批量导入*/  
   public static function getXLSData($uploadFile,$field){        
        
        $path = APPLICATION_PATH.'/../data/upload/service_number';
        
        if(!file_exists($path)){
            if(!mkdir($path,0700,true)){
                $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('上传目录不存在创建文件目录失败'));
                return $result;
            }
        }
        $config = array();
        $config['upload_path']      = $path;
        $config['allowed_types']    = 'xls|xlsx|csv';
        $config['max_size']         = '150000';
        $config['encrypt_name']     = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload($_FILES,$field) ){
            $result['ask'] = '0';
            $result['message'] = '上传文件失败';
            $result['error'] =  $upload->display_errors();
            return $result;
            exit;
        }

        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if(empty($resultArray) || empty($full_path)){
            $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('数据不存在'));
            return $result;
            exit;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $resultArray = Common_Upload::readEXCEL($full_path);
                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }
        if(empty($resultArray) || !is_array($resultArray)){
            $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
            //echo json_encode($result);
            //exit;
        }
        @unlink($full_path);
        return $resultArray;
    }

    /*用于批量导入*/  
   public static function getXLSDataNew($uploadFile,$field){        
        
        $path = APPLICATION_PATH.'/../data/upload/service_number';
        
        if(!file_exists($path)){
            if(!mkdir($path,0700,true)){
                $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('上传目录不存在创建文件目录失败'));
                return $result;
            }
        }
        $config = array();
        $config['upload_path']      = $path;
        $config['allowed_types']    = 'xls|xlsx|csv';
        $config['max_size']         = '150000';
        $config['encrypt_name']     = true;
        $upload = new Common_UploadFile($config);
        $upload->set_upload_path($path);
        if (!$upload->do_upload($_FILES,$field) ){
            $result['ask'] = '0';
            $result['message'] = '上传文件失败';
            $result['error'] =  $upload->display_errors();
            return $result;
            exit;
        }

        $resultArray = $upload->data();
        $full_path = $resultArray['full_path'];
        if(empty($resultArray) || empty($full_path)){
            $result = array("ask"=>0,"message"=>"上传文件失败失败",'error'=>array('数据不存在'));
            return $result;
            exit;
        }
        switch($resultArray['file_ext']){
            case ".xls":
            case ".xlsx":
                $resultArray = Common_Upload::readEXCELNew($full_path);
                break;
            case ".csv":
                $resultArray = Common_Upload::readCSV($full_path);
                break;
            default:
                $resultArray = array();
                break;
        }
        if(empty($resultArray) || !is_array($resultArray)){
            $result = array("ask"=>0,"message"=>"文件内容不符合格式或数据为空.",'error'=>array());
            //echo json_encode($result);
            //exit;
        }
        @unlink($full_path);
        return $resultArray;
    }

    /*** 
    * 运输代码排序  kevin
    */  
    public static function multisort($arr){
        $sort = array(  
                'direction' => 'SORT_ASC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序  
                'field'     => 'sm_code',       //排序字段  
        );  
        $arrSort = array();  
        foreach($arr AS $uniqid => $row){  
            foreach($row AS $key=>$value){  
                $arrSort[$key][$uniqid] = $value;  
            }  
        }  
        if($sort['direction']){  
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arr);  
        }
        return $arr;
    }
    public static function assocArrayToXML($arr,$dom=0,$item=0,$root='Request')
    {
    if (!$dom){
        $dom = new DOMDocument("1.0",'utf-8');
    }
    if(!$item){
        $item = $dom->createElement($root); 
        $dom->appendChild($item);
    }
    foreach ($arr as $key=>$val){
        $itemx = $dom->createElement(is_string($key)?$key:"item");
        $item->appendChild($itemx);
        if (!is_array($val)){
            $text = $dom->createTextNode($val);
            $itemx->appendChild($text);
            
        }else {
            self::assocArrayToXML($val,$dom,$itemx);
        }
    }
    return $dom->saveXML();
    }

    public static function removeLastSeparator( $path ) {
        $tmp = $path;
        if( is_string( $tmp ) && $tmp ) {
            $tmp = trim( $tmp );
            $pi = pathinfo( $tmp );
            $tmp = $pi['dirname']. DIRECTORY_SEPARATOR . $pi['basename'];
        }
        return $tmp;
    }
    /* @author:gilbert
     * @date:2017-06-16
     *
     * 如果数组是 array( a=>array( array( b=>1,c=>2 ), array( b=>1,c=>2 ) ) ) 这种格式，它会返回 <a><b>1</b><c>2</c></a> <a><b>1</b><c>2</c></a>
     * 如果数组是 array( a=>array( x=>array( b=>1,c=>2 ), array( b=>1,c=>2 ) ) ) 这种格式，它会返回 <a> <x><b>1</b><c>2</c></x> <item><b>1</b><c>2</c></item> </a>
     */
    public static function arrayToXML( $data, $dom = 0, $item = 0, $root = 'Request') {
        if (!$dom) {
            $dom = new DOMDocument("1.0", 'UTF-8');
            $dom->xmlStandalone = false;
        }
        if (!$item) {
            $item = $dom->createElement( $root );
            $dom->appendChild($item);
        }
        if (is_array( $data ) ) {
            foreach ( $data as $key => $value) {
                $newItem = $dom->createElement( is_string($key) ? $key : "item" );
                $item->appendChild( $newItem );
                if (!is_array( $value  )) {
                    $text = $dom->createTextNode( $value );
                    $newItem->appendChild($text);

                } else {
                    $isAssocKey = true;
                    foreach ($value as $tmpKey => $tmpValue ) {
                        if (is_int( $tmpKey ) ) {
                            $isAssocKey = false;
                            break;
                        }
                    }
                    if ($isAssocKey) {
                        self::arrayToXML($value, $dom, $newItem);
                    } else {
                        $i = 0;
                        foreach ($value as $v) {
                            if ($i > 0) {
                                $newItem = $dom->createElement(is_string($key) ? $key : "item");
                                $item->appendChild( $newItem );
                            }
                            self::arrayToXML( $v, $dom, $newItem );
                            ++$i;
                        }
                    }
                }
            }
        } else {
            $text = $dom->createTextNode( $data );
            $item->appendChild( $text );
        }
        return $dom->saveXML();
    }
    /* @desc 输入索引，返回列名
     * $param int $index 索引 从0开始
     */
    public static function getColumnName( $index ) {
        $charAt = 65;
        $quotient = intval( $index / 26);
        $remainder = $index % 26;
        $f = $quotient>0 ? chr( $charAt + $quotient - 1 ) : '';
        $s = $remainder>=0 ? chr( $charAt + $remainder ) : '';
        return $f . $s;
    }

    /* @todo:获取开始和结束时间
     * @param string $startDate 开始时间
     * @param string $endDate   结束时间
     * @param string $sFormat   开始时间格式
     * @param string $eFormat   结束时间格式
     * @return array
     */
    public static function getStartAndEndTime( $startDate, $endDate, $sFormat = '', $eFormat = '' ) {
        $sDate = $eDate = '';
        $sTime = $eTime = false;
        if( $startDate ) {
            $sTime = strtotime( $startDate );
            $sDate = $startDate;
        }
        if( $endDate ) {
            $eTime = strtotime( $endDate );
            $eDate = $endDate;
        }
        if( $sTime !== false &&  $eTime !== false ) {
            if( $sTime > $eTime ) {
                $tmpTime = $sTime;
                $sTime   = $eTime;
                $eTime   = $tmpTime;

                $tmpDate = $sDate;
                $sDate   = $eDate;
                $eDate   = $tmpDate;
            }
        }
        if( $sTime !== false && $sFormat !== '' ) {
            $sDate = date( $sFormat, $sTime );
        }
        if( $eTime !== false && $eFormat !== '' ) {
            $eDate = date( $eFormat, $eTime );
        }
        return array( $sDate, $eDate );
    }
}
//class end
