Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.37 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Clase que encapsula las funciones de subida de archivos con su
  5. * seguridad correspondiente
  6. * @author Brandon Sanchez
  7. *
  8. */
  9. class Upload
  10. {
  11. private $carpeta = '';
  12. private $type = array();
  13. private $maxLength = 0;
  14. private $extension = array();
  15. private $mensajes = array('errores' => array(), 'success' => array('cargado' => 0,
  16. 'mensaje' => '', 'url' => ''));
  17.  
  18. /**
  19. * Inicia la clase asignando la ruta de la carpeta para subir los archivos,
  20. * si la carpeta no existe la crea, y verifica los permisos de la misma
  21. *
  22. * @param string $carpeta -> Ruta relativa a partir del archivo hacia la carpeta donde se subiran los archivos
  23. */
  24. function __construct($carpeta)
  25. {
  26. $this->asignarCarpeta($carpeta);
  27. $this->loadMimeTypes();
  28. $this->loadMaxSize();
  29. }
  30.  
  31. /**
  32. * Funcion para crear carpeta si no existe
  33. *
  34. * @global object $aplicacion
  35. * @param string $carpeta -> Ruta de la carpeta asignada en el momento de instanciar la clase
  36. */
  37. private function asignarCarpeta($carpeta)
  38. {
  39. $carpeta = $carpeta;
  40.  
  41. if (!is_dir($carpeta)) {
  42. if (!mkdir($carpeta)) {
  43. $this->mensajes['errores'][] = array('codigo' => '003', 'titulo' => 'Error de carpeta',
  44. 'mensaje' => 'La carpeta no existe "'.$carpeta.'" y no pudo ser creada.');
  45. } else {
  46. copy($dir_uploads.'index.html', $carpeta);
  47. $this->carpeta = $carpeta;
  48. }
  49. } else {
  50. $this->carpeta = $carpeta;
  51. }
  52. }
  53.  
  54. /**
  55. * Asigna las extensiones permitidas, con ello se asigna directamente el mime/type.
  56. * Si no se asigna ninguna Extension se da por hecho que todas son permitidas sin
  57. * restriccion, sin embargo debe ser acorde a su mime/type.
  58. *
  59. * @param string or Array $valor -> Contine las extensiones permitidas puede agregar varias en un array de la forma array('ext1', 'ext2', ...)
  60. */
  61. public function setExtension($valor)
  62. {
  63. if (is_array($valor)) {
  64. $this->extension = $valor;
  65. } else {
  66. $this->extension[] = $valor;
  67. }
  68. }
  69.  
  70. /**
  71. * Carga el tamaño maximo de archivo en bytes desde el archivo config.yml
  72. *
  73. * @global object $aplicacion
  74. */
  75. public function loadMaxSize()
  76. {
  77. $this->maxLength = 15728640; // máximo tamaño en bytes
  78. }
  79.  
  80. /**
  81. * Carga todos los mime/type disponibles en un arra con su respectiva extension
  82. */
  83. public function loadMimeTypes()
  84. {
  85. $this->type = array("323" => "text/h323",
  86. "acx" => "application/internet-property-stream",
  87. "ai" => "application/postscript",
  88. "aif" => "audio/x-aiff",
  89. "aifc" => "audio/x-aiff",
  90. "aiff" => "audio/x-aiff",
  91. "asf" => "video/x-ms-asf",
  92. "asr" => "video/x-ms-asf",
  93. "asx" => "video/x-ms-asf",
  94. "au" => "audio/basic",
  95. "avi" => "video/x-msvideo",
  96. "axs" => "application/olescript",
  97. "bas" => "text/plain",
  98. "bcpio" => "application/x-bcpio",
  99. "bin" => "application/octet-stream",
  100. "bmp" => "image/bmp",
  101. "c" => "text/plain",
  102. "cat" => "application/vnd.ms-pkiseccat",
  103. "cdf" => "application/x-cdf",
  104. "cer" => "application/x-x509-ca-cert",
  105. "class" => "application/octet-stream",
  106. "clp" => "application/x-msclip",
  107. "cmx" => "image/x-cmx",
  108. "cod" => "image/cis-cod",
  109. "cpio" => "application/x-cpio",
  110. "crd" => "application/x-mscardfile",
  111. "crl" => "application/pkix-crl",
  112. "crt" => "application/x-x509-ca-cert",
  113. "csh" => "application/x-csh",
  114. "css" => "text/css",
  115. "dcr" => "application/x-director",
  116. "der" => "application/x-x509-ca-cert",
  117. "dir" => "application/x-director",
  118. "dll" => "application/x-msdownload",
  119. "dms" => "application/octet-stream",
  120. "doc" => "application/msword",
  121. "dot" => "application/msword",
  122. "dvi" => "application/x-dvi",
  123. "dxr" => "application/x-director",
  124. "eps" => "application/postscript",
  125. "etx" => "text/x-setext",
  126. "evy" => "application/envoy",
  127. "exe" => "application/octet-stream",
  128. "fif" => "application/fractals",
  129. "flr" => "x-world/x-vrml",
  130. "gif" => "image/gif",
  131. "gtar" => "application/x-gtar",
  132. "gz" => "application/x-gzip",
  133. "h" => "text/plain",
  134. "hdf" => "application/x-hdf",
  135. "hlp" => "application/winhlp",
  136. "hqx" => "application/mac-binhex40",
  137. "hta" => "application/hta",
  138. "htc" => "text/x-component",
  139. "htm" => "text/html",
  140. "html" => "text/html",
  141. "htt" => "text/webviewhtml",
  142. "ico" => "image/x-icon",
  143. "ief" => "image/ief",
  144. "iii" => "application/x-iphone",
  145. "ins" => "application/x-internet-signup",
  146. "isp" => "application/x-internet-signup",
  147. "jfif" => "image/pipeg",
  148. "jpe" => "image/jpeg",
  149. "jpeg" => "image/jpeg",
  150. "jpg" => "image/jpeg",
  151. "js" => "application/x-javascript",
  152. "latex" => "application/x-latex",
  153. "lha" => "application/octet-stream",
  154. "lsf" => "video/x-la-asf",
  155. "lsx" => "video/x-la-asf",
  156. "lzh" => "application/octet-stream",
  157. "m13" => "application/x-msmediaview",
  158. "m14" => "application/x-msmediaview",
  159. "m3u" => "audio/x-mpegurl",
  160. "man" => "application/x-troff-man",
  161. "mdb" => "application/x-msaccess",
  162. "me" => "application/x-troff-me",
  163. "mht" => "message/rfc822",
  164. "mhtml" => "message/rfc822",
  165. "mid" => "audio/mid",
  166. "mny" => "application/x-msmoney",
  167. "mov" => "video/quicktime",
  168. "movie" => "video/x-sgi-movie",
  169. "mp2" => "video/mpeg",
  170. "mp3" => "audio/mpeg",
  171. "mpa" => "video/mpeg",
  172. "mpe" => "video/mpeg",
  173. "mpeg" => "video/mpeg",
  174. "mpg" => "video/mpeg",
  175. "mpp" => "application/vnd.ms-project",
  176. "mpv2" => "video/mpeg",
  177. "ms" => "application/x-troff-ms",
  178. "mvb" => "application/x-msmediaview",
  179. "nws" => "message/rfc822",
  180. "oda" => "application/oda",
  181. "p10" => "application/pkcs10",
  182. "p12" => "application/x-pkcs12",
  183. "p7b" => "application/x-pkcs7-certificates",
  184. "p7c" => "application/x-pkcs7-mime",
  185. "p7m" => "application/x-pkcs7-mime",
  186. "p7r" => "application/x-pkcs7-certreqresp",
  187. "p7s" => "application/x-pkcs7-signature",
  188. "pbm" => "image/x-portable-bitmap",
  189. "pdf" => "application/pdf",
  190. "pfx" => "application/x-pkcs12",
  191. "pgm" => "image/x-portable-graymap",
  192. "pko" => "application/ynd.ms-pkipko",
  193. "pma" => "application/x-perfmon",
  194. "pmc" => "application/x-perfmon",
  195. "pml" => "application/x-perfmon",
  196. "pmr" => "application/x-perfmon",
  197. "pmw" => "application/x-perfmon",
  198. "png" => "image/png",
  199. "pnm" => "image/x-portable-anymap",
  200. "pot" => "application/vnd.ms-powerpoint",
  201. "ppm" => "image/x-portable-pixmap",
  202. "pps" => "application/vnd.ms-powerpoint",
  203. "ppt" => "application/vnd.ms-powerpoint",
  204. "prf" => "application/pics-rules",
  205. "ps" => "application/postscript",
  206. "pub" => "application/x-mspublisher",
  207. "qt" => "video/quicktime",
  208. "ra" => "audio/x-pn-realaudio",
  209. "ram" => "audio/x-pn-realaudio",
  210. "ras" => "image/x-cmu-raster",
  211. "rgb" => "image/x-rgb",
  212. "rmi" => "audio/mid",
  213. "roff" => "application/x-troff",
  214. "rtf" => "application/rtf",
  215. "rtx" => "text/richtext",
  216. "scd" => "application/x-msschedule",
  217. "sct" => "text/scriptlet",
  218. "setpay" => "application/set-payment-initiation",
  219. "setreg" => "application/set-registration-initiation",
  220. "sh" => "application/x-sh",
  221. "shar" => "application/x-shar",
  222. "sit" => "application/x-stuffit",
  223. "snd" => "audio/basic",
  224. "spc" => "application/x-pkcs7-certificates",
  225. "spl" => "application/futuresplash",
  226. "src" => "application/x-wais-source",
  227. "sst" => "application/vnd.ms-pkicertstore",
  228. "stl" => "application/vnd.ms-pkistl",
  229. "stm" => "text/html",
  230. "svg" => "image/svg+xml",
  231. "sv4cpio" => "application/x-sv4cpio",
  232. "sv4crc" => "application/x-sv4crc",
  233. "t" => "application/x-troff",
  234. "tar" => "application/x-tar",
  235. "tcl" => "application/x-tcl",
  236. "tex" => "application/x-tex",
  237. "texi" => "application/x-texinfo",
  238. "texinfo" => "application/x-texinfo",
  239. "tgz" => "application/x-compressed",
  240. "tif" => "image/tiff",
  241. "tiff" => "image/tiff",
  242. "tr" => "application/x-troff",
  243. "trm" => "application/x-msterminal",
  244. "tsv" => "text/tab-separated-values",
  245. "txt" => "text/plain",
  246. "uls" => "text/iuls",
  247. "ustar" => "application/x-ustar",
  248. "vcf" => "text/x-vcard",
  249. "vrml" => "x-world/x-vrml",
  250. "wav" => "audio/x-wav",
  251. "wcm" => "application/vnd.ms-works",
  252. "wdb" => "application/vnd.ms-works",
  253. "wks" => "application/vnd.ms-works",
  254. "wmf" => "application/x-msmetafile",
  255. "wps" => "application/vnd.ms-works",
  256. "wri" => "application/x-mswrite",
  257. "wrl" => "x-world/x-vrml",
  258. "wrz" => "x-world/x-vrml",
  259. "xaf" => "x-world/x-vrml",
  260. "xbm" => "image/x-xbitmap",
  261. "xla" => "application/vnd.ms-excel",
  262. "xlc" => "application/vnd.ms-excel",
  263. "xlm" => "application/vnd.ms-excel",
  264. "xls" => "application/vnd.ms-excel",
  265. "xlt" => "application/vnd.ms-excel",
  266. "xlw" => "application/vnd.ms-excel",
  267. "xof" => "x-world/x-vrml",
  268. "xpm" => "image/x-xpixmap",
  269. "xwd" => "image/x-xwindowdump",
  270. "z" => "application/x-compress",
  271. "zip" => "application/zip");
  272. }
  273.  
  274. /**
  275. * Funcion para verificar si hay filtro por extension o no
  276. *
  277. * @return boolean
  278. */
  279. private function verificarExtension()
  280. {
  281. $flag = true;
  282.  
  283. if (is_array($this->extension) && count($this->extension) == 0) {
  284. $flag = false;
  285. } else if ($this->extension == '') {
  286. $flag = false;
  287. }
  288. return $flag;
  289. }
  290.  
  291. /**
  292. * Funcion final para subir archivo
  293. *
  294. * @param string $var -> nombre del input del archivo que cargará
  295. * @param boolean $hash -> Si el nombre debe generar un aleatorio
  296. * @return array -> Mensajes de error y/o success
  297. */
  298. public function subirArchivo($var, $hash = true)
  299. {
  300. if (isset($_FILES[$var]) && count($_FILES[$var]) > 0) {
  301. $destino = substr($this->carpeta, -1, 1) != '/' ? $this->carpeta.'/'
  302. : $this->carpeta;
  303.  
  304. $tipo = $_FILES[$var]['type'];
  305. $peso = $_FILES[$var]['syze'];
  306. $nombre_tmp = $_FILES[$var]['tmp_name'];
  307. $nombre = $_FILES[$var]['name'];
  308. $extension = strtolower(end(explode('.', $nombre)));
  309.  
  310. if ($this->verificarExtension()) {
  311. if (in_array($extension, $this->extension) === false) {
  312. $this->mensajes['errores'][] = array('codigo' => '059', 'titulo' => 'Extensión invalida',
  313. 'mensaje' => 'El archivo no corresponde a ninguna de las extensiones permitidas: Extensión del archivo: '.$extension.', permitidas: '.implode(', ',
  314. $this->extension));
  315. } else if ($tipo != $this->type[$extension]) {
  316. $this->mensajes['errores'][] = array('codigo' => '219', 'titulo' => 'Tipo de archivo invalido',
  317. 'mensaje' => 'El tipo de archivo no es válido. Según la extensión ('.$extension.') debe ser '.$this->type[$extension].' y se obtuvo '.$tipo);
  318. }
  319. }
  320.  
  321. if ($peso > $this->maxLength) {
  322. $this->mensajes['errores'][] = array('codigo' => '521', 'titulo' => 'Exceso de tamaño',
  323. 'mensaje' => 'El tamaño del archivo debe ser menor que '.floor($this->maxLength
  324. / 1024).' y el archivo pesa '.floor($peso / 1024));
  325. }
  326.  
  327. if (empty($this->mensajes['errores'])) {
  328. if ($hash) {
  329. $ruta_destino = $destino.$this->generarNombre($nombre);
  330. } else {
  331. $ruta_destino = $destino.preg_replace("/ /", "_", $nombre);
  332. }
  333. if (move_uploaded_file($nombre_tmp, $ruta_destino)) {
  334. $this->mensajes['success'] = array('cargado' => 1, 'mensaje' => 'El archivo se ha cargado satisfactoriamente.',
  335. 'url' => $ruta_destino);
  336. } else {
  337. $this->mensajes['errores'][] = array('codigo' => '777', 'titulo' => 'Archivo no movido',
  338. 'mensaje' => 'No se ha cargado un archivo con la variable '.$var.' revise permisos en el directorio.');
  339. }
  340. }
  341. } else {
  342. $this->mensajes['errores'][] = array('codigo' => '000', 'titulo' => 'Archivo Invalido',
  343. 'mensaje' => 'No se ha cargado un archivo con la variable '.$var);
  344. }
  345.  
  346. return $this->mensajes;
  347. }
  348.  
  349. /**
  350. * Funcion para generar nombre aleatorio siempre y cuando la variable $hash de Subir archivo este en true
  351. *
  352. * @global object $aplicacion
  353. * @param string $nombre_archivo
  354. * @return string
  355. */
  356. private function generarNombre($nombre_archivo)
  357. {
  358. $rand = microtime().'-'.mt_srand(time());
  359. $hash = sha1(md5($rand));
  360.  
  361. $nombre = $hash.'-'.preg_replace("/ /", "_", $nombre_archivo);
  362. return $nombre;
  363. }
  364. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement