ÿØÿà JFIF ` ` ÿþ
Server : Apache System : Linux ruga7-004.fmcity.com 3.10.0-1160.119.1.el7.x86_64 #1 SMP Tue Jun 4 14:43:51 UTC 2024 x86_64 User : tkt_travelbus ( 1137) PHP Version : 7.0.0p1 Disable Function : mysql_pconnect Directory : /tkt_travelbus/www/LibClass/ |
Upload File : |
<?php /************************************************************************ HopegiverPHP - Web Application Development Framework for PHP Copyright (C) 2007 MalgnSoft, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. ************************************************************************/ class File { var $errMsg; var $type; var $path; var $debug; var $uploadPath; var $uploadCallback; var $addTimestamp; var $checkFTPSize; /* FTP 사용량 체크 */ var $maxFTPSize = 0; /* FTP 업로드 제한 용량 (0=무제한) 단위:byte */ var $currentFTPsize = -1; /* 현재 FTP사용량(캐시용)*/ var $imageOnly = FALSE; /* 이미지만 업로드 허용 여부 */ var $filePermission = 0606; /* 업로드한 파일의 퍼미션 */ static $mimes = NULL; /* file MIME타입 배열 */ function File($path="") { $this->path = $path; $this->debug = 0; $this->uploadBase = ''; $this->uploadPath = ''; $this->uploadCallback = ''; $this->urlBase = ''; $this->urlPath = ''; $this->_allowed = ''; $this->_allowedMimes = ''; $this->_denied = ''; $this->_deniedMimes = ''; $this->encType = 0; $this->addTimestamp = 0; $this->checkFTPSize = FALSE; /* FTP 사용량 체크유무 */ $this->maxFTPSize = 0; /* FTP 사용량 bytes */ $this->currentFTPsize = -1; $this->filePermission = 0606; $this->_deniedMimesFixed = array( 'application/x-httpd-php', // php 'text/x-php', // php 'text/x-c++', // php? cpp? 'application/x-httpd-php-source', // phps 'text/html', // html, htm 'text/x-script.perl', // pl 'application/xhtml+xml', // xml 'application/xml', // xml 'text/xml', // xml 'text/asp', // asp 'text/jsp', // jsp 'magnus-internal/jsp', // jsp 'application/x-javascript', // js 'application/javascript', // js 'application/ecmascript', // js 'text/javascript', // js 'text/ecmascript', // js 'magnus-internal/cgi', // cgi ); } function read() { if(!$this->exists()) return false; if($fp = fopen($this->path, "r")) { $buffer = fread($fp, filesize($this->path)); fclose($fp); return $buffer; } else return $this->setError("$this->path 파일을 열수 없습니다."); } function exists() { if(file_exists($this->path)) return true; else { return $this->setError("$this->path 파일이 존재하지 않습니다."); } } function write($str, $type="w") { //if(!$this->exists()) return false; if($fp = fopen($this->path, $type)) { if(!fwrite($fp, $str)) return $this->setError("파일쓰기에 실패했습니다."); fclose($fp); return true; } else return $this->setError("$this->path 파일을 열수 없습니다."); } function append($str) { return $this->write($str, "a"); } function move($path) { return rename($this->path, $path); } function delete() { if(!@unlink($this->path)) return $this->setError("파일삭제에 실패했습니다."); return true; } function allow($ext) { $this->_allowed = $ext; } function deny($ext) { $this->_denied = $ext; } function allowMimes($mime_types) { if ( !is_array($mime_types) ) { $this->_allowedMimes = explode("|", $mime_types); }else{ $this->_allowedMimes = $mime_types; } } function denyMimes($mime_types='*') { if ( $mime_types == '*' ) { $this->_deniedMimes = '*'; }else{ if ( !is_array($mime_types) ) { $this->_deniedMimes = explode("|", $mime_types); }else{ $this->_deniedMimes = $mime_types; } } } function setImageOnly($image_only=TRUE) { $this->imageOnly = $image_only; } function setFilePermission($permission) { $this->filePermission = $permission; } function setUploadPath($uploadPath, $uploadBase = '', $permission=0707) { if ($uploadBase) { $this->uploadBase = $uploadBase; } $this->uploadBase = preg_replace('/\/$/', '', $this->uploadBase); if ($uploadPath) { if ($this->uploadBase) { $this->uploadPath = $this->uploadBase . '/' . $uploadPath; $this->urlPath = $this->urlBase . '/' . $uploadPath; } else { $this->uploadPath = $uploadPath; $this->urlPath = $urlPath; } } else { $this->uploadPath = $this->uploadBase; $this->urlPath = $this->urlBase; } if ( !is_dir($this->uploadPath) ) { @mkdir($this->uploadPath, $permission, TRUE); //chmod($this->uploadPath, 0707); } return true; } function upload($name, $path='', $overwrite=0) { if (empty($_FILES[$name])) { return false; } if ($path) { $this->setUploadPath($path); } if (!is_writable($this->uploadPath)) { return $this->setError('업로드 디렉토리에 쓰기 권한이 없습니다.'); } if (is_array($_FILES[$name]['name'])) { $result = array(); for ($i=0, $ci=count($_FILES[$name]['name']); $i<$ci; $i++) { if ($_FILES[$name]['tmp_name'][$i] && $_FILES[$name]['name'][$i]) { $file = array( 'name' => $_FILES[$name]['name'][$i], 'tmp_name' => $_FILES[$name]['tmp_name'][$i], 'size' => $_FILES[$name]['size'][$i], 'type' => $_FILES[$name]['type'][$i], ); $result[] = $this->uploadSingle($file, $path, $overwrite); } else { $result[] = false; } } return $result; } else { return $this->uploadSingle($_FILES[$name], $path, $overwrite); } } function uploadSingle($file, $path='', $overwrite=0) { if (!$file['tmp_name'] || !$file['name']) { return $this->setError('업로드되지 않았습니다.'); } if (!is_uploaded_file($file['tmp_name'])) { return $this->setError('파일이 정상적으로 업로드되지 않았습니다.'); } // 파일 mime타입 $file_real_mime_type = $this->getFileMimeType($file); if ( $this->imageOnly ) { if ( ! $this->isImage($file_real_mime_type) ) { @unlink($file['tmp_name']); return $this->setError('업로드가 제한된 파일 확장자입니다.(이미지파일만 등록가능)'); } } if ($this->_allowed && !preg_match('/\.('.$this->_allowed.')$/i', $file['name'])) { @unlink($file['tmp_name']); return $this->setError('업로드가 제한된 파일 확장자입니다.'); } if ( is_array($this->_allowedMimes) && !in_array($file_real_mime_type, $this->_allowedMimes) ) { @unlink($file['tmp_name']); return $this->setError('업로드가 제한된 파일 확장자입니다!'); } if ($this->_denied && preg_match('/\.('.$this->_denied.')(\.|$)/i', $file['name'])) { @unlink($file['tmp_name']); return $this->setError('업로드가 제한된 파일 확장자입니다.'); } if (preg_match('/\.(php[0-9]*|html|htm|inc|pl|xml|asp|jsp|exe|com|vbs|js)(\.|$)/i', $file['name'])) { @unlink($file['tmp_name']); return $this->setError('업로드가 제한된 파일 확장자입니다.'); } if ( in_array($file_real_mime_type, $this->_deniedMimesFixed) ) { @unlink($file['tmp_name']); return $this->setError('업로드가 제한된 파일 확장자입니다!!'); } if ( is_array($this->_deniedMimes) && count($this->_deniedMimes)>0 ) { if ( in_array($file_real_mime_type, $this->_deniedMimes) ) { @unlink($file['tmp_name']); return $this->setError('업로드가 제한된 파일 확장자입니다!!!'); } } // FTP총 용량 제한일 경우 if ( $this->checkFTPSize == TRUE && $this->maxFTPSize > 0 ){ // 현재FTP용량 확인 if ( $this->currentFTPsize<0 ){ $this->currentFTPsize = $this->getFtpUsed(); } if ( $this->maxFTPSize < $this->currentFTPsize + intval($file['size']) ){ @unlink($file['tmp_name']); return $this->setError( sprintf("FTP사용제한 용량을 초과하였습니다.(%s/%s)", byteConvert($this->currentFTPsize), byteConvert($this->maxFTPSize)) ); } } $check_name = explode(".",$file['name']); if (preg_match('/[^a-zA-Z0-9_]/', $check_name[0])) { $file['name'] = strtotime('now')."_".rand(100,999).".".$check_name[1]; } $filename = $this->encodeSiteFilePath($file['name'], false); $pos = strrpos($filename, '.'); if ( $pos===FALSE ) $pos = strlen($filename); // .이 존재하지 않으면 $filebase = substr($filename, 0, $pos); $pos_src = strrpos($file['name'], '.'); if ( $pos_src===FALSE ) $pos_src = strlen($file['name']); // .이 존재하지 않으면 $filebase_src = substr($file['name'], 0, $pos_src); if ($this->addTimestamp == 1) { $filebase .= "_" . time(); $filebase_src .= "_" . time(); } if ($this->encType == 2) { $filebase = md5($filebase); $filebase_src = md5($filebase_src); } else if ($this->encType == 1 && preg_match('/[^a-z0-9_ ]/', $filebase)) { $filebase = strtr(base64_encode($filebase), '+/=', '-_~'); $filebase_src = strtr(base64_encode($filebase_src), '+/=', '-_~'); } else { $filebase = strtr($filebase, '. ', ',_'); $filebase_src = strtr($filebase_src, '. ', ',_'); } $fileext = substr($filename, $pos+1); $fileext_src = substr($file['name'], $pos_src+1); if ($this->uploadCallback && function_exists($this->uploadCallback)) { $target_src = $target = $this->uploadCallback($file, $this->uploadPath, $overwrite); } else { $target = $filebase . '.' . $fileext; $target_src = $filebase_src . '.' . $fileext_src; if (!$overwrite) { $i = 1; while (is_file($this->uploadPath . '/' . $target)) { $target = $filebase . '_' . $i . '.' . $fileext; $target_src = $filebase_src . '_' . $i . '.' . $fileext_src; $i++; } } } $this->path = $this->uploadPath . '/' . $target; if (!move_uploaded_file($file['tmp_name'], $this->path)) { return $this->setError('업로드된 '.$file['name'].' 파일을 이동시키지 못했습니다.'); } chmod($this->path, $this->filePermission); $filepath = $this->decodeSiteFilePath($this->path, false); $ret = array(); $ret['name'] = $file['name']; $ret['new_name']= $target_src; $ret['path'] = str_replace($this->uploadBase . '/', '', $filepath); $ret['url'] = $this->urlBase . '/' . $ret['path']; $ret['size'] = $file['size']; $ret['type'] = $file['type']; $ret['ext'] = $fileext; $ret['mime'] = $file_real_mime_type; $ret['is_image'] = $this->isImage($file_real_mime_type); return $ret; } function download($filename="") { global $HTTP_USER_AGENT; set_time_limit(0); if($filename == "") $filename = getbasename($this->path); if(eregi("MSIE 5.5", $HTTP_USER_AGENT)) { // IE 5.5 버그로 인해 분리함. Header("Content-type: application/attachment"); Header("Content-Disposition: filename=".trim($filename)); } else { Header("Content-type: application/octet-stream"); Header("Content-Disposition: attachment; filename=".trim($filename)); } Header("Content-Length: ".filesize($this->path)); //Header("Cache-Control:no-cache"); //Header("Pragma: no-cache"); HTTP 1.0 에서 사용 1.1 에서도 호환 //header("Cache-Control: private"); //Header("Expires: 0"); $fp = fopen($this->path, "rb"); while(!feof($fp)) { print(fread($fp, 2048)); flush(); } fclose($fp); } function getTypeIcon($filename) { $ext = $this->getExt($filename); $url = "../html/images/file_icons/$ext.gif"; return "<img src='$url' align='absmiddle' width='15' height='15'>"; } function getExt($filename) { return strtolower(substr($filename, strrpos($filename, ".") + 1)); } function getFileList($path="") { if($path) $this->path = $path; if(!$handle = opendir($this->path)) return Exception("Open Directory Error: $this->path"); $ret = array(); $ret['file'] = $ret['dir'] = $ret['link'] = array(); while ($file = readdir($handle)) { if($file == "." || $file == "..") continue; if(is_file($this->path . "/" . $file)) $name = "file"; elseif(is_dir($this->path . "/" . $file)) $name = "dir"; elseif(is_link($this->path . "/" . $file)) $name = "link"; $ret[$name][] = $file; } return $ret; } function encodeSiteFilePath($filepath, $urlencode = false) { if (getConf('site.charset') != getConf('site.charset_file')) { $filepath = iconv(getConf('site.charset'), getConf('site.charset_file'), $filepath); } if ($urlencode) { $filepath = implode('/', array_map('urlencode', explode('/', $filepath))); } return $filepath; } function decodeSiteFilePath($filepath, $urldecode = false) { if ($urldecode) { $filepath = implode('/', array_map('urldecode', explode('/', $filepath))); } if (getConf('site.charset') != getConf('site.charset_file')) { $filepath = iconv(getConf('site.charset_file'), getConf('site.charset'), $filepath); } return $filepath; } // 디렉토리 내에 있는 파일들과 같이 삭제 function removeDirectoryRecursive($dir) { if (!is_dir($dir)) { return false; } $msg = ""; $files = array_diff(scandir($dir), array('.','..')); foreach ($files as $file) { if (is_dir($dir . "/" . $file)) { removeDirectoryRecursive($dir . "/" . $file); } else { if (unlink($dir . "/" . $file)) {; $msg .= $dir . "/" . $file."\n"; } } } if (rmdir($dir)) { $msg .= $dir ." deleted\n"; } return $msg; } // 디렉토리 용량 /* static 으로 사용가능 * File::getDirSize(getConf('dir.data')); */ function getDirSize($path) { $size = 0; // 윈도우OS일경우 느리지만;; if ( strtoupper(substr(PHP_OS, 0, 3)) == 'WIN' ){ $path = realpath($path); if($path!==false){ foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){ $size += $object->getSize(); } } }else{ $io = popen('/usr/bin/du -sb '.$path, 'r'); $size = intval(fgets($io,80)); pclose($io); } return $size; } // FTP(HDD) 사용량 /* static 으로 사용가능 * File::getFtpUsed(); */ function getFtpUsed() { $size = 0; $ftp_quota_path = realpath(getConf('dir.root').'/../.ftpquota'); if ( file_exists($ftp_quota_path) ) { $ftp_quota_body = @file_get_contents($ftp_quota_path); list($file_count, $size) = preg_split("/[\s]+/", trim($ftp_quota_body)); } return $size; } function setError($msg) { $this->errMsg = $msg; if($this->debug == 1) debug($msg); else if($this->debug == 2) error($msg); return false; } /** * Validate the image * * $file_type : file MIME-type * * @return bool */ function isImage($file_type) { // IE will sometimes return odd mime-types during upload, so here we just standardize all // jpegs or pngs to the same file type. $png_mimes = array('image/x-png'); $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); $bmp_mimes = array('image/bmp', 'image/x-windows-bmp'); if (in_array($file_type, $png_mimes)){ $file_type = 'image/png'; } if (in_array($file_type, $jpeg_mimes)){ $file_type = 'image/jpeg'; } if (in_array($file_type, $bmp_mimes)){ $file_type = 'image/bmp'; } $img_mimes = array( 'image/gif', 'image/jpeg', 'image/png', 'image/bmp', ); return (in_array($file_type, $img_mimes, TRUE)) ? TRUE : FALSE; } /** * File MIME type * * Detects the (actual) MIME type of the uploaded file, if possible. * The input array is expected to be $_FILES[$field] * * @param array * @return void */ function getFileMimeType($file) { // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; /* Fileinfo extension - most reliable method * * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the * more convenient FILEINFO_MIME_TYPE flag doesn't exist. */ if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); if (is_resource($finfo)) { // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system $mime = @finfo_file($finfo, $file['tmp_name']); finfo_close($finfo); /* According to the comments section of the PHP manual page, * it is possible that this function returns an empty string * for some files (e.g. if they don't exist in the magic MIME database) */ if (is_string($mime) && preg_match($regexp, $mime, $matches)) { return $matches[1]; } } } /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better * than mime_content_type() as well, hence the attempts to try calling the command line with * three different functions. * * Notes: * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system * - many system admins would disable the exec(), shell_exec(), popen() and similar functions * due to security concerns, hence the function_exists() checks */ if (DIRECTORY_SEPARATOR !== '\\') { $cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1'; if (function_exists('exec')) { /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. * However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy * value, which is only put to allow us to get the return status code. */ $mime = @exec($cmd, $mime, $return_status); if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) { return $matches[1]; } } if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec')) { $mime = @shell_exec($cmd); if (strlen($mime) > 0) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { return $matches[1]; } } } if (function_exists('popen')) { $proc = @popen($cmd, 'r'); if (is_resource($proc)) { $mime = @fread($proc, 512); @pclose($proc); if ($mime !== FALSE) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { return $matches[1]; } } } } } // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) if (function_exists('mime_content_type')) { $file_type = @mime_content_type($file['tmp_name']); if (strlen($file_type) > 0) { // It's possible that mime_content_type() returns FALSE or an empty string return $file_type; } } return $file['type']; } function getMimesTypes($file_ext) { if (count(File::$mimes) == 0) { if ( is_file(getConf('dir.lib') .'/mimes.php') ) { include getConf('dir.lib') .'/mimes.php'; } else { return FALSE; } File::$mimes = $mimes; unset($mimes); } return ( ! isset(File::$mimes[$file_ext])) ? FALSE : File::$mimes[$file_ext]; } }