Просмотр файла app/classes/FileUpload.php

Размер файла: 10.2Kb
  1. <?php
  2. /**
  3. * class FileUpload
  4. * Дополнительно реализовано, расширеные подсказки в ошибках
  5. * Возможность загрузки файлов, только определенных расширений
  6. */
  7. class FileUpload extends upload {
  8.  
  9. function translate($str, $tokens = [])
  10. {
  11.  
  12. // sets default language
  13. $this->translation = [];
  14. $this->translation['file_error'] = 'Файловая ошибка. Попробуйте еще раз.';
  15. $this->translation['local_file_missing'] = 'Локальный файл не существует.';
  16. $this->translation['local_file_not_readable'] = 'Локальный файл закрыт для чтения.';
  17. $this->translation['uploaded_too_big_ini'] = 'Ошибка! Загруженный файл превышает лимит директивы the upload_max_filesize';
  18. $this->translation['uploaded_too_big_html'] = 'Ошибка! Загруженный файл превышает лимит директивы MAX_FILE_SIZE';
  19. $this->translation['uploaded_partial'] = 'Ошибка загрузки файла (Файл загружен частично).';
  20. $this->translation['uploaded_missing'] = 'Ошибка загрузки файла (Файл не был загружен).';
  21. $this->translation['uploaded_no_tmp_dir'] = 'Ошибка загрузки файла (Временная папка не найдена).';
  22. $this->translation['uploaded_cant_write'] = 'Ошибка загрузки файла (Не удалось записать файл на диск).';
  23. $this->translation['uploaded_err_extension'] = 'Ошибка загрузки файла (Не удалось определить расширение).';
  24. $this->translation['uploaded_unknown'] = 'Ошибка загрузки файла (Неизвестный код ошибки).';
  25. $this->translation['try_again'] = 'Ошибка загрузки файла. Попробуйте еще раз.';
  26. $this->translation['file_too_big'] = 'Ошибка! Слишком большой вес файла! Максимум %s';
  27. $this->translation['no_mime'] = 'Невозможно определить MIME-тип файла.';
  28. $this->translation['incorrect_file'] = 'Ошибка! Некорректный тип файла.';
  29. $this->translation['incorrect_ext'] = 'Ошибка! Недопустимое расширение файла. Разрешено: %s';
  30. $this->translation['image_too_wide'] = 'Ошибка! Размер изображения очень широкий. Максимум %s px';
  31. $this->translation['image_too_narrow'] = 'Ошибка! Размер изображения очень узкий. Минимум %s px';
  32. $this->translation['image_too_high'] = 'Ошибка! Размер изображения очень высокий. Максимум %s px';
  33. $this->translation['image_too_short'] = 'Ошибка! Размер изображения очень короткий. Минимум %s px';
  34. $this->translation['ratio_too_high'] = 'Соотношение сторон очень велико (Изображение очень широкое).';
  35. $this->translation['ratio_too_low'] = 'Соотношение сторон очень мало (Изображение очень высокое).';
  36. $this->translation['too_many_pixels'] = 'В изображении очень много пикселей.';
  37. $this->translation['not_enough_pixels'] = 'В изображении недостаточно пикселей.';
  38. $this->translation['file_not_uploaded'] = 'Файл не загружен. Невозможно продолжить процесс.';
  39. $this->translation['already_exists'] = '%s существует. Измените имя файла.';
  40. $this->translation['temp_file_missing'] = 'Некорректный временый файл. Невозможно продолжить процесс.';
  41. $this->translation['source_missing'] = 'Некорректный загруженный файл. Невозможно продолжить процесс.';
  42. $this->translation['destination_dir'] = 'Директория назначения не может быть создана. Невозможно продолжить процесс.';
  43. $this->translation['destination_dir_missing'] = 'Директория назначения не существует. Невозможно продолжить процесс.';
  44. $this->translation['destination_path_not_dir'] = 'Путь назначения не является директорией. Невозможно продолжить процесс.';
  45. $this->translation['destination_dir_write'] = 'Директория назначения закрыта для записи. Невозможно продолжить процесс.';
  46. $this->translation['destination_path_write'] = 'Путь назначения закрыт для записи. Невозможно продолжить процесс.';
  47. $this->translation['temp_file'] = 'Невозможно создать временный файл. Невозможно продолжить процесс.';
  48. $this->translation['source_not_readable'] = 'Исходный файл нечитабельный. Невозможно продолжить процесс.';
  49. $this->translation['no_create_support'] = 'Создание из %s не поддерживается.';
  50. $this->translation['create_error'] = 'Ошибка создания %s изображения из оригинала.';
  51. $this->translation['source_invalid'] = 'Невозможно прочитать исходный файл.';
  52. $this->translation['gd_missing'] = 'Библиотека GD не обнаружена.';
  53. $this->translation['watermark_no_create_support'] = '%s не поддерживается, невозможно прочесть водный знак.';
  54. $this->translation['watermark_create_error'] = '%s не поддерживается чтение, невозможно создать водный знак.';
  55. $this->translation['watermark_invalid'] = 'Неизвестный формат изображения, невозможно прочесть водный знак.';
  56. $this->translation['file_create'] = '%s не поддерживается.';
  57. $this->translation['no_conversion_type'] = 'Тип конверсии не указан.';
  58. $this->translation['copy_failed'] = 'Ошибка копирования файла на сервер. Команда copy() выполнена с ошибкой.';
  59. $this->translation['reading_failed'] = 'Ошибка чтения файла.';
  60.  
  61. if (array_key_exists($str, $this->translation)) $str = $this->translation[$str];
  62. if (is_array($tokens) && sizeof($tokens) > 0) $str = vsprintf($str, $tokens);
  63. return $str;
  64. }
  65.  
  66. function init()
  67. {
  68. parent::init(); // Array list of allowed extensions
  69. $this->ext_check = [];
  70. }
  71.  
  72. function process($server_path = null)
  73. {
  74. $this->error = '';
  75. $this->processed = true;
  76.  
  77. if (!$this->uploaded) {
  78. $this->error = $this->translate('file_not_uploaded');
  79. $this->processed = false;
  80. }
  81.  
  82. if ($this->processed) {
  83. if (!empty($this->ext_check) && !in_array($this->file_src_name_ext, $this->ext_check)) {
  84. $this->processed = false;
  85. $this->error = $this->translate('incorrect_ext', [implode(', ', $this->ext_check)]);
  86. } else {
  87. $this->log .= '- file ext OK<br />';
  88. }
  89. }
  90.  
  91. if ($this->processed) {
  92. // checks file max size
  93. if ($this->file_src_size > $this->file_max_size) {
  94. $this->processed = false;
  95. $this->error = $this->translate('file_too_big', [formatsize($this->file_max_size)]);
  96. } else {
  97. $this->log .= '- file size OK<br />';
  98. }
  99. }
  100.  
  101. if ($this->processed) {
  102. if ($this->file_is_image) {
  103. if (is_numeric($this->image_src_x) && is_numeric($this->image_src_y)) {
  104.  
  105. if (!is_null($this->image_max_width) && $this->image_src_x > $this->image_max_width) {
  106. $this->processed = false;
  107. $this->error = $this->translate('image_too_wide', [$this->image_max_width]);
  108. }
  109. if (!is_null($this->image_min_width) && $this->image_src_x < $this->image_min_width) {
  110. $this->processed = false;
  111. $this->error = $this->translate('image_too_narrow', [$this->image_min_width]);
  112. }
  113. if (!is_null($this->image_max_height) && $this->image_src_y > $this->image_max_height) {
  114. $this->processed = false;
  115. $this->error = $this->translate('image_too_high', [$this->image_max_height]);
  116. }
  117. if (!is_null($this->image_min_height) && $this->image_src_y < $this->image_min_height) {
  118. $this->processed = false;
  119. $this->error = $this->translate('image_too_short', [$this->image_min_height]);
  120. }
  121. } else {
  122. $this->log .= '- no image properties available, can\'t enforce dimension checks : ' . $this->file_src_mime . '<br />';
  123. }
  124. }
  125. }
  126.  
  127. if ($this->processed) {
  128. parent::process($server_path);
  129. }
  130. }
  131. }