<?php
class onezhtml{
  var $html=array();
  var $block=array();
  var $A=array();
  var $B=array();
  var $editor=false;
  
  var $files=array();
  
  var $showSql=false;
  var $sql=array();
  var $tableName='';
  
  var $borderNum=0;
  var $borders=array();
  #增加字段
  function addinput($label,$field,$value,$type,$require=0,$dataType='',$vars=array()){
    settype($vars,'array');
    $name=$vars['name'];
    !$name && $name='S';
    $str='<div class="field">';
    $str.='<label for="onez-'.$field.'">';
    $require && $str.='<span style="color:#c00">*</span> ';
    if($label){
      $str.=$label.': ';
    }
    $str.='</label>';
    $other=" require='".($require ? 'true' : 'false')."'$vars[other]";
    $dataType && $other.=" dataType='$dataType'";
    $vars['accept'] && $other.=" accept='$vars[accept]'";
    $vars['min'] && $other.=" min='$vars[min]'";
    $vars['max'] && $other.=" max='$vars[max]'";
    $vars['msg'] && $other.=" msg='$vars[msg]'";
    $vars['operator'] && $other.=" operator='$vars[operator]'";
    $vars['to'] && $other.=" to='$vars[to]'";
    $vars['format'] && $other.=" format='$vars[format]'";
    $vars['regexp'] && $other.=" regexp='$vars[regexp]'";
    $vars['style'] && $other.=" style='$vars[style]'";
    if($vars['style']){
      if(is_array($vars['style'])){
        $other.=" style='".implode('; ',$vars['style'])."'";
      }else{
        $other.=" style='$vars[style]'";
      }
    }
    if($require && !$dataType){
      $other.=" dataType='Require'";
    }
    
    $class=strtolower($type);
    $vars['class'] && $class=$vars['class'];
    $class.=" f-input";
    switch(strtolower($type)){
      case'hidden':
        if($this->showSql){
          if($require){
            $this->sql[]="$field int(11) not null DEFAULT '0' COMMENT '$label',";
          }else{
            $this->sql[]="$field char(50) DEFAULT NULL COMMENT '$label',";
          }
        }
        $this->block[]='<input type="hidden" name="'.$name.'['.$field.']" value="'.$value.'" />';
        return;
        break;
      case'name':
        $this->showSql && $field!='action' && $this->sql[]="$field char(50) DEFAULT NULL COMMENT '$label',";
        $this->block[]='<input type="hidden" name="'.$field.'" value="'.$value.'" />';
        return;
        break;
      case'view':
        $str.=$value;
        if(!$value)return;
        break;
      case'html':
        $str.=$value;
        break;
      case'text':
        $this->showSql && $this->sql[]="$field char(50) DEFAULT NULL COMMENT '$label',";
        if($require && !$vars['msg']){
          $other.=" msg='{$label}不能为空'";
        }
        $str.='<input type="text" id="s_'.$field.'" name="'.$name.'['.$field.']" value="'.$value.'" class="'.$class.'"'.$other.' />';
        break;
      case'file':
        $this->showSql && $this->sql[]="$field char(50) DEFAULT NULL COMMENT '$label',";
        $str.='<input type="file" size="30" name="'.$field.'" class="f-input" />';
        $this->files[]=$field;
        $this->block[]='<input type="hidden" name="F[]" value="'.$field.'" />';
        if($value){
          $vars['tip']=$GLOBALS['homepage'].'/'.$value;
        }
        break;
      case'password':
        $this->showSql && $this->sql[]="$field char(32) DEFAULT NULL COMMENT '$label',";
        $class='text';
        if($require && !$vars['msg']){
          $other.=" msg='{$label}不能为空'";
        }
        $str.='<input type="password" id="s_'.$field.'" name="'.$name.'['.$field.']" value="" class="'.$class.'"'.$other.' />';
        break;
      case'password2':
        $this->showSql && $this->sql[]="$field char(32) DEFAULT NULL COMMENT '$label',";
        $class='text';
        if($require && !$vars['msg']){
          $other.=" msg='{$label}不能为空'";
        }
        $str.='<input type="password" id="s_'.$field.'" name="'.$name.'['.$field.']" value="'.$value.'" class="'.$class.'"'.$other.' />';
        break;
      case'textarea':
        $this->showSql && $this->sql[]="$field longtext COMMENT '$label',";
        if($require && !$vars['msg']){
          $other.=" msg='{$label}不能为空'";
        }
        $str.='<textarea class="'.$class.'" id="s_'.$field.'" name="'.$name.'['.$field.']"'.$other.'>'.$value.'</textarea>';
        break;
      case'editor':
        $this->showSql && $this->sql[]="$field longtext COMMENT '$label',";
        if(!$this->editor){
          $this->editor=true;
          $str.='<script type="text/javascript" src="js/xheditor/xheditor.js"></script> ';
        }
        if($require && !$vars['msg']){
          $other.=" msg='{$label}不能为空'";
        }
        $str.='<textarea class="'.$class.' editor" id="s_'.$field.'" name="'.$name.'['.$field.']"'.$other.'>'.$value.'</textarea>';
        break;
      case'fck':
        $this->showSql && $this->sql[]="$field longtext COMMENT '$label',";
        !$vars['style'] && $vars['style']='Default';
        SetEditor('S['.$field.']',$value,'Default');
        break;
      case'radio':
        $this->showSql && $this->sql[]="$field char(50) DEFAULT NULL COMMENT '$label',";
        if($require && !$vars['msg']){
          $other.=" msg='请选择{$label}'";
        }
        settype($vars['data'],'array');
        foreach($vars['data'] as $k=>$v){
          if($v==end($vars['data']))$other2=$other;
          $str.='<input type="radio" name="'.$name.'['.$field.']" id="s_'.$field.'_'.$k.'" value="'.$k.'" class="'.$class.'"'.($k==$value ? ' checked':'').''.$other2.' />';
          $str.='<label for="s_'.$field.'_'.$k.'">'.$v.'</label> ';
        }
        break;
      case'checkbox':
        $this->showSql && $this->sql[]="$field char(50) DEFAULT NULL COMMENT '$label',";
        if($require && !$vars['msg']){
          $other.=" msg='请选择{$label}'";
        }
        settype($vars['data'],'array');
        settype($value,'array');
        foreach($vars['data'] as $k=>$v){
          if($v==end($vars['data']))$other2=$other;
          $str.='<input type="checkbox" name="'.$name.'['.$field.']" id="s_'.$field.'_'.$k.'" value="'.$k.'" class="'.$class.'"'.(in_array($k,$value) ? ' checked':'').''.$other2.' />';
          $str.='<label for="s_'.$field.'_'.$k.'">'.$v.'</label> ';
        }
        break;
      case'select':
        $this->showSql && $this->sql[]="$field char(50) DEFAULT NULL COMMENT '$label',";
        if($require && !$vars['msg']){
          $other.=" msg='请选择{$label}'";
        }
        $str.='<select id="s_'.$field.'" name="'.$name.'['.$field.']"'.$other.'>';
        if(isset($vars['min']) && $vars['max']){
          for($i=$vars['min'];$i<=$vars['max'];$i++){
            $k=$i;
            if($vars['fix']){
              $k=str_pad($k,$vars['fix'],'0',STR_PAD_LEFT);
            }
            $str.='<option value="'.$k.'"'.($k==$value ? ' selected':'').'>'.$k.'</option>';
          }
        }else{
          settype($vars['data'],'array');
          foreach($vars['data'] as $k=>$v){
            if(is_array($v)){
              $str.='<optgroup label="'.$k.'">';
              foreach($v as $a=>$b){
                $vars['nokey'] && (!$a || is_numeric($a)) && $a=$b;
                $str.='<option value="'.$a.'"'.($a==$value ? ' selected':'').'>'.$b.'</option>';
              }
              $str.='</optgroup>';
            }else{
              $vars['nokey'] && (!$k || is_numeric($k)) && $k=$v;
              $str.='<option value="'.$k.'"'.($k==$value ? ' selected':'').'>'.$v.'</option>';
            }
          }
        }
        $str.='</select>';
        break;
      case'sql':
        $this->showSql && $this->sql[]="$field $value COMMENT '$label',";
        return;
        break;
    }
    $str.=$vars['end'];
    #备注
    $vars['tip'] && $str.=' <span class="hint">'.$vars['tip'].'</span>';
    $str.='</div>';
    $this->block[]=$str;
  }
  #显示表单
  function setform($btnName='提交'){
    array_unshift($this->block,'<div class="sect">','<form method="post" name="myform" onSubmit="return Validator.Validate(this,3)"'.($this->files ? ' enctype="multipart/form-data"' : '').'>');
    array_push($this->block,'<div class="act"><input type="submit" value="'.$btnName.'" name="commit" id="submit" class="formbutton"/></div>','</form>','</div>');
    $this->html=array_merge($this->html,$this->block);
    $this->block=array();
  }
  function setview($btnName='返回'){
    array_unshift($this->block,'<div class="sect">');
    if($btnName!==false){
      array_push($this->block,'<div class="act"><input type="button" value="'.$btnName.'" name="commit" id="button" class="formbutton" onclick="history.go(-1)"/></div>');
    }
    array_push($this->block,'</div>');
    $this->html=array_merge($this->html,$this->block);
    $this->block=array();
  }
  function addline($label,$html){
    $str='<div class="field">';
    $str.='<label>';
    $require && $str.='<span style="color:#c00">*</span> ';
    if($label){
      $str.=$label.': ';
    }
    $str.='</label>';
    $str.='</div>';
    $str.=$html;
    $this->html[]=$str;
  }
  #显示代码
  function flush(){
    echo implode("\n",$this->html);
    $this->html=array();
  }
  #获取代码
  function gethtml(){
    $html=implode("\n",$this->html);
    $this->html=array();
    return $html;
  }
  #增加CSS
  function addcss($file,$type=0){
    if($type==0){
      $this->html[]='<link rel="stylesheet" href="'.$GLOBALS['homepage'].'/'.$file.'" type="text/css" media="screen" charset="utf-8" />';
    }elseif($type==1){
      $this->html[]='<link rel="stylesheet" href="'.theme($file).'" type="text/css" media="screen" charset="utf-8" />';
    }elseif($type==2){
      $this->html[]='<style type="text/css">'.$file.'</style>';
    }
  }
  #增加JS
  function addjs($file,$type=0){
    if($type==0){
      $this->html[]='<script type="text/javascript" src="'.$GLOBALS['homepage'].'/'.$file.'"></script>';
    }elseif($type==1){
      $this->html[]='<script type="text/javascript" src="'.theme($file).'"></script>';
    }elseif($type==2){
      $this->html[]='<script type="text/javascript">'.$file.'</script>';
    }
  }
  #增加代码
  function addhtml($html){
    $this->html[]=$html;
  }
  #增加标题
  function addtitle($ti){
    $this->html[]='<div class="wholetip clear"><h3>'.$ti.'</h3></div>';
  }
  #增加信息
  function addinfo($ti,$arr){
    $this->html[]='<div class="wholetip clear"><h3>'.$ti.'</h3></div>';
    $this->html[]='<div style="margin:0 20px;" class="info">';
    settype($arr,'array');
    foreach($arr as $v){
      $this->html[]='<p>'.$v.'</p>';
    }
    $this->html[]='</div>';
  }
  #标题
  function addhead($text,$links=array()){
    if($links){
      global $a,$b,$d;
      $d && $d=str_replace('&amp;','&',$d);
      $filter='<ul class="filter">';
      foreach($links as $k=>$v){
        $filter.='<li'.($d==$k ? ' class="current"' : '').'><a href="?a='.$a.'&b='.$k.'&d='.urlencode($k).'" class="ajaxlink">'.$v.'</a></li>';
      }
      $filter.='</ul>';
    }
    $this->html[]='<div class="head"><h2>'.$text.'</h2>'.$filter.'</div>';
  }
  
  #增加边框
  function borderA(){
    $this->borderNum++;
    $this->borders[$this->borderNum]=array();
    $args=func_get_args();
    foreach($args as $k=>$type){
      if($type=='box' || $type=='box2'){
        $this->html[]='<div class="'.$type.'"><div class="'.$type.'-top"></div><div class="'.$type.'-content">';
        array_unshift($this->borders[$this->borderNum],'</div><div class="'.$type.'-bottom"></div></div>');
      }elseif($type=='sbox'){
        $this->html[]='<div class="sbox"><div class="sbox-top"></div><div class="sbox-content">';
        array_unshift($this->borders[$this->borderNum],'</div><div class="sbox-bottom"></div></div>');
      }elseif($type=='sbox2'){
        $this->html[]='<div class="sbox"><div class="sbox-top2">'.$args[1].'</div><div class="sbox-content">';
        array_unshift($this->borders[$this->borderNum],'</div><div class="sbox-bottom"></div></div>');
        break;
      }elseif($type=='sidebar'){
        $this->html[]='<div id="content">';
        array_unshift($this->borders[$this->borderNum],'</div><div id="sidebar">'.(function_exists('sidebar') ? sidebar() : '').'</div><div class="clear"></div>');
      }elseif(substr($type,0,1)=='#'){
        $this->html[]='<div id="'.substr($type,1).'">';
        array_unshift($this->borders[$this->borderNum],'</div>');
      }elseif(substr($type,0,1)=='.'){
        $this->html[]='<div class="'.substr($type,1).'">';
        array_unshift($this->borders[$this->borderNum],'</div>');
      }else{
        $this->html[]='<div class="'.$type.'">';
        array_unshift($this->borders[$this->borderNum],'</div>');
      }
    }
  }
  function borderB($toEnd=0){
    settype($this->borders[$this->borderNum],'array');
    foreach($this->borders[$this->borderNum] as $v){
      $this->html[]=$v;
    }
    unset($this->borders[$this->borderNum]);
    $this->borderNum--;
    if($this->borderNum>0 && $toEnd){
      $this->borderB($toEnd);
    }
  }
  
  #增加项目
  function setlist($table,$idname,$arr){
    $col=count($arr);
    $this->html[]='<div class="sect">';
    $this->html[]='<table cellspacing="0" cellpadding="0" border="0" class="table">';
    $this->html[]='<tr>';
    foreach($arr as $v){
      $this->html[]='<th'.($v==end($arr) ? ' class="last"' : '').''.($v['width'] ? ' width="'.$v['width'].'"' : '').'>'.$v['label'].'</th>';
    }
    $this->html[]='</tr>';
    settype($table[0],'array');
    $js=array();
    foreach($table[0] as $k=>$rs){
      $this->html[]='<tr'.($k % 2==0 ? ' class="alt"' : '').'>';
      foreach($arr as $v){
        $value='';
        switch($v['type']){
          case'image':
            if($rs[$v['token']]){
              $value='<img src="'.$rs[$v['token']].'"'.($v['width']?' width="'.$v['width'].'"':'').($v['height']?' height="'.$v['height'].'"':'').' />';
            }
            break;
          case'bool':
            $value=$rs[$v['token']] ? '<font color="green">是</font>' : '<font color="red">否</font>';
            break;
          case'radio':
            $value=$v['values'][$rs[$v['token']]];
            break;
          case'date':
            if($rs[$v['token']]){
              $value=date($v['format'] ? $v['format'] : 'Y-m-d H:i:s',$rs[$v['token']]);
            }else{
              $value='---';
            }
            break;
          case'func':
            $value=$v['token']($rs);
            break;
          case'url':
            $value='<a href="'.$rs[$v['token']].'" target="_blank">'.$rs[$v['token']].'</a>';
            break;
          case'static':
            $value=$v['token'];
            break;
          case'btns':
            global $a,$b;
            foreach($v['btns'] as $k=>$v){
              if(strpos($k,'edit')!==false || $k=='view'){
                $js[$k]="location.href='?a=$a&b=$k&c=$b&$idname='+$idname;";
              }elseif($k=='del'){
                $js[$k]="if(confirm('您确定要删除这条记录吗？')){ $.post('?a=$a&b=$b','action=$k&$idname='+$idname,function(s){if(s=='Y'){location.reload();}else{alert(s);}});}";
              }elseif($k=='copy' || $k=='up' || $k=='down'){
                $js[$k]="$.post('?a=$a&b=$b','action=$k&$idname='+$idname,function(s){if(s=='Y'){location.reload();}else{alert(s);}});";
              }else{
                $js[$k]="$.post('?a=$a&b=$b','action=set&$idname='+$idname,function(s){if(s=='Y'){location.reload();}else{alert(s);}});";
              }
              $value.='<input type="button" class="btn" name="btn" value="'.$v.'" onclick="Opt(\''.$k.'\',\''.$rs[$idname].'\')" /> ';
            }
            break;
          default:
            $value=$rs[$v['token']];
            break;
        }
        if($v['url']){
          $value='<a href="'.preg_replace('/\{([^\}]+)\}/ie','$rs[$1]',$v['url']).'" target="_blank">'.$value.'</a>';
        }
        $this->html[]='<td'.($v['type']=='btns' ? ' class="op"' : '').'>'.$value.'</td>';
      }
      $this->html[]='</tr>';
    }
    $this->html[]='<tr><td colspan="'.$col.'">'.$table[1].'</td></tr>';
    $this->html[]='</table>';
    $this->html[]='</div>';
    if($js){
      $this->html[]='<script type="text/javascript">';
      $this->html[]='function Opt(token,'.$idname.'){';
      $this->html[]='switch(token){';
      foreach($js as $k=>$v){
        $this->html[]="case'$k':";
        $this->html[]=$v;
        $this->html[]="break;";
      }
      $this->html[]='}';
      $this->html[]='}';
      $this->html[]='</script>';
    }
  }
  #模块是否存在
  function is_block($a,$b,$c,$path='main'){
    if(in_array($b,array('productinfo','viewpage'))){
      $file1=ONEZ_ROOT.'blocks/global/base.php';
      $file2=ONEZ_ROOT.'blocks/global/'.$b.'.php';
    }elseif(in_array($c,array('productinfo','viewpage'))){
      $file1=ONEZ_ROOT.'blocks/global/base.php';
      $file2=ONEZ_ROOT.'blocks/global/'.$c.'.php';
    }else{
      $file1=ONEZ_ROOT.'blocks/'.$path.'/'.$a.'/base.php';
      $file2=ONEZ_ROOT.'blocks/'.$path.'/'.$a.'/'.($c ? $c : $b).'.php';
    }
    if(file_exists($file2)){
      $this->tableName=$a;
      if(!file_exists($file1)){
        $file1=false;
      }
    }else{
      $file1=false;
      $file2=false;
    }
    return array($file1,$file2);
  }
  #数据库操作
  function save($tablename='',$idname='',$vars=array()){
    global $S,$F,$time,$action,$onlineip,$$idname;
    InitGP(array('S','F','A','action'),'P');
    if(!$action)return;
    $id=$S[$idname];
    !$id && $id=$$idname;
    settype($S,'array');
    settype($F,'array');
    settype($A,'array');
    settype($vars['YN'],'array');
    settype($vars['int'],'array');
    settype($vars['float'],'array');
    settype($vars['date'],'array');
    settype($vars['opts'],'array');
    settype($vars['white'],'array');
    settype($vars['black'],'array');
    settype($vars['add'],'array');
    settype($vars['file'],'array');
    settype($vars['all'],'array');
    #验证合法性
    if($vars['opts'] && !in_array($action,$vars['opts']))return;
    #上传
    foreach($F as $v){
      $r=upload_image($v);
      
      if($r){
        $S[$v]=$r;
      }
    }
    #附加
    foreach($vars['add'] as $k=>$v){
      $S[$k]=$v;
    }
    #无过滤
    foreach($vars['all'] as $v){
      if(isset($S[$v])){
        $S[$v]=$_POST['S'][$v];
      }
    }
    #是否
    foreach($vars['YN'] as $v){
      if(isset($S[$v])){
        $S[$v]=$S[$v]=='Y' ? 'Y' : 'N';
      }
    }
    #整数
    foreach($vars['int'] as $v){
      if(isset($S[$v])){
        $S[$v]=(int)$S[$v];
      }
    }
    #浮点
    foreach($vars['float'] as $v){
      if(isset($S[$v])){
        $S[$v]=(float)$S[$v];
      }
    }
    #日期
    foreach($vars['date'] as $v){
      if(isset($S[$v])){
        $S[$v]=(int)$S[$v];
        if(!$S[$v])$S[$v]=$time;
      }
    }
    #白名单
    if($vars['white']){
      foreach($S as $k=>$v){
        if(!in_array($k,$vars['white'])){
          unset($S[$k]);
        }
      }
    }
    #黑名单
    if($vars['black']){
      foreach($S as $k=>$v){
        if(in_array($k,$vars['black'])){
          unset($S[$k]);
        }
      }
    }
    switch($action){
      case'add':
        if(isset($S['password'])){
          $S['password']=md5($S['password']);
        }
        DB()->insert($tablename,$S);
        $A['table']=array($S['uid']?$S['uid']:$GLOBALS['uid'],$tablename);setoptions($A);
        if(function_exists('save_add'))save_add();
        jump('notice','添加成功','?a='.$GLOBALS['a'].($vars['b'] ? '&b='.$vars['b'] : ''));
        break;
      case'edit':
        if(isset($S['password'])){
          if($S['password']){
            $S['password']=md5($S['password']);
          }else{
            unset($S['password']);
          }
        }
        DB()->update($tablename,$S,"$idname='$id'$vars[where]");
        $A['table']=array($S['uid']?$S['uid']:$GLOBALS['uid'],$tablename);setoptions($A);
        jump('notice','编辑成功','?a='.$GLOBALS['a'].($vars['b'] ? '&b='.$vars['b'] : ''));
        break;
      case'set':
        DB()->update($tablename,$S,"$idname='$id'$vars[where]");
        exit('Y');
        break;
      case'del':
        ob_clean();
        $S=DB()->one($tablename,"*","$idname='$id'$vars[where]");
        $A['table']=array($S['uid']?$S['uid']:$GLOBALS['uid'],$tablename);setoptions($A,1);
        DB()->delete($tablename,"$idname='$id'$vars[where]");
        exit('Y');
        break;
      case'copy':
        ob_clean();
        $S=DB()->one($tablename,"*","$idname='$id'$vars[where]");
        unset($S[$idname]);
        DB()->insert($tablename,$S);
        if($S['uid']){
          $T=DB()->record('options','*',"uid='$S[uid]' and tablename='$tablename'");
          foreach($T as $rs){
            DB()->insert('options',array(
              'uid'=>$S['uid'],
              'tablename'=>$tablename,
              'token'=>$rs['token'],
              'value'=>$rs['value'],
              'isarray'=>$rs['isarray'],
            ));
          }
        }
        exit('Y');
        break;
      case'up':
        ob_clean();
        $myorderby=DB()->select($tablename,"orderby","$idname='$id'$vars[where]");
        $T=DB()->one($tablename,"$idname,orderby","orderby<$myorderby$vars[where] order by orderby desc");
        if($T){
          $upid=$T[$idname];
          $uporderby=$T['orderby'];
          DB()->update($tablename,array('orderby'=>$myorderby),"$idname='$upid'$vars[where]");
          DB()->update($tablename,array('orderby'=>$uporderby),"$idname='$id'$vars[where]");
        }
        exit('Y');
        break;
      case'down':
        ob_clean();
        $myorderby=DB()->select($tablename,"orderby","$idname='$id'$vars[where]");
        $T=DB()->one($tablename,"$idname,orderby","orderby>$myorderby$vars[where] order by orderby asc");
        if($T){
          $downid=$T[$idname];
          $uporderby=$T['orderby'];
          DB()->update($tablename,array('orderby'=>$myorderby),"$idname='$downid'$vars[where]");
          DB()->update($tablename,array('orderby'=>$uporderby),"$idname='$id'$vars[where]");
        }
        exit('Y');
        break;
      case'option':
        global $OPTION;
        settype($OPTION,'array');
        foreach($S as $k=>$v){
          $OPTION[$k]=$v;
        }
        $file=ONEZ_ROOT.'onezdata/options.php';
        @touch($file);
        if(is_writable($file)){
          writeover($file,'<?php
$OPTION='.var_export($OPTION,true).';
?>');
          jump('notice','保存成功');
        }else{
          jump('error','保存失败');
        }
        break;
      case'page':
        $k=$S['tokenname'];
        $v=$S[$k];
        unset($S['tokenname'],$S[$k]);
        if(DB()->rows($tablename,"$k='$v'")==0){
          $S[$k]=$v;
          DB()->insert($tablename,$S);
        }else{
          DB()->update($tablename,$S,"$k='$v'");
        }
        jump('notice','保存成功');
        break;
    }
  }
  
}
?>