View file modules/downloads/controllers/downloads.php

File size: 8.3Kb
<?php
/**
 * Ant0ha's project
 *
 * @package
 * @author Anton Pisarenko <[email protected]>
 * @copyright Copyright (c) 2006 - 2010, Anton Pisarenko
 * @license http://ant0ha.ru/license.txt
 * @link http://ant0ha.ru
 */

//---------------------------------------------


/**
 * Контроллер пользовательской части загруз центра
 */
class Downloads_Controller extends Controller {
	/**
	* Construct
	*/
	public function __construct() {
		parent::__construct();
		if(@$_GET['preview'] > 10 && @$_GET['preview'] <= 200) $_SESSION['downloads_preview'] = intval($_GET['preview']);
		define('DOWNLOADS_DIRECTORY', 'files/downloads/');
		# Хелпер загрузок
		a_import('modules/downloads/helpers/downloads');
		# Максимальный размер файла для скачивания через force_download
		define('FORCE_DOWNLOAD_MAX_FILESIZE', 8 * 1024 * 1024);
	}

	/**
	* Метод по умолчанию
	*/
	public function action_index() {
		$this->action_list_files();
	}

	/**
	* Выбор превьюшек
	*/
	public function change_previews() {
		$this->tpl->display('preview');
		exit;
	}

	/**
	* Листинг файлов
	*/
	public function action_list_files() {
		if(!isset($_SESSION['downloads_preview'])) $_SESSION['downloads_preview'] = 60;

      	if(empty($_GET['directory_id']) OR !is_numeric($_GET['directory_id'])) $directory_id = 0;
      	else $directory_id = intval($_GET['directory_id']);

      	if($directory_id != 0 && !$directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '$directory_id'")) {
      		a_error('Папка не найдена!');
      	}
        else {
            # Определяем папка с файлами или папками
            if($this->db->get_one("SELECT file_id FROM #__downloads_files WHERE directory_id = $directory_id")) {
                $files_directory = TRUE;
                $this->per_page = $this->config['downloads']['files_per_page'];
            }
            else {
                $files_directory = FALSE;
                $this->per_page = $this->config['downloads']['directories_per_page'];
            }
        }

        if($directory['images'] == 'yes' && !isset($_GET['preview']) && !isset($_GET['start'])) {
        	$this->change_previews();
        }

      	$directory_path = downloads::get_path($directory_id, $this->db);
		$namepath = downloads::get_namepath($directory_path, ' » ');

      	# Получаем список папок и файлов
        $sql  = "SELECT SQL_CALC_FOUND_ROWS directory_id AS file_id, name, (SELECT 'directory') AS type, (SELECT 'directory') AS file_ext,
                    (SELECT COUNT(*) FROM #__downloads_files AS df WHERE df.path_to_file LIKE CONCAT('%/', dd.directory_id, '/%') AND df.status != 'moderate' AND real_name != '') AS count_files,
                    (SELECT COUNT(*) FROM #__downloads_files AS df WHERE df.path_to_file LIKE CONCAT('%/', dd.directory_id, '/%') AND df.status != 'moderate' AND real_name != '' AND time > UNIX_TIMESTAMP() - 24 * 3600) AS new_day,
                    (SELECT 0) AS real_name,
                    (SELECT 0) AS filesize,
                    (SELECT 0) AS time,
                    (SELECT 0) AS path_to_file,
                    (SELECT 0) AS downloads,
                    (SELECT 0) AS screen1,
                    (SELECT 0) AS about,
                    (SELECT 0) AS previews,
                    position
                    FROM #__downloads_directories AS dd WHERE parent_id = '$directory_id'\n";
        $sql .= "UNION ALL\n";
        $sql .= "SELECT file_id, name, (SELECT 'file') AS type, file_ext,
                    (SELECT 0) AS count_files,
                    (SELECT 0) AS new_day,
                    real_name,
                    filesize,
                    time,
                    path_to_file,
                    downloads,
                    screen1,
                    about,
                    previews,
                    (SELECT 0) AS position
                    FROM #__downloads_files
                    WHERE
                    directory_id = '$directory_id' AND
                    status = 'active' AND
                    real_name != ''\n";

        $sql .= "ORDER BY type ASC, ";

        # Сортировка
        if($files_directory) {
            switch(@$_SESSION['sort']) {
	            case 'name':
	            	$sql .= "name ASC ";
	            break;
	            case 'downloads':
	            	$sql .= "downloads DESC ";
	            break;
	            default:
	            	$sql .= "time DESC ";
	            break;
            }
        }
        else $sql .= "position ASC ";

        $sql .= " LIMIT $this->start, $this->per_page";

        $files = $this->db->get_array($sql);
        $total = $this->db->get_one("SELECT FOUND_ROWS()");

        # Пагинация
        $pg_conf['base_url'] = a_url('downloads/list_files', 'directory_id='. intval(@$_GET['directory_id']) .'&amp;start=');
        $pg_conf['total_rows'] = $total;
        $pg_conf['per_page'] = $this->per_page;

        a_import('libraries/pagination');
        $pg = new CI_Pagination($pg_conf);

        $this->tpl->assign(array(
        	'files' => $files,
        	'total' => $total,
        	'namepath' => $namepath,
			'pagination' => $pg->create_links(),
			'directory' => @$directory
        ));

        $this->tpl->display('list_files');
	}

	/**
	* Скачивание файла
	*/
	public function action_download_file() {
		$file = $_GET['file'];
        preg_match('#([0-9]*)_#', $file, $matches);
        $file_id = $matches[1];

        if(!$file = $this->db->get_row("SELECT * FROM #__downloads_files WHERE file_id = '$file_id'"))
                a_error('Файл не найден!');

        # Обновляем количество закачек файла
        $this->db->query("UPDATE #__downloads_files SET downloads = downloads + 1 WHERE file_id = '$file_id'");

        if(!file_exists(ROOT . $file['path_to_file'] .'/'. $file['real_name']))
        	a_error('Файл отсутствует!');

        if($file['filesize'] > FORCE_DOWNLOAD_MAX_FILESIZE) {
        	header('location: '. URL . $file['path_to_file'] .'/'. $file['real_name']);
        	exit;
        }
        else {
        	$file_content = file_get_contents(ROOT . $file['path_to_file'] .'/'. $file['real_name']);
			downloads::force_download($file['real_name'], $file_content, $file_id .'_'. $CONFIG['downloads_prefix'] .'_', FALSE);
		}
	}

	/**
	* Получение jad из jar
	*/
	public function action_get_jad() {
		if(!$file = $this->db->get_row("SELECT * FROM #__downloads_files WHERE file_id = '". intval($_GET['file_id']) ."'"))
    		a_error("Файл не найден!");

    	if($file['file_ext'] != 'jar') a_error("Это не JAR файл!");

    	if(!class_exists('PclZip')) a_import('libraries/pclzip.lib');
    	a_import('libraries/j2me_tools');

        $jar_path = ROOT . $file['path_to_file'] .'/'. $file['real_name'];
        $jar_url = URL . $file['path_to_file'] .'/'. $file['real_name'];
        $jad_contents = j2me_tools::get_jad($jar_path, $jar_url);

        header('Content-type: text/vnd.sun.j2me.app-descriptor;charset=UTF-8');
        echo $jad_contents;
	}

	/**
	* Просмотр деталей файла
	*/
	public function action_view_file() {
		# Инфо о файле
		if(!$file = $this->db->get_row("SELECT *,
		 	(SELECT username FROM #__users AS u WHERE u.user_id = df.user_id) AS username,
		 	(SELECT COUNT(*) FROM #__comments_posts WHERE module = 'downloads' AND item_id = df.file_id) comments
		 	FROM #__downloads_files AS df WHERE df.file_id = '". intval($_GET['file_id']) ."'"))
			a_error('Файл не найден!');

		$directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '". $file['directory_id'] ."'");

		$directory_path = downloads::get_path($file['directory_id'], $this->db);
		$namepath = downloads::get_namepath($directory_path, ' &raquo; ');

        $this->tpl->assign(array(
        	'file' => $file,
        	'directory' => $directory,
        	'namepath' => $namepath
        ));

        $this->tpl->display('view_file');
	}
}
?>