/** * Return the mime type of a file. * * @return string|bool Returns the mime type or FALSE if the mime type could not be discovered */ public function getMimeType() { $mimeType = FALSE; if ($this->isFile()) { $fileExtensionToMimeTypeMapping = $GLOBALS['TYPO3_CONF_VARS']['SYS']['FileInfo']['fileExtensionToMimeType']; $lowercaseFileExtension = strtolower($this->getExtension()); if (!empty($fileExtensionToMimeTypeMapping[$lowercaseFileExtension])) { $mimeType = $fileExtensionToMimeTypeMapping[$lowercaseFileExtension]; } else { if (function_exists('finfo_file')) { $fileInfo = new \finfo(); $mimeType = $fileInfo->file($this->getPathname(), FILEINFO_MIME_TYPE); } elseif (function_exists('mime_content_type')) { $mimeType = mime_content_type($this->getPathname()); } } } if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Type\File\FileInfo::class]['mimeTypeGuessers']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Type\File\FileInfo::class]['mimeTypeGuesser'])) { foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS'][\TYPO3\CMS\Core\Type\File\FileInfo::class]['mimeTypeGuesser'] as $mimeTypeGuesser) { $hookParameters = array('mimeType' => &$mimeType); \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction($mimeTypeGuesser, $hookParameters, $this); } } return $mimeType; }
function execute($temp_name, $allow_existing_file = false) { if ($this->_autoRename) { $this->_cleanFilename(); $this->_path_target = $this->_findSafeFilename(); } if (!isset($this->_whitelist[$this->_file_extension])) { die('File extension is not permitted.'); } $finfo = new finfo(FILEINFO_MIME); $mime_type = $finfo->file($temp_name); $mime_type = explode(';', $mime_type); $mime_type = $mime_type[0]; if ($mime_type != $this->_whitelist[$this->_file_extension]) { die('File type/extension combination not permitted for security reasons.'); } if (is_uploaded_file($temp_name)) { if (!move_uploaded_file($temp_name, $this->_path_target)) { return false; } } elseif ($allow_existing_file) { if (!rename($temp_name, $this->_path_target)) { return false; } } else { return false; } chmod($this->_path_target, 0755); AMP_s3_save($this->_path_target); AMP_lookup_clear_cached('downloads'); return true; }
/** * Attachment constructor. * * @param string $filePath * @param string|null $type * @throws MessageException */ public function __construct(string $filePath, string $type = null) { // Check if file exists and is readable if (!@is_readable($filePath)) { throw MessageException::attachmentUnreadable(__METHOD__, $filePath); } $this->path = $filePath; // Save file path $this->type = $type; // Content type (if specified) $this->name = basename($this->path); $this->id = null; $this->disposition = "attachment"; // Check if content type is not explicit if (!$this->type) { // Check if "fileinfo" extension is loaded if (extension_loaded("fileinfo")) { $fileInfo = new \finfo(FILEINFO_MIME_TYPE); $this->type = $fileInfo->file($this->path); } if (!$this->type) { $this->type = self::fileType($this->name); } } }
/** * Defined by Zend_Validate_Interface * * Returns true if the mimetype of the file does not matche the given ones. Also parts * of mimetypes can be checked. If you give for example "image" all image * mime types will not be accepted like "image/gif", "image/jpeg" and so on. * * @param string $value Real file to check for mimetype * @param array $file File data from Zend_File_Transfer * @return boolean */ public function isValid($value, $file = null) { // Is file readable ? require_once 'Zend/Loader.php'; if (!Zend_Loader::isReadable($value)) { return $this->_throw($file, self::NOT_READABLE); } if ($file !== null) { if (class_exists('finfo', false) && defined('MAGIC')) { $mime = new finfo(FILEINFO_MIME); $this->_type = $mime->file($value); unset($mime); } elseif (function_exists('mime_content_type') && ini_get('mime_magic.magicfile')) { $this->_type = mime_content_type($value); } else { $this->_type = $file['type']; } } if (empty($this->_type)) { return $this->_throw($file, self::NOT_DETECTED); } $mimetype = $this->getMimeType(true); if (in_array($this->_type, $mimetype)) { return $this->_throw($file, self::FALSE_TYPE); } $types = explode('/', $this->_type); $types = array_merge($types, explode('-', $this->_type)); foreach ($mimetype as $mime) { if (in_array($mime, $types)) { return $this->_throw($file, self::FALSE_TYPE); } } return true; }
/** * Try download file */ public function download() { if ($this->fileInfo instanceof \SplFileInfo) { if ($this->fileInfo->isFile()) { if (is_array($this->validatorExtension)) { if (!in_array($this->fileInfo->getExtension(), $this->validatorExtension)) { throw new \Exception("Extensão invalida!"); } } if (!$this->fileInfo->isReadable()) { throw new \Exception("O Arquivo não pode ser lido!"); } if (is_null($this->newName)) { $this->setNewName($this->fileInfo->getBasename()); } $finfo = new \finfo(); header("Content-Type: {$finfo->file($this->fileInfo->getRealPath(), FILEINFO_MIME)}"); header("Content-Length: {$this->fileInfo->getSize()}"); header("Content-Disposition: attachment; filename={$this->newName}"); readfile($this->fileInfo->getRealPath()); } else { throw new \Exception("Por favor, adicione um arquivo valido!"); } } else { throw new \Exception("Por favor, adicione o arquivo primeiro!"); } }
/** * Attempt to get the mime type from a file. This method is horribly * unreliable, due to PHP being horribly unreliable when it comes to * determining the mime type of a file. * * $mime = File::mime($file); * * @param string $filename file name or path * * @return string mime type on success * @return FALSE on failure */ public static function mime($filename) { // Get the complete path to the file $filename = realpath($filename); // Get the extension from the filename $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); if (preg_match('/^(?:jpe?g|png|[gt]if|bmp|swf)$/', $extension)) { // Use getimagesize() to find the mime type on images try { $file = getimagesize($filename); } catch (\Exception $e) { } if (isset($file['mime'])) { return $file['mime']; } } if (class_exists('finfo', false)) { if ($info = new \finfo(defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE : FILEINFO_MIME)) { return $info->file($filename); } } if (ini_get('mime_magic.magicfile') and function_exists('mime_content_type')) { // The mime_content_type function is only useful with a magic file return mime_content_type($filename); } if (!empty($extension)) { return self::mime_by_ext($extension); } // Unable to find the mime-type return false; }
/** * Returns the suggested MIME type for an actual file. Using file-based heuristics * (data points in the ACTUAL file), it will utilize either the PECL FileInfo extension * OR the Magic MIME extension (if either are available) to determine the MIME type. If all * else fails, it will fall back to the basic GetMimeTypeForFilename() method. * * @param string $strFilePath the absolute file path of the ACTUAL file * @return string */ public static function GetMimeTypeForFile($strFilePath) { // Clean up the File Path and pull out the filename $strRealPath = realpath($strFilePath); if (!is_file($strRealPath)) { throw new QCallerException('File Not Found: ' . $strFilePath); } $strFilename = basename($strRealPath); $strToReturn = null; // First attempt using the PECL FileInfo extension if (class_exists('finfo')) { if (QMimeType::$MagicDatabaseFilePath) { $objFileInfo = new finfo(FILEINFO_MIME, QMimeType::$MagicDatabaseFilePath); } else { $objFileInfo = new finfo(FILEINFO_MIME); } $strToReturn = $objFileInfo->file($strRealPath); } // Next, attempt using the legacy MIME Magic extension if (!$strToReturn && function_exists('mime_content_type')) { $strToReturn = mime_content_type($strRealPath); } // Finally, use Qcodo's owns method for determining MIME type if (!$strToReturn) { $strToReturn = QMimeType::GetMimeTypeForFilename($strFilename); } if ($strToReturn) { return $strToReturn; } else { return QMimeType::_Default; } }
/** * Tries to determine the file type magically * @param string $data * @returns a string, the mime type, or null if none was found. */ public static function magicMimeType($data) { if (self::$finfo == null) { if (!class_exists('finfo')) { I2CE::raiseError('Magic file utilties not enabled. Please run \'pecl install Fileinfo\' or some such thing.'); return null; } $config = I2CE::getConfig(); $magic_file = null; if ($config->setIfIsSet($magic_file, "/modules/MimeTypes/magic_file")) { $magic_file = I2CE::getFileSearch()->search('MIME', $magic_file); if (!$magic_file) { $magic_file == null; } } //I2CE::raiseError("Using $magic_file"); //@self::$finfo = new finfo(FILEINFO_MIME, $magic_file); @(self::$finfo = new finfo(FILEINFO_MIME)); if (!self::$finfo) { I2CE::raiseError('Unable to load magic file database ' . $magic_file, E_USER_NOTICE); return null; } } if (!($mime_type = self::$finfo->buffer($data))) { I2CE::raiseError('Unable to determine mime type magically', E_USER_NOTICE); //some error occured return null; } return $mime_type; }
/** * @return string * * @throws Backend\SourceFileException */ public function getSource() { if ($this->src !== NULL) { return $this->src; } $source = file_get_contents($this->getPathname()); if ($source == '') { $this->src = ''; return ''; } if ($this->encoding == 'auto') { $info = new \finfo(); $this->encoding = $info->file((string) $this, FILEINFO_MIME_ENCODING); } try { $source = iconv($this->encoding, 'UTF-8//TRANSLIT', $source); } catch (\ErrorException $e) { throw new SourceFileException('Encoding error - conversion to UTF-8 failed', SourceFileException::BadEncoding, $e); } // Replace xml relevant control characters by surrogates $this->src = preg_replace_callback('/(?![\\x{000d}\\x{000a}\\x{0009}])\\p{C}/u', function (array $matches) { $unicodeChar = '\\u' . (2400 + ord($matches[0])); return json_decode('"' . $unicodeChar . '"'); }, $source); return $this->src; }
public function fileSave($data, \Uppu3\Entity\User $user) { $fileResource = new File(); //$fileResource->saveFile($data['load']); $fileResource->setName($data['load']['name']); $fileResource->setSize($data['load']['size']); $finfo = new \finfo(FILEINFO_MIME_TYPE); $fileResource->setExtension($finfo->file($data['load']['tmp_name'])); //$fileResource->setMediainfo($data['load']['tmp_name']); $fileResource->setComment($_POST['comment']); $mediainfo = \Uppu3\Entity\MediaInfo::getMediaInfo($data['load']['tmp_name']); //$mediainfo = json_encode($mediainfo); $fileResource->setMediainfo($mediainfo); $fileResource->setUploaded(); $fileResource->setUploadedBy($user); $this->em->persist($fileResource); $this->em->flush(); $id = $fileResource->getId(); $tmpFile = $data['load']['tmp_name']; $newFile = \Uppu3\Helper\FormatHelper::formatUploadLink($id, $data['load']['name']); $result = move_uploaded_file($tmpFile, $newFile); if (in_array($fileResource->getExtension(), $this->pictures)) { $path = \Uppu3\Helper\FormatHelper::formatUploadResizeLink($id, $data['load']['name']); $resize = new \Uppu3\Helper\Resize(); $resize->resizeFile($newFile, $path); } return $fileResource; }
public static function upload($data, $file) { if (isset($file)) { $tmpFile = $_FILES["file"]["tmp_name"]; $idArticle = $data['idArticle']; $finfo = new \finfo(FILEINFO_MIME_TYPE); $mime = $finfo->file($file['tmp_name']); switch ($mime) { case 'image/jpeg': $extension = ".jpg"; $destination = IMAGES_PATH; break; case 'image/png': $extension = ".png"; $destination = IMAGES_PATH; break; case 'image/gif': $extension = ".gif"; $destination = IMAGES_PATH; break; case 'application/pdf': $extension = ".pdf"; $destination = DOCS_PATH; break; default: throw new UploadException("Ce n'est pas le bon type de fichier"); break; } $fileName = !empty($nameOfFile) ? uniqid('articleFile_' . $idArticle . '_') : ''; $chemin = $destination . $fileName . $extension; list($width, $height) = getimagesize($tmpFile); } }
public function __construct($file, $validate) { parent::__construct(); if (!is_string($file) || (!is_readable($file))) { throw new DocBlox_Reflection_Exception('The given file should be a string, should exist on the filesystem and should be readable'); } if ($validate) { exec('php -l '.escapeshellarg($file), $output, $result); if ($result != 0) { throw new DocBlox_Reflection_Exception('The given file could not be interpreted as it contains errors: '.implode(PHP_EOL, $output)); } } $this->filename = $file; $this->name = $this->filename; $contents = file_get_contents($file); // detect encoding and transform to UTF-8 $info = new finfo(); $mime = $info->file($file, FILEINFO_MIME); $mime_info = explode('=', $mime); if (strtolower($mime_info[1]) != 'utf-8') { $contents = iconv($mime_info[1], 'UTF-8', $contents); } $this->contents = $contents; $this->setHash(filemtime($file)); }
public function addFile($field_name, $absolute_filename_path) { $file_info = new \finfo(FILEINFO_MIME); $mime_type = $file_info->buffer(file_get_contents($absolute_filename_path)); $mime = explode(';', $mime_type); $this->files[$field_name] = curl_file_create($absolute_filename_path, reset($mime), basename($absolute_filename_path)); }
/** * checks mime type of file * @param string $file * @return bool * @access private */ public static function getMime($file) { $mime = null; if (class_exists("finfo")) { $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->file($file); } if (function_exists("finfo_open")) { $finfo = finfo_open(FILEINFO_MIME); $mime = finfo_file($finfo, $file); finfo_close($finfo); } else { $fp = fopen($file, 'r'); $str = fread($fp, 4); fclose($fp); switch ($str) { case "ÿØÿà": $mime = 'image/jpeg'; break; case "‰PNG": $mime = 'image/png'; break; case 'GIF8': $mime = 'image/gif'; break; default: trigger_error("Tell the guy behind the levers of i² to see {$str} as a valid file. Thank you //Sincerely, i ", E_USER_ERROR); $mime = $str; } } if (preg_match("/[a-zA-Z]+\\/[a-zA-Z]+.+/", $mime)) { $mime = preg_replace("/([a-zA-Z]+\\/[a-zA-Z]+)(.+)/", "\$1", $mime); } return $mime; }
/** * * @param string $filepath */ public function __construct($filepath) { $this->filepath = $filepath; $this->basename = basename($filepath); $finfo = new \finfo(FILEINFO_MIME); list($this->mime, $this->charset) = explode('; ', $finfo->file($filepath)); }
private function file_check() { try { if (!isset($_FILES['upfile']['error']) || !is_int($_FILES['upfile']['error'])) { throw new RuntimeException("不正なパラメータです。管理人にお問い合わせください。"); } switch ($_FILES["upfile"]["error"]) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: throw new RuntimeException("ファイルが選択されていません。"); break; case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new RuntimeException("ファイルサイズが許容値を超えています。"); break; default: throw new RuntimeException("不明なエラーが発生しました。"); } $finfo = new finfo(FILEINFO_MIME_TYPE); if (!array_search($finfo->file($_FILES["upfile"]["tmp_name"]), array("oud" => 'text/plain'), true) || pathinfo($_FILES["upfile"]["name"])["extension"] !== "oud") { throw new RuntimeException("oudファイルではありません。"); } $fp = fopen($_FILES["upfile"]["tmp_name"], "r"); if (!preg_match("/FileType=OuDia/", fgets($fp))) { throw new RuntimeException("oudファイルですが、書式が正しくありません。"); } fclose($fp); } catch (Exception $e) { echo "エラーが発生しました:" . $e->getMessage(); exit; } }
/** * Overloaded method onSave() * Executed whenever the user clicks at the save button */ public function onSave() { // first, use the default onSave() $object = parent::onSave(); // if the object has been saved if ($object instanceof Product) { $source_file = 'tmp/' . $object->photo_path; $target_file = 'images/' . $object->photo_path; $finfo = new finfo(FILEINFO_MIME_TYPE); // if the user uploaded a source file if (file_exists($source_file) and $finfo->file($source_file) == 'image/png') { // move to the target directory rename($source_file, $target_file); try { TTransaction::open($this->database); // update the photo_path $object->photo_path = 'images/' . $object->photo_path; $object->store(); TTransaction::close(); } catch (Exception $e) { new TMessage('error', '<b>Error</b> ' . $e->getMessage()); TTransaction::rollback(); } } } }
public function validateTheFIle($UserInputedFIle) { $acceptable = array('image/gif', 'image/jpeg', 'image/png', 'application/x-shockwave-flash', 'image/psd', 'image/bmp', 'image/tiff', 'image/tiff', 'image/jp2', 'image/iff', 'image/vnd.wap.wbmp', 'image/xbm', 'image/vnd.microsoft.icon'); try { $finfo = new finfo(FILEINFO_MIME); $type = $finfo->file($UserInputedFIle['userfile']['tmp_name']); $mime = substr($type, 0, strpos($type, ';')); if (!in_array($mime, $acceptable)) { throw new RuntimeException('Invalid file type. Only JPG, GIF and PNG types are accepted.'); } elseif ($UserInputedFIle['userfile']['size'] > 1073741824) { throw new RuntimeException('Exceeded filesize limit.'); } elseif ($UserInputedFIle['userfile']['size'] < 0.5) { throw new RuntimeException('You have to choose a file'); } else { $this->response[0] = true; $UserInputedFIle['userfile']['name'] = $this->changeName($UserInputedFIle['userfile']['name'], pathinfo($UserInputedFIle["userfile"]["name"], PATHINFO_EXTENSION)); $this->response[1] = $UserInputedFIle['userfile']['name']; return $this->response; } } catch (RuntimeException $ex) { $this->response[0] = false; $this->response[1] = $ex->getMessage(); return $this->response; } }
public function checkForImages($arrFiles) { global $GLOBALS; if (isset($GLOBALS['TL_CONFIG']['krakenIo_enable']) && $GLOBALS['TL_CONFIG']['krakenIo_enable'] == true) { if (isset($GLOBALS['TL_CONFIG']['krakenIo_apiKey']) && isset($GLOBALS['TL_CONFIG']['krakenIo_apiSecret'])) { $getMimeType = new \finfo(FILEINFO_MIME_TYPE); $allowedTypes = array('image/jpeg', 'image/png'); $krakenIoApi = new KrakenIoApi($GLOBALS['TL_CONFIG']['krakenIo_apiKey'], $GLOBALS['TL_CONFIG']['krakenIo_apiSecret']); foreach ($arrFiles as $file) { if (in_array($getMimeType->file(TL_ROOT . '/' . $file), $allowedTypes)) { if (!strpos('assets', $file)) { $params = array('file' => TL_ROOT . '/' . $file, 'wait' => true); if (isset($GLOBALS['TL_CONFIG']['krakenIo_enable']) && $GLOBALS['TL_CONFIG']['krakenIo_enable'] == true) { $params['lossy'] = true; } $krakenIoApiResponse = $krakenIoApi->upload($params); $this->parseKrakenIoResponse($krakenIoApiResponse, $file); } } } } else { \System::log($GLOBALS['TL_LANG']['ERR']['krakenIo_404'], 'krakenIoInterface parseKrakenIoResponse()', TL_ERROR); } } }
public function validate($data) { // test if the host supports finfo try { $supportsFinfo = class_exists('finfo'); } catch (loader_ClassNotFoundException $e) { $supportsFinfo = false; } if ($data == '') { return true; // if finfo class exists then use that for mime validation } elseif ($supportsFinfo && $data['tmp_name']) { $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->file($data['tmp_name']); if (strpos($mime, ';')) { $mime = substr($mime, 0, strpos($mime, ';')); } if (in_array($mime, $this->mimeTypes)) { return true; } $incorrectExtensionArr = $this->getExtensionFromMime($mime); // reply on the browsers mime type : not always present & secruity vunrebility } elseif (isset($data['type'])) { if (in_array($data['type'], $this->mimeTypes)) { return true; } $incorrectExtensionArr = $this->getExtensionFromMime($data['type']); } throw new ValidationIncorrectFileTypeException(sf('File should be a valid %s%s', $this->extensionText, count($incorrectExtensionArr) ? sf(' (not a %s)', implode('/', $incorrectExtensionArr)) : '')); }
/** * @param $filepath * @param string|null $type set mime type * @return mixed */ public function send($filepath, $type = null) { if (empty($type)) { $finfo = new \finfo(FILEINFO_MIME_TYPE); $type = $finfo->file($filepath); } $getData = array(); $url = 'upload/'; $postData = array('|file[]' => '@' . $filepath . ";type=" . trim($type, ';') . ";"); $addToken = true; if (!is_string($filepath)) { throw new Exception('$file_url doit être une chaîne de caractères.'); } $this->getClient()->buildURL($url, $getData, $postData, $addToken); $ch = curl_init(); curl_setopt_array($ch, array(CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLINFO_HEADER_OUT => true, CURLOPT_HEADER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData)); $res = explode("\r\n\r\n", curl_exec($ch)); $info = curl_getinfo($ch); $info = array('request' => array('url' => $info['url'], 'header' => curl_getinfo($ch, CURLINFO_HEADER_OUT), 'post_data' => json_encode($postData), 'content_type' => $info['content_type']), 'response' => array('header' => $res[0], 'http_code' => $info['http_code'], 'data' => json_decode($res[1], true))); $this->getClient()->setLastRequest($info['request']); $this->getClient()->setLastResponse($info['response']); if ($info['response']['http_code'] != '200') { $this->getClient()->getLogger()->critical('CURL Request failed'); if ($this->getClient()->isDebugMode()) { throw new Exception('CURL Request failed.'); } } curl_close($ch); $jsonData = json_decode($res[2], true); return isset($jsonData['data'][0]) ? $jsonData['data'][0] : null; }
/** * Determine the mime-type of a file. * * @param string $filename The full, absolute path to a file. * @return string The mime type. */ public static function get_mime_type($filename) { if (extension_loaded('fileinfo')) { try { $finfo = new \finfo(FILEINFO_MIME_TYPE); return $finfo->file($filename); } catch (\Exception $e) { // Try next option... } } if (function_exists('mime_content_type')) { try { return mime_content_type($filename); } catch (\Exception $e) { // Try next option... } } $mime = \pdyn\filesystem\Mimetype::ext2mime(static::get_ext($filename)); // Strip out encoding, if present. if (mb_strpos($mime, ';') !== false) { $mime = explode(';', $mime); $mime = $mime[0]; } return $mime; }
/** * Renders a scaled version of the image referenced by the provided filename, taken any (optional) manipulators into consideration. * @param String $sourceData The binary data of the original source image. * @param Array $scaleParams * @param Int $imageType One of the PHP image type constants, such as IMAGETYPE_JPEG * @return Array * ['resource'] The image file data string * ['mime'] Mime type of the generated cache file * ['timestamp'] Timestamp of the generated cache file **/ public function scale($sourceData, $scaleParams, $imageType) { $this->_setInputParams($scaleParams); $mem = new Garp_Util_Memory(); $mem->useHighMemory(); if (strlen($sourceData) == 0) { throw new Exception("This is an empty file!"); } if (!($source = imagecreatefromstring($sourceData))) { $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->buffer($sourceData); throw new Exception("This source image could not be scaled. It's probably not a valid file type. Instead, this file is of the following type: " . $mime); } $this->_analyzeSourceImage($source, $imageType); $this->_addOmittedCanvasDimension(); if ($this->_isFilterDefined($scaleParams)) { Garp_Image_Filter::filter($source, $scaleParams['filter']); } if ($this->_isSourceEqualToTarget($scaleParams)) { $outputImage = $sourceData; } else { $canvas = $this->_createCanvasImage($imageType); $this->_projectSourceOnCanvas($source, $canvas); // Enable progressive jpegs imageinterlace($canvas, true); $outputImage = $this->_renderToImageData($canvas); imagedestroy($canvas); } $output = array('resource' => $outputImage, 'mime' => $this->params['mime'], 'timestamp' => time()); imagedestroy($source); return $output; }
function isValid() { $filePathId = $this->getFieldValue(); import('lib.pkp.classes.file.TemporaryFileDAO'); $tempFileDAO = new TemporaryFileDAO(); $finfo = new finfo(FILEINFO_MIME); foreach ($filePathId as $fId) { if (is_numeric($fId)) { $user =& Request::getUser(); $tempFile = $tempFileDAO->getTemporaryFile($fId, $user->getId()); $file_path = $tempFile->getFilePath(); $fType = $finfo->file($file_path); $pattern = "/application\\/zip/"; $patternPDF = "/application\\/pdf/"; if (preg_match($pattern, $fType)) { return true; } if (preg_match($patternPDF, $fType)) { return true; } return false; } return true; } }
/** * Check file mime type * @access public * @param string $name * @param string $path * @param string $type * @return bool */ public function check($name, $path) { $extension = strtolower(substr($name, strrpos($name, '.') + 1)); $mimetype = null; if (function_exists('finfo_open')) { if (!($finfo = new finfo(FILEINFO_MIME_TYPE))) { return true; } $mimetype = $finfo->file($path); } else { if (function_exists('mime_content_type')) { $mimetype = @mime_content_type($path); } } if ($mimetype) { $mime = self::getMime($mimetype); if ($mime) { if (!in_array($extension, $mime)) { return false; } } } // server doesn't support mime type check, let it through... return true; }
public function prepare() { if (!isset($this->img['src'])) { $this->gifsupport = function_exists('imagegif'); // if mimetype detected and in imagemap -> change format if (class_exists("finfo") && ($finfo = new finfo(FILEINFO_MIME_TYPE))) { if ($ftype = @$finfo->file($this->img['filepath'])) { if (array_key_exists($ftype, $this->image_mimetype_map)) { $this->img['format'] = $this->image_mimetype_map[$ftype]; } } } // ----- detect image format if ($this->img['format'] == 'jpg' || $this->img['format'] == 'jpeg') { $this->img['format'] = 'jpeg'; $this->img['src'] = @imagecreatefromjpeg($this->img['filepath']); } elseif ($this->img['format'] == 'png') { $this->img['src'] = @imagecreatefrompng($this->img['filepath']); imagealphablending($this->img['src'], false); imagesavealpha($this->img['src'], true); } elseif ($this->img['format'] == 'gif') { if ($this->gifsupport) { $this->img['src'] = @imagecreatefromgif($this->img['filepath']); } } elseif ($this->img['format'] == 'wbmp') { $this->img['src'] = @imagecreatefromwbmp($this->img['filepath']); } if (isset($this->img['src'])) { $this->refreshDimensions(); } } }
function forceDownload($original, $ghost) { if (is_readable($original)) { if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } $ghost = empty($ghost) ? basename($original) : $ghost; $finfo = new finfo(FILEINFO_MIME_TYPE); $mime = $finfo->file($original); header('Pragma: public'); // required header('Expires: 0'); // no cache header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($original)) . ' GMT'); header('Cache-Control: private', false); header('Content-Type: ' . $mime); // Add the mime type from CodeIgniter. header('Content-Disposition: attachment; filename="' . basename($ghost) . '"'); // Add the file name header('Content-Transfer-Encoding: binary'); header('Content-Length: ' . filesize($original)); // provide file size header('Connection: close'); readfile($original); // push it out exit; } else { die('Requested file not found!'); } }
function uploadFile($uploadUrl, $filePath, $blockSize = 1024) { $filePath = realpath($filePath); /* determing file mime-type */ $finfo = new finfo(FILEINFO_MIME_TYPE); $contentType = $finfo->file($filePath); $fileSize = filesize($filePath); $fp = fopen($filePath, "rb"); /* Perform chunked file uploading */ for ($i = 0; $i * $blockSize < $fileSize; $i++) { if (($i + 1) * $blockSize > $fileSize) { $size = $fileSize - $i * $blockSize; } else { $size = $blockSize; } $data = fread($fp, $size); $opts = array('http' => array('method' => 'PUT', 'header' => array('Content-type: ' . $contentType, "X-File-Chunk: {$i}"), 'content' => $data)); $context = stream_context_create($opts); $uploadResponse = json_decode(file_get_contents($uploadUrl, false, $context)); if (!$uploadResponse->ok) { return (object) array("ok" => FALSE, "errorMessage" => $uploadResponse->errorMessage); } } return (object) array("ok" => TRUE, "numberOfChunks" => $fileSize / $blockSize + 1); }
function getImageType($image_binary) { $data = base64_decode($image_binary); $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->buffer($data); return $type; }
/** * Pasa el archivo cache * @param string $ubicacion * @param string $nombre * @return string hash del cache */ public function cache($ubicacion, $nombre = null, $bo_file = true) { $this->_hash = null; $cache = $this->_ci->cache->iniciar(); while (is_null($this->_hash)) { $this->_hash = $this->_ci->random->rand_string(20) . time(); if ($existe = $cache->load($this->_hash)) { $this->_hash = null; } } if (is_null($nombre)) { $nombre = basename($ubicacion); } if ($bo_file) { $archivo = file_get_contents($ubicacion); $mime = mime_content_type($ubicacion); $tipo = pathinfo($ubicacion, PATHINFO_EXTENSION); } else { $archivo = $ubicacion; $finfo = new finfo(FILEINFO_MIME); $mime = $finfo->buffer($ubicacion); $explode = explode(".", $nombre); $tipo = strtolower($explode[count($explode) - 1]); } $cache->save(array("archivo" => $archivo, "archivo_nombre" => $nombre, "mime" => $mime, "tipo" => $tipo), $this->_hash); return $this->_hash; }