<?php

/**
 *      【橙创家校通v4.0】 (C)2010-2012 Tuntron Inc.
 *      
 *    	 http://www.tuntron.com   QQ：1121251729
 *
 *      &科目基类文件&
 */

if (!defined('IS_RUN')) die('Forbidden');

class tj_subject extends tj_model {

	var $table = 'dbpre_subject';
    var $key = 'fileid';

	function __construct() {
		parent::__construct();
		$this->init_field();
	}

    function msm_fileouncement() {
        $this->__construct();
    }

	function init_field() {
		$this->add_field('fileid,type,filename,fid,fileurl,subjectize,down_count,author,addtime');
		$this->add_field_fun('fileid,fid,subjectize,down_count,addtime', 'intval');
		$this->add_field_fun('type,fileurl', 'trim');
        $this->add_field_fun('filename,author', '_T');
	}

	function read_all($type=null) {
        $this->db->from($this->table);
        if($type) {
            $this->db->where('fid', $type);
        }
		$this->db->order_by('addtime','DESC');//必须为大写DESC或ASC
        $this->db->select('fileid,type,filename,fid,fileurl,subjectize,down_count,author,addtime');
        return $this->db->fetch_all_assoc();
    }
	
	function read_one($fileid) {
        $this->db->from($this->table);
        $this->db->where('fileid', $fileid);
        $this->db->select('fileid,type,filename,fid,fileurl,subjectize,down_count,author,addtime');
        return $this->db->once_fetch_assoc();
    }
	
	
	
    function save(& $post, $fileid=NULL, $cache=TRUE) {
        if(!$post['filename']) Note('文件名称不能为空！');
        if(!$fileid) {
			global $_CO;
			$this->check_post($post);
            $post['author'] = $_CO['username'];
            $post['addtime'] = $this->global['timestamp'];
        }
        return parent::save($post, $fileid, $cache, FALSE);
    }

    function update($post) {
        if(!is_array($post)) Note('global_op_unselect');
        foreach($post as $fileid => $val) {
            $val['fileid'] = (int) $val['fileid'];
            $this->db->from($this->table);
            $this->db->set($val);
            $this->db->where('fileid',$fileid);
            $this->db->update();
        }
    }
	
	// 增加下载统计次数
    function down_num_add($fileid, $num=1) {
        $this->db->from($this->table);
        $this->db->set_add('down_count', $num);
        $this->db->where('fileid', $fileid);
        $this->db->update();
    }
	
	function delfile($fileid) {
		
		$fileurl = $this->read_one($fileid);
		
        $this->db->where('fileid', $fileid);  
		
		$this->db->from($this->table);     

        $this->db->delete();
		
		@unlink(TUNTRON_PATH.$fileurl['fileurl']);
		
        
    }

    function check_post($post,$is_edit=false) {
        if(!$post['type']) Note('文件类型不能为空！');
		if(!$post['fid']) Note('该文件所属文件夹不存在！');
	    if(!$post['fileurl']) Note('文件下载地址不能为空！');
		if(!$post['subjectize']) Note('文件大小不能为0！');
    }
}
?>