function __construct($interface, $files_directory) { $field = filter_input(INPUT_POST, 'field', FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES); // Check for file upload. if ($field === NULL || empty($_FILES) || !isset($_FILES['file'])) { return; } $this->interface = $interface; // Create a new result object. $this->result = new stdClass(); // Set directory. $this->files_directory = $files_directory; // Create the temporary directory if it doesn't exist. $dirs = array('', '/files', '/images', '/videos', '/audios'); foreach ($dirs as $dir) { if (!H5PCore::dirReady($this->files_directory . $dir)) { $this->result->error = $this->interface->t('Unable to create directory.'); return; } } // Get the field. $this->field = json_decode($field); if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $this->type = finfo_file($finfo, $_FILES['file']['tmp_name']); finfo_close($finfo); } elseif (function_exists('mime_content_type')) { // Deprecated, only when finfo isn't available. $this->type = mime_content_type($_FILES['file']['tmp_name']); } else { $this->type = $_FILES['file']['type']; } $this->extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); $this->size = $_FILES['file']['size']; }
/** * 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; } }
/** * Converts a file path into a "file" format value * @param string $filename * @param string $uploads_dir * @return string */ function P4A_Filename2File($filename, $uploads_dir) { if (!is_file($filename)) { return false; } $aFile['name'] = basename($filename); $aFile['path'] = str_replace($uploads_dir, '', $filename); $aFile['size'] = filesize($filename); $aFile['type'] = null; if (function_exists("mime_content_type")) { $aFile['type'] = mime_content_type($filename); } if (empty($aFile['type']) and class_exists("finfo")) { $finfo = new finfo(FILEINFO_MIME); $aFile['type'] = $finfo->file($filename); $finfo->close(); } list($type, $subtype) = explode('/', $aFile['type']); if ($type == 'image') { list($aFile['width'], $aFile['height']) = getimagesize($filename); } else { $aFile['width'] = null; $aFile['height'] = null; } return P4A_Array2File($aFile); }
/** * 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; }
/** * 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; }
public function __construct($video, $mime = null, $isBinary = false) { if (isset($video) and !empty($video)) { if (!$isBinary) { if (is_file($video)) { $peaces = explode("/", $video); $this->name = $peaces[count($peaces) - 1]; $this->path = str_replace($this->name, "", $video); $this->mime = isset($mime) ? $mime : mime_content_type($video); } else { throw new \Exception("Video is invalid!"); } } else { if ($isBinary) { if (empty($mime) || !isset($mime) || $mime == null) { throw new \Exception("Mime is empty!"); } $this->TMP = true; $this->name = rand(0, 100) . date("d-m-Y-His") . ".tmp"; $this->path = __DIR__ . "/resources/TMP/"; $ponteiro = fopen($this->path . $this->name, "w"); fwrite($ponteiro, $video); fclose($ponteiro); unset($video); $this->mime = $mime; } else { throw new \Exception("Video is invalid!"); } } } else { throw new \Exception("Video is empty!"); } }
function check($contents, $file) { $this->scanned_files[] = $file; if (preg_match('/<\\?php/', $contents) == false) { return; } $infected = false; foreach ($this->scan_patterns as $pattern) { if (preg_match($pattern, $contents)) { if ($file !== __FILE__) { $this->infected_files[] = array('file' => $file, 'pattern_matched' => $pattern); $infected = true; break; } } } if (substr($file, -4) == '.php') { $mime = mime_content_type($file); $mime_a = explode('/', $mime); if ($mime_a[0] != "text") { if ($infected) { $pattern_desc = $this->infected_files[count($this->infected_files) - 1]['pattern_matched']; $this->infected_files[count($this->infected_files) - 1]['pattern_matched'] = $pattern_desc . " - suspicious mime ({$mime})"; } else { $this->infected_files[count($this->infected_files) - 1]['pattern_matched'] = array('file' => $file, 'pattern_matched' => "suspicious mime type ({$mime})"); } } } }
function get_file_mime_type($filename, $debug = false) { if (function_exists('finfo_open') && function_exists('finfo_file') && function_exists('finfo_close')) { $fileinfo = finfo_open(FILEINFO_MIME); $mime_type = finfo_file($fileinfo, $filename); finfo_close($fileinfo); if (!empty($mime_type)) { if (true === $debug) { return array('mime_type' => $mime_type, 'method' => 'fileinfo'); } return $mime_type; } } if (function_exists('mime_content_type')) { $mime_type = mime_content_type($filename); if (!empty($mime_type)) { if (true === $debug) { return array('mime_type' => $mime_type, 'method' => 'mime_content_type'); } return $mime_type; } } $mime_types = array('ai' => 'application/postscript', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'asc' => 'text/plain', 'asf' => 'video/x-ms-asf', 'asx' => 'video/x-ms-asf', 'au' => 'audio/basic', 'avi' => 'video/x-msvideo', 'bcpio' => 'application/x-bcpio', 'bin' => 'application/octet-stream', 'bmp' => 'image/bmp', 'bz2' => 'application/x-bzip2', 'cdf' => 'application/x-netcdf', 'chrt' => 'application/x-kchart', 'class' => 'application/octet-stream', 'cpio' => 'application/x-cpio', 'cpt' => 'application/mac-compactpro', 'csh' => 'application/x-csh', 'css' => 'text/css', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'djv' => 'image/vnd.djvu', 'djvu' => 'image/vnd.djvu', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'doc' => 'application/msword', 'dvi' => 'application/x-dvi', 'dxr' => 'application/x-director', 'eps' => 'application/postscript', 'etx' => 'text/x-setext', 'exe' => 'application/octet-stream', 'ez' => 'application/andrew-inset', 'flv' => 'video/x-flv', 'gif' => 'image/gif', 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'hdf' => 'application/x-hdf', 'hqx' => 'application/mac-binhex40', 'htm' => 'text/html', 'html' => 'text/html', 'ice' => 'x-conference/x-cooltalk', 'ief' => 'image/ief', 'iges' => 'model/iges', 'igs' => 'model/iges', 'img' => 'application/octet-stream', 'iso' => 'application/octet-stream', 'jad' => 'text/vnd.sun.j2me.app-descriptor', 'jar' => 'application/x-java-archive', 'jnlp' => 'application/x-java-jnlp-file', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'js' => 'application/x-javascript', 'kar' => 'audio/midi', 'kil' => 'application/x-killustrator', 'kpr' => 'application/x-kpresenter', 'kpt' => 'application/x-kpresenter', 'ksp' => 'application/x-kspread', 'kwd' => 'application/x-kword', 'kwt' => 'application/x-kword', 'latex' => 'application/x-latex', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'm3u' => 'audio/x-mpegurl', 'man' => 'application/x-troff-man', 'me' => 'application/x-troff-me', 'mesh' => 'model/mesh', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mif' => 'application/vnd.mif', 'mov' => 'video/quicktime', 'movie' => 'video/x-sgi-movie', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpe' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpga' => 'audio/mpeg', 'ms' => 'application/x-troff-ms', 'msh' => 'model/mesh', 'mxu' => 'video/vnd.mpegurl', 'nc' => 'application/x-netcdf', 'odb' => 'application/vnd.oasis.opendocument.database', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odf' => 'application/vnd.oasis.opendocument.formula', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odi' => 'application/vnd.oasis.opendocument.image', 'odm' => 'application/vnd.oasis.opendocument.text-master', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odt' => 'application/vnd.oasis.opendocument.text', 'ogg' => 'application/ogg', 'otg' => 'application/vnd.oasis.opendocument.graphics-template', 'oth' => 'application/vnd.oasis.opendocument.text-web', 'otp' => 'application/vnd.oasis.opendocument.presentation-template', 'ots' => 'application/vnd.oasis.opendocument.spreadsheet-template', 'ott' => 'application/vnd.oasis.opendocument.text-template', 'pbm' => 'image/x-portable-bitmap', 'pdb' => 'chemical/x-pdb', 'pdf' => 'application/pdf', 'pgm' => 'image/x-portable-graymap', 'pgn' => 'application/x-chess-pgn', 'png' => 'image/png', 'pnm' => 'image/x-portable-anymap', 'ppm' => 'image/x-portable-pixmap', 'ppt' => 'application/vnd.ms-powerpoint', 'ps' => 'application/postscript', 'qt' => 'video/quicktime', 'ra' => 'audio/x-realaudio', 'ram' => 'audio/x-pn-realaudio', 'ras' => 'image/x-cmu-raster', 'rgb' => 'image/x-rgb', 'rm' => 'audio/x-pn-realaudio', 'roff' => 'application/x-troff', 'rpm' => 'application/x-rpm', 'rtf' => 'text/rtf', 'rtx' => 'text/richtext', 'sgm' => 'text/sgml', 'sgml' => 'text/sgml', 'sh' => 'application/x-sh', 'shar' => 'application/x-shar', 'silo' => 'model/mesh', 'sis' => 'application/vnd.symbian.install', 'sit' => 'application/x-stuffit', 'skd' => 'application/x-koan', 'skm' => 'application/x-koan', 'skp' => 'application/x-koan', 'skt' => 'application/x-koan', 'smi' => 'application/smil', 'smil' => 'application/smil', 'snd' => 'audio/basic', 'so' => 'application/octet-stream', 'spl' => 'application/x-futuresplash', 'src' => 'application/x-wais-source', 'stc' => 'application/vnd.sun.xml.calc.template', 'std' => 'application/vnd.sun.xml.draw.template', 'sti' => 'application/vnd.sun.xml.impress.template', 'stw' => 'application/vnd.sun.xml.writer.template', 'sv4cpio' => 'application/x-sv4cpio', 'sv4crc' => 'application/x-sv4crc', 'swf' => 'application/x-shockwave-flash', 'sxc' => 'application/vnd.sun.xml.calc', 'sxd' => 'application/vnd.sun.xml.draw', 'sxg' => 'application/vnd.sun.xml.writer.global', 'sxi' => 'application/vnd.sun.xml.impress', 'sxm' => 'application/vnd.sun.xml.math', 'sxw' => 'application/vnd.sun.xml.writer', 't' => 'application/x-troff', 'tar' => 'application/x-tar', 'tcl' => 'application/x-tcl', 'tex' => 'application/x-tex', 'texi' => 'application/x-texinfo', 'texinfo' => 'application/x-texinfo', 'tgz' => 'application/x-gzip', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'torrent' => 'application/x-bittorrent', 'tr' => 'application/x-troff', 'tsv' => 'text/tab-separated-values', 'txt' => 'text/plain', 'ustar' => 'application/x-ustar', 'vcd' => 'application/x-cdlink', 'vrml' => 'model/vrml', 'wav' => 'audio/x-wav', 'wax' => 'audio/x-ms-wax', 'wbmp' => 'image/vnd.wap.wbmp', 'wbxml' => 'application/vnd.wap.wbxml', 'wm' => 'video/x-ms-wm', 'wma' => 'audio/x-ms-wma', 'wml' => 'text/vnd.wap.wml', 'wmlc' => 'application/vnd.wap.wmlc', 'wmls' => 'text/vnd.wap.wmlscript', 'wmlsc' => 'application/vnd.wap.wmlscriptc', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wrl' => 'model/vrml', 'wvx' => 'video/x-ms-wvx', 'xbm' => 'image/x-xbitmap', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'xls' => 'application/vnd.ms-excel', 'xml' => 'text/xml', 'xpm' => 'image/x-xpixmap', 'xsl' => 'text/xml', 'xwd' => 'image/x-xwindowdump', 'xyz' => 'chemical/x-xyz', 'zip' => 'application/zip'); $ext = strtolower(array_pop(explode('.', $filename))); if (!empty($mime_types[$ext])) { if (true === $debug) { return array('mime_type' => $mime_types[$ext], 'method' => 'from_array'); } return $mime_types[$ext]; } if (true === $debug) { return array('mime_type' => 'application/octet-stream', 'method' => 'last_resort'); } return 'application/octet-stream'; }
/** * @param GetResponseEvent $event */ public function onKernelRequest(GetResponseEvent $event) { if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) { return; } /* @var $request Request */ $request = $event->getRequest(); $file = $request->getScriptName() == '/app_dev.php' ? $request->getPathInfo() : $request->getScriptName(); if (is_file($file = $this->root_dir . '/../web' . $file)) { $response = (new Response())->setPublic(); // caching in prod env if ($this->env == 'prod') { $response->setEtag(md5_file($file))->setExpires((new \DateTime())->setTimestamp(time() + 2592000))->setLastModified((new \DateTime())->setTimestamp(filemtime($file)))->headers->addCacheControlDirective('must-revalidate', true); // response was not modified for this request if ($response->isNotModified($request)) { $event->setResponse($response); return; } } // set content type $mimes = ['css' => 'text/css', 'js' => 'text/javascript']; if (isset($mimes[$ext = pathinfo($file, PATHINFO_EXTENSION)])) { $response->headers->set('Content-Type', $mimes[$ext]); } else { $response->headers->set('Content-Type', mime_content_type($file)); } $event->setResponse($response->setContent(file_get_contents($file))); } }
public function download($nombre) { $path = PATH_FILES . $nombre; $type = ''; if (is_file($path)) { $size = filesize($path); if (function_exists('mime_content_type')) { $type = mime_content_type($path); } else { if (function_exists('finfo_file')) { $info = finfo_open(FILEINFO_MIME); $type = finfo_file($info, $path); finfo_close($info); } } if ($type == '') { $type = "application/force-download"; } header("Content-Type: {$type}"); header("Content-Disposition: attachment; filename={$nombre}"); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . $size); readfile($path); } else { die("El archivo no existe."); } }
public static function getMime($file) { // Check if file is an image. $info = @getimagesize($file); if ($info) { $type = $info['mime']; } elseif (function_exists('finfo_open')) { // We have fileinfo. $finfo = finfo_open(FILEINFO_MIME_TYPE); $type = finfo_file($finfo, $file); finfo_close($finfo); } elseif (function_exists('mime_content_type')) { // We have mime magic. $type = mime_content_type($file); } else { $type = false; } return $type; }
/** * Detect archive format * * @param string $filePath archive file path * * @return string archive format see $_availableFormats property values */ public static function getArchiveFormat($filePath) { if (!is_readable($filePath)) { throw new BaseZF_Archive_Exception(sprintf('Could not open file "%s"', $filePath)); } $extention = pathinfo($filePath, PATHINFO_EXTENSION); $mimeType = null; // use $minType only if mime_content_type is available if (function_exists('mime_content_type')) { $mimeType = trim(mime_content_type($filePath)); } // compare mine types foreach (self::$_availableFormats as $formatExtention => $format) { $className = self::_getClassNameByFormat($format); $formatMimeType = call_user_func($className . '::getFileMimeType'); if (!is_null($mimeType) && $formatMimeType == $mimeType) { return $format; } else { if ($extention == $formatExtention) { return $format; } } } // no mine types match if (!is_null($mimeType)) { throw new BaseZF_Archive_Exception(sprintf('Could not detect archive format for file "%s", with mine type "%s"', $filePath, $mimeType)); } else { throw new BaseZF_Archive_Exception(sprintf('Could not detect archive format for file "%s"', $filePath)); } }
/** * Completes track information from a given path using mediainfo. * @param Track $track */ public function autocompleteTrack(Track $track) { $only_audio = true; //initialized true until video track is found. if (!$track->getPath()) { throw new \BadMethodCallException('Input track has no path defined'); } $json = json_decode($this->getMediaInfo($track->getPath())); if (!$this->jsonHasMediaContent($json)) { throw new \InvalidArgumentException("This file has no accesible video " . "nor audio tracks\n" . $track->getPath()); } $track->setMimetype(mime_content_type($track->getPath())); $track->setBitrate(intval($json->format->bit_rate)); $aux = intval((string) $json->format->duration); $track->setDuration(ceil($aux)); $track->setSize((string) $json->format->size); foreach ($json->streams as $stream) { switch ((string) $stream->codec_type) { case "video": $track->setVcodec((string) $stream->codec_name); $track->setFramerate((string) $stream->avg_frame_rate); $track->setWidth(intval($stream->width)); $track->setHeight(intval($stream->height)); $only_audio = false; break; case "audio": $track->setAcodec((string) $stream->codec_name); $track->setChannels(intval($stream->channels)); break; } $track->setOnlyAudio($only_audio); } }
/** * Play/stream a song. * * @link https://github.com/phanan/koel/wiki#streaming-music * * @param Song $song The song to stream. * @param null|bool $transcode Whether to force transcoding the song. * If this is omitted, by default Koel will transcode FLAC. * @param null|int $bitRate The target bit rate to transcode, defaults to OUTPUT_BIT_RATE. * Only taken into account if $transcode is truthy. * * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector */ public function play(Song $song, $transcode = null, $bitRate = null) { if ($song->s3_params) { return (new S3Streamer($song))->stream(); } // If `transcode` parameter isn't passed, the default is to only transcode FLAC. if ($transcode === null && ends_with(mime_content_type($song->path), 'flac')) { $transcode = true; } $streamer = null; if ($transcode) { $streamer = new TranscodingStreamer($song, $bitRate ?: config('koel.streaming.bitrate'), request()->input('time', 0)); } else { switch (config('koel.streaming.method')) { case 'x-sendfile': $streamer = new XSendFileStreamer($song); break; case 'x-accel-redirect': $streamer = new XAccelRedirectStreamer($song); break; default: $streamer = new PHPStreamer($song); break; } } $streamer->stream(); }
/** * Detects the MIME type of a given file * @param string $fileName The full path to the name whose MIME type you want to find out * @return string The MIME type, e.g. image/jpeg */ static function getMimeType($fileName) { $mime = null; // Try fileinfo first if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME); if ($finfo !== false) { $mime = finfo_file($finfo, $fileName); finfo_close($finfo); } } // Fallback to mime_content_type() if finfo didn't work if (is_null($mime) && function_exists('mime_content_type')) { $mime = mime_content_type($fileName); } // Final fallback, detection based on extension if (is_null($mime)) { $extension = self::getTypeIcon(getTypeIcon); if (array_key_exists($extension, self::$mimeMap)) { $mime = self::$mimeMap[$extension]; } else { $mime = "application/octet-stream"; } } return $mime; }
public function upload($file) { $filePath = realpath($this->filenames['basePath'] . $file); $binary = file_get_contents($filePath); $binaryLength = strlen($binary); $chunkLength = 1024 * 1024; $chunks = str_split($binary, $chunkLength); $mimeType = mime_content_type($filePath); foreach ($chunks as $chunkIndex => $chunk) { $chunkSize = strlen($chunk); $tempFileName = tempnam('/tmp/', 'file-'); file_put_contents($tempFileName, $chunk); $fileUpload = new UploadedFile($tempFileName, $file, $mimeType); $data = array('flowChunkNumber' => $chunkIndex + 1, 'flowChunkSize' => $chunkLength, 'flowCurrentChunkSize' => $chunkSize, 'flowTotalSize' => $binaryLength, 'flowIdentifier' => $binaryLength . $file, 'flowFilename' => $file, 'flowRelativePath' => $file, 'flowTotalChunks' => count($chunks)); $this->client->request('GET', '/' . $this->api['backend'] . '/media/upload/image/', $data, [], ['CONTENT_TYPE' => 'application/json']); $this->client->request('POST', '/' . $this->api['backend'] . '/media/upload/image/', $data, ['file' => $fileUpload], ['CONTENT_TYPE' => 'application/json']); } $response = $this->client->getResponse(); $content = $response->getContent(); $statusCode = $response->getStatusCode(); $result = json_decode($content, true); $this->assertEquals($statusCode, 201); $this->assertNotNull($result); $image = $this->dm->getRepository('Aisel\\MediaBundle\\Document\\Media')->findOneBy(['id' => $result['id']]); $filePath = realpath($this->filenames['basePath'] . $file); $binary = file_get_contents($filePath); $binaryLength = strlen($binary); $uploadedFile = realpath(static::$kernel->getContainer()->getParameter('assetic.write_to') . $image->getFilename()); $uploadedBinary = file_get_contents($uploadedFile); $uploadedBinaryLength = strlen($uploadedBinary); $this->assertEquals($image->getType(), 'image'); $this->assertEquals($uploadedBinaryLength, $binaryLength); return $result; }
/** * @param string $file * @return FileAnalysisResult */ public static function analyse($file) { //check if file exists if (false === file_exists($file)) { return null; } //is not a file if (false === is_file($file)) { return null; } //get file size $size = filesize($file); $mimeType = null; //mime type getter if (function_exists('finfo_open')) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $mimeType = finfo_file($finfo, $file); } else { if (function_exists('mime_content_type')) { $mimeType = mime_content_type($file); } } //default mime type if (strlen($mimeType) == 0) { //default mime type $mimeType = 'application/octet-stream'; } return new FileAnalysisResult($mimeType, $size, $file); }
/** * Processes the next item on the work queue. Emits a JSON messages to * indicate current progress. * * Returns: * TRUE/NULL if the migration was successful */ function next() { # Fetch next item -- use the last item so the array indices don't # need to be recalculated for every shift() operation. $info = array_pop($this->queue); # Attach file to the ticket if (!($info['data'] = @file_get_contents($info['path']))) { # Continue with next file return $this->error(sprintf('%s: Cannot read file contents', $info['path'])); } # Get the mime/type of each file # XXX: Use finfo_buffer for PHP 5.3+ $info['type'] = mime_content_type($info['path']); if (!($fileId = AttachmentFile::save($info))) { return $this->error(sprintf('%s: Unable to migrate attachment', $info['path'])); } # Update the ATTACHMENT_TABLE record to set file_id db_query('update ' . TICKET_ATTACHMENT_TABLE . ' set file_id=' . db_input($fileId) . ' where attach_id=' . db_input($info['attachId'])); # Remove disk image of the file. If this fails, the migration for # this file would not be retried, because the file_id in the # TICKET_ATTACHMENT_TABLE has a nonzero value now if (!@unlink($info['path'])) { $this->error(sprintf('%s: Unable to remove file from disk', $info['path'])); } # TODO: Log an internal note to the ticket? return true; }
function _getFileInfo($file, $realPath = false) { $authCheck = $this->_basePath($file); //Will perform permissions check if it has the path. $r = array(); $r['path'] = $file; //TODO: this is it's real path, get it's vfs path? $f = ($realPath ? "" : $this->_basePath()) . $file; $r['name'] = basename($f); if (is_dir($f)) { $r["type"] = "text/directory"; } else { if (is_file($f)) { $r["modified"] = date("F d Y H:i:s.", filemtime($f)); $r["size"] = filesize($f); $r["type"] = mime_content_type($f); if ($r["type"] == false) { $r["type"] = mime_content_type_alt($f); } } } //get ID3 info if available if (function_exists("id3_get_tag")) { $id3 = id3_get_tag($f); foreach ($id3 as $key => $value) { $r["id3" . str_replace(" ", "", ucwords($key))] = $value; } } return $r; }
public function resize($filename, $dst, $dst_w, $dst_h) { list($width, $height) = getimagesize($filename); $center_width = $width > $height ? $dst_w * $height / $dst_h : $width; $center_height = $height > $width ? $dst_h * $width / $dst_w : $height; $src_x = $width > $height ? ($width - $center_width) / 2 : 0; $src_y = $height > $width ? ($height - $center_height) / 2 : 0; $thumb = imagecreatetruecolor($dst_w, $dst_h); $type = mime_content_type($filename); switch (substr($type, 6)) { case 'jpeg': $source = imagecreatefromjpeg($filename); imagecopyresampled($thumb, $source, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $center_width, $center_height); imagejpeg($thumb, $dst); break; case 'gif': $source = imagecreatefromgif($filename); imagecopyresampled($thumb, $source, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $center_width, $center_height); imagegif($thumb, $dst); break; case 'png': $source = imagecreatefrompng($filename); imagecopyresampled($thumb, $source, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $center_width, $center_height); imagepng($thumb, $dst); break; } imagedestroy($thumb); }
/** * Loads an image from a file path * * @param string $filename Full path to the file which will be manipulated * @return ImageGD */ public function load($filename) { if (function_exists("finfo_open")) { // not supported everywhere https://github.com/openphoto/frontend/issues/368 $finfo = finfo_open(FILEINFO_MIME_TYPE); $this->type = finfo_file($finfo, $filename); } else { if (function_exists("mime_content_type")) { $this->type = mime_content_type($filename); } else { if (function_exists('exec')) { $this->type = exec('/usr/bin/file --mime-type -b ' . escapeshellarg($filename)); if (!empty($this->type)) { $this->type = ""; } } } } if (preg_match('/png$/', $this->type)) { $this->image = imagecreatefrompng($filename); } elseif (preg_match('/gif$/', $this->type)) { $this->image = @imagecreatefromgif($filename); } else { $this->image = @imagecreatefromjpeg($filename); } if (!$this->image) { OPException::raise(new OPInvalidImageException('Could not create image with GD library')); } $this->width = imagesx($this->image); $this->height = imagesy($this->image); return $this; }
public function imageManager() { $response = array(); // Image types. $image_types = array("image/gif", "image/jpeg", "image/pjpeg", "image/jpeg", "image/pjpeg", "image/png", "image/x-png"); // Filenames in the uploads folder. $fnames = scandir(BASE . "/files/site/uploads/"); // Check if folder exists. if ($fnames) { // Go through all the filenames in the folder. foreach ($fnames as $name) { // Filename must not be a folder. if (!is_dir($name)) { // Check if file is an image. if (in_array(mime_content_type(getcwd() . "/files/site/uploads/" . $name), $image_types)) { // Build the image. $img = new StdClass(); $img->url = "/files/site/uploads/" . $name; $img->thumb = "/files/site/uploads/" . $name; $img->name = $name; // Add to the array of image. array_push($response, $img); } } } } else { $response = new StdClass(); $response->error = "Images folder does not exist!"; } $response = json_encode($response); // Send response. echo stripslashes($response); }
/** * * @copyright 2010-2015 izend.org * @version 7 * @link http://www.izend.org */ function file_mime_type($file, $encoding = true) { $mime = false; if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); $mime = @finfo_file($finfo, $file); finfo_close($finfo); } else { if (substr(PHP_OS, 0, 3) == 'WIN') { $mime = mime_content_type($file); } else { $file = escapeshellarg($file); $cmd = "file -iL {$file}"; exec($cmd, $output, $r); if ($r == 0) { $mime = substr($output[0], strpos($output[0], ': ') + 2); } } } if (!$mime) { return false; } if ($encoding) { return $mime; } return substr($mime, 0, strpos($mime, '; ')); }
/** * 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; }
/** * Load the XML file into a DOMDocument. * @param $xmlfile path to the XML file to be loaded. * @param $dtdfile path to dtd file to validate the XML */ public function __construct($xmlfile = null, $dtdfile = null) { // initialize the logger $this->logger = new \core\util\log\FileLogger("XMLDocument", "../xmldocument.log"); // initialize the document if (!is_null($xmlfile) && file_exists($xmlfile) && strncmp(mime_content_type($xmlfile), "application/xml", 15) == 0) { // create a validatable DOMDocument first and // run validation on the xmlfile using the dtd provided if (!is_null($dtdfile) && file_exists($dtdfile)) { $dvalidatable = $this->createValidatableDocument($xmlfile, $dtdfile); if (!is_null($dvalidatable) && @$dvalidatable->validate()) { $this->doc = $dvalidatable; $dvalidatable = null; } else { $this->logger->logge("%", array(new \core\exception\xml\XMLNotValidException("XML not valid", 2)), "ERR"); throw new \core\exception\xml\XMLNotValidException("XML not valid", 2); } } else { $this->logger->logge("%", array(new \core\exception\xml\XMLNoValidDTDException()), "ERR"); throw new \core\exception\xml\XMLNoValidDTDException(); } } else { $this->logger->logge("%", array(new \core\exception\xml\XMLNotValidException()), "ERR"); throw new \core\exception\xml\XMLNotValidException(); } }
/** * @desc Retrieve the corresponding MIME type, if one exists * @param String $file File Name (relative location such as "image_test.jpg" or full "http://site.com/path/to/image_test.jpg") * @return String $MIMEType - The type of the file passed in the argument */ public function getMimeType($file = NULL) { if (is_file($file)) { /** * Attempts to retrieve file info from FINFO * If FINFO functions are not available then try to retrieve MIME type from pre-defined MIMEs * If MIME type doesn't exist, then try (as a last resort) to use the (deprecated) mime_content_type function * If all else fails, just return application/octet-stream */ if (!function_exists("finfo_open")) { $extension = $this->getExtension($file); if (array_key_exists($extension, $this->mimeTypes)) { return $this->mimeTypes[$extension]; } else { if (function_exists("mime_content_type")) { $type = mime_content_type($file); return !empty($type) ? $type : "application/octet-stream"; } else { return "application/octet-stream"; } } } else { $finfo = finfo_open(FILEINFO_MIME); $MIMEType = finfo_file($finfo, $file); finfo_close($finfo); return $MIMEType; } } else { return "##INVALID_FILE##FILE=" . $file . "##"; } }
/** * Process the data so it can be imported into the entry. * @param $value The value to import * @param $entry_id If a duplicate is found, an entry ID will be provided. * @return The data returned by the field object */ public function import($value, $entry_id = null) { $destination = $this->field->get('destination'); $filename = str_replace('/workspace/', '/', $destination) . '/' . str_replace($destination, '', trim($value)); // Check if the file exists: if (file_exists(DOCROOT . $destination . '/' . trim($value))) { // File exists, create the link: // Check if there already exists an entry with this filename. If so, this entry will not be stored (filename must be unique) $sql = 'SELECT COUNT(*) AS `total` FROM `tbl_entries_data_' . $this->field->get('id') . '` WHERE `file` = \'' . $filename . '\';'; $total = Symphony::Database()->fetchVar('total', 0, $sql); if ($total == 0) { $fileData = $this->field->processRawFieldData($value, $this->field->__OK__); $fileData['file'] = trim($filename); $fileData['size'] = filesize(DOCROOT . $destination . '/' . $value); $fileData['mimetype'] = mime_content_type(DOCROOT . $destination . '/' . $value); $fileData['meta'] = serialize($this->field->getMetaInfo(DOCROOT . $destination . '/' . $value, $fileData['mimetype'])); return $fileData; } else { // File already exists, don't store: return false; } } else { // File is stored in the CSV, but does not exists. Save it anyway, for database sake: if (!empty($value)) { $fileData = $this->field->processRawFieldData($value, $this->field->__OK__); $fileData['file'] = trim($filename); $fileData['size'] = filesize(DOCROOT . $destination . '/' . $value); $fileData['mimetype'] = ''; // mime_content_type(DOCROOT . $destination . '/' . $value); $fileData['meta'] = serialize($this->field->getMetaInfo(DOCROOT . $destination . '/' . $value, $fileData['mimetype'])); return $fileData; } } return false; }
/** * 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; }
public static function processemail($emailsrc, $pdfout, $coverfile = '') { $combfilelist = array(); # Process the email $emailparts = Mail_mimeDecode::decode(array('include_bodies' => true, 'decode_bodies' => true, 'decode_headers' => true, 'input' => file_get_contents($emailsrc), 'crlf' => "\r\n")); # Process the cover if it exists if ($coverfile !== '') { $combfilelist[] = self::processpart(file_get_contents($coverfile), mime_content_type($coverfile)); } # Process the parts $combfilelist = array_merge($combfilelist, self::processparts($emailparts)); # Create an intermediate file to build the pdf $tmppdffilename = sys_get_temp_dir() . '/e2p-' . (string) abs((int) (microtime(true) * 100000)) . '.pdf'; # Build the command to combine all of the intermediate files into one $conbcom = str_replace(array_merge(array('INTFILE', 'COMBLIST'), array_keys(self::$driver_paths)), array_merge(array($tmppdffilename, implode(' ', $combfilelist)), array_values(self::$driver_paths)), self::$mime_drivers['gs']); exec($conbcom); # Remove the intermediate files foreach ($combfilelist as $combfilename) { unlink($combfilename); } # Write the intermediate file to the final destination $intfileres = fopen($tmppdffilename, 'rb'); $outfileres = fopen($pdfout, 'ab'); while (!feof($intfileres)) { fwrite($outfileres, fread($intfileres, 8192)); } fclose($intfileres); fclose($outfileres); # Remove the intermediate file unlink($tmppdffilename); }
/** * @param mixed:string|\SplFileInfo $input * @param array $options * @throws ParseException * @return array */ public static function parse($input, array $options = array()) { $default_options = array('delimiter' => ';', 'encoding_source' => 'UTF-8', 'encoding_target' => 'UTF-8'); $options = array_merge($default_options, $options); // if input is a file, process it $file = null; if (false === strpos($input, '\\r\\n') && is_file($input)) { if (false === is_readable($input)) { throw new ParseException(sprintf('Unable to parse \'%s\' as the file is not readable.', $input)); } if ($input instanceof \SplFileInfo) { if (!in_array(mime_content_type($input->getPathname()), array('text/csv', 'text/plain'))) { throw new ParseException('This is not a CSV file.'); } } else { if (!in_array(mime_content_type($input), array('text/csv', 'text/plain'))) { throw new ParseException('This is not a CSV file.'); } } $file = $input; $input = file_get_contents($file); } $csv = new Csv\Parser(); try { return $csv->parse($input, $options['delimiter'], $options); } catch (ParseException $e) { if (!is_null($file)) { $e->setParsedFile($file); } throw $e; } }