整理的tp常用function函数

<?php

/*截取中文*/
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)  
{  
if(function_exists("mb_substr")){  

        if($suffix)  

            return mb_substr($str, $start, $length, $charset)."...";  

        else

            return mb_substr($str, $start, $length, $charset);  

      }  

      elseif(function_exists('iconv_substr')) {  

         if($suffix)  

              return iconv_substr($str,$start,$length,$charset)."...";  

         else

              return iconv_substr($str,$start,$length,$charset);  

      }  

       $re['utf-8']   = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef]
                [x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";  

       $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";  

       $re['gbk']    = "/[x01-x7f]|[x81-xfe][x40-xfe]/";  

       $re['big5']   = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";  

       preg_match_all($re[$charset], $str, $match);  

       $slice = join("",array_slice($match[0], $start, $length));  

       if($suffix) return $slice."…";  

       return $slice;

  }


  

    /*****post请求******/

     function postDataCurl($url,$data=array()){

        $this->checkSumBuilder();        //发送请求前需先生成checkSum

        if(!empty($data)){

            $json=json_encode($data);

        }else{

            $json="";

        }

        $timeout = 5000;  

        $http_header = array(

            'AppKey:'.$this->AppKey,

            'Nonce:'.$this->Nonce,

            'CurTime:'.$this->CurTime,

            'CheckSum:'.$this->CheckSum,

            'Content-Type: application/json;charset=utf-8;',

            'Content-Length: ' . strlen($json)

        );

        $ch = curl_init(); 

        curl_setopt ($ch, CURLOPT_URL, $url);

        curl_setopt ($ch, CURLOPT_POST, 1);

        curl_setopt ($ch, CURLOPT_POSTFIELDS, $json);

        curl_setopt ($ch, CURLOPT_HEADER, false); 

        curl_setopt ($ch, CURLOPT_HTTPHEADER,$http_header);

        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,false);

        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 

        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

         

        $result = curl_exec($ch);  

        if (false === $result) {

            $result =  curl_errno($ch);

        }

        curl_close($ch); 

        return json_decode($result,true) ;

    } 


    /**

* author jackluo

* $url 地址,$count 总数,$page 当前面,$Pagesize 分页大小

*/

function page_paper($url,$count,$page,$pagesize){

  $allpage = ceil($count/$pagesize);

  if($allpage<=3){

   for($i=1;$i<=$allpage;$i++){

    if($i==$page){

     echo '<a href="'.$url.'&page='.$page.'" class="page_ovr">'.$i.'</a>';

    }else{

     echo '<a href="'.$url.'&page='.$i.'" >'.$i.'</a>';

    }

   }

  }else{

   $currentpage =  $allpage-$page;

   if($page<=3){

    for($i=1;$i<=$page;$i++){

     if($i == $page){

      echo '<a href="'.$url.'&page='.$i.'" class="page_ovr">'.$i.'</a>';

     }else{

      echo '<a href="'.$url.'&page='.$i.'" >'.$i.'</a>';

     }

    }

    //后三条

    if($currentpage<=3){

     for($i=($page+1);$i<=$allpage;$i++){

      echo '<a href="'.$url.'&page='.$i.'" >'.$i.'</a>';

     }

    }else{

     for($i=($page+1);$i<=($page+3);$i++){

      echo '<a href="'.$url.'&page='.$i.'" >'.$i.'</a>';

     }

    }

   }else{

    //前三条

    for($i=($page-3);$i<=$page;$i++){

     if($i == $page){

      echo '<a href="'.$url.'&page='.$i.'" class="page_ovr">'.$i.'</a>';

     }else{

      echo '<a href="'.$url.'&page='.$i.'" >'.$i.'</a>';

     }

    }

    if($currentpage<=3){

     for($i=($page+1);$i<=$allpage;$i++){

      echo '<a href="'.$url.'&page='.$i.'" >'.$i.'</a>';

     }

    }else{

     //后三条

     for($i=($page+1);$i<=($page+3);$i++){

       echo '<a href="'.$url.'&page='.$i.'" >'.$i.'</a>';

     }

    }

   }

  }

}

//获得手机归属地

function phonenumberinfo($phone){

  $list = array();

  $soap =  new SoapClient('http://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl');

  $result =(array) $soap->getMobileCodeInfo(array(

    'mobileCode'=>$phone

  ));

  list($moblie,$location,$lbs) = explode(' ', $result['getMobileCodeInfoResult']);

  if($lbs){

   $type =  array('移动','电信','联通');

   foreach($type as $key=>$value){

    $ps = strpos($lbs, $value);

    if($ps){

     $procver = substr($lbs, 0,$ps);

     $list['province'] = $procver;

     $list['operator'] = $value;

     $list['city'] = $location;

     $list['type'] = $key;

     break;

    }

   }

   return $list;

  }

}


/*自动滑落
*$rid  推荐人id
*$lv   推荐人层数
 */
function autohuoluo($rid){

  global $temp;
  global $userlist;
  
    for ($i=1; $i <11 ; $i++) { 
      unset($GLOBALS['csmem']);
      $hunum = cengnum($rid,$i);  /*每层会员数*/

      $cengall = pow(3,$i);  /*每层的会员数*/
      if ($hunum>0) {

        if ($hunum<$cengall) {

          $ceng = $i-1;
          break;
        }

      }else{
        $ceng = $i-1;
        break;
      } 
    }
    $userlist =cengget($rid,$ceng);
 
    if (count($userlist)>0) {
      if (!isset($temp)) {
          foreach ($userlist as $key => $value) {
            
            if ($value['p_num']==0&&!isset($temp)) {
              $temp=$value;

              break;

            }  

          }
      }
        
      if (!isset($temp)) {
        foreach ($userlist as $key => $value) {
          
            if ($value['p_num']==1&&!isset($temp)) {
              $temp=$value;
              break;
            }  
          }

      }
        
        if (!isset($temp)) {
           foreach ($userlist as $key => $value) {
          
            if ($value['p_num']==2&&!isset($temp)) {
              $temp=$value;
              break;
            }  
          }

        }
    }else{
      $cnmem = cengget($rid,$ceng-1);  /*每层会员数*/
      if (!isset($temp)) {
          foreach ($cnmem as $key => $value) {
            
            if ($value['p_num']==0&&!isset($temp)) {
              $temp=$value;
              break;

            }  

          }
      }
        
      if (!isset($temp)) {
        foreach ($cnmem as $key => $value) {
          
            if ($value['p_num']==1&&!isset($temp)) {
              $temp=$value;
              break;
            }  
          }

      }
        
        if (!isset($temp)) {
           foreach ($cnmem as $key => $value) {
          
            if ($value['p_num']==2&&!isset($temp)) {
              $temp=$value;
              break;
            }  
          }

        }
    }

    return $temp;
}

function cengnum($uid,$lv=1,$level=1){
  global $csmem;

    $user = M('Member')->field("id,username,p_level,p_path,p_num,p_name,p_id,position")->where(array('p_id' => $uid))->order('position')->select();
    $data = array();
    foreach ($user as $value) {
        $data[]=$value;
    }
    if(!empty($data)){
        foreach ($data as $key => $value) {

            if ($level == $lv) {
              $csmem++;
            }
            if ($level<=$lv) {
              cengnum($value['id'],$lv,$level+1);
            }
            
        }
        
    }
    return $csmem;

}

/*添加log*/
function log_result($file,$word)
{
 $fp = fopen($file,"a");
 flock($fp, LOCK_EX) ;
 fwrite($fp,"执行日期:".strftime("%Y-%m-%d-%H:%M:%S",time())."\n".$word."\n\n");
 flock($fp, LOCK_UN);
 fclose($fp);
}

/**
 * 获取数组中的某一列
 * @param array $arr 数组
 * @param string $key_name  列名
 * @return array  返回那一列的数组
 */

function get_arr_column($arr, $key_name)
{
  $arr2 = array();
  foreach($arr as $key => $val){
    $arr2[] = $val[$key_name];        
  }
  return $arr2;
}

/**
 * 获取url 中的各个参数  类似于 pay_code=alipay&bank_code=ICBC-DEBIT
 * @param type $str
 * @return type
 */
function parse_url_param($str){
    $data = array();
    $str = explode('?',$str);
   
    $str = end($str);
    $parameter = explode('&',$str);
    foreach($parameter as $val){
        $tmp = explode('=',$val);
        $data[$tmp[0]] = $tmp[1];
    }
    return $data;
}
/**
 * 二维数组排序
 * @param $arr
 * @param $keys
 * @param string $type
 * @return array
 */
function array_sort($arr, $keys, $type = 'desc')
{
    $key_value = $new_array = array();
    foreach ($arr as $k => $v) {
        $key_value[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($key_value);
    } else {
        arsort($key_value);
    }
    reset($key_value);
    foreach ($key_value as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}
/**
 * 多维数组转化为一维数组
 * @param 多维数组
 * @return array 一维数组
 */
function array_multi2single($array)
{
    static $result_array = array();
    foreach ($array as $value) {
        if (is_array($value)) {
            array_multi2single($value);
        } else
            $result_array [] = $value;
    }
    return $result_array;
}
/**
 * 友好时间显示
 * @param $time
 * @return bool|string
 */
function friend_date($time)
{
    if (!$time)
        return false;
    $fdate = '';
    $d = time() - intval($time);
    $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
    $md = $time - mktime(0, 0, 0, date('m'), 0, date('Y')); //得出月
    $byd = $time - mktime(0, 0, 0, date('m'), date('d') - 2, date('Y')); //前天
    $yd = $time - mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')); //昨天
    $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
    $td = $time - mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')); //明天
    $atd = $time - mktime(0, 0, 0, date('m'), date('d') + 2, date('Y')); //后天
    if ($d == 0) {
        $fdate = '刚刚';
    } else {
        switch ($d) {
            case $d < $atd:
                $fdate = date('Y年m月d日', $time);
                break;
            case $d < $td:
                $fdate = '后天' . date('H:i', $time);
                break;
            case $d < 0:
                $fdate = '明天' . date('H:i', $time);
                break;
            case $d < 60:
                $fdate = $d . '秒前';
                break;
            case $d < 3600:
                $fdate = floor($d / 60) . '分钟前';
                break;
            case $d < $dd:
                $fdate = floor($d / 3600) . '小时前';
                break;
            case $d < $yd:
                $fdate = '昨天' . date('H:i', $time);
                break;
            case $d < $byd:
                $fdate = '前天' . date('H:i', $time);
                break;
            case $d < $md:
                $fdate = date('m月d日 H:i', $time);
                break;
            case $d < $ld:
                $fdate = date('m月d日', $time);
                break;
            default:
                $fdate = date('Y年m月d日', $time);
                break;
        }
    }
    return $fdate;
}
/**
 * 返回状态和信息
 * @param $status
 * @param $info
 * @return array
 */
function arrayRes($status, $info, $url = "")
{
    return array("status" => $status, "info" => $info, "url" => $url);
}

/**
 * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
 * @return boolean
 */
/**
  * 是否移动端访问访问
  *
  * @return bool
  */
function isMobile()
{
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    return true;

    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
        // 找不到为flase,否则为true
        if(stristr($_SERVER['HTTP_VIA'], "wap"))return true;
    }
    // 脑残法,判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT'])){
        $clientkeywords = array ('nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel','lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm','operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile');
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))return true;
         
        $pos = strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "android") ||  strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "mobile");
        if($pos)return true;
    }
        // 协议法,因为有可能不准确,放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
    // 如果只支持wml并且不支持html那一定是移动设备
    // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
            return false;
 }
 function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    } return false;
}
 

function is_qq() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'QQ') !== false) {
        return true;
    } return false;
}
function is_alipay() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
        return true;
    } return false;
}
function is_ios()
{
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
        return true;
    }
    return false;
}

//php获取中文字符拼音首字母
function getFirstCharter($str){
      if(empty($str))
      {
            return '';          
      }
      $fchar=ord($str{0});
      if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
      $s1=iconv('UTF-8','gb2312//TRANSLIT//IGNORE',$str);
      $s2=iconv('gb2312','UTF-8//TRANSLIT//IGNORE',$s1);
      $s=$s2==$str?$s1:$str;
      $asc=ord($s{0})*256+ord($s{1})-65536;
     if($asc>=-20319&&$asc<=-20284) return 'A';
     if($asc>=-20283&&$asc<=-19776) return 'B';
     if($asc>=-19775&&$asc<=-19219) return 'C';
     if($asc>=-19218&&$asc<=-18711) return 'D';
     if($asc>=-18710&&$asc<=-18527) return 'E';
     if($asc>=-18526&&$asc<=-18240) return 'F';
     if($asc>=-18239&&$asc<=-17923) return 'G';
     if($asc>=-17922&&$asc<=-17418) return 'H';
     if($asc>=-17417&&$asc<=-16475) return 'J';
     if($asc>=-16474&&$asc<=-16213) return 'K';
     if($asc>=-16212&&$asc<=-15641) return 'L';
     if($asc>=-15640&&$asc<=-15166) return 'M';
     if($asc>=-15165&&$asc<=-14923) return 'N';
     if($asc>=-14922&&$asc<=-14915) return 'O';
     if($asc>=-14914&&$asc<=-14631) return 'P';
     if($asc>=-14630&&$asc<=-14150) return 'Q';
     if($asc>=-14149&&$asc<=-14091) return 'R';
     if($asc>=-14090&&$asc<=-13319) return 'S';
     if($asc>=-13318&&$asc<=-12839) return 'T';
     if($asc>=-12838&&$asc<=-12557) return 'W';
     if($asc>=-12556&&$asc<=-11848) return 'X';
     if($asc>=-11847&&$asc<=-11056) return 'Y';
     if($asc>=-11055&&$asc<=-10247) return 'Z';
     return null;
}
/**
 * 获取整条字符串汉字拼音首字母
 * @param $zh
 * @return string
 */
function pinyin_long($zh){
    $ret = "";
    $s1 = iconv("UTF-8","gb2312", $zh);
    $s2 = iconv("gb2312","UTF-8", $s1);
    if($s2 == $zh){$zh = $s1;}
    for($i = 0; $i < strlen($zh); $i++){
        $s1 = substr($zh,$i,1);
        $p = ord($s1);
        if($p > 160){
            $s2 = substr($zh,$i++,2);
            $ret .= getFirstCharter($s2);
        }else{
            $ret .= $s1;
        }
    }
    return $ret;
}

function ajaxReturn($data)
{
    exit(json_encode($data, JSON_UNESCAPED_UNICODE));
}
/**
 *  作用:array转xml
 */
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
        if (is_numeric($val))
        {
            $xml.="<".$key.">".$val."</".$key.">";

        }
        else
            $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
    }
    $xml.="</xml>";
    return $xml;
}

/**
 * 比较两个版本大小, $v1>v2:1 ; $v1=v2:0 ;$v1<v2:0
 * @param unknown $v1
 * @param unknown $v2
 * @return number
 */
function compareVersion($v1, $v2) {
    $v1 = explode(".",$v1);
    $v2 =  explode(".",$v2);
    $len = max(count($v1), count($v2));

    while(count($v1) < $len) {
        array_push($v1, 0);
    }

    while(count($v2) < $len) {
        array_push($v2, 0);
    }
    for($i = 0; $i < $len;$i++) {
        $num1 = intval($v1[$i]);
        $num2 = intval($v2[$i]);
        if ($num1 > $num2) {
            return 1;
        } else if ($num1 < $num2) {
            return -1;
        }
    }
    return 0;
}

/**
 * 传时间戳
 * @param $time
 * @return bool|string
 */
function time_to_str($time){
    if ($time > strtotime(date("Y-m-d"))) {
        $text = '今天 ' . date("H:i", $time);
    } elseif ($time > strtotime(date("Y-m-d", strtotime('-1 day')))) {
        $text = '昨天 ' . date("H:i", $time);
    } elseif (empty($time)) {
        $text = '';
    } else {
        $text = date("Y-m-d H:i:s", $time);
    }
    return $text;
}

/**
 * 转换SQL关键字
 *
 * @param unknown_type $string
 * @return unknown
 */
function strip_sql($string) {
  $pattern_arr = array(
            "/\bunion\b/i",
            "/\bselect\b/i",
            "/\bupdate\b/i",
            "/\bdelete\b/i",
            "/\boutfile\b/i",
            "/\bor\b/i",
            "/\bchar\b/i",
            "/\bconcat\b/i",
            "/\btruncate\b/i",
            "/\bdrop\b/i",            
            "/\binsert\b/i", 
            "/\brevoke\b/i", 
            "/\bgrant\b/i",      
            "/\breplace\b/i", 
            "/\balert\b/i", 
            "/\brename\b/i",            
            "/\bcreate\b/i",
            "/\bmaster\b/i",
            "/\bdeclare\b/i",
            "/\bsource\b/i",
            "/\bload\b/i",
            "/\bcall\b/i", 
            "/\bexec\b/i",            
  );
  $replace_arr = array(
            'union',
            'select',
            'update',
            'delete',
            'outfile',
            'or',
            'char',
            'concat',
            'truncate',
            'drop',            
            'insert',
            'revoke',
            'grant',
            'replace',
            'alert',
            'rename',
            'create',
            'master',
            'declare',
            'source',
            'load',
            'call',         
            'exec',            
  );

  return is_array($string) ? array_map('strip_sql', $string) : preg_replace($pattern_arr, $replace_arr, $string);
}

// 检查图片是否含有木马病毒
 function checkHex($image) {
    if (file_exists($image)) {
        $resource = fopen($image, 'rb');
        $fileSize = filesize($image);
        fseek($resource, 0);
        if ($fileSize > 512) { // 取头和尾
            $hexCode = bin2hex(fread($resource, 512));
            fseek($resource, $fileSize - 512);
            $hexCode .= bin2hex(fread($resource, 512));
        } else { // 取全部
            $hexCode = bin2hex(fread($resource, $fileSize));
        }
        fclose($resource);
        /* 匹配16进制中的 <% ( ) %> */
        /* 匹配16进制中的 <? ( ) ?> */
        /* 匹配16进制中的 <script | /script> 大小写亦可*/
        if (preg_match("/(3c25)|(3c3f.*?706870)|(3C534352495054)|(2F5343524950543E)|(3C736372697074)|(2F7363726970743E)/is", $hexCode)) {
            $status = 209;
        }else{
            $status = 0;
        }
        return $status;
    } else {
        return $status = 209;
    }
}

 /**
 * 调用新浪接口将长链接转为短链接
 * @param  string        $source     默认调用官方的key
 * @param  array|string  $url_long  长链接,支持多个转换(需要先执行urlencode)
 * @param  string        $api         默认调用新浪微博的接口 自定义需要换成开发文档的地址
 * @return array
 */

    public function getSinaShortUrl($url_long , $source = "2849184197", $api = "http://api.weibo.com/2/short_url/shorten.json" )
    {
        // 参数检查
        if(empty($source) || !$url_long){
            return false;
        }
        // 参数处理,字符串转为数组
        if(!is_array($url_long)){
            $url_long = array($url_long);
        }
        // 拼接url_long参数请求格式
        $url_param = array_map(function($value){
            return '&url_long='.urlencode($value);
        }, $url_long);
        $url_param = implode('', $url_param); 
        // 请求url
        $request_url = sprintf($api.'?source=%s%s', $source, $url_param);
        $result = [];
        // 执行请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $request_url);
        $data = curl_exec($ch);
        if($error=curl_errno($ch)){
            return false;
        }
        curl_close($ch);
        $result = json_decode($data, true);
        return $result;
    }

    public function substr_cut($user_name){
    $strlen     = mb_strlen($user_name, 'utf-8');
    $firstStr     = mb_substr($user_name, 0, 2, 'utf-8');
    $lastStr     = mb_substr($user_name, -2, 2, 'utf-8');
    return $strlen == 2 ? mb_substr($user_name, 0, 1, 'utf-8') . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . "**" . $lastStr;
  }

/*删除文件夹*/
function rmdirr($dirname)
{
  if (!file_exists($dirname)) {
    return false;
  }

  if (is_file($dirname) || is_link($dirname)) {
    return unlink($dirname);
  }

  $dir = dir($dirname);

  if ($dir) {
    while (false !== $entry = $dir->read()) {
      if (($entry == '.') || ($entry == '..')) {
        continue;
      }

      rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
    }
  }

  $dir->close();
  return rmdir($dirname);
}


/*下载文件*/


function DownloadFile($fileName)
{
  ob_end_clean();
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Content-Description: File Transfer');
  header('Content-Type: application/octet-stream');
  header('Content-Length: ' . filesize($fileName));
  header('Content-Disposition: attachment; filename=' . basename($fileName));
  readfile($fileName);
}

function download_file($file, $o_name = '')
{
  if (is_file($file)) {
    $length = filesize($file);
    $type = mime_content_type($file);
    $showname = ltrim(strrchr($file, '/'), '/');

    if ($o_name) {
      $showname = $o_name;
    }

    header('Content-Description: File Transfer');
    header('Content-type: ' . $type);
    header('Content-Length:' . $length);

    if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
      header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
    } else {
      header('Content-Disposition: attachment; filename="' . $showname . '"');
    }

    readfile($file);
    exit();
  } else {
    exit('文件不存在');
  }
}


/*检测字符串是否有注入风险*/
function checkstr($strsql)
{
  //检测字符串是否有注入风险
    $strsql = str_replace("'","",$strsql);
  $strsql = trim($strsql);  $check=preg_match('/select|SELECT|or|OR|and|AND|char|CHAR|create|CREATR|drop|DROP|database|DATABASE|table|TABLE|insert|INSERT|script|SCRIPT|function|FUNCTION|update|UPDATE|delete|DELETE|exec|EXEC|system|SYSTEM|passthru|PASSTHRU|shell_exec|SHELL_EXEC|<|\`|\%|\"|\'|\/\*|\*|\.\.\/|\.\/|union|UNION|into|INTO|load_file|LOAD_FILE|outfile|OUTFILE/i',$strsql);

  if($check)
  {
    return 1;
  }

}


/**
 * [ajaxReturn ajax提示款]
 * @param  [type]  $message [提示文字]
 * @param  integer $status  [1=成功 0=失败]
 * @param  string  $url     [跳转地址]
 * @param  string  $extra   [回传数据]
 * @return [type]           [json数据]
 */
function ajaxReturn($message,$status=0, $url ='',$extra='') {
    // 返回JSON数据格式到客户端 包含状态信息
    header('Content-Type:application/json; charset=utf-8');
    $result = array(
        'message' => $message,
        'status'  =>  $status,
        'url' => $url,
        'result'  =>  $extra
    );
    
    exit(json_encode($result));
}

// =陶==js消息提示框===
function error_alert($mes){
    echo "<meta charset=\"utf-8\"/><script>alert('".$mes."');javascript:history.back(-1);</script>";
    exit;
}
function success_alert($mes,$url=''){
    if($url!=''){
        echo "<meta charset=\"utf-8\"/><script>alert('".$mes."');location.href='" .$url. "';</script>";
    }else{
       echo "<meta charset=\"utf-8\"/><script>alert('".$mes."');location.href='" .$jumpUrl. "';</script>"; 
    }
    exit;
}
// =陶==js消息提示框===



//防注入,字符串处理,禁止构造数组提交
//字符过滤
//陶
function safe_replace($string) {
    if(is_array($string)){ 
       $string=implode(',',$string);
       $string=htmlspecialchars(str_shuffle($string));
    } else{
        $string=htmlspecialchars($string);
    }
    $string = str_replace('%20','',$string);
    $string = str_replace('%27','',$string);
    $string = str_replace('%2527','',$string);
    $string = str_replace('*','',$string);
    $string=str_replace("select","",$string);
    $string=str_replace("join","",$string);
    $string=str_replace("union","",$string);
    $string=str_replace("where","",$string);
    $string=str_replace("insert","",$string);
    $string=str_replace("delete","",$string);
    $string=str_replace("update","",$string);
    $string=str_replace("like","",$string);
    $string=str_replace("drop","",$string);
    $string=str_replace("create","",$string);
    $string=str_replace("modify","",$string);
    $string=str_replace("rename","",$string);
    $string=str_replace("alter","",$string);
    $string=str_replace("cas","",$string);
    $string=str_replace("or","",$string);
    $string=str_replace("=","",$string);
    $string = str_replace('"','&quot;',$string);
    $string = str_replace("'",'',$string);
    $string = str_replace('"','',$string);
    $string = str_replace(';','',$string);
    $string = str_replace('<','&lt;',$string);
    $string = str_replace('>','&gt;',$string);
    $string = str_replace("{",'',$string);
    $string = str_replace('}','',$string);
    $string = str_replace('--','',$string);
    $string = str_replace('(','',$string);
    $string = str_replace(')','',$string);

    return $string;
}
/**
 * TODO 基础分页的相同代码封装,使前台的代码更少
 * @param $count 要分页的总记录数
 * @param int $pagesize 每页查询条数
 * @return \Think\Page
 */
function getpage($count, $pagesize = 8) {
    $p = new Think\Page($count, $pagesize);
    $p -> setConfig('header', '<li class="rows">共<b>%TOTAL_ROW%</b>条记录&nbsp;第<b>%NOW_PAGE%</b>页/共<b>%TOTAL_PAGE%</b>页</li>');
    $p -> setConfig('prev', '上一页');
    $p -> setConfig('next', '下一页');
    $p -> setConfig('last', '末页');
    $p -> setConfig('first', '首页');
    $p -> setConfig('theme', '%FIRST%%UP_PAGE%%LINK_PAGE%%DOWN_PAGE%%END%%HEADER%');
    $p -> lastSuffix = false;
    //最后一页不显示为总页数
    return $p;
}

/**
 * 下拉选择框
 */
function select($array = array(), $id = 0, $str = '', $default_option = '') {
    $string = '<select ' . $str . '>';
    $default_selected = (empty($id) && $default_option) ? 'selected' : '';
    if ($default_option)
        $string .= "<option value='' $default_selected>$default_option</option>";
    if (!is_array($array) || count($array) == 0)
        return false;
    $ids = array();
    if (isset($id))
        $ids = explode(',', $id);
    foreach ($array as $key => $value) {
        $selected = in_array($key, $ids) ? 'selected' : '';
        $string .= '<option value="' . $key . '" ' . $selected . '>' . $value . '</option>';
    }
    $string .= '</select>';
    return $string;
}

/**
 * 复选框
 * 
 * @param $array 选项 二维数组
 * @param $id 默认选中值,多个用 '逗号'分割
 * @param $str 属性
 * @param $defaultvalue 是否增加默认值 默认值为 -99
 * @param $width 宽度
 */
function checkbox($array = array(), $id = '', $str = '', $defaultvalue = '', $width = 0, $field = '') {
    $string = '';
    
    if (!empty($id)){
        $id = trim($id);
        $id = strpos($id, ',') ? explode(',', $id) : array($id);
    }   
    if ($defaultvalue)
        $string .= '<input type="hidden" ' . $str . ' value="-99">';
    $i = 1;
    foreach ($array as $key => $value) {
        $key = trim($key);
        $checked = ($id && in_array($key, $id)) ? 'checked' : '';
        if ($width)
            $string .= '<label class="ib" style="width:' . $width . 'px">';
        $string .= '<input type="checkbox" ' . $str . ' id="' . $field . '_' . $i . '" ' . $checked . ' value="' . $key . '"> ' . $value;
        if ($width)
            $string .= '</label>';
        $i++;
    }
    return $string;
}

/**
 * 单选框
 * 
 * @param $array 选项 二维数组
 * @param $id 默认选中值
 * @param $str 属性
 */
function radio($array = array(), $id = 0, $str = '', $width = 0, $field = '') {
    $string = '';
    foreach ($array as $key => $value) {
        $checked = trim($id) == trim($key) ? 'checked' : '';
        if ($width)
            $string .= '<label class="ib" style="width:' . $width . 'px">';
        $string .= '<input type="radio" ' . $str . ' id="' . $field . '_' . $key . '" ' . $checked . ' value="' . $key . '"> ' . $value;
        if ($width)
            $string .= '</label>';
    }
    return $string;
}

/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function sp_random_string($len = 6) {
	$chars = 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", "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", "0", "1", "2",
			"3", "4", "5", "6", "7", "8", "9"
	);
	$charsLen = count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output = "";
	for ($i = 0; $i < $len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;
}
/**
 * 随机字符串生成 英文
 * @param int $len 生成的字符串长度
 * @return string
 */
function sp_random_string_en($len = 6) {
	$chars = 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", "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"
	);
	$charsLen = count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output = "";
	for ($i = 0; $i < $len; $i++) {
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;
}

/**
 * 清空系统缓存,兼容sae
 */
function sp_clear_cache(){
		import ( "ORG.Util.Dir" );
		$dirs = array ();
		// runtime/
		$rootdirs = sp_scan_dir( RUNTIME_PATH."*" );
		//$noneed_clear=array(".","..","Data");
		$noneed_clear=array(".","..");
		$rootdirs=array_diff($rootdirs, $noneed_clear);
		foreach ( $rootdirs as $dir ) {

			if ($dir != "." && $dir != "..") {
				$dir = RUNTIME_PATH . $dir;
				if (is_dir ( $dir )) {
					//array_push ( $dirs, $dir );
					$tmprootdirs = sp_scan_dir ( $dir."/*" );
					foreach ( $tmprootdirs as $tdir ) {
						if ($tdir != "." && $tdir != "..") {
							$tdir = $dir . '/' . $tdir;
							if (is_dir ( $tdir )) {
								array_push ( $dirs, $tdir );
							}else{
								@unlink($tdir);
							}
						}
					}
				}else{
					@unlink($dir);
				}
			}
		}
		$dirtool=new \Dir("");
		foreach ( $dirs as $dir ) {
			$dirtool->delDir ( $dir );
		}

		if(sp_is_sae()){
			$global_mc=@memcache_init();
			if($global_mc){
				$global_mc->flush();
			}

			$no_need_delete=array("THINKCMF_DYNAMIC_CONFIG");
			$kv = new SaeKV();
			// 初始化KVClient对象
			$ret = $kv->init();
			// 循环获取所有key-values
			$ret = $kv->pkrget('', 100);
			while (true) {
				foreach($ret as $key =>$value){
                    if(!in_array($key, $no_need_delete)){
                    	$kv->delete($key);
                    }
                }
				end($ret);
				$start_key = key($ret);
				$i = count($ret);
				if ($i < 100) break;
				$ret = $kv->pkrget('', 100, $start_key);
			}

		}

}

/**
 * 保存数组变量到php文件
 */
function sp_save_var($path,$value){
	$ret = file_put_contents($path, "<?php\treturn " . var_export($value, true) . ";?>");
	return $ret;
}
/**
 * 生成参数列表,以数组形式返回
 */
function sp_param_lable($tag = ''){
	$param = array();
	$array = explode(';',$tag);
	foreach ($array as $v){
		$v=trim($v);
		if(!empty($v)){
			list($key,$val) = explode(':',$v);
			$param[trim($key)] = trim($val);
		}
	}
	return $param;
}

/*
字符串截取处理,纯字符,纯中文,中英混合
*/
function substr_cut($str){
	if(preg_match("/[\x7f-\xff]/", $str)){//含有中文
		if(!eregi("[^\x80-\xff]",$str)){//全是中文
			$length = 7;
		}else{
			$length = 13;
		}
	}else{//没有中文
		$length = 16;
	}
	// 过滤掉emoji表情
	$str = filterEmoji($str);
	return mb_substr($str, 0,$length,"UTF-8");
}

// 过滤掉emoji表情
function filterEmoji($str)
{
    $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

     return $str;
}

//封神榜 日榜/周榜/月榜/总榜
//获取系统全局收益榜或贡献打赏榜:日榜/周榜/月榜/总榜
function getSystemRankingList($limit_begin=0,$limit_num=10,$rank='day'){
	$model = M("DevicePlayLog");
	$where = array(
		'play_result' => array('gt',0),
		'status' => 1,
	);
	$field = "count(a.id) as num,uid,avatar,user_nicename,play_time,smeta,video_status";
	$join = "LEFT JOIN ".C("DB_PREFIX")."users as b on b.id = a.uid";
	switch ($rank) {
		case 'day':
			$where["DATE_FORMAT(a.play_time,'%Y-%m-%d')"] = date("Y-m-d");
			break;
		case 'week':
			$where["WEEK(DATE_FORMAT(a.play_time,'%Y-%m-%d'))"] = strftime('%U');
			break;
		case 'month':
			$where["DATE_FORMAT(a.play_time,'%m')"] = strftime('%m');
			break;
		case 'year':
			$where["DATE_FORMAT(a.play_time,'%Y')"] = strftime('%Y');
			break;
		case 'all':

			break;
	}

	$data = $model->alias('a')->join($join)->where($where)->field($field)->limit($limit_begin . ',' . $limit_num)->group('uid')->order("num desc")->select();

	return $data;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_41997115

您的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值