<?php
    
class attr_file_private extends attr {
    function getDBType() {
    	return "int(12)";
    }

    function render_input() {
    	
		$html = '<input class="input" type="file" name="' . $this->attr_name . '">';    	
		$html .= '<input class="input" type="hidden" name="' . $this->attr_name . '" value="1">';    	
		if ( $this->getCurVal() ) {
			$html .= '<br><label><input class="checkbox" type="checkbox" name="' . $this->attr_name . '_del" value="1"> Удалить</label>';    	
		}
		return $html;
    }
    
  function lPost() {
    	$tmpObj = new cobject( '_sys_files' );
    	$file = $_FILES[$this->attr_name];

    	$fileContent = file_get_contents($file['tmp_name']);
    	$fname = md5($fileContent);

        $fpath = substr($fname,0,2);
        $fpath2 = substr($fname,2,2);
        @mkdir( _FILES_DIR_ . $fpath . '/' . $fpath2, 0777, true );
        $fname = $fpath .'/' . $fpath2 . '/' . $fname;


    	
    	if ($_POST[$this->attr_name . '_del']) {
	    	$this->obj->set( $this->attr_name, 0 );
    	}

    	if (!$file['error']) {
	    	if ( move_uploaded_file( $file['tmp_name'], _FILES_DIR_.$fname ) ) {
		    	$tmpObj->set('filename', $fname );
		    	$tmpObj->set('realname', $file['name'] );
		    	$tmpObj->set('ext', $file['type'] );
		    	$tmpObj->set('private', 1 );
		    	$tmpObj->save();
		    	$this->obj->set( $this->attr_name, $tmpObj->id );
	    	} else {
	    		die('Error: проверьте права на сохранение в ' . _FILES_DIR_ . $fpath . '/' . $fpath2);
	    	}
    	}
    }

    function render_text( $crop = false ) {
    	if ($crop) {
    		$val = '<a href="file.php?id='.$this->getCurVal().'">Скачать</a>';	
    	} else {
    		$val = $this->getCurVal();
    	}
    	return $val;
    }


}

?>