<?php
/**
 * @Cscms 3.5 open source management system
 * @copyright 2009-2013 chshcms.com. All rights reserved.
 * @Author:Cheng Jie
 * @Dtime:2013-04-27
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

 class CsdjAdmin extends CI_Model
 {
    function __construct (){
	   parent:: __construct ();
           $this->db->cache_off();
           $this->load->library('session'); //加载session
    }

    //分页
    function get_page($url,$pagejs=1,$pages=1,$num=8){

       //首页
       $str='<a href="'.$url.'&page=1">首 页</a>&nbsp;'; 

       //上一页
       if($pages>1){
            $str.='<a href="'.$url.'&page='.($pages-1).'">上一页</a>&nbsp;'; 
       }else{
            $str.='<a href="'.$url.'&page=1">上一页 </a>&nbsp;'; 
       }

       $pagenum='';
       if($pagejs<=$num){
           for($i=1;$i<=$pagejs;$i++){
               if($pages==$i){
                      $pagenum.='<a href="'.$url.'&page='.$i.'"><font color=red><b>'.$i.'</b></font>&nbsp;</a>'; 
               }else{
                      $pagenum.='<a href="'.$url.'&page='.$i.'">'.$i.'&nbsp;</a>'; 
               }
          }
       }else{
 		if($pages>=$num){
 			for($i=$pages-intval($num/2);$i<=$pages+(intval($num/2));$i++){
   				if($i<=$pagejs){
                                       if($pages==$i){
                                            $pagenum.='<a href="'.$url.'&page='.$i.'"><font color=red><b>'.$i.'</b></font>&nbsp;</a>'; 
                                       }else{
                      			    $pagenum.='<a href="'.$url.'&page='.$i.'">'.$i.'&nbsp;</a>'; 
                                       }
    			        }
  			}
  			if($i<=$pagejs){ 
                      			$pagenum.='<a href="'.$url.'&page='.$pagejs.'">'.$pagejs.'&nbsp;</a>';
   			}
   		}else{
  			for($i=1;$i<=$num;$i++){
                                       if($pages==$i){
                                            $pagenum.='<a href="'.$url.'&page='.$i.'"><font color=red><b>'.$i.'</b></font>&nbsp;</a>'; 
                                       }else{
                      			    $pagenum.='<a href="'.$url.'&page='.$i.'">'.$i.'&nbsp;</a>'; 
                                       }
 		        } 

 		        if($i<=$pagejs){ 
	  		     $pagenum.='<a href="'.$url.'&page='.$pagejs.'">'.$pagejs.'&nbsp;</a>';
    			}
 		 }
       }
       $str.=$pagenum;

       //下一页
       if($pages<$pagejs){
            $str.='<a href="'.$url.'&page='.($pages+1).'">下一页</a>&nbsp;'; 
       }else{
            $str.='<a href="'.$url.'&page='.$pagejs.'">下一页</a>&nbsp;'; 
       }
       //末页
       $str.='<a href="'.$url.'&page='.$pagejs.'">尾 页</a>&nbsp;'; 

            $strs="<select name='sldd' style='width:42px' onchange='location.href=this.options[this.selectedIndex].value;'>";
            for($i=1;$i<=$pagejs;$i++){
                if($pages==$i){
                     $strs.="<option value='".$url."&page=".$i."' selected>".$i."</option>";
                }else{
                     $strs.="<option value='".$url."&page=".$i."'>".$i."</option>";
                }
            }
            $strs.="</select>";

       return $str;
    }

    //操作提示信息
    function Admin_Url($title,$url,$type='ts') {
            echo "<html>
		<head>
		<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\" />
		<title>提示信息</title>
		<style>
		.ts_title{width:400px;BORDER: #aaccee 1px solid;  FONT-SIZE: 12px;  COLOR: #1f376d; HEIGHT: 28px; line-height:28px; text-align:left; border-width:1px 1px 0 1px;background:#EBF3FB; text-indent:10px; margin-top:100px;}
		.ts_msg{text-align:left; line-height:25px;width:400px;height:100;font-size:12px;border:1px solid #B8D4F1;background-color:#fff;border-width:0 1px 1px 1px;COLOR: #1f376d;}
		.ts_msg span{ float:left;}
		.ts_msg a{COLOR: #1f376d;}
		</style>
		<base target='_self'/>
		</head>
		<body leftmargin='0' topmargin='0'>
		<center>
		<script>
		function JumpUrl(){
		       location.href='".$url."';
		}
		document.write(\"<div class='ts_title'>提示信息</div>\");
		document.write(\"<div class='ts_msg'><span><img src='http://".Web_Url.Web_Path."csdj/images/".$type.".gif'></span><br/>\");
		document.write(\"".$title."\");
		document.write(\"<br /><a href='".$url."'>如果你的浏览器没反应，请点击这里...</a><br/></div>\");
		setTimeout('JumpUrl()',5000);</script>
		</center>
		</body>
		</html>"; 
                exit();
     }

    //检测后台权限
    function Admin_Qx($Column) {
          $query=$this->db->query("SELECT * FROM ".CS_SqlPrefix."admin where cs_id='".$this->session->userdata('admin_id')."'");
	  $admin=$query->result();
	  if($admin){
             $admin_qx=$admin[0]->CS_Quanx;
          }else{
             die($this->Admin_Url('<font color=red>对不起，您无权限操作此功能！</font>','javascript:history.go(-1);'));
          }
             $SystemPermission=explode(",",$admin_qx);
             $StateOK=0;
             $ArrSystemPermission=count($SystemPermission);
                for($k=0;$k<$ArrSystemPermission;$k++){
                   if($SystemPermission[$k]==$Column){
                          $StateOK=1;   
                   }
                }
                if($StateOK==0){
                    die($this->Admin_Url('<font color=red>对不起，您无权限操作此功能！</font>','javascript:history.go(-1);'));
                } 
    }

    //检测插件是否需要更新
    function getplubversion($id,$v='') {
          if($v==''){
               $vzt='no';
          }else{
               $upurl=CS_YPTURL.'index.php/plub/up?id='.$id.'&v='.$v;
               $vzt=$this->HtmlAll($upurl);
               if(empty($vzt) || $vzt=='no'){
                     $vzt='no';
               }
          }
          return $vzt;
    }

    //检测后台登入
    function Admin_Login($key='') {
		  if(!empty($key)){
			  $str  = explode("-cscms-",sys_auth($key,'D'));
              $id   = intval($str[0]);
              $name = $str[1];
              $pass = $str[2];
		  }else{
              $id   = intval($this->session->userdata('admin_id'));
              $name = $this->session->userdata('admin_name');
              $pass = $this->session->userdata('admin_pass');
		  }

          if(empty($id)||empty($name)||empty($pass)){
                 die("<script language='javascript'>window.parent.location='".site_url('admin/login/')."';</script>");
          }else{
                $query=$this->db->query("SELECT * FROM ".CS_SqlPrefix."admin where cs_id=".$id."");
		$admin=$query->result();
		if($admin){
                       if(md5($admin[0]->CS_AdminPass)!=$pass || $admin[0]->CS_AdminName!=$name){
                            die("<script language='javascript'>window.parent.location='".site_url('admin/login/')."';</script>");
                       }
                }else{
                        die("<script language='javascript'>window.parent.location='".site_url('admin/login/')."';</script>");
                }
          }
    }

    //补全静态目录地址
    function gethtmls($html){
          if(empty($html)){
                return '';
          }else{
                if(substr($html,-5)!=".html" && substr($html,-4)!=".htm" && substr($html,-5)!=".shtm" && substr($html,-6)!=".shtml" && substr($html,-4)!=".php"){
                    if(substr($html,-1)!="/") $html.="/";
                    $html.="index.html";
                }
                if(substr($html,0,2)!="./"){
                    $html="./".substr($html,1);
                }
                return $html;
          }
    }
    //获取远程补丁
    function HtmlUp($url){
        if(empty($url)) return '';
        $ConTent = @file_get_contents($url);
	if(empty($ConTent) && function_exists('curl_init')){
		$curl = curl_init(); //初始化curl
		curl_setopt($curl, CURLOPT_URL, $url); //设置访问的网站地址
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //模拟用户使用的浏览器
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);    //自动设置来路信息
		curl_setopt($curl, CURLOPT_TIMEOUT, 100);      //设置超时限制防止死循环
		curl_setopt($curl, CURLOPT_HEADER, 0);         //显示返回的header区域内容
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //获取的信息以文件流的形式返回
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); 
		$ConTent = curl_exec($curl);
		curl_close($curl);
	}
        return $ConTent;
    }

    //获取页面内容
    function HtmlAll($url,$codes='gb2312'){
          if(empty($url)) return '';
          $ConTent = @file_get_contents($url);
	  if(empty($ConTent) && function_exists('curl_init')){
		$curl = curl_init(); //初始化curl
		curl_setopt($curl, CURLOPT_URL, $url); //设置访问的网站地址
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //模拟用户使用的浏览器
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);    //自动设置来路信息
		curl_setopt($curl, CURLOPT_TIMEOUT, 100);      //设置超时限制防止死循环
		curl_setopt($curl, CURLOPT_HEADER, 0);         //显示返回的header区域内容
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //获取的信息以文件流的形式返回
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); 
		$ConTent = curl_exec($curl);
		curl_close($curl);
	  }
          if(strtolower($codes)=='utf-8'){
               if(function_exists("mb_convert_encoding")){
                    $ConTent=mb_convert_encoding($ConTent,'GBK',$codes);
               }else{
                    $ConTent=@iconv($codes,'GBK',$ConTent);
               }
          }
          $ConTent=str_replace('.js','js',$ConTent);
          $ConTent=str_replace('ajaxjs','ajax.js',$ConTent);
          $ConTent=str_replace('</textarea>','&lt;/textarea&gt;',$ConTent);
          return $ConTent;
    }

    // 字符串截取函数  
    function str_substr($start, $end, $str, $sid='1'){   

        if($start && $end){
             $temp = explode($start, $str);  
             if(!empty($temp[1])){
                 $content = explode($end, $temp[1], 2);  
                 if($sid==2){
                   $content[0] = preg_replace("/<a[^>]+>(.+?)<\/a>/i","$1",$content[0]);
	           //过滤换行符
	           $content[0] = preg_replace("/ /","",$content[0]);
	           $content[0] = preg_replace("/&nbsp;/","",$content[0]);
	           $content[0] = preg_replace("/　/","",$content[0]);
	           $content[0] = preg_replace("/\r\n/","",$content[0]);
	           $content[0] = str_replace(chr(13),"",$content[0]);
	           $content[0] = str_replace(chr(10),"",$content[0]);
	           $content[0] = str_replace(chr(9),"",$content[0]);

                 }
             }else{
                 $content[0]="";
             } 
        }else{
             $content[0]="";
        }   
        return $content[0];      
    }  

    //返回结果 字符串数组
    function getArr($startstr,$endstr,$content,$pid='1')
    {
	  $newars="";$sll=0;
          if(strpos($startstr,'a href')){
	     $startstrs='a(.*?)href';
             $startstr=str_replace('a href',$startstrs,$startstr);
             $sll=1;
          }
	  $startstr=str_replace('/','\/',$startstr);
	  $endstr=str_replace('/','\/',$endstr);
	  $theregstr='/'.$startstr.'(.*?)'.$endstr.'/';
	  preg_match_all($theregstr,$content,$match_array);
          if($sll==1){
	      $newarray=$match_array[2];
          }else{
	      $newarray=$match_array[1];
          }
          if($newarray){
              if($pid==1){
 	           foreach ($newarray as $row) { 
                       if(substr($row,0,7)!="http://") $row=$this->session->userdata('CS_Url').$row;
        	       $newars[]=$row;
 	           }
              }else{
 	           foreach ($newarray as $rowp) { 
                       $newars.=$rowp."$$$";
 	           }
                   $newars.="]]]";
                   $newars=str_replace('$$$]]]','',$newars);
                   $newars=str_replace("$$$","\r\n",$newars);
              }
          }else{
               $newars="";
          }
	  return $newars;
    }

    //采集内容替换
    function collectRep($str,$reg){
      if(!empty($reg)){
	$reg=str_replace('\\','',$reg);
	$regArr=explode("\n",$reg);
	for($i=0;$i<count($regArr);$i++){
		$restr=explode('@cscms@',$regArr[$i]);
		$ostr=$restr[0];
		$nstr=@$restr[1];
		$str=str_replace($ostr,$nstr,$str);
	}
      }
      return $str;	
    }

    // HTML转JS  
    function htmltojs($str){
         $re='';
            $str=str_replace('\\','\\\\',$str);
            $str=str_replace("'","\'",$str);
            $str=str_replace('"','\"',$str);
            $str=str_replace('\t','',$str);
            $str= split("\r\n",$str);
            for($i=0;$i<count($str);$i++){
                $re.="document.writeln(\"".$str[$i]."\");\r\n";
            }
            return $re;
    }


    //文件夹文件归替
    function dirtofiles($dir,$hz='mp3'){ 
        $dir = rtrim($dir,'/');    $handle = opendir($dir);    /////////////////dufulin
        $sizeResult=0;
        $filesResult= "";
        while (false!==($FolderOrFile = readdir($handle)))
        { 
            if($FolderOrFile != "." && $FolderOrFile != "..") 
            { 
                if(is_dir("$dir/$FolderOrFile")){ 

                   $filesResult[]=$this->dirtofiles("$dir/$FolderOrFile",$hz); 

                }else{ 
                    $sys=pathinfo($FolderOrFile);//获取文件名后缀
                    if(is_int(strpos($hz,$sys['extension'])) !== false){  //只显示要扫描的文件
                        $filesResult[]= $dir."/".$FolderOrFile; 
                    }
                }
            }    
        }
        closedir($handle);
        return $this->array_hebing($this->array_multi2array($filesResult));/////////////////dufulin
    }

    //多维数组转一维数组
    function array_multi2array($array,$goon=False) {
      if(!empty($array)){
      if(!$goon) {static $result_array = NULL;$result_array = array();} else {static $result_array = array();} ////////////////dufulin
	foreach($array as $value) {
		if (is_array($value)) {
			$this->array_multi2array($value,TRUE);
		} else $result_array[] = $value;
	}
      }else{
         $result_array="";
      }
	return $result_array;
    }

    //一维数组合并相同的值/////////////////dufulin
    function array_hebing($array) {
		$tempArray = array();
		foreach($array as $val)
			$tempArray[$val] = true;
	return array_keys($tempArray);
    }

    //删除目录和文件
    function deldir($dir,$sid='ok') {
         //先删除目录下的文件：
         $dh=opendir($dir);
         while ($file=readdir($dh)) {
           if($file!="." && $file!="..") {
             $fullpath=$dir."/".$file;
             if(!is_dir($fullpath)) {
                 @unlink($fullpath);
             } else {
                 $this->deldir($fullpath);
             }
           }
         }
         closedir($dh);
         //删除当前文件夹：
         if($sid=='ok'){
            if(@rmdir($dir)) {
                return true;
            } else {
                return false;
            }
         }else{
            return true;
         }
    }

    //下载文件到本地
    function get_files_file($file,$filename) {   
        if (! $file) {  
           return '-1';  
        }   
        if (ini_get('allow_url_fopen')) {
            $data=@file_get_contents($file);
        }
        if (empty($data) && function_exists('curl_init') && function_exists('curl_exec')) {
		$curl = curl_init(); //初始化curl
		curl_setopt($curl, CURLOPT_URL, $file); //设置访问的网站地址
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); //模拟用户使用的浏览器
		curl_setopt($curl, CURLOPT_AUTOREFERER, 1);    //自动设置来路信息
		curl_setopt($curl, CURLOPT_TIMEOUT, 100);      //设置超时限制防止死循环
		curl_setopt($curl, CURLOPT_HEADER, 0);         //显示返回的header区域内容
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //获取的信息以文件流的形式返回
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); 
		$data = curl_exec($curl);
		curl_close($curl);
        }
        if(empty($data)){
            return '-2'; 
        }else{
            if (!@file_put_contents($filename, $data)){
                 return '-3';
            }else{
                 return false;
            }
        }
    } 
}

