PageRenderTime 24ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/classes/qqfileuploader.php

https://bitbucket.org/denisOg/soft-site
PHP | 361 lines | 312 code | 26 blank | 23 comment | 15 complexity | 140507ab2f976789509aabefa10adb01 MD5 | raw file
  1. <?php
  2. class qqFileUploader
  3. {
  4. private $allowedExtensions = array();
  5. private $sizeLimit = 104857600;
  6. private $file;
  7. private $uploadDirectory;
  8. // сохранять в папку tmp в указанной папке
  9. public $save_in_tmp = FALSE;
  10. function __construct(array $param= array())
  11. {
  12. $oCI = $this->_get_inst();
  13. $oCI->load->library('image_lib');
  14. $oCI->lang->load('error_auten');
  15. $this->save_in_tmp = (!empty($param['save_in_tmp']))?$param['save_in_tmp']:FALSE;
  16. $allowedExtensions = (!empty($param['allowedExtensions']))?array_map("strtolower", $param['allowedExtensions']):array();
  17. $this->allowedExtensions = $allowedExtensions;
  18. $this->sizeLimit = (!empty($param['sizeLimit']))?$param['sizeLimit']:$this->sizeLimit;
  19. $this->checkServerSettings();
  20. if (isset($_GET['qqfile']))
  21. {
  22. $this->file = new qqUploadedFileXhr();
  23. } elseif (isset($_FILES['qqfile']))
  24. {
  25. $this->file = new qqUploadedFileForm();
  26. } else
  27. {
  28. $this->file = false;
  29. }
  30. }
  31. protected function _get_inst()
  32. {
  33. $inst = & get_instance();
  34. return $inst;
  35. }
  36. private function checkServerSettings()
  37. {
  38. /* $postSize = $this->toBytes(ini_get('post_max_size'));
  39. $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));
  40. if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
  41. $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';
  42. die("{'error':'increase post_max_size and upload_max_filesize to $size'}");
  43. } */
  44. }
  45. private function toBytes($str)
  46. {
  47. $val = trim($str);
  48. $last = strtolower($str[strlen($str) - 1]);
  49. switch ($last)
  50. {
  51. case 'g':
  52. $val *= 1024;
  53. case 'm':
  54. $val *= 1024;
  55. case 'k':
  56. $val *= 1024;
  57. }
  58. return $val;
  59. }
  60. /*
  61. * Upload File (image,video,audio,txt. ect)
  62. * @param string $main_patch
  63. * @param string $file_name
  64. * return array
  65. * */
  66. function UploadFile($main_path = false, $file_name = false)
  67. {
  68. $path_length = strlen($main_path);
  69. if($main_path[$path_length-1]!='/'){
  70. $main_path .= '/';
  71. }
  72. if (!$main_path || (!is_dir(realpath('.').$main_path)) || (!is_writable(realpath('.').$main_path)))
  73. {
  74. echo "No directory". realpath('.').$main_path ."or no 777";
  75. return false;
  76. }
  77. //echo 'tmp is ='.$this->save_in_tmp;
  78. if ($this->save_in_tmp)
  79. {
  80. $main_path =$main_path . 'tmp/';
  81. if (!is_dir(realpath('.').$main_path)){
  82. mkdir(realpath('.').$main_path, 0777);
  83. }
  84. }
  85. if (!$file_name)
  86. {
  87. $file_name = md5(time() . uniqid());
  88. }
  89. $pathinfo = pathinfo($this->file->getName());
  90. $ext = $pathinfo['extension'];
  91. $this->uploadDirectory = realpath('.') . $main_path;
  92. $path_real_file = $this->uploadDirectory . $file_name . '.' . $ext;
  93. $save_result = $this->file->save($path_real_file); //save
  94. if ($save_result)
  95. {
  96. return array('file_name' => $file_name . '.' . $ext, 'main_path' => $main_path);
  97. }
  98. return false;
  99. }
  100. /*
  101. * Upload Image (image,video,audio,txt. ect)
  102. * @param string $main_patch
  103. * @param string $file_name
  104. * @param array $array_copy=array('{width}','{height}',{path},{outsize/insize})
  105. * return array/boolean(TRUE/FALSE)
  106. * */
  107. public function UploadImage($main_path = false, $file_name = false, $array_copy = null)
  108. {
  109. if (!$main_path) return FALSE;
  110. $result = $this->UploadFile($main_path, $file_name);
  111. if($result && is_array($array_copy))
  112. {
  113. foreach ($array_copy as $value)
  114. {
  115. //prn($array_copy);
  116. $width = (!empty($value[0]))?$value[0]:'';
  117. $height = (!empty($value[1]))?$value[1]:'';
  118. $path = (!empty($value[2]))?$value[2]:'';
  119. $type_resize = (!empty($value[3]))?$value[3]:'inside';
  120. $this->ResizeImage($result['file_name'],$main_path,$width,$height,$path,$type_resize);
  121. }
  122. }
  123. return $result;
  124. }
  125. public function ResizeImage($file_name=null,$path_in=null,$width=null,$height=null,$path_out=null,$type_resize = 'inside')
  126. {
  127. if((!$file_name)||(!$path_in)||(!is_dir(realpath('.').$path_in)) ||(!$path_out) ||(!is_dir(realpath('.').$path_out))) return FALSE;
  128. $path_in_file = realpath('.').$path_in.$file_name;
  129. $pref = ($width)?$width:time();
  130. $path_out_file = realpath('.').$path_out.$pref.'_'.$file_name;
  131. $this->imageResize($path_in_file,$path_out_file, $width, $height, TRUE,$type_resize);
  132. return $pref.'_'.$file_name;
  133. }
  134. private function CheckErrors()
  135. {
  136. if (!is_writable($this->uploadDirectory))
  137. {
  138. return array('error' => "Server error. Upload directory isn't writable.");
  139. }
  140. if (!$this->file)
  141. {
  142. return array('error' => 'No files were uploaded.');
  143. }
  144. $size = $this->file->getSize();
  145. if ($size == 0)
  146. {
  147. return array('error' => 'File is empty');
  148. }
  149. if ($size > $this->sizeLimit)
  150. {
  151. return array('error' => 'File is too large');
  152. }
  153. $pathinfo = pathinfo($this->file->getName());
  154. $ext = $pathinfo['extension'];
  155. if ($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions))
  156. {
  157. $these = implode(', ', $this->allowedExtensions);
  158. return array('error' => 'File has an invalid extension, it should be one of ' . $these . '.');
  159. }
  160. }
  161. //$type_resize = inside||outside
  162. function imageResize($uplFile, $newFile, $width = null, $height = null, $ratio = TRUE, $type_resize = 'outside')
  163. {
  164. $width = (int)$width;
  165. $height = (int)$height;
  166. if ($width > 0 || $height > 0)
  167. {
  168. $config = array();
  169. $config['image_library'] = 'gd2'; // выбираем библиотеку
  170. $config['source_image'] = $uplFile;
  171. $config['maintain_ratio'] = TRUE; // сохранять пропорции
  172. if ($width > 0)
  173. {
  174. $config['width'] = $width;
  175. }
  176. if ($height > 0)
  177. {
  178. $config['height'] = $height;
  179. }
  180. $img_param = getimagesize($uplFile);
  181. // если ширина > высоты
  182. //(при таких настройках обрезка работает по принципу достигли одной координаты, перестали уменьшать)
  183. // если поменять условие, то будет работать по принципу чтоб обе координаты вмещались в заданую область
  184. if ($type_resize == 'inside')
  185. {
  186. if ($img_param[0] > $img_param[1])
  187. {
  188. $config['master_dim'] = 'height';
  189. } else
  190. {
  191. $config['master_dim'] = 'width';
  192. }
  193. } else
  194. {
  195. if($type_resize=='outside_full'){
  196. // картинка будет обрезаться до большей координаты из указанных для обрезания
  197. //при этом учитываются соотношение сторон самой картинки
  198. if ($img_param[0] < $img_param[1]){
  199. $config['master_dim'] = 'width';
  200. } else{
  201. $config['master_dim'] = 'height';
  202. }
  203. /*if($width >= $height){
  204. if ($img_param[0] < $img_param[1]){
  205. $config['master_dim'] = 'width';
  206. } else{
  207. $config['master_dim'] = 'height';
  208. }
  209. }
  210. else{
  211. // если ширина блока меньше высоты
  212. if ($img_param[0] < $img_param[1]){
  213. $config['master_dim'] = 'width';
  214. } else{
  215. $config['master_dim'] = 'height';
  216. }
  217. }*/
  218. //echo 'master = '.$config['master_dim'].' width = '.$width.' \n ';
  219. }
  220. else{
  221. if ($img_param[0] < $img_param[1]){
  222. $config['master_dim'] = 'height';
  223. } else{
  224. $config['master_dim'] = 'width';
  225. }
  226. }
  227. }
  228. $config['new_image'] = $newFile;
  229. $oCI = $this->_get_inst();
  230. $oCI->load->library('image_lib', $config); // загружаем библиотеку
  231. $oCI->image_lib->initialize($config);
  232. if (!$oCI->image_lib->resize())
  233. {
  234. echo $oCI->image_lib->display_errors();
  235. }
  236. $oCI->image_lib->clear();
  237. }
  238. }
  239. }
  240. /**
  241. * Handle file uploads via XMLHttpRequest
  242. */
  243. class qqUploadedFileXhr
  244. {
  245. /**
  246. * Save the file to the specified path
  247. * @return boolean TRUE on success
  248. */
  249. function save($path)
  250. {
  251. $input = fopen("php://input", "r");
  252. $temp = tmpfile();
  253. $realSize = stream_copy_to_stream($input, $temp);
  254. fclose($input);
  255. if ($realSize != $this->getSize())
  256. {
  257. return false;
  258. }
  259. $target = fopen($path, "w");
  260. fseek($temp, 0, SEEK_SET);
  261. stream_copy_to_stream($temp, $target);
  262. fclose($target);
  263. return true;
  264. }
  265. function getName()
  266. {
  267. return $_GET['qqfile'];
  268. }
  269. function getSize()
  270. {
  271. if (isset($_SERVER["CONTENT_LENGTH"]))
  272. {
  273. return (int)$_SERVER["CONTENT_LENGTH"];
  274. } else
  275. {
  276. throw new Exception('Getting content length is not supported.');
  277. }
  278. }
  279. }
  280. /**
  281. * Handle file uploads via regular form post (uses the $_FILES array)
  282. */
  283. class qqUploadedFileForm
  284. {
  285. /**
  286. * Save the file to the specified path
  287. * @return boolean TRUE on success
  288. */
  289. function save($path)
  290. {
  291. if (!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path))
  292. {
  293. return false;
  294. }
  295. return true;
  296. }
  297. function getName()
  298. {
  299. return $_FILES['qqfile']['name'];
  300. }
  301. function getSize()
  302. {
  303. return $_FILES['qqfile']['size'];
  304. }
  305. }