<?php

class form{
    
    public static function _must($must = 0){
        return $must ? '<b>*</b>' : '';
    }
    
    public static function _rand($len = 12){
        $password1 = '';
        $low_ascii_bound=48;
        $upper_ascii_bound=122;
        $notuse=array(58,59,60,61,62,63,64,91,92,93,94,95,96);
        $i = 0;
        while($i < $len){
            if(PHP_VERSION<'4.2.0'){
                mt_srand((double)microtime()*1000000);
            }
            $randnum=mt_rand($low_ascii_bound,$upper_ascii_bound);
            if(!in_array($randnum,$notuse)){
                $password1=$password1.chr($randnum);
                $i++;
            }
        }
        return $password1;
    }
    
    # elements
    
    public static function tip($user, $action){
        return '<div class="formtext">Hi，<b>'.$user.'</b>，你正在'.$action.'！</div>';
    }
    
    public static function start($name = 'form1'){
        return '<form method="post" action="" onsubmit="return false" id="'.$name.'">';
    }
    
    public static function end(){
        return '</form>';
    }
    
    public static function input($array = array()){
        $connect = '';
        if (isset($array['connect']) && $array['connect']){
            $connect = '&nbsp;&nbsp;<input type="button" class="btn" value="选择" onclick="_connect($(this), \''.$array['connect_url'].'\', \''.$array['connect_type'].'\');" style="background-image: linear-gradient(to bottom,#fff 0,#e0e0e0 100%);border:1px solid #ccc;color: #333; width: 60px; height: 32px;"/>';
            $array['readonly'] = 1;
        }
        $only = $array['readonly'] == 1 ? ' readonly' : '';
        $css = $array['readonly'] == 1 ? 'background: #eee;cursor: not-allowed;' : '';
        $img = '';
        if (isset($array['file'])){
            $img = '&nbsp;&nbsp;<img src="'.$array['file'].'static/images/file.png" align="absmiddle" onclick="_file(1, $(this));"/>';
        }
        $html = '
        <li>
            <label>'.$array['title'].form::_must($array['must']).'</label>';
        if ($connect){
            $field1 = $array['name'];
            $field2 = $array['name'].'_value';
            $value1 = $value2 = '';
            if (isset($array['db']) && $array['db']){
                $value1 = $array['db'][$field1];
                $value2 = $array['db'][$field2];
            }
            if (isset($array['_fid']) && $array['_fid'] && $array['_fid']['name'] == $array['name']){
                $value1 = $array['_fid']['id'];
                $value2 = $array['_fid']['value'];
                $connect = '';
            }
            $html .= form::input_hidden($array['name'], $value1);
            $html .= '<input name="'.$array['name'].'_value" type="text" class="dfinput" placeholder="'.$array['placeholder'].'"  style="'.$array['style'].$css.'" value="'.$value2.'" '.$only.'/>';
        }else{
            $html .= '<input name="'.$array['name'].'" type="text" class="dfinput" placeholder="'.$array['placeholder'].'"  style="'.$array['style'].$css.'" value="'.$array['value'].'" '.$only.'/>';
        }
        $html .=  $img.$connect.'</li>';
        return $html;
    }
    
    public static function textarea($array = array()){
        $only = $array['readonly'] == 1 ? ' readonly' : '';
        return '
        <li>
            <label>'.$array['title'].form::_must($array['must']).'</label>
            <textarea name="'.$array['name'].'" class="dfarea" placeholder="'.$array['placeholder'].'"  style="'.$array['style'].'" '.$only.'>'.$array['value'].'</textarea>
        </li>';
    }
    
    public static function input_hidden($name, $value){
        return '<input type="hidden" name="'.$name.'" value="'.$value.'" />';
    }
    
    public static function password($title, $name, $must = 0, $placeholder = '', $style = ''){
        return '
        <li>
            <label>'.$title.form::_must($must).'</label>
            <input name="'.$name.'" type="password" class="dfinput" placeholder="'.$placeholder.'"  style="'.$style.'"/>
        </li>';
    }
    
    public static function select($title, $name, $must = 0, $options = array(), $vars = '', $width = 345, $value = '', $connect = 0){
        $option_html = '';
        $connect_value = '';
        if ($options){
            list($field1, $field2) = explode('::', $vars);
            foreach ($options as $option){
                $selected = '';
                if (($value || is_numeric($value)) && $value == $option[$field1]){
                    $selected = 'selected';
                    $connect_value = $option[$field2];
                }
                $option_html .= '<option value="'.$option[$field1].'" '.$selected.'>'.$option[$field2].'</option>';
            }
        }
        $change = '';
        $hidden = '';
        if ($connect){
            $change = 'onchange="$(this).parent().parent().find(\'input\').val($(this).find(\'option:selected\').text());"';
            $hidden = form::input_hidden($name.'_value', $connect_value);
        }
        return '
        <li>
            <label>'.$title.form::_must($must).'</label> 
            <div class="vocation">
                '.$hidden.'
                <select class="'.$name.'" name="'.$name.'" '.$change.'>
                    <option value="">-- 请选择 --</option>
                    '.$option_html.'
                </select>
            </div>
            <script>
                $(function(){
                    $(".'.$name.'").uedSelect({
                        width: '.$width.'
                    });
                });
            </script>
        </li>';
    }
    
    public static function submit($title, $name = 'btn_post'){
        return '<li><label>&nbsp;</label><input name="'.$name.'" type="button" class="btn '.$name.'" value="'.$title.'"/></li>';
    }
    
    public static function radio($title, $name, $must = 0, $options = array(), $vars = ''){
        $radio_html = '';
        if ($options){
            foreach ($options as $radio){
                list($field1, $field2, $value) = explode('::', $vars);
                $checked = $value == $radio[$field1] ? ' checked' : '';
                $radio_html .= '<input name="'.$name.'" type="radio" value="'.$radio[$field1].'" '.$checked.'/> '.$radio[$field2].'&nbsp;&nbsp;';
            }
        }
        return '
        <li>
            <label>'.$title.form::_must($must).'</label>
            <cite>
                '.$radio_html.'
            </cite>
        </li>';
    }
    
    public static function checkbox($title, $name, $must = 0, $options = array(), $vars = '', $value = array()){
        $checkbox_html = '';
        if ($options){
            foreach ($options as $checkbox){
                list($field1, $field2) = explode('::', $vars);
                $checked = in_array($checkbox[$field1], $value) ? 'checked' : '';
                $checkbox_html .= '<input name="'.$name.'[]" type="checkbox" value="'.$checkbox[$field1].'" '.$checked.'/> '.$checkbox[$field2].'&nbsp;&nbsp;';
            }
        }
        return '
        <li>
            <label>'.$title.form::_must($must).'</label>
            <cite>
                '.$checkbox_html.'
            </cite>
        </li>';
    }
    
    public static function onclick($form_name, $btn_name, $btn_value = '', $url = '', $jum = ''){
        $timer = 't'.$form_name;
        $int = 'i'.$form_name;
        $function = 'timer'.$form_name;
        $btn1 = $btn_value;
        $btn2 = $btn_value.'中';
        $btn3 = $btn_value.'成功';
        return '
        <script>
            var '.$timer.';
            var '.$int.' = 0;
            function '.$function.'(){
                '.$int.'++;
                if ('.$int.' === 4){
                    '.$int.' = 1;
                }
                var str = ["", ".", "..", "..."];
                $(".'.$btn_name.'").val("'.$btn2.' " + str['.$int.']);
            }
            $(function(){
                $(".'.$btn_name.'").click(function(){
                    $(".'.$btn_name.'").attr("disabled", "disabled");
                    $(".'.$btn_name.'").val("'.$btn2.' ");
                    '.$timer.' = setInterval('.$function.',1000);
                    $.post("'.$url.'", $("#'.$form_name.'").serializeArray(), function(ret){
                        console.log(ret);
                        if (ret == "ok"){
                            $(".'.$btn_name.'").val("'.$btn3.'");
                            setTimeout(function(){
                                location.href = "'.$jum.'";
                            }, 500);
                        }else{
                            alert(ret);
                            $(".'.$btn_name.'").val("'.$btn1.'");
                            $(".'.$btn_name.'").removeAttr("disabled");
                        }
                        clearInterval('.$timer.');
                    });
                });
            });
        </script>';
    }        
    
    # nonce
    
    public static function nonce($id, $action = -1, $name = '_nonce'){
        return '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . form::create_nonce( $id, $action ) . '" />';
    }
    
    public static function verify_nonce($id, $nonce, $action = -1){
	if ( empty( $nonce ) ) {
            return false;
	}
        
        $doo = Doo::session(Doo::conf()->SESSION_NAME);
        $token = $doo->ckrnd;
        
	$tick = ceil(time() / ( 86400 / 2 ));
        
        # one  0-12
        $str = $tick.'|'.$action.'|'.$id.'|'.$token;
        $hash = form::_hash_hmac('md5', $str, $action);
        $expected = substr($hash, -12, 10);
        if (form::_hash_equals($expected, $nonce)){
            return 1;
        }
        
        # two 12-24
        $str = ($tick - 1).'|'.$action.'|'.$id.'|'.$token;
        $hash = form::_hash_hmac('md5', $str, $action);
        $expected = substr($hash, -12, 10);
        if (form::_hash_equals($expected, $nonce)){
            return 2;
        }
        
        return false;
    }

    public static function create_nonce($id, $action){
        $doo = Doo::session(Doo::conf()->SESSION_NAME);
        $token = $doo->ckrnd;
        $tick = ceil(time() / ( 86400 / 2 ));
        $str = $tick.'|'.$action.'|'.$id.'|'.$token;
        $hash = form::_hash_hmac('md5', $str, $action);
        return substr($hash, -12, 10);
    }
    
    public static function _hash_hmac($algo, $data, $key, $raw_output = false) {
        $packs = array('md5' => 'H32', 'sha1' => 'H40');

        if ( !isset($packs[$algo]) ){
            return false;
        }

        $pack = $packs[$algo];

        if (strlen($key) > 64){
            $key = pack($pack, $algo($key));
        }

        $key = str_pad($key, 64, chr(0));

        $ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64));
        $opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64));

        $hmac = $algo($opad . pack($pack, $algo($ipad . $data)));

        if ( $raw_output ){
            return pack( $pack, $hmac );
        }
        return $hmac;	
    }
    
    public static function _hash_equals( $a, $b ) {
        $a_length = strlen( $a );
        if ( $a_length !== strlen( $b ) ) {
            return false;
        }
        $result = 0;

        for ( $i = 0; $i < $a_length; $i++ ) {
            $result |= ord( $a[ $i ] ) ^ ord( $b[ $i ] );
        }

        return $result === 0;
    }
    
    # tip
    
    public static function alert($class, $base_url, $id = '_id'){
        return '<div class="tip '.$class.'">
            <input type="hidden" id="'.$id.'" value="0" />
            <div class="tiptop"><span>提示信息</span><a onclick="_alert_hide(\''.$class.'\');"></a></div>
            <div class="tipinfo">
                <span><img src="'.$base_url.'static/images/ticon.png" /></span>
                <div class="tipright">
                    <p>是否确认对信息的修改 ？</p>
                    <cite>如果是请点击确定按钮 ，否则请点取消。</cite>
                </div>
            </div>
            <div class="tipbtn">
                <input type="button" class="sure" value="确定" onclick="_'.$class.'();"/>&nbsp;
                <input type="button" class="cancel" value="取消" onclick="_alert_hide(\''.$class.'\');"/>
            </div>
        </div>';
    }
    
    public static function alert_confirm($class, $post, $nonce, $id = '_id'){
        return '<script>function _'.$class.'(){
                var _id = $("#'.$id.'").val();
                $(".'.$class.' .sure").val("提交中");
                $(".'.$class.' .sure").attr("disabled", "disabled");
                $.post("'.$post.'", {
                    id: _id,
                    _nonce: "'.$nonce.'"
                }, function(ret){
                    console.log(ret);
                    if (ret == "ok"){
                        _alert_hide();
                        setTimeout(function(){
                            location.reload();
                        }, 500);
                    }else{
                        alert(ret);
                        $(".'.$class.' .sure").val("确定");
                        $(".'.$class.' .sure").removeAttr("disabled");
                    }
                });
            }</script>';
    }
}