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

Размер файла: 37.97Kb
  1. <?php
  2.  
  3. /**
  4. * MobileCMS
  5. *
  6. * Open source content management system for mobile sites
  7. *
  8. * @author MobileCMS Team <support@mobilecms.pro>
  9. * @copyright Copyright (c) 2011-2019, MobileCMS Team
  10. * @link https://mobilecms.pro Official site
  11. * @license MIT license
  12. */
  13. // Папка с файлами загрузок
  14. define('DOWNLOADS_DIRECTORY', 'files/downloads/');
  15. // Максимальный размер файла для скачивания через force_download
  16. define('FORCE_DOWNLOAD_MAX_FILESIZE', 0);
  17.  
  18. /**
  19. * Контроллер пользовательской части загруз-центра
  20. */
  21. class Downloads_Controller extends Controller {
  22.  
  23. /**
  24. * Construct
  25. */
  26. public function __construct() {
  27. parent::__construct();
  28. if (isset($_GET['preview'])) {
  29. if ($_GET['preview'] == 0 || $_GET['preview'] == 20 || $_GET['preview'] == 60 || $_GET['preview'] == 100)
  30. $_SESSION['downloads_preview'] = $_GET['preview'];
  31. }
  32. if (isset($_GET['order_by'])) {
  33. if ($_GET['order_by'] == 'name' || $_GET['order_by'] == 'time' || $_GET['order_by'] == 'downloads')
  34. $_SESSION['order_by'] = $_GET['order_by'];
  35. }
  36. # Хелпер загрузок
  37. a_import('modules/downloads/helpers/downloads');
  38. }
  39.  
  40. /**
  41. * Метод по умолчанию
  42. */
  43. public function action_index() {
  44. $this->action_list_files();
  45. }
  46.  
  47. /**
  48. * Выбор превьюшек
  49. */
  50. public function change_previews() {
  51. $this->tpl->display('preview');
  52. exit;
  53. }
  54.  
  55. /**
  56. * Листинг файлов
  57. */
  58. public function action_list_files() {
  59. if (!isset($_SESSION['downloads_preview']))
  60. $_SESSION['downloads_preview'] = 60;
  61.  
  62. if (empty($_GET['directory_id']) OR ! is_numeric($_GET['directory_id'])) {
  63. $directory_id = 0;
  64. } else {
  65. $directory_id = intval($_GET['directory_id']);
  66. if (!$directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '$directory_id'")) {
  67. a_error('Папка не найдена!');
  68. }
  69. }
  70.  
  71. switch ($_GET['action']) {
  72. # Поиск файлов
  73. case 'search':
  74. $action = 'search';
  75. $title = 'Результаты поиска';
  76. $sql = "SELECT SQL_CALC_FOUND_ROWS
  77. file_id,
  78. name,
  79. 'file' AS type,
  80. file_ext,
  81. 0 AS count_files,
  82. 0 AS new_day,
  83. real_name,
  84. filesize,
  85. time,
  86. path_to_file,
  87. downloads,
  88. screen1,
  89. about,
  90. previews,
  91. (SELECT 0) AS position
  92. FROM #__downloads_files
  93. WHERE status = 'active' AND
  94. name LIKE '%" . a_safe($_GET['search_word']) . "%' ";
  95.  
  96. if ($directory_id != 0)
  97. $sql .= " AND path_to_file LIKE '%/" . $directory_id . "/%' ";
  98. if (empty($_GET['search_word']))
  99. $sql .= " AND 1 = 0 ";
  100.  
  101. $sql .= " LIMIT $this->start, $this->per_page";
  102. break;
  103.  
  104. # Список новых файлов
  105. case 'new_files':
  106. $action = 'new_files';
  107. $title = 'Новые файлы';
  108. $sql = "SELECT SQL_CALC_FOUND_ROWS
  109. file_id,
  110. name,
  111. 'file' AS type,
  112. file_ext,
  113. 0 AS count_files,
  114. 0 AS new_day,
  115. real_name,
  116. filesize,
  117. time,
  118. path_to_file,
  119. downloads,
  120. screen1,
  121. about,
  122. previews,
  123. (SELECT 0) AS position
  124. FROM #__downloads_files
  125. WHERE status = 'active' AND 1 = 1 ";
  126.  
  127. if ($directory_id != 0)
  128. $sql .= " AND path_to_file LIKE '%/" . $directory_id . "/%' ";
  129.  
  130. $sql .= " ORDER BY time DESC ";
  131. $sql .= " LIMIT $this->start, $this->per_page";
  132. break;
  133.  
  134. # Список папок и файлов
  135. default:
  136. $action = 'list';
  137. $title = 'Загрузки' . (!empty($directory['name']) ? ' | ' . $directory['name'] : '');
  138. # Определяем папка с файлами или папками
  139. if ($this->db->get_one("SELECT file_id FROM #__downloads_files WHERE directory_id = $directory_id AND real_name != ''")) {
  140. $is_files_directory = true;
  141. $this->per_page = $this->config['downloads']['files_per_page'];
  142. } else {
  143. $is_files_directory = false;
  144. $this->per_page = $this->config['downloads']['directories_per_page'];
  145. }
  146.  
  147. $this->tpl->assign('is_files_directory', $is_files_directory);
  148.  
  149. if ($directory['images'] == 'yes' && !isset($_GET['preview']) && !isset($_GET['start'])) {
  150. $this->change_previews();
  151. }
  152.  
  153. $directory_path = downloads::get_path($directory_id, $this->db);
  154. $namepath = downloads::get_namepath($directory_path, ' » ');
  155.  
  156.  
  157. # Получаем список папок и файлов
  158. $sql = "SELECT SQL_CALC_FOUND_ROWS
  159. dd.directory_id AS file_id,
  160. dd.name,
  161. 'directory' AS type,
  162. 'directory' AS file_ext,
  163. 0 AS real_name,
  164. 0 AS filesize,
  165. 0 AS time,
  166. 0 AS path_to_file,
  167. 0 AS downloads,
  168. 0 AS screen1,
  169. 0 AS about,
  170. 0 AS previews,
  171. dd.position
  172. FROM #__downloads_directories AS dd
  173. WHERE dd.parent_id = '$directory_id'" . PHP_EOL;
  174. $sql .= "UNION ALL" . PHP_EOL;
  175. $sql .= "SELECT
  176. file_id,
  177. name,
  178. 'file' AS type,
  179. file_ext,
  180. real_name,
  181. filesize,
  182. time,
  183. path_to_file,
  184. downloads,
  185. screen1,
  186. about,
  187. previews,
  188. (SELECT 0) AS position
  189. FROM #__downloads_files
  190. WHERE
  191. directory_id = '$directory_id' AND
  192. status = 'active' AND
  193. real_name != ''" . PHP_EOL;
  194.  
  195. $sql .= "ORDER BY type ASC, ";
  196.  
  197. # Сортировка
  198. if ($is_files_directory) {
  199. switch ($_SESSION['order_by']) {
  200. case 'name':
  201. $sql .= "name ASC ";
  202. break;
  203. case 'downloads':
  204. $sql .= "downloads DESC ";
  205. break;
  206. default:
  207. $sql .= "time DESC ";
  208. break;
  209. }
  210. } else {
  211. $sql .= "position ASC ";
  212. }
  213.  
  214. $sql .= " LIMIT $this->start, $this->per_page";
  215. break;
  216. }
  217.  
  218. # Работаем с кешем
  219. if ($action == 'list' && !$is_files_directory && $this->config['downloads']['cache_time'] > 0) {
  220. $using_cache = true;
  221.  
  222. $cache_key = 'downloads_' . $directory_id . '_' . $this->start;
  223. $files = $this->cache->get($cache_key, $this->config['downloads']['cache_time'] * 60);
  224. }
  225.  
  226. if (empty($files)) {
  227. $result = $this->db->query($sql);
  228. $total = $this->db->get_one("SELECT FOUND_ROWS()");
  229.  
  230. $files = array();
  231. while ($file = $this->db->fetch_array($result)) {
  232. # Получаем счетчики файлов в папках
  233. if ($file['type'] == 'directory') {
  234. $counts = $this->db->get_row("SELECT
  235. COUNT(CASE WHEN status = 'active' THEN 1 END) AS count_files,
  236. COUNT(CASE WHEN time > UNIX_TIMESTAMP( ) - 86400 THEN 1 END) AS new_day
  237. FROM #__downloads_files
  238. WHERE path_to_file LIKE '%/" . $file['file_id'] . "/%'
  239. ");
  240.  
  241. $file['count_files'] = $counts['count_files'];
  242. $file['new_day'] = $counts['new_day'];
  243. }
  244.  
  245. $files[] = $file;
  246. }
  247.  
  248. $files['total'] = $total;
  249.  
  250. if ($using_cache)
  251. $this->cache->set($cache_key, $files);
  252. }
  253.  
  254. # Пагинация
  255. $http_query = http_build_query(array(
  256. 'directory_id' => $_GET['directory_id'],
  257. 'action' => $_GET['action'],
  258. 'search_word' => $_GET['search_word']
  259. ), '', '&amp;');
  260.  
  261. $pg_conf['base_url'] = $_GET['directory_id'] == 0 ? a_url('downloads/list_files', $http_query . '&amp;start=', true) : a_url('downloads/list_files', $http_query . '&amp;start=');
  262. $pg_conf['total_rows'] = $files['total'];
  263. $pg_conf['per_page'] = $this->per_page;
  264.  
  265. a_import('libraries/pagination');
  266. $pg = new CI_Pagination($pg_conf);
  267.  
  268. # Удаляем лишние данные
  269. unset($files['total']);
  270.  
  271. $this->tpl->assign(array(
  272. 'files' => $files,
  273. 'total' => $total,
  274. 'action' => $action,
  275. 'title' => $title,
  276. 'navigation' => $namepath,
  277. 'pagination' => $pg->create_links(),
  278. 'directory' => $directory,
  279. '_config' => $this->config['downloads'],
  280. ));
  281.  
  282. $this->tpl->display('list_files');
  283. }
  284.  
  285. /**
  286. * Форма поиска
  287. */
  288. public function action_search_form() {
  289. if (empty($_GET['directory_id']) || !is_numeric($_GET['directory_id'])) {
  290. $directory_id = 0;
  291. } else {
  292. $directory_id = intval($_GET['directory_id']);
  293.  
  294. if (!$directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '$directory_id'"))
  295. a_error('Папка не найдена');
  296. }
  297.  
  298. $directory_path = downloads::get_path($directory['directory_id'], $this->db);
  299. $navigation = downloads::get_namepath($directory_path, ' &raquo; ');
  300.  
  301. if ($directory['directory_id'] > 0)
  302. $navigation .= (!empty($navigation) ? ' &raquo; ' : '') . '<a href="' . URL . 'downloads/' . $directory['directory_id'] . '">' . $directory['name'] . '</a>';
  303.  
  304. if ($_GET['send']) {
  305. if (empty($_GET['search_word']))
  306. $this->error .= 'Укажите запрос<br />';
  307.  
  308. if (!$this->error) {
  309. header('Location: ' . a_url('downloads/list_files', 'action=search&directory_id=' . ($directory_id > 0 ? $directory_id : '') . '&search_word=' . urlencode($_GET['search_word'])));
  310. exit;
  311. }
  312. }
  313.  
  314. $this->tpl->assign(array(
  315. 'error' => $this->error,
  316. 'directory' => $directory,
  317. 'directory_id' => $directory_id,
  318. 'navigation' => $navigation,
  319. ));
  320.  
  321. $this->tpl->display('search_form');
  322. }
  323.  
  324. /**
  325. * Скачивание файла
  326. */
  327. public function action_download_file() {
  328. $file_id = intval($_GET['file_id']);
  329.  
  330. if (!$file = $this->db->get_row("SELECT * FROM #__downloads_files WHERE file_id = '$file_id'"))
  331. a_error('Файл не найден!');
  332.  
  333. # Обновляем количество закачек файла
  334. $this->db->query("UPDATE #__downloads_files SET downloads = downloads + 1 WHERE file_id = '$file_id'");
  335.  
  336. if (!file_exists(ROOT . $file['path_to_file'] . '/' . $file['real_name']))
  337. a_error('Файл отсутствует!');
  338.  
  339. if ($file['filesize'] > FORCE_DOWNLOAD_MAX_FILESIZE) {
  340. header('location: ' . URL . $file['path_to_file'] . '/' . $file['real_name']);
  341. exit;
  342. } else {
  343. $file_content = file_get_contents(ROOT . $file['path_to_file'] . '/' . $file['real_name']);
  344. downloads::force_download($file['real_name'], $file_content, $file_id . '_' . $CONFIG['downloads_prefix'] . '_', FALSE);
  345. }
  346. }
  347.  
  348. /**
  349. * Получение jad из jar
  350. */
  351. public function action_get_jad() {
  352. if (!$file = $this->db->get_row("SELECT * FROM #__downloads_files WHERE file_id = '" . intval($_GET['file_id']) . "'"))
  353. a_error("Файл не найден!");
  354.  
  355. if (is_numeric($_GET['add_file'])) {
  356. if (!empty($file['add_file_real_name_' . $_GET['add_file']])) {
  357. $jar_name = $file['add_file_real_name_' . $_GET['add_file']];
  358. $file_ext = array_pop(explode('.', $jar_name));
  359. } else
  360. a_error("Дополнительный файл не найтен!");
  361. } else {
  362. $jar_name = $file['real_name'];
  363. $file_ext = $file['file_ext'];
  364. }
  365.  
  366. if ($file_ext != 'jar')
  367. a_error("Это не JAR файл!");
  368.  
  369. # Увеличиваем количество скачиваний файла
  370. $this->db->query("UPDATE a_downloads_files SET downloads = downloads + 1 WHERE file_id = '" . $file['file_id'] . "'");
  371.  
  372. if (!class_exists('PclZip'))
  373. a_import('libraries/pclzip.lib');
  374. a_import('libraries/j2me_tools');
  375.  
  376. $jar_path = ROOT . $file['path_to_file'] . '/' . $jar_name;
  377. $jar_url = URL . $file['path_to_file'] . '/' . $jar_name;
  378. $jad_contents = j2me_tools::get_jad($jar_path, $jar_url);
  379.  
  380. header('Content-type: text/vnd.sun.j2me.app-descriptor;charset=UTF-8');
  381. echo $jad_contents;
  382. }
  383.  
  384. /**
  385. * Просмотр деталей файла
  386. */
  387. public function action_view_file() {
  388. # Инфо о файле
  389. if (!$file = $this->db->get_row("SELECT *,
  390. (SELECT username FROM #__users AS u WHERE u.user_id = df.user_id) AS username,
  391. (SELECT COUNT(*) FROM #__comments_posts WHERE module = 'downloads' AND item_id = df.file_id) comments
  392. FROM #__downloads_files AS df WHERE df.file_id = '" . intval($_GET['file_id']) . "'"))
  393. a_error('Файл не найден!');
  394.  
  395. $directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '" . $file['directory_id'] . "'");
  396. if ($this->db->get_one("SELECT id FROM a_rating_logs WHERE ip = '" . a_safe($_SERVER['REMOTE_ADDR']) . "' AND module = 'downloads' AND item_id = '" . $file['file_id'] . "'"))
  397. $file['rated'] = true;
  398. else
  399. $file['rated'] = false;
  400.  
  401. # Получаем скриншоты файла
  402. $file['screens'] = '';
  403. if (!empty($file['screen1']) && empty($_GET['s']))
  404. $file['screens'] .= '<img src="' . URL . $file['path_to_file'] . '/' . $file['screen1'] . '" alt="" /><br />';
  405. elseif (!empty($file['screen2']) && $_GET['s'] == 2)
  406. $file['screens'] .= '<img src="' . URL . $file['path_to_file'] . '/' . $file['screen2'] . '" alt="" /><br />';
  407. elseif (!empty($file['screen3']) && $_GET['s'] == 3)
  408. $file['screens'] .= '<img src="' . URL . $file['path_to_file'] . '/' . $file['screen3'] . '" alt="" /><br />';
  409.  
  410. if (!empty($file['screen2'])) {
  411. $file['screens'] .= empty($_GET['s']) ? '<b>1</b>' : '<a href="' . a_url('downloads/view_file', 'file_id=' . $file['file_id']) . '">1</a>';
  412. $file['screens'] .= ', ' . (($_GET['s'] == 2) ? '<b>2</b>' : '<a href="' . a_url('downloads/view_file', 'file_id=' . $file['file_id'] . '&amp;s=2') . '">2</a>');
  413. if (!empty($file['screen3']))
  414. $file['screens'] .= ', ' . (($_GET['s'] == 3) ? '<b>3</b>' : '<a href="' . a_url('downloads/view_file', 'file_id=' . $file['file_id'] . '&amp;s=3') . '">3</a>');
  415. }
  416.  
  417. if (!empty($file['screens']))
  418. $file['screens'] .= '<br /><br />';
  419.  
  420. $file['about'] = nl2br(main::bbcode($file['about']));
  421. $file['rating_stars'] = file_get_contents(URL . 'main/rating?rate=' . $file['rating']);
  422.  
  423. $directory_path = downloads::get_path($file['directory_id'], $this->db);
  424. $navigation = downloads::get_namepath($directory_path, ' » ');
  425.  
  426. if ($directory['directory_id'] > 0)
  427. $navigation .= (!empty($navigation) ? ' » ' : '') . '<a href="' . a_url('downloads', 'directory_id=' . $directory['directory_id']) . '">' . $directory['name'] . '</a>';
  428.  
  429. $this->tpl->assign(array(
  430. 'file' => $file,
  431. 'directory' => $directory,
  432. 'navigation' => $navigation
  433. ));
  434.  
  435. $this->tpl->display('view_file');
  436. }
  437.  
  438. /**
  439. * Изменение рейтинга файла
  440. */
  441. public function action_rating_change() {
  442. if (!$file = $this->db->get_row("SELECT file_id, user_id FROM a_downloads_files WHERE file_id = '" . intval($_GET['file_id']) . "'"))
  443. a_error("Файл не найден!");
  444.  
  445. if ($this->db->get_one("SELECT id FROM a_rating_logs WHERE module = 'downloads' AND ip = '" . a_safe($_SERVER['REMOTE_ADDR']) . "' AND item_id = '" . $file['file_id'] . "'"))
  446. a_error("Вы голосовали за данный файл ранее!");
  447.  
  448. if ($file['user_id'] == USER_ID)
  449. a_error("Голосовать за свой файл нельзя!");
  450.  
  451. $est = intval($_GET['est']);
  452. if ($est != 1 && $est != 2 && $est != 3 && $est != 4 && $est != 5)
  453. a_error("Оценка не определена!");
  454.  
  455. # Увеличиваем количество голосов
  456. $this->db->query("UPDATE a_downloads_files SET
  457. rating = (rating * rating_voices + $est) / (rating_voices + 1),
  458. rating_voices = rating_voices + 1
  459. WHERE file_id = '" . $file['file_id'] . "'
  460. ");
  461.  
  462. # Добавляем голос в логи
  463. $this->db->query("INSERT INTO a_rating_logs SET
  464. module = 'downloads',
  465. ip = '" . a_safe($_SERVER['REMOTE_ADDR']) . "',
  466. item_id = '" . $file['file_id'] . "',
  467. time = UNIX_TIMESTAMP()
  468. ");
  469.  
  470. a_notice("Оценка принята!", URL . 'downloads/view/' . $file['file_id']);
  471. }
  472.  
  473. /**
  474. * Управление файлами пользователей
  475. */
  476. public function action_user_files() {
  477. // Запрет выгрузки гостям
  478. if (USER_ID == -1)
  479. a_error('Для выгрузки файлов на сайт необходимо <a href="' . a_url('user/login') . '">войти</a> или <a href="' . a_url('user/registration') . '">зарегистрироваться</a>');
  480.  
  481. // Запрет выгрузки файлов пользователями
  482. if ($this->config['downloads']['user_upload'] == 0)
  483. a_error('Выгрузка файлов на сайт пользователями запрещена');
  484.  
  485. // Проверка действия
  486. if ($_GET['action'] != 'add' && $_GET['action'] != 'edit' && $_GET['action'] != 'delete')
  487. a_error('Не выбрано действие');
  488.  
  489. // Проверка директории
  490. if ($_GET['action'] == 'add' && !$directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '" . intval($_GET['directory_id']) . "' AND user_files = 'yes'"))
  491. a_error('Папка не найдена, либо не предназначена для выгрузки файлов пользователями в нее');
  492.  
  493. switch ($_GET['action']) {
  494. case 'add':
  495. $action = 'add';
  496. $title = 'Добавление файла';
  497.  
  498. $directory_path = downloads::get_path($directory['directory_id'], $this->db);
  499. $navigation = downloads::get_namepath($directory_path, ' &raquo; ');
  500.  
  501. if ($directory['directory_id'] > 0)
  502. $navigation .= (!empty($navigation) ? ' &raquo; ' : '') . '<a href="' . URL . 'downloads/' . $directory['directory_id'] . '">' . $directory['name'] . '</a>';
  503.  
  504. // Обработка формы выгрузки файла
  505. if ($_POST['submit']) {
  506. // Фильтрация данных
  507. $name = htmlspecialchars(trim($_POST['name']));
  508. $about = htmlspecialchars(trim($_POST['about']));
  509.  
  510. // Массивс информацией о файле
  511. $file = array();
  512.  
  513. // Проверка корректности данных
  514. if (!empty($name) && main::strlen($name) > 32)
  515. $this->error .= 'Имя файла не должно быть длинее 32 символов<br />';
  516.  
  517. if (!empty($about) && main::strlen($about) > 5000)
  518. $this->error .= 'Описание не должно быть длинее 5000 символов<br />';
  519.  
  520. // Получение информации о файле
  521. if (!empty($_FILES['file_upload']['tmp_name'])) {
  522. $type = 'upload';
  523. $file['real_name'] = $_FILES['file_upload']['name'];
  524. $file['file_ext'] = array_pop(explode('.', $file['real_name']));
  525. $file['filesize'] = filesize($_FILES['file_upload']['tmp_name']);
  526. } else if (!empty($_POST['file_import']) && $_POST['file_import'] != 'http://') {
  527. $type = 'import';
  528. $file['real_name'] = basename($_POST['file_import']);
  529. $file['file_ext'] = array_pop(explode('.', $file['real_name']));
  530. $file['filesize'] = downloads::get_filesize($_POST['file_import']);
  531. } else {
  532. $this->error = 'Укажите загружаемый файл<br />';
  533. }
  534.  
  535. // Проверка типа файла
  536. if (!strstr(';' . $this->config['downloads']['allowed_filetypes'] . ';', ';' . $file['file_ext'] . ';') && $type) {
  537. $this->error .= 'Вы пытаетесь загрузить запрещенный тип файла<br />';
  538. }
  539.  
  540. // Проверка размера файла
  541. if (($file['filesize'] > $this->config['downloads']['max_filesize'] * 1048576) || $file['filesize'] === FALSE) {
  542. $this->error .= 'Размер загружаемого файла превышает допустимый размер (' . $this->config['downloads']['max_filesize'] . ' Mb)<br />';
  543. }
  544.  
  545. // Сохранение файла
  546. if (!$this->error) {
  547. // Получение ID файла
  548. $this->db->query("INSERT INTO #__downloads_files SET file_id = 'NULL'");
  549. $file_id = $this->db->insert_id();
  550.  
  551. $directory_path = downloads::get_path($directory['directory_id'], $this->db);
  552. $realpath = downloads::get_realpath($directory_path);
  553. $realpath = ($realpath != '' ? $realpath . '/' : '') . ($directory['directory_id'] == 0 ? '' : $directory['directory_id'] . '/');
  554.  
  555. // Создание папки для файла
  556. mkdir(ROOT . DOWNLOADS_DIRECTORY . $realpath . $file_id);
  557. chmod(ROOT . DOWNLOADS_DIRECTORY . $realpath . $file_id, 0777);
  558.  
  559. $path_to_file = DOWNLOADS_DIRECTORY . ($realpath != '' ? $realpath : '') . $file_id;
  560.  
  561. if ($type == 'upload') {
  562. $file_path = ROOT . $path_to_file . '/' . $_FILES['file_upload']['name'];
  563. copy($_FILES['file_upload']['tmp_name'], $file_path);
  564. } else {
  565. $file_path = ROOT . $path_to_file . '/' . basename($_POST['file_import']);
  566. copy($_POST['file_import'], $file_path);
  567. }
  568.  
  569. // Работа со скриншотом к основному файлу
  570. if (!empty($_FILES['screen1']['tmp_name'])) {
  571. $screen_path = ROOT . $path_to_file . '/' . $_FILES['screen1']['name'];
  572.  
  573. if (copy($_FILES['screen1']['tmp_name'], $screen_path)) {
  574. if ($this->config['downloads']['screens_width'] > 0) {
  575. main::image_resize($screen_path, $screen_path, intval($this->config['downloads']['screens_width']));
  576. }
  577.  
  578. $file['screen1'] = $_FILES['screen1']['name'];
  579. }
  580. } else if (!empty($_POST['screen1']) && $_POST['screen1'] != 'http://') {
  581. $import_file_path = fm::get_real_file_path($_POST['screen_1']);
  582. $import_file_name = basename($import_file_path);
  583. $screen_path = ROOT . $path_to_file . '/' . $import_file_name;
  584.  
  585. if (copy($import_file_path, $screen_path)) {
  586. if ($this->config['downloads']['screens_width'] > 0) {
  587. main::image_resize($screen_path, $screen_path, intval($this->config['downloads']['screens_width']));
  588. }
  589.  
  590. $file['screen1'] = $import_file_name;
  591. }
  592. }
  593.  
  594. $file['name'] = $_POST['name'];
  595. $file['about'] = $_POST['about'];
  596. if ($this->config['downloads']['moderation'] == 1) {
  597. $file['status'] = 'moderate';
  598. } else {
  599. $file['status'] = 'active';
  600. }
  601. $file['user_id'] = USER_ID;
  602. $file['path_to_file'] = $path_to_file;
  603. $file['directory_id'] = $directory['directory_id'];
  604.  
  605. // Выполнение действий над определенными типами файлов
  606. $file = downloads::filetype_actions($file);
  607.  
  608. // Изменение файла в базе
  609. downloads::update_file($this->db, $file_id, $file);
  610.  
  611. a_notice($this->config['downloads']['moderation'] == 1 ? 'Файл успешно загружен. Он будет доступен для скачиваниями другими пользователями после прохождения модерации' : 'Файл успешно загружен', URL . 'downloads/view/' . $file_id);
  612. }
  613. }
  614. break;
  615.  
  616. case 'edit':
  617. $action = 'edit';
  618. $title = 'Изменение файла';
  619.  
  620. // Проверка файла
  621. if (!$file = $this->db->get_row("SELECT * FROM #__downloads_files WHERE file_id = '" . intval($_GET['file_id']) . "' AND user_id = '" . USER_ID . "' AND path_to_file != ''"))
  622. a_error('Файл не найден');
  623.  
  624. $directory = $this->db->get_row("SELECT * FROM #__downloads_directories WHERE directory_id = '$file[directory_id]'");
  625.  
  626. $directory_path = downloads::get_path($directory['directory_id'], $this->db);
  627. $navigation = downloads::get_namepath($directory_path, ' &raquo; ');
  628.  
  629. if ($directory['directory_id'] > 0)
  630. $navigation .= (!empty($navigation) ? ' &raquo; ' : '') . '<a href="' . URL . 'downloads/' . $directory['directory_id'] . '">' . $directory['name'] . '</a>';
  631.  
  632. // Обработка формы выгрузки файла
  633. if ($_POST['submit']) {
  634. // Фильтрация данных
  635. $name = htmlspecialchars(trim($_POST['name']));
  636. $about = htmlspecialchars(trim($_POST['about']));
  637.  
  638. // Проверка корректности данных
  639. if (!empty($name) && main::strlen($name) > 32) {
  640. $this->error .= 'Имя файла не должно быть длинее 32 символов<br />';
  641. }
  642.  
  643. if (!empty($about) && main::strlen($about) > 5000) {
  644. $this->error .= 'Описание не должно быть длинее 5000 символов<br />';
  645. }
  646.  
  647. // Получение информации о файле
  648. if (!empty($_FILES['file_upload']['tmp_name'])) {
  649. @unlink(ROOT . $file['path_to_file'] . '/' . $file['real_name']);
  650. $type = 'upload';
  651. $file['real_name'] = $_FILES['file_upload']['name'];
  652. $file['file_ext'] = array_pop(explode('.', $file['real_name']));
  653. $file['filesize'] = filesize($_FILES['file_upload']['tmp_name']);
  654. } else if (!empty($_POST['file_import']) && $_POST['file_import'] != 'http://') {
  655. @unlink(ROOT . $file['path_to_file'] . '/' . $file['real_name']);
  656. $type = 'import';
  657. $file['real_name'] = basename($_POST['file_import']);
  658. $file['file_ext'] = array_pop(explode('.', $file['real_name']));
  659. $file['filesize'] = downloads::get_filesize($_POST['file_import']);
  660. }
  661.  
  662. // Проверка типа файла
  663. if (!strstr(';' . $this->config['downloads']['allowed_filetypes'] . ';', ';' . $file['file_ext'] . ';') && $type) {
  664. $this->error .= 'Вы пытаетесь загрузить запрещенный тип файла<br />';
  665. }
  666.  
  667. // Проверка размера файла
  668. if (($file['filesize'] > $this->config['downloads']['max_filesize'] * 1048576) || $file['filesize'] === FALSE) {
  669. $this->error .= 'Размер загружаемого файла превышает допустимый размер (' . $this->config['downloads']['max_filesize'] . ' Mb)<br />';
  670. }
  671.  
  672. // Сохранение файла
  673. if (!$this->error) {
  674. // Получение ID файла
  675. $file_id = $file['file_id'];
  676.  
  677. $path_to_file = $file['path_to_file'];
  678.  
  679. if ($type && $type == 'upload') {
  680. $file_path = ROOT . $path_to_file . '/' . $_FILES['file_upload']['name'];
  681. copy($_FILES['file_upload']['tmp_name'], $file_path);
  682. } elseif ($type && $type == 'import') {
  683. $file_path = ROOT . $path_to_file . '/' . basename($_POST['file_import']);
  684. copy($_POST['file_import'], $file_path);
  685. }
  686.  
  687. // Работа со скриншотом к основному файлу
  688. if (!empty($_FILES['screen1']['tmp_name'])) {
  689. @unlink(ROOT . $path_to_file . '/' . $file['screen1']);
  690.  
  691. $screen_path = ROOT . $path_to_file . '/' . $_FILES['screen1']['name'];
  692.  
  693. if (copy($_FILES['screen1']['tmp_name'], $screen_path)) {
  694. if ($this->config['downloads']['screens_width'] > 0) {
  695. main::image_resize($screen_path, $screen_path, intval($this->config['downloads']['screens_width']));
  696. }
  697.  
  698. $file['screen1'] = $_FILES['screen1']['name'];
  699. }
  700. } else if (!empty($_POST['screen1']) && $_POST['screen1'] != 'http://') {
  701. @unlink(ROOT . $path_to_file . '/' . $file['screen1']);
  702.  
  703. $import_file_path = fm::get_real_file_path($_POST['screen_1']);
  704. $import_file_name = basename($import_file_path);
  705. $screen_path = ROOT . $path_to_file . '/' . $import_file_name;
  706.  
  707. if (copy($import_file_path, $screen_path)) {
  708. if ($this->config['downloads']['screens_width'] > 0) {
  709. main::image_resize($screen_path, $screen_path, intval($this->config['downloads']['screens_width']));
  710. }
  711.  
  712. $file['screen1'] = $import_file_name;
  713. }
  714. }
  715.  
  716. $file['name'] = $_POST['name'];
  717. $file['about'] = $_POST['about'];
  718. if ($this->config['downloads']['moderation'] == 1) {
  719. $file['status'] = 'moderate';
  720. } else {
  721. $file['status'] = 'active';
  722. }
  723. $file['user_id'] = USER_ID;
  724. $file['path_to_file'] = $path_to_file;
  725. $file['directory_id'] = $directory['directory_id'];
  726.  
  727. // Выполнение действий над определенными типами файлов
  728. $file = downloads::filetype_actions($file);
  729.  
  730. // Изменение файла в базе
  731. downloads::update_file($this->db, $file_id, $file);
  732.  
  733. a_notice($this->config['downloads']['moderation'] == 1 ? 'Файл успешно изменен. Он будет доступен для скачиваниями другими пользователями после прохождения модерации' : 'Файл успешно загружен', URL . 'downloads/view/' . $file_id);
  734. }
  735. }
  736. break;
  737.  
  738. case 'delete':
  739. $action = 'delete';
  740. $title = 'Удаление файла';
  741.  
  742. // Проверка файла
  743. if (!$file = $this->db->get_row("SELECT * FROM #__downloads_files WHERE file_id = '" . intval($_GET['file_id']) . "' AND user_id = '" . USER_ID . "' AND path_to_file != ''"))
  744. a_error('Файл не найден');
  745.  
  746. if (!empty($_GET['confirm'])) {
  747. // Удаление папки из ФС
  748. main::delete_dir(ROOT . $file['path_to_file']);
  749.  
  750. // Удаление файла из БД
  751. $this->db->query("DELETE FROM #__downloads_files WHERE file_id = '" . $file['file_id'] . "'");
  752.  
  753. a_notice('Файл успешно удален', URL . 'downloads/' . $file['directory_id']);
  754. } else {
  755. a_confirm('Вы подтверждаете удаление данного файла?', a_url('downloads/user_files', 'action=delete&amp;file_id=' . $file['file_id'] . '&amp;confirm=ok'), URL . 'downloads/view/' . $file['file_id']);
  756. }
  757. break;
  758. }
  759.  
  760. $this->tpl->assign(array(
  761. 'error' => $this->error,
  762. 'directory' => $directory,
  763. 'action' => $action,
  764. 'title' => $title,
  765. 'file' => $file,
  766. 'navigation' => $navigation,
  767. ));
  768.  
  769. $this->tpl->display('user_files');
  770. }
  771.  
  772. /**
  773. * Файлы и комментарии пользователя
  774. */
  775. public function action_my() {
  776. // Запрет доступа гостям
  777. if (USER_ID == -1)
  778. a_error('Для доступа к странице необходимо <a href="' . a_url('user/login') . '">войти</a> или <a href="' . a_url('user/registration') . '">зарегистрироваться</a>');
  779.  
  780. // Проверка действия
  781. if ($_GET['action'] != 'files' && $_GET['action'] != 'comments')
  782. a_error('Не выбрано действие');
  783.  
  784. switch ($_GET['action']) {
  785. case 'files':
  786. $action = 'files';
  787. $title = 'Мои файлы';
  788.  
  789. $result = $this->db->query("SELECT * FROM #__downloads_files WHERE user_id = '" . USER_ID . "' ORDER BY time DESC LIMIT $this->start, $this->per_page");
  790. $total = $this->db->get_one("SELECT COUNT(*) FROM #__downloads_files WHERE user_id = '" . USER_ID . "'");
  791.  
  792. $files = array();
  793. while ($file = $this->db->fetch_array($result)) {
  794. $files[] = $file;
  795. }
  796.  
  797. $files['total'] = $total;
  798.  
  799. $pg_conf['base_url'] = a_url('downloads/my', 'action=files&amp;start=');
  800. $pg_conf['total_rows'] = $files['total'];
  801. $pg_conf['per_page'] = $this->per_page;
  802.  
  803. a_import('libraries/pagination');
  804. $pg = new CI_Pagination($pg_conf);
  805.  
  806. // Удаляем лишние данные
  807. unset($files['total']);
  808.  
  809. $this->tpl->assign(array(
  810. 'title' => $title,
  811. 'action' => $action,
  812. 'pagination' => $pg->create_links(),
  813. 'total' => $total,
  814. 'files' => $files,
  815. 'start' => $this->start,
  816. '_config' => $this->config['downloads'],
  817. ));
  818.  
  819. $this->tpl->display('my_files');
  820. break;
  821.  
  822. case 'comments':
  823. break;
  824. }
  825. }
  826.  
  827. }
  828.  
  829. ?>