Skip to content
  • P
    Projects
  • G
    Groups
  • S
    Snippets
  • Help

孙龙 / note-library

  • This project
    • Loading...
  • Sign in
Go to a project
  • Project
  • Repository
  • Issues 0
  • Merge Requests 0
  • Pipelines
  • Wiki
  • Snippets
  • Settings
  • Activity
  • Graph
  • Charts
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
  • Files
  • Commits
  • Branches
  • Tags
  • Contributors
  • Graph
  • Compare
  • Charts
Find file
Normal viewHistoryPermalink
Switch branch/tag
  • note-library
  • app
  • Http
  • Function.php
Function.php 10.7 KB
孙龙's avatar
init
1f46a6ed
 
孙龙 committed 5 years ago
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
<?php 
	/** 公用函数 */

    //导出数据
    function exportExcel($expTitle, $expCellName, $expTableData)
    {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);

        // vendor("PHPExcel.PHPExcel");

        $objPHPExcel = new PHPExcel(); 
        include_once(__DIR__."/../../vendor/PHPExcel/PHPExcel/IOFactory.php");
        set_time_limit(0);//不对php(主要是写数据)执行时间做限制
        ini_set("memory_limit", "1024M");//设置内存(防爆内存)
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;//设置缓存策略(减少内存占用)
        //判断缓存策略是否可用
        if (!\PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
            die($cacheMethod . " 缓存方法不可用" . EOL);
        }

        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        //显示导出名称和导出时间
        // $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
        // $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  导出时间:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'1', $expCellName[$i][1]);
        }
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), $expTableData[$i][$expCellName[$j][0]]);
            }
        }

        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.csv"');
        header("Content-Disposition:attachment;filename=$fileName.csv");//attachment新窗口打印inline本窗口打印
        //输出bom
        print(chr(0xEF).chr(0xBB).chr(0xBF));
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
        $objWriter->save('php://output');
        exit;
    }

    // curl 
	function curlApi( $url , $params = array(), $method = 'GET' , $multi = false, $extheaders = array())
	{
        if(!function_exists('curl_init')) exit('Need to open the curl extension');
        $method = strtoupper($method);
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($ci, CURLOPT_TIMEOUT, 3);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ci, CURLOPT_HEADER, false);
        $headers = (array)$extheaders;
        switch ($method)
        {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                if (!empty($params))
                {
                    if($multi)
                    {
                        foreach($multi as $key => $file)
                        {
                            $params[$key] = '@' . $file;
                        }
                        curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                        $headers[] = 'Expect: ';
                    }
                    else
                    {
                        curl_setopt($ci, CURLOPT_POSTFIELDS, http_build_query($params));
                    }
                }
                break;
            case 'DELETE':
            case 'GET':
                $method == 'DELETE' && curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
                if (!empty($params))
                {
                    $url = $url . (strpos($url, '?') ? '&' : '?')
                        . (is_array($params) ? http_build_query($params) : $params);
                }
                break;
        }
        curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );
        curl_setopt($ci, CURLOPT_URL, $url);
        if($headers)
        {
            curl_setopt($ci, CURLOPT_HTTPHEADER, $headers );
        }

        $response = curl_exec($ci);
        curl_close ($ci);
        return $response;
    }

    /**
     * 导出CSV文件
     * @param array $data        数据
     * @param array $header_data 首行数据
     * @param string $file_name  文件名称
     * @return string
     */
    function export_csv($data = [], $header_data = [], $file_name = '')
    {
        set_time_limit(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename='.$file_name);
        header('Cache-Control: max-age=0');

        $fp = fopen('php://output', 'a');

        if (!empty($header_data)) {
            foreach ($header_data as $key => $value) {
                $header_data[$key] = iconv('utf-8', 'gbk', $value);
            }

            fputcsv($fp, $header_data);
        }

        $num = 0;
        
        $limit = 100000; //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
        
        $count = count($data); //逐行取出数据,不浪费内存

        if ($count > 0) {
            for ($i = 0; $i < $count; $i++) {
                $num++;
                //刷新一下输出buffer,防止由于数据过多造成问题
                if ($limit == $num) {
                    ob_flush();
                    flush();
                    $num = 0;
                }

                $row = $data[$i];

                foreach ($row as $key => $value) {
                    $row[$key] = iconv('utf-8', 'gbk', $value);
                }

                fputcsv($fp, $row);
            }
        }

        fclose($fp);exit;
    }

    /**
     * 获取客户端IP地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
     * @return mixed
     */
    function get_client_ip($type = 0, $adv = false)
    {
        $type      = $type ? 1 : 0;
        static $ip = null;
        if (null !== $ip) {
            return $ip[$type];
        }

        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) {
                    unset($arr[$pos]);
                }

                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }

    function errorLog($err_code, $err_msg)
    {
        $near_trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
        $backtrace = array_pop($near_trace);

        $file = !empty($near_trace[0]['file']) ? $near_trace[0]['file'] : '';
        $line = !empty($near_trace[0]['line']) ? $near_trace[0]['line'] : 0;
        $method = !empty($backtrace['function']) ? $backtrace['function'] : '';

        \LogReport::write(\LogReport::anlyError($err_msg, $file, $line, $err_code, $method));
    }

    // 系统菜单
    function Crumbs($menus, $uri)
    {
        $actives = [];
        CheckActive($menus, $actives, $uri);
孙龙's avatar
init
29756f12
 
孙龙 committed 5 years ago
212

孙龙's avatar
init
1f46a6ed
 
孙龙 committed 5 years ago
213 214
        $ret = '';
        foreach ($actives as $k => $v) {
孙龙's avatar
init
29756f12
 
孙龙 committed 5 years ago
215
            if ($k != 0 && $k == count($actives) - 1) {
孙龙's avatar
init
1f46a6ed
 
孙龙 committed 5 years ago
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
                $ret .= '<li class="active"><a>' . $menus[$actives[0]]->childs[$actives[1]]->title . '</a></li>';
            } else {
                $ret .= '<li><a href="#">' . $menus[$actives[0]]->title . '</a></li>';
            }
        }

        return $ret;
    }
    
    function CheckActive($menus, &$arr, $url)
    {
        for ($i = 0; $i < count($menus); $i++) {
            $menu = $menus[$i];
            array_push($arr, $i);

            if (isset($menu->href) && ($menu->href == $url || ($menu->href == '/' && $url == '//')))
                return true;
            if (isset($menu->childs) && count($menu->childs) > 0) {
                $ret = CheckActive($menu->childs, $arr, $url);
                if ($ret)
                    return $ret;
            }
            array_pop($arr);
        }

        return false;
    }

    function createMenuReal($menus, $active, $level)
    {
        $subclass = ($level == 0) ? 'nav-second-level' : 'nav-third-level';

        $ret = '';
        for ($ii = 0; $ii < ($level == 0 ? 1 : 2); $ii++) {
            for ($i = 0; $i < count($menus); $i++) {
                $menu = $menus[$i];
                $act = (count($active) > $level && $active[$level] == $i) ? true : false;
                $actclass = $act ? ' class="active"' : '';
                $actmenu  = $act ? ' in': '';

                if (isset($menu->childs) && count($menu->childs) > 0) {
                    if ($ii != 0 && $level > 0)
                        continue;
                    $ret .= '<li'. $actclass .'><a><i class="'
                        . $menu->class . '"></i><span class="nav-label">'
                        . $menu->title . '</span><span class="fa arrow"></span></a>'
                        . '<ul class="nav ' . $subclass . ' collapse' . $actmenu . '">'
                        . createMenuReal($menu->childs, $act ? $active : [], $level + 1)
                        . '</ul></li>';
                } else {
                    if ($ii != 1 && $level > 0)
                        continue;
                    $ret .= '<li' . $actclass . '><a href="'. $menu->href . '"><i class="' .
                        $menu->class . '"></i><span class="nav-label">' . $menu->title . '</span></a></li>';
                }
            }
        }

        return $ret;
    }

    function createMenu($menus, $url)
    {
        $actives = [];
        $ret = CheckActive($menus, $actives, $url);
        if (!$ret)
            $actives = [];
        return createMenuReal($menus, $actives, 0);
    }

    //上传文件接口签名
    function Autograph(){
        $url=Config('params.api_domain');
        $data['k1']=time();
        $data['k2']=MD5(MD5($data['k1']).Config('params.upload_key'));
        echo '<script>
                k1="'.$data['k1'].'";
                k2="'.$data['k2'].'";
                UploadImgUrl="'.$url.'"
            </script>';
    }