<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class ModDownload extends Module {
    protected $_filters = array(
        'check_login' => '{fullist}{download}{recentdownloads}'
    );


    public function fullist() {
        $this->_layout = 'frontpage';

        /* the default download category */
        $curr_download_category = new DownloadCategory();
        $curr_download_category->name = __('Downloads');

        $cad_id = trim(ParamHolder::get('cad_id', '0'));
        // No category
        $cad_id = '0';
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        $curr_locale = trim(SessionHolder::get('_LOCALE'));

        $search_where = '';
        $search_params = array();
        $download_keyword = trim(ParamHolder::get('download_keyword', ''));
        if (strlen($download_keyword) > 0) {
            $search_where = ' AND (name LIKE ? OR description LIKE ?)';
            $search_params = array('%'.$download_keyword.'%', '%'.$download_keyword.'%');
            $this->assign('download_keyword', $download_keyword);
        }
        if (intval($cad_id) > 1) {
            $search_where .= ' AND download_category_id=?';
            $search_params = array_merge($search_params, array($cad_id));
            $curr_download_category = new DownloadCategory($cad_id);
        }
        try {
            $now = time();
            $o_download = new Download();
            /**
             * Add 02/08/2010
             */
            include_once(P_LIB.'/pager.php');
            
            if ($user_role == '{admin}') {
                $download_data =&
                    Pager::pageByObject('download',
                        "((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND s_locale=?".$search_where,
                        array_merge(array($now, $now, $now, $now, $curr_locale), $search_params),
                        "ORDER BY `create_time` DESC");
            } else {
                $download_data =&
                    Pager::pageByObject('download',
                        "((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND for_roles LIKE ? AND s_locale=?".$search_where,
                        array_merge(array($now, $now, $now, $now, '%'.$user_role.'%', $curr_locale), $search_params),
                        "ORDER BY `create_time` DESC");
            }

           $this->assign('page_title', $curr_download_category->name);

            $this->assign('downloads', $download_data['data']);
            $this->assign('pager', $download_data['pager']);
            $this->assign('category', $curr_download_category);
            $this->assign('download_keyword', $download_keyword);
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }

    }

    public function recentdownloads() {
        $list_size = trim(ParamHolder::get('down_reclst_size'));
        if (!is_numeric($list_size) || strlen($list_size) == 0) {
            $list_size = '5';
        }
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        $o_download = new Download();
        if ($user_role == '{admin}') {
                $downloads = $o_download->findAll("published='1' AND s_locale=? ", array($curr_locale),
                            "ORDER BY `create_time` DESC LIMIT ".$list_size);
        } else {
                $downloads = $o_download->findAll("published='1' AND s_locale=? AND for_roles LIKE ? ", array($curr_locale, '%'.$user_role.'%'),
                            "ORDER BY `create_time` DESC LIMIT ".$list_size);
        }

        $this->assign('downloads', $downloads);
    }
    
    public function download() {
        $this->_layout = 'null';
        $file_name = ParamHolder::get('file_name', '0');
        $dw_id = ParamHolder::get('dw_id', '0');
        if (intval($dw_id) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
            return '_error';
        }
        $curr_locale = trim(SessionHolder::get('_LOCALE'));
        $user_role = trim(SessionHolder::get('user/s_role', '{guest}'));
        try {
        	$now = time();
            $o_dw = new Download();
            if ($user_role != '{admin}') {
                $curr_dw =& $o_dw->find("`id`=? AND "
                            ."((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND for_roles LIKE ? AND s_locale=?",
                        array($dw_id, $now, $now, $now, $now, '%'.$user_role.'%', $curr_locale));
            } else {
                $curr_dw =& $o_dw->find("`id`=? AND "
                            ."((`pub_start_time`<? AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`<? AND `pub_end_time`='-1') OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`>=?) OR "
                            ."(`pub_start_time`='-1' AND `pub_end_time`='-1')) AND "
                            ."published='1' AND s_locale=?",
                        array($dw_id, $now, $now, $now, $now, $curr_locale));
            }
            if(sizeof($curr_dw) <= 0) {
                $this->assign('json', Toolkit::jsonERR(__('Invalid ID!')));
                return '_error';
            }
        } catch (Exception $ex) {
            $this->assign('json', Toolkit::jsonERR($ex->getMessage()));
            return '_error';
        }
        if (!file_exists(ROOT.'/upload/file/'.$curr_dw->name)) {
            $this->assign('json', Toolkit::jsonERR(__('File does not exist!')));
            return '_error';
        }
		include_once P_LIB."/download.php";
		$o_filedownload = new file_download();
		$o_filedownload->downloadfile(ROOT.'/upload/file/'.$curr_dw->name);
        //$this->file_download(ROOT.'/upload/file/'.$curr_dw->name);
    }

    private function file_download($file_path) {
		$path_parts = pathinfo($file_path);
		$file_dir = $path_parts["dirname"].'/';
		$file_name = $path_parts["basename"];
		$file_ext = $path_parts["extension"];
		$file = fopen($file_dir.$file_name,"r");
		header( "Pragma: public" );
		header( "Expires: 0" );
		header( "Cache-Component: must-revalidate, post-check=0, pre-check=0" );
		header( "Content-type:application/octet-stream");
		header( "Content-Length: " . filesize($file_name));
		header( "Content-Disposition: attachment; filename=$file_name" );
		header( 'Content-Transfer-Encoding: binary' );
		readfile($file_dir.$file_name);
}

}
?>
