Просмотр файла modules/downloads/controllers/downloads.php

Размер файла: 12.32Kb
<?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');
	}

	/**
	* Выгрузка файла пользователя
	*/
	public function action_add_file() {
    	if(USER_ID == -1) a_notice('Гости не имеют права загружать файлы', a_url('user/login'));

    	if(!$directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '". intval($_GET['directory_id']) ."' AND user_files = 'yes'"))
        	a_error('Папка не найдена, либо она не предназначена для загрузки файлов в неё');

        if(isset($_POST['submit'])) {
        	$file = array();

        	if(!empty($_FILES['file_upload']['tmp_name'])) {
        		$type = 'upload';
        		$file['real_name'] = $_FILES['file_upload']['name'];
        		$file['file_ext'] = array_pop(explode('.', $file['real_name']));
        		$file['filesize'] = filesize($_FILES['file_upload']['tmp_name']);
        	}
        	elseif(!empty($_POST['file_import']) && $_POST['file_import'] != 'http://') {
        		$type = 'import';
        		$file['real_name'] = basename($_POST['file_import']);
        		$file['file_ext'] = array_pop(explode('.', $file['real_name']));
        		$file['filesize'] = downloads::get_filesize($_POST['file_import']);
        	}
        	else $this->error = 'Укажите загружаемый файл<br />!';

        	if(!strstr(';'. $this->config['downloads']['allowed_filetypes'] .';', ';'. $file['file_ext'] .';'))
        		$this->error .= 'Вы пытаетесь загрузить запрещенный тип файла<br />';

			if(($file['filesize'] > $this->config['downloads']['max_filesize'] * 1048576) || $file['filesize'] === false)
				$this->error .= 'Размер загружаемого файла превышает допустимый размер ('. $this->config['downloads']['max_filesize'] .' Mb)<br />';

        	if(!$this->error) {
            	# Получаем ID файла
				$this->db->query("INSERT INTO #__downloads_files SET file_id = 'NULL'");
				$file_id = $this->db->insert_id();

				$directory_path = downloads::get_path($directory['directory_id'], &$this->db);
		   		$realpath = downloads::get_realpath($directory_path);
				$realpath = ($realpath != '' ? $realpath . '/' :  '') . ($directory['directory_id'] == 0 ? '' : $directory['directory_id'] . '/');

				# Создаем папку для файла
				mkdir(ROOT . DOWNLOADS_DIRECTORY . $realpath . $file_id);
   				chmod(ROOT . DOWNLOADS_DIRECTORY . $realpath . $file_id, 0777);

   				$path_to_file = DOWNLOADS_DIRECTORY . ($realpath != '' ? $realpath : '') . $file_id;

   				if($type == 'upload') {
   					$file_path = ROOT . $path_to_file .'/'. $_FILES['file_upload']['name'];
               		copy($_FILES['file_upload']['tmp_name'], $file_path);
               	}
               	else {
               		$file_path = ROOT . $path_to_file .'/'. basename($_POST['file_import']);
               		copy($_POST['file_import'], $file_path);
               	}

				$file['name'] = $_POST['name'];
				$file['about'] = $_POST['about'];
                $file['status'] = 'moderate';
                $file['user_id'] = USER_ID;
				$file['path_to_file'] = $path_to_file;
				$file['directory_id'] = $directory['directory_id'];

				# Выполняем действия над определенными типами файлов
				$file = downloads::filetype_actions($file);

               	# Изменяем файл в базе
                downloads::update_file(&$this->db, $file_id, $file);

                a_notice('Файл успешно загружен, он будет доступен для скачивания другими пользователями после прохождения модерации', URL .'downloads/'. $directory['directory_id']);
        	}
        }
        if(!isset($_POST['submit']) OR $this->error) {
         	$this->tpl->assign(array(
         		'error' => $this->error
         	));

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