PageRenderTime 29ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/core/components/slideshowmanager/model/fileuploader.class.php

https://github.com/jgulledge19/Slideshowmanager
PHP | 355 lines | 212 code | 26 blank | 117 comment | 77 complexity | 721f98406d39385be5eb1be78bf1854f MD5 | raw file
  1. <?php
  2. /*
  3. * Upload images and resize them if nessicary
  4. *
  5. */
  6. /**
  7. *
  8. * Joshua Gulledge <jgulledge19@hotmail.com>
  9. *
  10. * This program is distributed in the hope that it will be useful, but WITHOUT
  11. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  13. * details.
  14. *
  15. * Date: 7-09-2012
  16. * Class purpose: upload & resize images
  17. *
  18. * @package slideshowmanager
  19. * @author Joshua Gulledge
  20. */
  21. class fileUploader{
  22. protected $error_array = array();
  23. protected $validate = false;
  24. protected $allow_file_types = array();
  25. protected $size_limit = 300;//300kb is default
  26. protected $allow_type = array('gif','jpeg','jpg','png');// default is images
  27. /**
  28. * @param (object) $modx
  29. */
  30. public $modx = NULL;
  31. /**
  32. * @param (Array) config
  33. */
  34. protected $config = array();
  35. /**
  36. * @param $modx
  37. * @param (Array) $config
  38. *
  39. */
  40. function __construct(modX &$modx,array $config = array()) {
  41. $this->modx =& $modx;
  42. $this->config = array_merge(array(
  43. ),$config);
  44. }
  45. public function isValid(){
  46. return $this->validate;
  47. }
  48. /**
  49. * Check if the file is in the correct format
  50. *
  51. * @return boolean - true on success and false on falure
  52. */
  53. public function checkFile($file, $required=false){
  54. # error
  55. $upload_errors = array(
  56. UPLOAD_ERR_INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
  57. UPLOAD_ERR_FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
  58. UPLOAD_ERR_PARTIAL => 'The uploaded file was only partially uploaded.',
  59. UPLOAD_ERR_NO_FILE => 'No file was uploaded.',
  60. UPLOAD_ERR_NO_TMP_DIR => 'Missing a temporary folder.',
  61. UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk.',
  62. UPLOAD_ERR_EXTENSION => 'File upload stopped by extension.',
  63. );
  64. $error_code = $_FILES[$file]['error'];
  65. if ( $error_code == UPLOAD_ERR_NO_FILE && $required ) {
  66. // @TODO: Rewrite?
  67. $this->error_array[$file] = 'Required';
  68. return FALSE;
  69. } else if($error_code !== UPLOAD_ERR_OK) {
  70. //echo '<br />Error: '.$file;
  71. $this->error_array[$file] = $upload_errors[$error_code].' '.$error_code;
  72. return FALSE;
  73. }
  74. # extention
  75. $filename = $_FILES[$file]['name'];
  76. //$file_basename = substr($filename, 0, strripos($filename, '.')); // strip extention
  77. $file_ext = strtolower(substr($filename, strripos($filename, '.')+1 ));
  78. $this->allow_file_types[$file]['ext'] = $file_ext;
  79. # size
  80. $limit = $this->size_limit;
  81. if ( isset($this->allow_file_types[$file]['size']) ) {
  82. $limit = $this->allow_file_types[$file]['size'];
  83. }
  84. $limit = $limit*1024;// convert to bytes
  85. if ( $_FILES[$file]['size'] > $limit) {
  86. if ( $limit > 1048576) { // 1 mb
  87. $limit_txt = number_format(($limit/1048576),3).' Mb';
  88. } else {
  89. $limit_txt = number_format(($limit/1024),0).' Kb';
  90. }
  91. $this->error_array[$file] = 'File size is to large, it must be smaller than: '.$limit_txt;
  92. return FALSE;
  93. }
  94. # type
  95. $allow_array = $this->allow_type;
  96. if ( isset($this->allow_file_types[$file]['allow']) ) {
  97. $allow_array = $this->allow_file_types[$file]['allow'];
  98. }
  99. if ( !in_array($file_ext, $allow_array) || !$this->_validFileType($file_ext, $_FILES[$file]['type']) ) {
  100. if( $file_ext == 'rtf' && $_FILES[$file]['type'] == 'application/msword' ) {
  101. // do nothing!
  102. } else{
  103. $this->error_array[$file] = 'Incorrect file type - ext: '.$file_ext.' mime type should be: '.$this->allow_file_types[$file]['allow']./*$this->_getFileType($file_ext)*/' but it is: '.$_FILES[$file]['type'];
  104. return FALSE;
  105. }
  106. }
  107. // check for the image width and height
  108. if ( $this->allow_file_types[$file]['constrain'] ){
  109. if ( $this->allow_file_types[$file]['width'] > 0 && $this->allow_file_types[$file]['height'] > 0 ) {
  110. // move file to tmp
  111. list($width, $height) = getimagesize($_FILES[$file]['tmp_name']);
  112. // width
  113. // height
  114. // echo 'W: '.$width.' - '.$this->allow_file_types[$file]['width'].' H: '.$height.' - '.$this->allow_file_types[$file]['height'];
  115. if ( $width != $this->allow_file_types[$file]['width'] || $height != $this->allow_file_types[$file]['height']) {
  116. //$this->error_array[$file] = 'Incorrect file width or height';
  117. //return FALSE;
  118. // resize image:
  119. $this->allow_file_types[$file]['runConstrain'] = true;
  120. }
  121. }
  122. }
  123. $this->validate = TRUE;
  124. return TRUE;
  125. }
  126. /**
  127. * Set file rules for the check function
  128. * @param (String) $file - the upload filename - name of the html element
  129. * @param (Int) $size_limit - in KB
  130. * @param (Array) $type_array - the allowed file extensions
  131. * @param (Int) $width - the width of an image
  132. * @param (Int) $height - the height of an image
  133. * @param (String) $tmp_directory - the path of a temp directory
  134. * @param (Boolean) $constrain - if true it will make image the set size
  135. *
  136. * @return void()
  137. */
  138. public function setFileRules($file, $size_limit, $type_array, $width=0, $height=0, $tmp_directory='',$constrain=TRUE ) {
  139. $this->allow_file_types[$file]['size'] = $size_limit;// in kilobytes
  140. $this->allow_file_types[$file]['allow'] = $type_array;
  141. $this->allow_file_types[$file]['width'] = $width;
  142. $this->allow_file_types[$file]['height'] = $height;
  143. $this->allow_file_types[$file]['tmp_dir'] = $tmp_directory;
  144. $this->allow_file_types[$file]['constrain'] = (boolean) $constrain;
  145. }
  146. /**
  147. * Move the file to the deseired locaiton
  148. *
  149. */
  150. public function moveFile($file, $destination, $new_name) { //file is the name of the input feild, destination is full path with name
  151. if ( $this->isValid() && isset($this->allow_file_types[$file]['ext']) ) {
  152. $org_file = $_FILES[$file]['tmp_name'];
  153. $new_file = $destination.$new_name.'.'.$this->allow_file_types[$file]['ext'];
  154. if ( move_uploaded_file ($org_file, $new_file)) {
  155. // constrain image?
  156. if ( isset($this->allow_file_types[$file]['runConstrain']) && $this->allow_file_types[$file]['runConstrain'] ) {
  157. $new_file = $this->_constrainImage($new_file, $file);
  158. }
  159. return $new_file;
  160. }
  161. }
  162. return false;
  163. }
  164. /**
  165. *
  166. */
  167. public function fileExt($file) {
  168. return $this->allow_file_types[$file]['ext'];
  169. }
  170. /**
  171. * @access protected
  172. * @param (string) $ext - file extenstion
  173. * @return (string) mime type
  174. */
  175. protected function _getFileType($ext) {
  176. return '';
  177. }
  178. /**
  179. * @access protected
  180. *
  181. */
  182. protected function _validFileType($ex, $mime) {
  183. $file_type_array = array(
  184. # documents
  185. 'doc' =>'application/msword',
  186. //'docx' =>'application/msword',
  187. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  188. 'rtf' => 'application/rtf',
  189. 'txt' => 'text/plain',
  190. 'pdf' => 'application/pdf',
  191. # powerpoint
  192. 'pot' => 'application/mspowerpoint',
  193. 'pps' => 'application/mspowerpoint',
  194. 'ppt' => 'application/mspowerpoint',
  195. 'ppz' => 'application/mspowerpoint',
  196. # excel
  197. 'csv' => 'application/octet-stream', //'application/x-msdownload',
  198. 'xlc' => 'application/vnd.ms-excel',
  199. 'xls' => 'application/vnd.ms-excel',
  200. # web images
  201. 'gif' => 'image/gif',
  202. 'jpeg' => 'image/jpeg',
  203. 'jpg' => 'image/jpeg',
  204. 'png' => 'image/png',
  205. 'tif' => 'image/tiff',
  206. 'tiff' => 'image/tiff',
  207. # web files
  208. 'css' => 'text/css',
  209. 'htm' => 'text/html',
  210. 'html' => 'text/html',
  211. 'xml' => 'text/xml',
  212. 'js' => 'application/x-javascript'
  213. );
  214. if ( $file_type_array[$ex] == $mime ) {
  215. return true;
  216. }
  217. // IE Specific mime types:
  218. // http://msdn.microsoft.com/en-us/library/ms775147.aspx + http://support.microsoft.com/kb/815455
  219. $ie_array = array(
  220. # web images image/x-xbitmap
  221. 'gif' => 'image/gif',
  222. 'jpeg' => 'image/pjpeg',
  223. 'jpg' => 'image/pjpeg',
  224. 'png' => 'image/x-png',
  225. 'tif' => 'image/tiff',
  226. 'tiff' => 'image/tiff',
  227. );
  228. if ( $ie_array[$ex] == $mime ) {
  229. return true;
  230. }
  231. return false;
  232. }
  233. ///////////////////////////////////////////////////////////////
  234. // RESIZE Stuff:
  235. /**
  236. * 1. if propution just resize
  237. * 2. if not proportional then resize to the largest side h or w
  238. * then fill in remainder with black
  239. * @param (string) $image - the image path & name
  240. * @param (string) $file - the file name
  241. */
  242. protected function _constrainImage($image, $file) {
  243. // help: http://www.plus2net.com/php_tutorial/gd-border.php
  244. $ext = explode(".",$image);
  245. $ext = strtolower(end($ext));
  246. $canvas_width = $this->allow_file_types[$file]['width'];
  247. $canvas_height = $this->allow_file_types[$file]['height'];
  248. // resize image:
  249. $image = $this->_resize($image, $canvas_height, $canvas_width);
  250. //return $image;
  251. list($width, $height) = getimagesize($image);
  252. if ($ext == "jpg") {
  253. $im = imagecreatefromjpeg($image);
  254. } else if ($ext == "gif") {
  255. $im = imagecreatefromgif ($image);
  256. } else if ($ext == "png") {
  257. $im = imagecreatefrompng ($image);
  258. }
  259. /**
  260. * Create an image (canvas) that is the size we want that will be all white
  261. */
  262. $canvas = imagecreatetruecolor($canvas_width,$canvas_height);
  263. $canvas_color = imagecolorallocate($canvas, 255, 255, 255);// white
  264. imagefilledrectangle($canvas, 0, 0, $canvas_width, $canvas_height, $canvas_color);
  265. // $difference_x = ($);
  266. $offset_x = 0;
  267. if ( $canvas_width > $width ) {
  268. $offset_x = ($canvas_width - $width )/2;
  269. }
  270. $offset_y = 0;
  271. if ( $canvas_height > $height ) {
  272. $offset_y = ($canvas_height - $height )/2;
  273. }
  274. // Finally let us create the new image by resizing the image
  275. imagecopyresized($canvas, $im, $offset_x, $offset_y, 0, 0, $width, $height, $width, $height);
  276. if ($ext == "jpg" || $ext == "jpeg") {
  277. imagejpeg($canvas, $image);
  278. } else if ($ext == "gif") {
  279. imagegif ($canvas, $image);
  280. } else if ($ext == "png") {
  281. imagepng ($canvas, $image,0);
  282. }
  283. return $image;
  284. }
  285. /**
  286. * Resize the image.
  287. * @param (String) $image - the path and name
  288. * @param (Int) $newHeight
  289. * @param (Int) $newWidth
  290. * @return (boolean)
  291. */
  292. protected function _resize ($image, $newHeight, $newWidth) {
  293. $ext = explode(".",$image);
  294. $ext = strtolower(end($ext));
  295. list($width, $height) = getimagesize($image);
  296. $ratio = $width/$height; // 500/300 = 1.5
  297. $new_ratio = $newWidth/$newHeight; // 600/300 = 2
  298. // end result = X/300
  299. if ( $new_ratio == $ratio ) {
  300. // just resample:
  301. } else if ($new_ratio > $ratio){ // height is the biggest
  302. $newWidth = $newHeight*$ratio;
  303. } else if ($new_ratio < $ratio) { // width is the biggest
  304. $newHeight = $newWidth*$ratio;
  305. }
  306. $normal = imagecreatetruecolor($newWidth, $newHeight);
  307. if ($ext == "jpg") {
  308. $src = imagecreatefromjpeg($image);
  309. } else if ($ext == "gif") {
  310. $src = imagecreatefromgif ($image);
  311. } else if ($ext == "png") {
  312. $src = imagecreatefrompng ($image);
  313. }
  314. //$this->modx->log(modX::LOG_LEVEL_ERROR,'[fileUploader()->_resize()] H: '.$height.' W: '.$width.' NH: '. $newHeight.' NW: '. $newWidth );
  315. $pre = $newWidth.'x'.$newHeight.'_';
  316. if ( imagecopyresampled($normal, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height)){
  317. //$this->info .= '<div>image was resized and saved.</div>';
  318. }
  319. if ($ext == "jpg" || $ext == "jpeg") {
  320. imagejpeg($normal, $image);
  321. } else if ($ext == "gif") {
  322. imagegif ($normal, $image);
  323. } else if ($ext == "png") {
  324. imagepng ($normal, $image,0);
  325. }
  326. return $image;
  327. }
  328. } // END
  329. ?>