/** * Get an associative array containing information about * a file with the given storage path. * * Resulting array fields include: * - fileExists * - size (filesize in bytes) * - mime (as major/minor) * - media_type (value to be used with the MEDIATYPE_xxx constants) * - metadata (handler specific) * - sha1 (in base 36) * - width * - height * - bits (bitrate) * - file-mime * - major_mime * - minor_mime * * @param string $path Filesystem path to a file * @param string|bool $ext The file extension, or true to extract it from the filename. * Set it to false to ignore the extension. * @return array * @since 1.28 */ public function getPropsFromPath($path, $ext) { $fsFile = new FSFile($path); $info = $this->newPlaceholderProps(); $info['fileExists'] = $fsFile->exists(); if ($info['fileExists']) { $info['size'] = $fsFile->getSize(); // bytes $info['sha1'] = $fsFile->getSha1Base36(); # MIME type according to file contents $info['file-mime'] = $this->magic->guessMimeType($path, false); # Logical MIME type $ext = $ext === true ? FileBackend::extensionFromPath($path) : $ext; $info['mime'] = $this->magic->improveTypeFromExtension($info['file-mime'], $ext); list($info['major_mime'], $info['minor_mime']) = File::splitMime($info['mime']); $info['media_type'] = $this->magic->getMediaType($path, $info['mime']); # Height, width and metadata $handler = MediaHandler::getHandler($info['mime']); if ($handler) { $info['metadata'] = $handler->getMetadata($fsFile, $path); /** @noinspection PhpMethodParametersCountMismatchInspection */ $gis = $handler->getImageSize($fsFile, $path, $info['metadata']); if (is_array($gis)) { $info = $this->extractImageSizeInfo($gis) + $info; } } } return $info; }
/** * Hook: MimeMagicInit * * @param MimeMagic $mimeMagic * @param object $addToList Callback function * @return bool Always true */ public static function MimeMagicInit($mimeMagic) { static $extraTypes = 'model/x-pdb pdb'; static $extraInfo = 'model/x-pdb [MODEL]'; $mimeMagic->addExtraTypes($extraTypes); $mimeMagic->addExtraInfo($extraInfo); return true; }
/** * This is called upon loading the special page. It should write output to the page with $wgOut. * * @param string $par The portion of the URI after Special:StaticDocServer/ */ public function execute($par) { #TODO: switch to $this->getOuput() and $this->getRequest() when we upgrade MW global $wgOut, $wgRequest; $wgOut->disable(); $found = FALSE; list($productName, $versionName, $path) = explode('/', $par, 3); if (substr($par, -1, 1) == '/') { $par .= 'index.html'; } // Validate parameters are set if (isset($productName) && isset($versionName) && PonyDocsProduct::GetProductByShortName($productName) && PonyDocsProductVersion::GetVersionByName($productName, $versionName)) { $filename = PONYDOCS_STATIC_DIR . "/{$par}"; if (file_exists($filename)) { $found = TRUE; } } if (!$found) { $wgRequest->response()->header("HTTP/1.1 404 Not Found"); echo "<html>\n"; echo "<head><title>Not Found</title></head>\n"; echo "<body>\n"; echo "<h1>Bad Request</h1>\n"; echo "<div>The documentation you have requested does not exist.</div>\n"; echo "</body>\n"; echo "</html>\n"; } else { $mimeMagic = MimeMagic::singleton(); $pathParts = pathinfo($filename); /* get mime-type for a specific file */ header('Content-type: ' . $mimeMagic->guessTypesForExtension($pathParts['extension'])); readfile($filename); } }
function showFile() { $i = strpos($this->mBasePath, '/'); $i = $i === false ? 0 : $i + 1; $filename = substr($this->mBasePath, $i); $i = strpos($filename, '.'); if ($i !== false) { $ext = substr($filename, $i + 1); $mime = MimeMagic::singleton(); $ctype = $mime->guessTypesForExtension($ext); } else { $ctype = 'application/octet-stream'; } $contents = $this->svn->getFile($this->mBasePath, $this->mRev == 'HEAD' ? null : $this->mRev); if ($this->mAction == 'raw' || $this->mAction == 'download') { global $wgOut; $wgOut->disable(); if ($this->mAction == 'raw') { header('Content-Type: ' . $ctype); } else { header('Content-Type: application/octet-stream'); } header('Content-Length: ' . strlen($contents)); print $contents; return; } if (substr($ctype, 0, 5) == 'text/') { return Xml::element('pre', array('style' => 'overflow: auto;'), $contents); } else { return wfMsgHTML('codebrowse-binary-file'); } }
function getMimeType() { if (!isset($this->mime)) { $magic = MimeMagic::singleton(); $this->mime = $magic->guessMimeType($this->path); } return $this->mime; }
/** * Utility function: Get a new file object for a file on disk but not actually in db. * * File must be in the path returned by getFilePath() * @param string $name File name * @param string $type MIME type [optional] * @return UnregisteredLocalFile */ protected function dataFile($name, $type = null) { if (!$type) { // Autodetect by file extension for the lazy. $magic = MimeMagic::singleton(); $parts = explode($name, '.'); $type = $magic->guessTypesForExtension($parts[count($parts) - 1]); } return new UnregisteredLocalFile(false, $this->repo, "mwstore://localtesting/data/{$name}", $type); }
private function _displayFile() { $registry = Zend_Registry::getInstance(); // Print the contents of the file $file = $registry->configuration->testcase->dir . '/' . $this->getRequest()->getParam(2); if ($stream = fopen($file, 'r')) { // Disable layout $layout = Zend_Layout::getMvcInstance(); $layout->disableLayout(); /// @todo: output headers and file information $mm = new MimeMagic(); /// @todo: fix in mimemagic instead header('Content-type: ' . $mm->get(realpath($file))); echo stream_get_contents($stream); fclose($stream); } else { throw new Exception("Attempted to view a non-existing file \"{$file}\"."); } }
function testFormat() { $this->assertNull(MimeMagic::format(true)); $this->assertNull(MimeMagic::format(5)); /* Currently arrays aren't validated */ // $this->assertNull(MimeMagic::format(array('foo' => 'bar'))); $this->assertNull(MimeMagic::format('does-not-exist.db')); $file = $this->TestData->getFile('text-html.snippet.html'); $this->assertNull(MimeMagic::format($file)); $file = $this->TestData->getFile('magic.apache.snippet.db'); $this->assertEqual(MimeMagic::format($file), 'Apache Module mod_mime_magic'); $file = $this->TestData->getFile('magic.freedesktop.snippet.db'); $this->assertEqual(MimeMagic::format($file), 'Freedesktop Shared MIME-info Database'); }
/** */ function wfGetType($filename, $safe = true) { global $wgTrivialMimeDetection; $ext = strrchr($filename, '.'); $ext = $ext === false ? '' : strtolower(substr($ext, 1)); # trivial detection by file extension, # used for thumbnails (thumb.php) if ($wgTrivialMimeDetection) { switch ($ext) { case 'gif': return 'image/gif'; case 'png': return 'image/png'; case 'jpg': return 'image/jpeg'; case 'jpeg': return 'image/jpeg'; } return 'unknown/unknown'; } $magic = MimeMagic::singleton(); // Use the extension only, rather than magic numbers, to avoid opening // up vulnerabilities due to uploads of files with allowed extensions // but disallowed types. $type = $magic->guessTypesForExtension($ext); /** * Double-check some security settings that were done on upload but might * have changed since. */ if ($safe) { global $wgFileBlacklist, $wgCheckFileExtensions, $wgStrictFileExtensions, $wgFileExtensions, $wgVerifyMimeType, $wgMimeTypeBlacklist, $wgRequest; $form = new UploadForm($wgRequest); list($partName, $extList) = $form->splitExtensions($filename); if ($form->checkFileExtensionList($extList, $wgFileBlacklist)) { return 'unknown/unknown'; } if ($wgCheckFileExtensions && $wgStrictFileExtensions && !$form->checkFileExtensionList($extList, $wgFileExtensions)) { return 'unknown/unknown'; } if ($wgVerifyMimeType && in_array(strtolower($type), $wgMimeTypeBlacklist)) { return 'unknown/unknown'; } } return $type; }
function setType( $image ) { $this->mimetype = $image->getMimeType(); $this->mediatype = $image->getMediaType(); #FIXME: ugly hack! do this on upload! if ( $this->mimetype == 'unknown/unknown' ) { $mime = MimeMagic::singleton(); $ext = preg_replace('!^.*\.([^.]+)$!', '\1', $image->getName()); $this->mimetype = $mime->guessTypesForExtension($ext); $this->mediatype = $mime->getMediaType(null, $this->mimetype); } if ( preg_match('!/(x-)?ogg$!', $this->mimetype) ) { if ( $this->mediatype == MEDIATYPE_AUDIO ) $this->mimetype = 'audio/ogg'; elseif ( $this->mediatype == MEDIATYPE_VIDEO ) $this->mimetype = 'video/ogg'; else $this->mimetype = 'application/ogg'; } }
/** */ function wfGetType($filename) { global $wgTrivialMimeDetection; # trivial detection by file extension, # used for thumbnails (thumb.php) if ($wgTrivialMimeDetection) { $ext = strtolower(strrchr($filename, '.')); switch ($ext) { case '.gif': return 'image/gif'; case '.png': return 'image/png'; case '.jpg': return 'image/jpeg'; case '.jpeg': return 'image/jpeg'; } return 'unknown/unknown'; } else { $magic =& MimeMagic::singleton(); return $magic->guessMimeType($filename); //full fancy mime detection } }
/** * Get an instance of this class * @return MimeMagic */ public static function &singleton() { if (!isset(self::$instance)) { self::$instance = new MimeMagic(); } return self::$instance; }
function getMediaType() { $magic = MimeMagic::singleton(); return $magic->getMediaType(null, $this->getMimeType()); }
/** * Get an associative array containing information about a file in the local filesystem. * * @param string $path Absolute local filesystem path * @param mixed $ext The file extension, or true to extract it from the filename. * Set it to false to ignore the extension. */ static function getPropsFromPath($path, $ext = true) { wfProfileIn(__METHOD__); wfDebug(__METHOD__ . ": Getting file info for {$path}\n"); $info = array('fileExists' => file_exists($path) && !is_dir($path)); $gis = false; if ($info['fileExists']) { $magic = MimeMagic::singleton(); $info['mime'] = $magic->guessMimeType($path, $ext); list($info['major_mime'], $info['minor_mime']) = self::splitMime($info['mime']); $info['media_type'] = $magic->getMediaType($path, $info['mime']); # Get size in bytes $info['size'] = filesize($path); # Height, width and metadata $handler = MediaHandler::getHandler($info['mime']); if ($handler) { $tempImage = (object) array(); $info['metadata'] = $handler->getMetadata($tempImage, $path); $gis = $handler->getImageSize($tempImage, $path, $info['metadata']); } else { $gis = false; $info['metadata'] = ''; } $info['sha1'] = self::sha1Base36($path); wfDebug(__METHOD__ . ": {$path} loaded, {$info['size']} bytes, {$info['mime']}.\n"); } else { $info['mime'] = NULL; $info['media_type'] = MEDIATYPE_UNKNOWN; $info['metadata'] = ''; $info['sha1'] = ''; wfDebug(__METHOD__ . ": {$path} NOT FOUND!\n"); } if ($gis) { # NOTE: $gis[2] contains a code for the image type. This is no longer used. $info['width'] = $gis[0]; $info['height'] = $gis[1]; if (isset($gis['bits'])) { $info['bits'] = $gis['bits']; } else { $info['bits'] = 0; } } else { $info['width'] = 0; $info['height'] = 0; $info['bits'] = 0; } wfProfileOut(__METHOD__); return $info; }
/** * Will load a file from various sources * * Supported formats: * - Freedesktop Shared MIME-info Database * - Apache Module mod_mime_magic * - PHP file containing variables formatted like: $data[0] = array(item, item, item, ...) * * @param mixed $file An absolute path to a magic file in apache, freedesktop * or a filename (without .php) of a file in the configs/ dir in CakePHP format * @return mixed A format string or null if format could not be determined * @access private * @link http://httpd.apache.org/docs/2.2/en/mod/mod_mime_magic.html * @link http://standards.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-0.13.html */ function __read($db) { $format = MimeMagic::format($db); if ($format === 'Array') { foreach ($db as $item) { $this->register($item); } } elseif ($format === 'PHP') { include $db; foreach ($data as $item) { $this->register($item); } } elseif ($format === 'Freedesktop Shared MIME-info Database') { $sectionRegex = '^\\[(\\d{1,3}):([-\\w.\\+]+\\/[-\\w.\\+]+)\\]$'; $itemRegex = '^(\\d*)\\>+(\\d+)=+([^&~\\+]{2})([^&~\\+]+)&?([^~\\+]*)~?(\\d*)\\+?(\\d*).*$'; $File = new File($db); $File->open('rb'); $File->offset(12); while (!feof($File->handle)) { $line = ''; if (!isset($chars)) { $chars = array(0 => $File->read(1), 1 => $File->read(1)); } else { $chars = array(0 => $chars[1], 1 => null); } while (!feof($File->handle) && !($chars[0] === "\n" && (ctype_digit($chars[1]) || $chars[1] === '>' || $chars[1] === '['))) { $line .= $chars[0]; $chars = array(0 => $chars[1], 1 => $File->read(1)); } if (preg_match('/' . $sectionRegex . '/', $line, $matches)) { $section = array('priority' => $matches[1], 'mime_type' => $matches[2]); } elseif (preg_match('/' . $itemRegex . '/', $line, $matches)) { $indent = empty($matches[1]) ? 0 : intval($matches[1]); $wordSize = empty($matches[6]) ? 1 : intval($matches[6]); $item = array('offset' => intval($matches[2]), 'value_length' => current(unpack('n', $matches[3])), 'value' => $this->__formatValue($matches[4], $wordSize), 'mask' => empty($matches[5]) ? null : $this->__formatValue($matches[5], $wordSize), 'range_length' => empty($matches[7]) ? 1 : intval($matches[7]), 'mime_type' => $section['mime_type']); $this->register($item, $indent, $section['priority']); } } } elseif ($format === 'Apache Module mod_mime_magic') { $itemRegex = '^(\\>*)(\\d+)\\t+(\\S+)\\t+([\\S^\\040]+)\\t*([-\\w.\\+]+\\/[-\\w.\\+]+)*\\t*(\\S*)$'; $File = new File($db); $File->open('rb'); while (!feof($File->handle)) { $line = trim(fgets($File->handle)); if (empty($line) || $line[0] === '#') { continue; } $line = preg_replace('/(?!\\B)\\040+/', "\t", $line); if (!preg_match('/' . $itemRegex . '/', $line, $matches)) { continue; } $item = array('offset' => intval($matches[2]), 'value' => $this->__formatValue($matches[4], $matches[3], true), 'mask' => null, 'range_length' => 0, 'mime_type' => empty($matches[5]) ? null : $matches[5], 'encoding' => empty($matches[6]) ? null : $matches[6]); $item['value_length'] = strlen($item['value']); $this->register($item, strlen($matches[1]), 80); } } else { trigger_error('MimeGlob::read - Unknown db format', E_USER_WARNING); } }
function getThumbType($ext, $mime) { global $wgDjvuOutputExtension; static $mime; if (!isset($mime)) { $magic = MimeMagic::singleton(); $mime = $magic->guessTypesForExtension($wgDjvuOutputExtension); } return array($wgDjvuOutputExtension, $mime); }
/** * Checks if the mime type of the uploaded file matches the file extension. * * @param string $mime the mime type of the uploaded file * @param string $extension The filename extension that the file is to be served with * @return bool */ function verifyExtension( $mime, $extension ) { $magic = MimeMagic::singleton(); if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) if ( !$magic->isRecognizableExtension( $extension ) ) { wfDebug( __METHOD__ . ": passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" ); return true; } else { wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" ); return false; } $match = $magic->isMatchingExtension( $extension, $mime ); if ( $match === null ) { wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" ); return true; } elseif ( $match === true ) { wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" ); # TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it! return true; } else { wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" ); return false; } }
} else { $commentText = file_get_contents($f); if (!$commentText) { echo " Failed to load comment file {$f}, using default comment. "; } } } if (!$commentText) { $commentText = $comment; } } # Import the file if (isset($options['dry'])) { echo " publishing {$file} by '" . $wgUser->getName() . "', comment '{$commentText}'... "; } else { $mwProps = new MWFileProps(MimeMagic::singleton()); $props = $mwProps->getPropsFromPath($file, true); $flags = 0; $publishOptions = []; $handler = MediaHandler::getHandler($props['mime']); if ($handler) { $publishOptions['headers'] = $handler->getStreamHeaders($props['metadata']); } else { $publishOptions['headers'] = []; } $archive = $image->publish($file, $flags, $publishOptions); if (!$archive->isGood()) { echo "failed. (" . $archive->getWikiText(false, false, 'en') . ")\n"; $failed++; continue; }
/** * Given a mime type, return a comma separated list of allowed extensions. * * @param $mime String mime type * @return String Comma separated list of allowed extensions (e.g. ".ogg, .oga") */ private function getExtensionList($mime) { $exts = MimeMagic::singleton()->getExtensionsForType($mime); if ($exts === null) { return ''; } $extArray = explode(' ', $exts); $extArray = array_unique($extArray); foreach ($extArray as &$ext) { $ext = '.' . $ext; } return $this->getLanguage()->commaList($extArray); }
public static function send($headers, $to, $from, $subject, $body, $priority = 0, $attachments = null) { global $wgEnotifMaxRecips, $wgSMTP; wfProfileIn(__METHOD__); require_once 'Mail2.php'; require_once 'Mail2/mime.php'; $logContext = array_merge($headers, ['issue' => 'SOC-910', 'method' => __METHOD__, 'to' => $to, 'subject' => $subject]); WikiaLogger::instance()->info('Queuing email for SendGrid', $logContext); wfSuppressWarnings(); $headers['Subject'] = UserMailer::quotedPrintable($subject); // Add a header for the server-name (helps us route where SendGrid will send bounces). if (!empty($_SERVER) && isset($_SERVER['SERVER_NAME'])) { $headers["X-ServerName"] = $_SERVER['SERVER_NAME']; } try { $mail_object =& Mail2::factory(WikiaSendgridMailer::$factory, $wgSMTP); } catch (Exception $e) { $logContext['errorMessage'] = $e->getMessage(); WikiaLogger::instance()->info('Failed to create mail object', $logContext); wfDebug("PEAR::Mail factory failed: " . $e->getMessage() . "\n"); wfRestoreWarnings(); wfProfileOut(__METHOD__); return $e->getMessage(); } $email_body_txt = $email_body_html = ""; if (is_array($body)) { if (isset($body['text'])) { $email_body_txt = $body['text']; } if (isset($body['html'])) { $email_body_html = $body['html']; } } else { $email_body_txt = $body; } $mime = new Mail_mime(); $mime->setTXTBody($email_body_txt); $params = array('head_charset' => 'UTF-8', 'html_charset' => 'UTF-8', 'text_charset' => 'UTF-8', 'text_encoding' => 'quoted-printable', 'html_encoding' => 'quoted-printable'); # send email with attachements if (!empty($attachments)) { if (!is_array($attachments)) { $attachments = array($attachments); } foreach ($attachments as $file) { if (!is_array($file)) { $magic = MimeMagic::singleton(); $mimeType = $magic->guessMimeType($file); $ext_file = end(explode('.', $file)); $file = array('file' => $file, 'ext' => $ext_file, 'mime' => $mimeType); } $filename = $file['file']; $ext_filename = $file['ext']; if (!file_exists($filename)) { continue; } $name = $filename; #basename( $filename ); if ($ext_filename) { $name = $filename . "." . $ext_filename; } $mime->addAttachment($filename, $file['mime'], $name); } } # Old version (1.16 MW with Wikia changes) of sendHTML method if ($email_body_html) { $mime->setHTMLBody($email_body_html); //do not ever try to call these lines in reverse order } $body = $mime->get($params); $headers = $mime->headers($headers); wfDebug("Sending mail via WikiaSendgridMailer::send\n"); $chunks = array_chunk((array) $to, $wgEnotifMaxRecips); foreach ($chunks as $chunk) { $headers['To'] = $chunk; $status = self::sendWithPear($mail_object, $chunk, $headers, $body); if (!$status->isOK()) { $logContext['errorMessage'] = $status->getMessage(); WikiaLogger::instance()->info('Failed to create mail object', $logContext); wfRestoreWarnings(); wfProfileOut(__METHOD__); return $status->getMessage(); } } wfProfileOut(__METHOD__); # return false to return Status::newGood() in UserMailer::send method return false; }
/** * Test to make sure that encoder=ffmpeg2theora doesn't trigger * MEDIATYPE_VIDEO (bug 63584) */ function testOggRecognize() { $oggFile = __DIR__ . '/../data/media/say-test.ogg'; $actualType = $this->mimeMagic->getMediaType($oggFile, 'application/ogg'); $this->assertEquals($actualType, MEDIATYPE_AUDIO); }
/** * @param $upload UploadBase * @param $mime * @param $error * @return bool */ public static function insertJobs($upload, $mime, &$error) { global $wgPdfCreateThumbnailsInJobQueue; if (!$wgPdfCreateThumbnailsInJobQueue) { return true; } if (!MimeMagic::singleton()->isMatchingExtension('pdf', $mime)) { return true; // not a PDF, abort } $title = $upload->getTitle(); $uploadFile = $upload->getLocalFile(); if (is_null($uploadFile)) { wfDebugLog('thumbnails', '$uploadFile seems to be null, should never happen...'); return true; // should never happen, but it's better to be secure } $metadata = $uploadFile->getMetadata(); $unserialized = unserialize($metadata); $pages = intval($unserialized['Pages']); $jobs = array(); for ($i = 1; $i <= $pages; $i++) { $jobs[] = new CreatePdfThumbnailsJob($title, array('page' => $i, 'jobtype' => self::BIG_THUMB)); $jobs[] = new CreatePdfThumbnailsJob($title, array('page' => $i, 'jobtype' => self::SMALL_THUMB)); } Job::batchInsert($jobs); return true; }
function testShippedAnalyze() { $file = dirname(dirname(dirname(dirname(__FILE__)))) . DS . 'vendors' . DS . 'mime_magic.db'; $skip = $this->skipIf(!file_exists($file), '%s. No shipped magic db.'); if ($skip) { /* Skipping does not silence the error */ $this->expectError(); } $Mime = new MimeMagic($file); $this->assertEqual($Mime->analyze($this->TestData->getFile('ms.snippet.avi')), 'video/x-msvideo'); $this->assertEqual($Mime->analyze($this->TestData->getFile('image-gif.gif')), 'image/gif'); $this->assertEqual($Mime->analyze($this->TestData->getFile('application-pdf.pdf')), 'application/pdf'); $this->assertEqual($Mime->analyze($this->TestData->getFile('postscript.snippet.ps')), 'application/postscript'); $this->assertEqual($Mime->analyze($this->TestData->getFile('tar.snippet.tar')), 'application/x-tar'); $this->assertEqual($Mime->analyze($this->TestData->getFile('wave.snippet.wav')), 'audio/x-wav'); $this->assertEqual($Mime->analyze($this->TestData->getFile('3gp.snippet.3gp')), 'video/3gpp'); $this->assertEqual($Mime->analyze($this->TestData->getFile('bzip2.snippet.bz2')), 'application/x-bzip'); //application/x-bzip2 $this->assertEqual($Mime->analyze($this->TestData->getFile('video.snippet.mp4')), 'video/mp4'); $this->assertEqual($Mime->analyze($this->TestData->getFile('gzip.snippet.gz')), 'application/x-gzip'); $this->assertEqual($Mime->analyze($this->TestData->getFile('text-html.snippet.html')), 'text/html'); $this->assertEqual($Mime->analyze($this->TestData->getFile('image-jpeg.snippet.jpg')), 'image/jpeg'); //audio/MP4A-LATM $this->assertEqual($Mime->analyze($this->TestData->getFile('video-mpeg.snippet.mpeg')), 'video/mpeg'); $this->assertEqual($Mime->analyze($this->TestData->getFile('video-ogg.snippet.ogv')), 'video/x-theora+ogg'); //application/ogg $this->assertEqual($Mime->analyze($this->TestData->getFile('audio-ogg.snippet.ogg')), 'audio/x-vorbis+ogg'); //application/ogg $this->assertEqual($Mime->analyze(__FILE__), 'application/x-php'); $this->assertEqual($Mime->analyze($this->TestData->getFile('image-png.png')), 'image/png'); $this->assertEqual($Mime->analyze($this->TestData->getFile('text-rtf.snippet.rtf')), 'application/rtf'); //text/rtf $this->assertEqual($Mime->analyze($this->TestData->getFile('ms-word.snippet.doc')), 'application/msword'); //audio/MP4A-LATM $this->assertEqual($Mime->analyze($this->TestData->getFile('xml.snippet.xml')), 'application/xml'); //text/xml /* Fail! */ /* $this->assertEqual($Mime->analyze($this->TestData->getFile('opendocument-writer.snippet.odt')), 'application/vnd.oasis.opendocument.text');//application/zip $this->assertEqual($Mime->analyze($this->TestData->getFile('ms-word.snippet.docx')), 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');//application/zip $this->assertEqual($Mime->analyze($this->TestData->getFile('audio-mpeg.snippet.mp3')), 'audio/mpeg'); $this->assertEqual($Mime->analyze($this->TestData->getFile('text-plain.snippet.txt')), 'text/plain'); $this->assertEqual($Mime->analyze($this->TestData->getFile('css.snippet.css')), 'text/css'); $this->assertEqual($Mime->analyze($this->TestData->getFile('javascript.snippet.js')), 'application/javascript'); $this->assertEqual($Mime->analyze($this->TestData->getFile('text-xhtml.snippet.xhtml')), 'application/xhtml+xml');//text/xml $this->assertEqual($Mime->analyze($this->TestData->getFile('po.snippet.po')), 'text/x-gettext-translation'); $this->assertEqual($Mime->analyze($this->TestData->getFile('text-pot.snippet.pot')), 'text/x-gettext-translation-template'); $this->assertEqual($Mime->analyze($this->TestData->getFile('mo.snippet.mo')), 'application/x-gettext-translation'); */ $this->assertEqual($Mime->analyze($this->TestData->getFile('video-flash.snippet.flv')), 'video/x-flv'); $this->assertEqual($Mime->analyze($this->TestData->getFile('audio.snippet.snd')), 'audio/basic'); $this->assertEqual($Mime->analyze($this->TestData->getFile('audio-apple.snippet.aiff')), 'audio/x-aiff'); $this->assertEqual($Mime->analyze($this->TestData->getFile('flash.snippet.swf')), 'application/x-shockwave-flash'); $this->assertEqual($Mime->analyze($this->TestData->getFile('audio-mpeg.snippet.m4a')), 'audio/mp4'); $this->assertEqual($Mime->analyze($this->TestData->getFile('audio-musepack.snippet.mpc')), 'audio/x-musepack'); $this->assertEqual($Mime->analyze($this->TestData->getFile('video-quicktime.snippet.mov')), 'video/quicktime'); $this->assertEqual($Mime->analyze($this->TestData->getFile('video-ms.snippet.wmv')), 'video/x-ms-asf'); /* Fail! */ /* $this->assertEqual($Mime->analyze($this->TestData->getFile('audio.snippet.aac')), 'audio/x-aac'); $this->assertEqual($Mime->analyze($this->TestData->getFile('audio-ms.snippet.wma')), 'audio/x-ms-asf'); $this->assertEqual($Mime->analyze($this->TestData->getFile('flac.snippet.flac')), 'audio/x-flac');//Fail only with freedesktop db! */ /* Audio formats to find/add/test: riff,wavpack, aac, ac3, ape, shorten, midi, voc, s3m, xm, it, mod, matroska, pac, bonk, dts, cda */ /* Fail! No data :( */ /* $this->assertEqual($Mime->analyze($this->TestData->getFile('java.snippet.class')), 'application/x-java'); $this->assertEqual($Mime->analyze($this->TestData->getFile('real-video.snippet.rm')), 'application/vnd.rn-realmedia'); */ }
function imageInfo($filename) { $info = array('width' => 0, 'height' => 0, 'bits' => 0, 'media' => '', 'major' => '', 'minor' => ''); $magic = MimeMagic::singleton(); $mime = $magic->guessMimeType($filename, true); list($info['major'], $info['minor']) = explode('/', $mime); $info['media'] = $magic->getMediaType($filename, $mime); $image = UnregisteredLocalFile::newFromPath($filename, $mime); $info['width'] = $image->getWidth(); $info['height'] = $image->getHeight(); $gis = $image->getImageSize($filename); if (isset($gis['bits'])) { $info['bits'] = $gis['bits']; } return $info; }
/** * Find or guess extension -- ensuring that our extension matches our mime type. * Since these files are constructed from php tempnames they may not start off * with an extension. * XXX this is somewhat redundant with the checks that ApiUpload.php does with incoming * uploads versus the desired filename. Maybe we can get that passed to us... */ public static function getExtensionForPath($path) { // Does this have an extension? $n = strrpos($path, '.'); $extension = null; if ($n !== false) { $extension = $n ? substr($path, $n + 1) : ''; } else { // If not, assume that it should be related to the mime type of the original file. $magic = MimeMagic::singleton(); $mimeType = $magic->guessMimeType($path); $extensions = explode(' ', MimeMagic::singleton()->getExtensionsForType($mimeType)); if (count($extensions)) { $extension = $extensions[0]; } } if (is_null($extension)) { throw new UploadStashFileException("extension is null"); } return File::normalizeExtension($extension); }
/** * Tests the WebP MIME detection. This should really be a separate test, but sticking it * here for now. * * @dataProvider provideTestGetMimeType */ public function testGuessMimeType($path) { $mime = MimeMagic::singleton(); $this->assertEquals('image/webp', $mime->guessMimeType($path, false)); }
/** * Checks if file extensions are compatible * * @param $old File Old file * @param string $new New name * * @return bool|null */ static function checkExtensionCompatibility(File $old, $new) { $oldMime = $old->getMimeType(); $n = strrpos($new, '.'); $newExt = self::normalizeExtension($n ? substr($new, $n + 1) : ''); $mimeMagic = MimeMagic::singleton(); return $mimeMagic->isMatchingExtension($newExt, $oldMime); }
/** * Checks if the mime type of the uploaded file matches the file extension. * * @param string $mime the mime type of the uploaded file * @param string $extension the filename extension that the file is to be served with * @return Boolean */ public static function verifyExtension($mime, $extension) { $magic = MimeMagic::singleton(); if (!$mime || $mime == 'unknown' || $mime == 'unknown/unknown') { if (!$magic->isRecognizableExtension($extension)) { wfDebug(__METHOD__ . ": passing file with unknown detected mime type; " . "unrecognized extension '{$extension}', can't verify\n"); return true; } else { wfDebug(__METHOD__ . ": rejecting file with unknown detected mime type; " . "recognized extension '{$extension}', so probably invalid file\n"); return false; } } $match = $magic->isMatchingExtension($extension, $mime); if ($match === null) { if ($magic->getTypesForExtension($extension) !== null) { wfDebug(__METHOD__ . ": No extension known for {$mime}, but we know a mime for {$extension}\n"); return false; } else { wfDebug(__METHOD__ . ": no file extension known for mime type {$mime}, passing file\n"); return true; } } elseif ($match === true) { wfDebug(__METHOD__ . ": mime type {$mime} matches extension {$extension}, passing file\n"); #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it! return true; } else { wfDebug(__METHOD__ . ": mime type {$mime} mismatches file extension {$extension}, rejecting file\n"); return false; } }
/** * Get the thumbnail extension and MIME type for a given source MIME type * * @param string $ext Extension of original file * @param string $mime MIME type of original file * @param array $params Handler specific rendering parameters * @return array Thumbnail extension and MIME type */ function getThumbType($ext, $mime, $params = null) { $magic = MimeMagic::singleton(); if (!$ext || $magic->isMatchingExtension($ext, $mime) === false) { // The extension is not valid for this MIME type and we do // recognize the MIME type $extensions = $magic->getExtensionsForType($mime); if ($extensions) { return [strtok($extensions, ' '), $mime]; } } // The extension is correct (true) or the MIME type is unknown to // MediaWiki (null) return [$ext, $mime]; }
/** * @return int|string */ function getMediaType() { if (isset($this->mInfo['mediatype'])) { return $this->mInfo['mediatype']; } $magic = MimeMagic::singleton(); return $magic->getMediaType(null, $this->getMimeType()); }