<?php
function ToAsc($str,$encode='utf-8'){
	$str = iconv($encode, "UTF-16BE", $str);
	for($i=0;$i<strlen($str); $i++,$i++){
		$code = ord($str{$i}) * 256 + ord($str{$i + 1});
		if($code<128){
			$output .= chr($code);
		}elseif($code!=65279) {
			$output.="&#".$code.";";
		}
	}
	return $output;
}
function readover($filename,$method="rb"){
	if($handle=@fopen($filename,$method)){
		flock($handle,LOCK_SH);
		$filedata=fread($handle,filesize($filename));
		fclose($handle);
	}
	return $filedata;
}
function writeover($filename,$data,$method="rb+",$iflock=1){
	touch($filename);
	$handle=fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
}
function mkdirs($dir){
  if(!is_dir($dir)){
    mkdirs(dirname($dir));
    mkdir($dir,0777);
  }
  return ;
}

function dir_empty($dir){
  if($dp = @dir($dir)){
    while($file = $dp->read()){
      if($file != '.' && $file != '..'){
        return false;
      }
    }
    $dp->close();
    return true;
  }else{
    return true;
  }
}
function oiconv($from,$to,$string){
  if(function_exists('mb_convert_encoding')){
    return mb_convert_encoding($string,$to,$from);
  }else{
    return iconv($from,$to,$string);
  }
}
function StrCode($string,$action='ENCODE'){
  global $_SERVER,$rndKey;
	$action != 'ENCODE' && $string = base64_decode($string);
	$code = '';
	$key  = substr(md5($rndKey),8,18);
	$keylen = strlen($key); $strlen = strlen($string);
	for ($i=0;$i<$strlen;$i++) {
		$k		= $i % $keylen;
		$code  .= $string[$i] ^ $key[$k];
	}
	return ($action!='DECODE' ? base64_encode($code) : $code);
}
function _cookie($var, $value=null,$life=31536000,$prefix=1) {
	global $time, $_SERVER,$_COOKIE;
	$cookiepre='onez_cn_my_';
	if($value==null){
    return $_COOKIE[$cookiepre.$var] ? $_COOKIE[$cookiepre.$var] : $_COOKIE[',_'.$cookiepre.$var];
	}elseif($value=='del'){
    $value='';
    $life=-20;
	}
	$cookiedomain='';
	$cookiepath='/';
	setcookie(($prefix ? $cookiepre : '').$var, $value,
		$life ? $time + $life : 0, $cookiepath,
		$cookiedomain, $_SERVER['SERVER_PORT'] == 443 ? 1 : 0);
}
function InitGP($keys,$method=null,$cvtype=1){//0=null,1=Char_cv,2=int
	!is_array($keys) && $keys = array($keys);
	foreach ($keys as $key) {
		if ($key == 'GLOBALS') continue;
		$GLOBALS[$key] = NULL;
		if ($method != 'P' && isset($_GET[$key])) {
			$GLOBALS[$key] = $_GET[$key];
		} elseif ($method != 'G' && isset($_POST[$key])) {
			$GLOBALS[$key] = $_POST[$key];
		}
		if (isset($GLOBALS[$key]) && !empty($cvtype) || $cvtype==2) {
			$GLOBALS[$key] = Char_cv($GLOBALS[$key],$cvtype==2,true);
		}
	}
}
function Char_cv($mixed,$isint=false,$istrim=false) {
	if (is_array($mixed)) {
		foreach ($mixed as $key => $value) {
			$mixed[$key] = Char_cv($value,$isint,$istrim);
		}
	} elseif ($isint) {
		$mixed = (int)$mixed;
	} elseif (!is_numeric($mixed) && ($istrim ? $mixed = trim($mixed) : $mixed) && $mixed) {
		$mixed = str_replace(array("\0","%00","\r"),'',$mixed);
		$mixed = preg_replace(
			array('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','/&(?!(#[0-9]+|[a-z]+);)/is'),
			array('','&amp;'),
			$mixed
		);
		$mixed = str_replace(array("%3C",'<'),'&lt;',$mixed);
		$mixed = str_replace(array("%3E",'>'),'&gt;',$mixed);
		$mixed = str_replace(array('"',"'","\t",'  '),array('&quot;','&#39;','    ','&nbsp;&nbsp;'),$mixed);
	}
	return $mixed;
}

function ero($msg1,$msg2="1"){
  if ($msg2=="0"){
    echo "<script language=\"javascript\">alert('".$msg1."');window.close();</script>";
    exit;
  }elseif($msg2=="1"){
    echo "<script language=\"javascript\">alert('".$msg1."');history.go(-1);</script>";
    exit;
  }elseif($msg2=="2"){
    echo "<script language=\"javascript\">alert('".$msg1."');</script>";
  }elseif ($msg2=="3"){
    echo "<script language=\"javascript\">location.href='".$msg1."';</script>";
    exit;
  }else{
    echo "<script language=\"javascript\">alert('".$msg1."');location.href='".$msg2."';</script>";
    exit;
  } 
}
function ostripslashes($string, $force = 0) {
  if(is_array($string)) {
    foreach($string as $key => $val) {
      $string[$key] = ostripslashes($val, $force);
    }
  } else {
    $string = stripslashes($string);
  }
	return $string;
}
function onez_json($a=false){
  if (is_null($a)) return 'null'; 
  if ($a === false) return 'false'; 
  if ($a === true) return 'true'; 
  if (is_scalar($a)){ 
    if (is_float($a)){ 
      return floatval(str_replace(",", ".", strval($a))); 
    } 
    if (is_string($a)) { 
      static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); 
      return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; 
    }else{
       return $a; 
    }
  } 
  $isList = true; 
  for($i = 0, reset($a); $i < count($a); $i++, next($a)){ 
    if(key($a) !== $i){ 
      $isList = false; 
      break; 
    } 
  } 
  $result = array(); 
  if ($isList){ 
    foreach ($a as $v) $result[] = onez_json($v); 
    return '[' . join(',', $result) . ']'; 
  }else{
    foreach ($a as $k => $v) $result[] = onez_json($k).':'.onez_json($v); 
    return '{' . join(',', $result) . '}'; 
  } 
}
function SetEditor($E_id,$E_content='',$style='Basic',$width='100%',$height='500'){
  global $homepage;
	include_once(ONEZ_ROOT.'fck/fckeditor.php');
	$FCKeditor=new FCKeditor($E_id);
	$FCKeditor->Width=$width;
	$FCKeditor->Height=$height;
	$FCKeditor->ToolbarSet=$style;
	$FCKeditor->Value=$E_content;
	$FCKeditor->Create();
}
function getpage($token){
  $T=DB()->one("page","*","token='$token'");
  if(!$T)return;
  return $T;
}
function cmd($data){
  $fp = @fsockopen('127.0.0.1',1728, $errno, $errstr, 5);
  @fwrite($fp,$data);
  while (!feof($fp)){
    $line=fgets($fp,2);
    if($line=="\r")break;
  }
  @fclose($fp);
}
function post($url,$fields='',$baseurl='',$header=0,$headers=array()){
  global $cookieFile;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  $headers && curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HEADER, $header);
  
  curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); //保存
  curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); //读取
  curl_setopt($ch, CURLOPT_REFERER,$baseurl ? $baseurl : 'http://d.web2.qq.com/proxy.html?v=20110331002&callback=2');
  if($fields){
    curl_setopt($ch, CURLOPT_POST,1);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
  }
  $output = curl_exec($ch);
  curl_close($ch);
  return $output;
}
function get_image_mime( $file ){
  $ext = strtolower(pathinfo( $file , PATHINFO_EXTENSION ));
  switch( $ext ){
    case 'jpg':
    case 'jpeg':
        $mime = 'image/jpg';
        break;
    case 'png':
        $mime = 'image/png';
        break;
    case 'bmp':
        $mime = 'image/bmp';
        break;
    case 'gif':
    default:
        $mime = 'image/gif';
        break;
  }
  return $mime;
}
function getusr($len=6){
  $usr=strtolower(chr(mt_rand(65,90)));
  $char='abcdefghijklmnopqrstuvwxyz0123456789';
  for($i=1;$i<=$len;$i++){
    $usr.=$char[rand(0,strlen($char)-1)];
  }
  return $usr;
}
function cookiefile($token,$clear=false){
  global $cookieFile;
  $cookieFile=ONEZ_ROOT.'onezdata/cookie/'.$token.'.txt';
  mkdirs(dirname($cookieFile));
  if($clear){
    @unlink($cookieFile);
  }
}
function vars($token,$A=false){
  $varFile=ONEZ_ROOT.'onezdata/vars/'.$token.'.txt';
  mkdirs(dirname($varFile));
  if($A){
    writeover($varFile,serialize($A));
  }else{
    return @unserialize(@readover($varFile));
  }
}
function needlogin($filter=array()){
  global $uid,$username,$a,$b,$c,$d,$Menu,$menu,$Footer,$title;
  InitGP(array('a','b','c','d'),'G');
  if(function_exists('Menu'))$Menu=Menu();
  if(function_exists('Footer'))$Footer=Footer();
  settype($Menu,'array');
  settype($Footer,'array');
  if($filter!==0){
    if(!$uid && ($a!='account' || $b!='login')){
      $leave=1;
      $M=array();
      settype($filter,'array');
      foreach($filter as $v){
        settype($v,'array');
        $M[$v[0]][$v[1]]='';
        if(($v[1] && $a==$v[0] && $b==$v[1]) || $a==$v[0]){
          $leave=0;
        }
      }
      foreach($Menu as $k=>$v){
        if(isset($M[$k])){
          if($M[$k]!=array(''=>'')){
            foreach($v[2] as $k2=>$v2){
              if(!isset($M[$k][$k2])){
                unset($Menu[$k][2][$k2]);
              }
            }
          }
        }else{
          unset($Menu[$k]);
        }
      }
      if($leave==0){
        return;
      }
      header('location:?a=account&b=login&jumpurl='.urlencode($_SERVER['REQUEST_URI']));
      exit();
    }
  }
  if($uid){
    gettable('users',"uid='$uid'");
  }
  !$a && $a=key($Menu);
  $menu=$Menu[$a][2];
  settype($menu,'array');
  !$b && $b=key($menu);
  $c=$menu[$b][2];
  $title=$menu[$b][0];
  !$title && $title=$Menu[$a][0];
}
function session_put($token,$value){
  $_SESSION[$token]=$value;
}
function session_get($token,$clear=false){
  $value=$_SESSION[$token];
  if($clear){
    unset($_SESSION[$token]);
  }
  return $value;
}
function jump($token,$value,$url=''){
  ob_clean();
  if($token){
    session_put($token,$value);
  }
  if(!$url){
    $url=$_SERVER['REQUEST_URI'];
  }
  header('location:'.$url);
  exit();
}
function option($token){
  global $OPTION;
  if(!isset($OPTION)){
    $file=ONEZ_ROOT.'onezdata/options.php';
    if(file_exists($file)){
      @include_once($file);
    }
    settype($OPTION,'array');
  }
  return $OPTION[$token];
}
function gettable($table,$where='',$return=false){
  $T=DB()->one($table,'*',$where);
  if(!$T)return false;
  if($return)return $T;
  foreach($T as $k=>$v){
    $GLOBALS[$k]=$v;
  }
  if($T['uid']){
    $T=DB()->record('options','*',"uid='$T[uid]' and tablename='$table'");
    foreach($T as $rs){
      $GLOBALS[$rs['token']]=$rs['isarray']?unserialize($rs['value']):$rs['value'];
    }
  }
  return true;
}
function gettitle($arr,$token){
  if(is_array($arr)){
    foreach($arr as $k=>$v){
      if(is_array($v)){
        $ti=gettitle($v,$token);
        if($ti){
          return $ti;
        }
      }elseif($k==$token){
        return $v;
      }
    }
  }
}
function upload_image($input, $width=0, $height=0) {
  include_once(ONEZ_ROOT.'include/Image.class.php');
	$year = date('Y'); $day = date('md'); $n = time().rand(1000,9999).'.jpg';
	$z = $_FILES[$input];
	if ($z && strpos($z['type'], 'image')===0 && $z['error']==0) {
    mkdirs( ONEZ_ROOT . '/onezdata/files/' . "{$year}/{$day}" );
    $image = "{$year}/{$day}/{$n}";
    $path = ONEZ_ROOT . '/onezdata/files/' . $image;
		move_uploaded_file($z['tmp_name'], $path);
		if($width && $height) {
			$npath = preg_replace('#(\d+)\.(\w+)$#', "\\1_index.\\2", $path); 
			Image::Convert($path, $npath, $width, $height, Image::MODE_CUT);
		}
		return 'onezdata/files/'.$image;
	} 
	return '';
}
function setoptions($A,$isdel=0){
  list($uid,$tablename)=$A['table'];settype($uid,'int');
  unset($A['table']);
  if(!$tablename)return;
  if($isdel){
    DB()->delete("options","uid='$uid' and tablename='$tablename'");
    return;
  }
  foreach($A as $k=>$v){
    if(!$k)continue;
    if($v){
      $isarray=0;
      if(is_array($v)){
        $v=serialize($v);
        $isarray=1;
      }
      if(DB()->rows("options","uid='$uid' and tablename='$tablename' and token='$k'")>0){
        DB()->update("options",array('value'=>$v,'isarray'=>$isarray),"uid='$uid' and tablename='$tablename' and token='$k'");
      }else{
        DB()->insert('options',array(
          'uid'=>$uid,
          'tablename'=>$tablename,
          'token'=>$k,
          'value'=>$v,
          'isarray'=>$isarray,
        ));
      }
    }else{
      DB()->delete("options","uid='$uid' and tablename='$tablename' and token='$k'");
    }
  }
}
function theme($file){
  global $theme;
  !$theme && $theme='default';
  $themeFile='themes/web/'.$theme.'/'.$file;
  !file_exists($file) && $themeFile='themes/web/default/'.$file;
  return $themeFile;
}
function theme_header(){
  global $a,$b,$c;
  include_once(theme('header.php'));
}
function theme_footer(){
  global $Footer;
  include_once(theme('footer.php'));
}
function G($token){
  return $GLOBALS[$token];
}
function getaddress($ip,$area=false){
  include_once(ONEZ_ROOT."include/ip.class.php");
  $p=new IpLocation();
  $l=$p->getlocation($ip);
  //print_r($l);
  $address=$l['country'];
  if($area)$address.=$l['area'];
  return $address;
}

function osubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
  if(function_exists("mb_substr")){
    if(mb_strlen($str, $charset) <= $length) return $str;
    $slice = mb_substr($str, $start, $length, $charset);
  }else{
    $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);
    if(count($match[0]) <= $length) return $str;
    $slice = join("",array_slice($match[0], $start, $length));
  }
  if($suffix) return $slice."…";
  return $slice;
}
function ostrlen($string = null) {
  preg_match_all("/[0-9]{1}/",$string,$arrNum);  
  preg_match_all("/[a-zA-Z]{1}/",$string,$arrAl);  
  preg_match_all("/./us",$string,$arrCh); 
  return count($arrNum[0]+$arrAl[0]+$arrCh[0]);
}
function onezVarA($key){
  return $GLOBALS[$key];
}
function onezVarB($qids){
  if($qids){
    $T=DB()->record("question","*","qid in ($qids) order by asknum desc");
    $n=0;
    $tmp='';
    foreach($T as $rs){
      $n++;
      $tmp.='<span>'.$n.'、</span><a href="javascript:byQid('.$rs['qid'].')">'.$rs['content'].'</a><br />';
    }
    if($n==1){
      $tmp=str_replace('<span>1、</span>','',$tmp);
    }
  }
  return $tmp;
}
function onezAnswer($T){
  global $A;
  if(!$T)return;
  foreach($T as $k=>$v){
    $$k=$v;
    $GLOBALS[$k]=$v;
  }
  $A['aid']=$aid;
  @eval($phpcode);
  
  
  //替换关键词
  $T=DB()->record("keywords","*",var_export(strip_tags($content),true)." like concat('%',word,'%')");
  foreach($T as $rs){
    if(!$rs['url']){
      $word='<a href="javascript:byWord('.var_export($rs['word'],true).')">'.$rs['word'].'</a>';
    }elseif(substr($rs['url'],0,1)=='Q' && is_numeric(substr($rs['url'],1))){
      $word='<a href="javascript:byQid('.substr($rs['url'],1).')">'.$rs['word'].'</a>';
    }elseif(substr($rs['url'],0,1)=='A' && is_numeric(substr($rs['url'],1))){
      $word='<a href="javascript:byAid('.substr($rs['url'],1).')">'.$rs['word'].'</a>';
    }elseif(strtolower(substr($rs['url'],0,7))=='http://'){
      $word='<a href="'.$rs['url'].'" target="_blank">'.$rs['word'].'</a>';
    }else{
      $word='<a href="javascript:byWord('.var_export($rs['url'],true).')">'.$rs['word'].'</a>';
    }
    $content=str_replace($rs['word'],$word,$content);
  }
  
  //替换php变量
  $content=preg_replace('/\{\$(.+?)\}/ie',"onezVarA('$1')",$content);
  $content=preg_replace('/\{([0-9,]+)\}/ie',"onezVarB('$1')",$content);
  
  $A['msg']=$content;
  $A['js']=(string)$jscode;
}