Exemplo n.º 1
0
 public static function autoDetect($file)
 {
     $mt = new MIME_Type();
     $mt->magicFile = static::getMagicFile();
     $mt->useMimeContentType = false;
     //fixme: finfo doesn't give the correct results
     // only fixed in PHP 5.4.4
     $mt->useFileCmd = true;
     $mt->useFinfo = false;
     $mt->useExtension = false;
     $type = $mt->autoDetect($file);
     if ($type !== 'text/plain') {
         return $type;
     }
     $type = MIME_Type::autoDetect($file);
     return $type;
 }
 /**
  * Parse a MIME type parameter and set object fields
  *
  * @param  string $param MIME type parameter to parse
  * @return void
  */
 function parse($param)
 {
     $comment = '';
     $param = MIME_Type::stripComments($param, $comment);
     $this->name = $this->getAttribute($param);
     $this->value = $this->getValue($param);
     $this->comment = $comment;
 }
Exemplo n.º 3
0
function mime_type_of_file($path)
{
    $result = FALSE;
    if (class_exists('MIME_Type')) {
        $result = MIME_Type::autoDetect($path);
        if (PEAR::isError($result)) {
            $result = FALSE;
        }
    }
    return $result;
}
Exemplo n.º 4
0
 /**
  * Return default MIME-type for the specified extension.
  *
  * @param string $type MIME-type
  *
  * @return string A file extension without leading period.
  */
 function getExtension($type)
 {
     include_once 'MIME/Type.php';
     // Strip parameters and comments.
     $type = MIME_Type::getMedia($type) . '/' . MIME_Type::getSubType($type);
     $extension = array_search($type, $this->extensionToType);
     if ($extension === false) {
         return PEAR::raiseError("Sorry, couldn't determine extension.");
     }
     return $extension;
 }
Exemplo n.º 5
0
 /**
  * @see File_Archive_Predicate::isTrue()
  */
 function isTrue(&$source)
 {
     $sourceMIME = $source->getMIME();
     foreach ($this->mimes as $mime) {
         if (MIME_Type::isWildcard($mime)) {
             $result = MIME_Type::wildcardMatch($mime, $sourceMIME);
         } else {
             $result = $mime == $sourceMIME;
         }
         if ($result !== false) {
             return $result;
         }
     }
     return false;
 }
Exemplo n.º 6
0
 /**
  * Returns mime type from the actual file using a detection library
  * @access protected
  * @return string or boolean
  */
 protected function autoDetectMIMETypeFromFile($filename)
 {
     $settings = $this->defaults['mime_type'];
     $support_libraries = array('fileinfo', 'mime_type', 'gd_mime_type');
     if (false === $settings['auto_detect']) {
         return false;
     }
     if (in_array(strtolower($settings['library']), $support_libraries) && '' !== $filename) {
         if ('gd_mime_type' === strtolower($settings['library'])) {
             if (!extension_loaded('gd')) {
                 throw new Exception('GD not enabled. Cannot detect mime type using GD.');
             }
             $imgData = GetImageSize($filename);
             if (isset($imgData['mime'])) {
                 return $imgData['mime'];
             } else {
                 return false;
             }
         }
         if ('fileinfo' === strtolower($settings["library"])) {
             if (function_exists('finfo_file')) {
                 // Support for PHP 5.3+
                 if (defined(FILEINFO_MIME_TYPE)) {
                     $finfo = finfo_open(FILEINFO_MIME_TYPE);
                 } else {
                     $finfo = finfo_open(FILEINFO_MIME);
                 }
                 return finfo_file($finfo, $filename);
             }
         }
         if ('mime_type' === strtolower($settings["library"])) {
             // Supressing warning as PEAR is not strict compliant
             @(require_once 'MIME/Type.php');
             if (method_exists('\\MIME_Type', 'autoDetect')) {
                 return @\MIME_Type::autoDetect($filename);
             }
         }
     }
     return false;
 }
Exemplo n.º 7
0
function sendEMail($par, $file = false)
{
    $recipients = $par['empfaenger'];
    $message_array = $par['message'];
    $from = '*****@*****.**';
    $backend = 'smtp';
    $subject = $message_array['subject'];
    $body_txt = $message_array['body_txt'];
    $crlf = "\n";
    $params = array('host' => '10.149.43.10', 'port' => 25, 'auth' => false, 'username' => false, 'password' => false, 'localhost' => 'localhost', 'timeout' => null, 'debug' => false);
    foreach ($recipients as $recipient) {
        $headers = array('From' => $from, 'To' => $recipient, 'Subject' => $subject);
        $mime = new Mail_mime($crlf);
        $mime->setTXTBody($body_txt);
        if (is_file($file)) {
            $ctype = MIME_Type::autoDetect($file);
            $mime->addAttachment($file, $ctype);
        }
        $body = $mime->get();
        $hdrs = $mime->headers($headers);
        $mail =& Mail::factory($backend, $params);
        $mail->send($recipient, $hdrs, $body);
    }
}
Exemplo n.º 8
0
 public function testComments()
 {
     $type = new MIME_Type('(UTF-8 Plain Text) text / plain ; charset = utf-8');
     $this->assertEquals('text/plain; charset="utf-8"', $type->get());
     $type = new MIME_Type('text (Text) / plain ; charset = utf-8');
     $this->assertEquals('text/plain; charset="utf-8"', $type->get());
     $type = new MIME_Type('text / (Plain) plain ; charset = utf-8');
     $this->assertEquals('text/plain; charset="utf-8"', $type->get());
     $type = new MIME_Type('text / plain (Plain Text) ; charset = utf-8');
     $this->assertEquals('text/plain; charset="utf-8"', $type->get());
     $type = new MIME_Type('text / plain ; (Charset=utf-8) charset = utf-8');
     $this->assertEquals('text/plain; charset="utf-8" (Charset=utf-8)', $type->get());
     $type = new MIME_Type('text / plain ; charset (Charset) = utf-8');
     $this->assertEquals('text/plain; charset="utf-8" (Charset)', $type->get());
     $type = new MIME_Type('text / plain ; charset = (UTF8) utf-8');
     $this->assertEquals('text/plain; charset="utf-8" (UTF8)', $type->get());
     $type = new MIME_Type('text / plain ; charset = utf-8 (UTF-8 Plain Text)');
     $this->assertEquals('text/plain; charset="utf-8" (UTF-8 Plain Text)', $type->get());
     $type = new MIME_Type('application/x-foobar;description="bbgh(kdur"');
     $this->assertEquals('application/x-foobar; description="bbgh(kdur"', $type->get());
     $type = new MIME_Type('application/x-foobar;description="a \\"quoted string\\""');
     $this->assertEquals('application/x-foobar; description="a \\"quoted string\\""', $type->get());
 }
<?php

ini_set('include_path', ini_get('include_path') . ':/home/dvaqpvvw/php/:');
ini_set('include_path', ini_get('include_path') . ':/home/dvaqpvvw/php/MIME/:');
ini_set('include_path', ini_get('include_path') . ':/home/dvaqpvvw/php/PEAR/:');
require_once '/home/dvaqpvvw/php/MIME/Type.php';
$filename = urldecode($_REQUEST['filename']);
$shortFilename = urldecode($_REQUEST['shortFilename']);
$mimeType = MIME_Type::autoDetect($filename);
header("Content-disposition: attachment; filename=" . $shortFilename);
header("Content-type:" . $mimeType);
readfile($filename);
function getMimeType()
{
}
Exemplo n.º 10
0
 public function detect($filepath)
 {
     return MIME_Type::autoDetect($filepath);
 }
Exemplo n.º 11
0
 /**
  * Autodetect a file's MIME-type
  *
  * This function may be called staticly.
  *
  * @param  string $file        Path to the file to get the type of
  * @param  string $custom_mime An optional custom 'default' value, mostly used for the filetype sent by the users' browser
  * @param  bool   $params      Append MIME parameters if true
  * @return string $file's      MIME-type on success, false boolean otherwise
  * @since 1.0.0beta1
  * @static
  */
 function autoDetect($file, $custom_mime = null, $custom_ext = null, $params = false)
 {
     if (function_exists('mime_content_type')) {
         $type = mime_content_type($file);
         if ($type == "application/octet-stream" || $type == "application/unknown") {
             if (!empty($custom_mime)) {
                 $type = $custom_mime;
             } elseif (!empty($custom_ext)) {
                 $type = MIME_Helper::convertExtensionToMime($custom_ext);
             }
         }
     } elseif (!empty($custom_mime)) {
         $type = $custom_mime;
     } else {
         $type = MIME_Type::_fileAutoDetect($file);
     }
     // _fileAutoDetect() may have returned an error.
     if ($type === false) {
         return $type;
     }
     //return PEAR::raiseError("Sorry, can't autodetect; you need the mime_magic extension or System_Command and 'file' installed to use this function.");
     if (!MIME_Helper::convertMimeToExtension($type)) {
         $type = MIME_Helper::convertExtensionToMime($custom_mime);
     }
     // flv (Flash Video format) files need exceptional handling (for now I'll provide a fictional mimetype)
     if ($custom_ext == "flv") {
         $type = "video/x-flv";
     }
     // Don't return an empty string
     if (!$type || !strlen($type)) {
         //return PEAR::raiseError("Sorry, couldn't determine file type.");
         return false;
     }
     // Strip parameters if present & requested
     if (MIME_Type::hasParameters($type) && !$params) {
         $type = MIME_Type::stripParameters($type);
     }
     return $type;
 }
Exemplo n.º 12
0
 /**
  * ファイル拡張子を取得する
  * ・ファイル情報からファイル拡張子を取得する
  * (自動判定するファイル拡張子:jpg, gif, png, zip, xls, pdf, doc, ppt, lzh)
  * ・ファイルタイプが自動判定されなかった場合は、ファイル名から拡張子を取り出す
  * ※ファイル保存されているファイルの拡張子を取得する場合に使用する
  * @access  public
  * @param string $path  ファイルパス
  * @return string ファイル拡張子
  */
 public function getExtension($path)
 {
     // パラメータチェック
     if (empty($path)) {
         throw new ApplicationException('Invalid parameter! $path=' . $path);
     }
     $realpath = realpath($path);
     if ($path === false) {
         throw new ApplicationException('Invalid parameter! $path=' . $path);
     } elseif (strncmp($path, $realpath, strlen($realpath)) !== 0) {
         throw new ApplicationException('Invalid parameter! $path=' . $path);
     }
     // 拡張子自動判定
     $mime_type = MIME_Type::autoDetect($path);
     $ext = $this->getExtentionEx($mime_type, $path);
     $temp = array();
     if (empty($ext)) {
         // ファイル名から拡張子を取得する
         preg_match("/^(.*)\\.(.*)\$/i", $path, $temp);
         $ext = $temp[2];
     }
     return $ext;
 }
Exemplo n.º 13
0
 public function dispatchLoopShutdown()
 {
     if (!Pimcore_Tool::isHtmlResponse($this->getResponse())) {
         return;
     }
     if ($this->supported && $this->enabled) {
         include_once "simple_html_dom.php";
         $body = $this->getResponse()->getBody();
         $html = str_get_html($body);
         if ($html) {
             $images = $html->find("img");
             foreach ($images as $image) {
                 $source = $image->src;
                 $path = null;
                 if (strpos($source, "http") === false) {
                     // check asset folder
                     if (is_file(PIMCORE_ASSET_DIRECTORY . $source)) {
                         $path = PIMCORE_ASSET_DIRECTORY . $source;
                     } else {
                         if (is_file(PIMCORE_DOCUMENT_ROOT . $source)) {
                             $path = PIMCORE_DOCUMENT_ROOT . $source;
                         }
                     }
                     if (is_file($path)) {
                         if (@filesize($path) < 20000) {
                             // only files < 20k because of IE8, 20000 because it's better to be a little bit under the limit
                             try {
                                 $mimetype = MIME_Type::autoDetect($path);
                                 if (is_string($mimetype)) {
                                     $image->src = 'data:' . $mimetype . ';base64,' . base64_encode(file_get_contents($path));
                                 }
                             } catch (Exception $e) {
                             }
                         }
                     }
                 }
             }
             $body = $html->save();
             $this->getResponse()->setBody($body);
         }
     }
 }
Exemplo n.º 14
0
 /**
  * Handle input, produce output
  *
  * @param array $args $_REQUEST contents
  *
  * @return void
  */
 function handle($args)
 {
     // undo headers set by PHP sessions
     $sec = session_cache_expire() * 60;
     header('Expires: ' . date(DATE_RFC1123, time() + $sec));
     header('Cache-Control: max-age=' . $sec);
     parent::handle($args);
     $path = $this->path;
     header('Content-Type: ' . MIME_Type::autoDetect($path));
     if (common_config('site', 'use_x_sendfile')) {
         header('X-Sendfile: ' . $path);
     } else {
         header('Content-Length: ' . filesize($path));
         readfile($path);
     }
 }
Exemplo n.º 15
0
 /**
  * Detects the GeSHi language format of a file.
  * It first detects the MIME type of the file and uses
  * $typeToFormat to map that to GeSHi language formats.
  *
  * @param string $filename Full or relative path of the file to detect
  *
  * @return string GeSHi language format (e.g. 'php')
  */
 protected function detectFormat($filename)
 {
     require_once 'MIME/Type.php';
     $type = MIME_Type::autoDetect($filename);
     if (!isset(self::$typeToFormat[$type])) {
         throw new Exception('No idea which format this is: ' . $type);
     }
     return self::$typeToFormat[$type];
 }
Exemplo n.º 16
0
<?php

/**
 * Demonstrates how to use a custom magic database.
 * The detected MIME type should be text/x-custom-mimetype
 */
require_once 'MIME/Type.php';
$mt = new MIME_Type();
$mt->magicFile = dirname(__FILE__) . '/custom-magic.magic';
$type = $mt->autoDetect(dirname(__FILE__) . '/custom-magic.php');
echo 'Type:    ' . $type . "\n";
echo 'Media:   ' . $mt->media . "\n";
echo 'Subtype: ' . $mt->subType . "\n";
Exemplo n.º 17
0
 static function getUploadedFileType($f)
 {
     require_once 'MIME/Type.php';
     $cmd =& PEAR::getStaticProperty('MIME_Type', 'fileCmd');
     $cmd = common_config('attachments', 'filecommand');
     $filetype = null;
     if (is_string($f)) {
         // assuming a filename
         $filetype = MIME_Type::autoDetect($f);
     } else {
         // assuming a filehandle
         $stream = stream_get_meta_data($f);
         $filetype = MIME_Type::autoDetect($stream['uri']);
     }
     if (common_config('attachments', 'supported') === true || in_array($filetype, common_config('attachments', 'supported'))) {
         return $filetype;
     }
     $media = MIME_Type::getMedia($filetype);
     if ('application' !== $media) {
         $hint = sprintf(_(' Try using another %s format.'), $media);
     } else {
         $hint = '';
     }
     throw new ClientException(sprintf(_('%s is not a supported file type on this server.'), $filetype) . $hint);
 }
Exemplo n.º 18
0
 /**
  * @expectedException PHPUnit_Framework_Error
  * @expectedExceptionMessage Call to undefined method MIME_TYPE::doesNotExist()
  */
 public function test__callStaticUnknownMethod()
 {
     MIME_Type::doesNotExist();
 }
Exemplo n.º 19
0
/**
 *	read a file's mimetype
 *
 *	first tries the PHP internal mime_content_type,
 * then falls back to PEAR library, the to unix file
 * to detect mimetype.
 *
 *	@access		public
 *	@param 		string	$file
 * @param		string	&$mime
 *	@return		bool
 *
 */
function read_mime($file, &$mime, $fallback_extension)
{
    global $file_binary, $ext_to_mime;
    $mime = '';
    if (function_exists('mime_content_type')) {
        $mime = @mime_content_type($file);
    }
    if ($mime != '') {
        return true;
    }
    if (function_exists('MIME_TYPE::autoDetect')) {
        $mime = @MIME_Type::autoDetect($file);
    }
    if ($mime != '') {
        return true;
    }
    unset($result);
    $cmd = $file_binary . " -b -i \"" . $file . "\"";
    @exec($cmd, $result);
    if (isset($result[0])) {
        if (preg_match("/^[a-zA-Z0-9-]+\\/[a-zA-Z0-9-]+\$/", trim($result[0]))) {
            $mime = trim($result[0]);
        }
    }
    if ($mime != '') {
        return true;
    } else {
        if ($fallback_extension) {
            if (key_exists($fallback_extension, $ext_to_mime)) {
                $mime = @$ext_to_mime[$fallback_extension];
            }
        }
    }
    if ($mime != '') {
        return true;
    } else {
        return false;
    }
}
Exemplo n.º 20
0
 /**
  * @return void
  */
 protected function update()
 {
     if (!$this->getFilename() && $this->getId() != 1) {
         $this->delete();
         throw new Exception("Asset requires filename, asset with id " . $this->getId() . " deleted");
     }
     // set date
     $this->setModificationDate(time());
     // save data
     $conf = Pimcore_Config::getSystemConfig();
     // create foldertree
     $destinationPath = $this->getFileSystemPath();
     if (!is_dir(dirname($destinationPath))) {
         mkdir(dirname($destinationPath), self::$chmod, true);
     }
     if ($this->_oldPath) {
         rename(PIMCORE_ASSET_DIRECTORY . $this->_oldPath, $this->getFileSystemPath());
     }
     if ($this->getType() != "folder") {
         // get data
         $this->getData();
         // remove if exists
         if (is_file($destinationPath)) {
             unlink($destinationPath);
         }
         file_put_contents($destinationPath, $this->getData());
         chmod($destinationPath, self::$chmod);
         // check file exists
         if (!is_file($destinationPath)) {
             throw new Exception("couldn't create new asset");
         }
         // set mime type
         $mimetype = MIME_Type::autoDetect($this->getFileSystemPath());
         $this->setMimetype($mimetype);
         // set type
         $this->setTypeFromMapping();
         // update scheduled tasks
         $this->saveScheduledTasks();
         // create version
         $this->getData();
         // load data from filesystem to put it into the version
         $version = new Version();
         $version->setCid($this->getId());
         $version->setCtype("asset");
         $version->setDate($this->getModificationDate());
         $version->setUserId($this->getUserModification());
         $version->setData($this);
         $version->save();
     }
     // save properties
     $this->getProperties();
     $this->getResource()->deleteAllProperties();
     if (is_array($this->getProperties()) and count($this->getProperties()) > 0) {
         foreach ($this->getProperties() as $property) {
             if (!$property->getInherited()) {
                 $property->setResource(null);
                 $property->setCid($this->getId());
                 $property->setCpath($this->getPath() . $this->getKey());
                 $property->save();
             }
         }
     }
     // save permissions
     $this->getPermissions();
     if (is_array($this->permissions)) {
         // remove all permissions
         $this->getResource()->deleteAllPermissions();
         foreach ($this->permissions as $permission) {
             $permission->setId(null);
             $permission->setCid($this->getId());
             $permission->setCpath($this->getFullPath());
             $permission->save();
         }
     }
     // save dependencies
     $d = $this->getDependencies();
     $d->clean();
     foreach ($this->resolveDependencies() as $requirement) {
         if ($requirement["id"] == $this->getId() && $requirement["type"] == "asset") {
             // dont't add a reference to yourself
             continue;
         } else {
             $d->addRequirement($requirement["id"], $requirement["type"]);
         }
     }
     $d->save();
     $this->getResource()->update();
     if ($this->_oldPath) {
         $this->getResource()->updateChildsPaths($this->_oldPath);
     }
     $this->clearDependedCache();
     //set object to registry
     Zend_Registry::set("asset_" . $this->getId(), $this);
     Pimcore_API_Plugin_Broker::getInstance()->postUpdateAsset($this);
 }
Exemplo n.º 21
0
 /**
  * Guess content type of file
  * 
  * First we try to use PEAR::MIME_Type, if installed, to detect the content 
  * type, else we check if ext/mime_magic is loaded and properly configured.
  *
  * Returns PEAR_Error if:
  *      o if PEAR::MIME_Type failed to detect a proper content type
  *        (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE)
  *      o ext/magic.mime is not installed, or not properly configured
  *        (HTTP_DOWNLOAD_E_NO_EXT_MMAGIC)
  *      o mime_content_type() couldn't guess content type or returned
  *        a content type considered to be bogus by setContentType()
  *        (HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE)
  * 
  * @access  public
  * @return  mixed   Returns true on success or PEAR_Error on failure.
  */
 function guessContentType()
 {
     if (class_exists('MIME_Type') || @(include_once 'MIME/Type.php')) {
         if (PEAR::isError($mime_type = MIME_Type::autoDetect($this->file))) {
             return PEAR::raiseError($mime_type->getMessage(), HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE);
         }
         return $this->setContentType($mime_type);
     }
     if (!function_exists('mime_content_type')) {
         return PEAR::raiseError('This feature requires ext/mime_magic!', HTTP_DOWNLOAD_E_NO_EXT_MMAGIC);
     }
     if (!is_file(ini_get('mime_magic.magicfile'))) {
         return PEAR::raiseError('ext/mime_magic is loaded but not properly configured!', HTTP_DOWNLOAD_E_NO_EXT_MMAGIC);
     }
     if (!($content_type = @mime_content_type($this->file))) {
         return PEAR::raiseError('Couldn\'t guess content type with mime_content_type().', HTTP_DOWNLOAD_E_INVALID_CONTENT_TYPE);
     }
     return $this->setContentType($content_type);
 }
Exemplo n.º 22
0
 /**
  * Autodetect a file's MIME-type
  *
  * This function may be called staticly.
  *
  * @param  string $file   Path to the file to get the type of
  * @param  bool   $params Append MIME parameters if true
  * @return string $file's MIME-type on success, PEAR_Error otherwise
  * @since 1.0.0beta1
  * @static
  */
 function autoDetect($file, $params = false)
 {
     @(include_once 'System/Command.php');
     if (function_exists('mime_content_type')) {
         $type = mime_content_type($file);
     } else {
         if (class_exists('System_Command')) {
             $type = MIME_Type::_fileAutoDetect($file);
         } else {
             return PEAR::raiseError("Sorry, can't autodetect; you need the mime_magic extension or System_Command and 'file' installed to use this function.");
         }
     }
     // _fileAutoDetect() may have returned an error.
     if (PEAR::isError($type)) {
         return $type;
     }
     // Don't return an empty string
     if (!$type || !strlen($type)) {
         return PEAR::raiseError("Sorry, couldn't determine file type.");
     }
     // Strip parameters if present & requested
     if (MIME_Type::hasParameters($type) && !$params) {
         $type = MIME_Type::stripParameters($type);
     }
     return $type;
 }
Exemplo n.º 23
0
 /**
  * Handles a detected MIME type and modifies it if necessary.
  *
  * @param string $type   MIME Type of a file
  * @param bool   $params Append MIME parameters if true
  *
  * @return string $file's MIME-type on success, PEAR_Error otherwise
  * @static
  */
 function _handleDetection($type, $params)
 {
     // _fileAutoDetect() may have returned an error.
     if (PEAR::isError($type)) {
         return $type;
     }
     // Don't return an empty string
     if (!$type || !strlen($type)) {
         return PEAR::raiseError("Sorry, couldn't determine file type.");
     }
     // Strip parameters if present & requested
     if (MIME_Type::hasParameters($type) && !$params) {
         $type = MIME_Type::stripParameters($type);
     }
     return $type;
 }
Exemplo n.º 24
0
 /**
  *   determines the mime-type for the given file
  *   @static
  *   @param  string  The file name
  *   @return string  The MIME type or FALSE in the case of an error
  */
 function getMimeType($strFile)
 {
     //MIME_Type doesn't return the right type for directories
     //The underlying functions MIME_Type used don't return it right,
     //so there is no chance to fix MIME_Type itself
     if (file_exists($strFile) && is_dir($strFile) || substr($strFile, -1) == '/') {
         return 'inode/directory';
     }
     $strMime = MIME_Type::autoDetect($strFile);
     if (!PEAR::isError($strMime)) {
         return $strMime;
     }
     //determine by extension | as MIME_TYPE doesn't support this, I have to do this myself
     $strExtension = Gtk_FileDrop::getFileExtension($strFile);
     switch ($strExtension) {
         case '.txt':
             $strType = 'text/plain';
             break;
         case '.gif':
             $strType = 'image/gif';
             break;
         case '.jpg':
         case '.jpeg':
             $strType = 'image/jpg';
             break;
         case '.png':
             $strType = 'image/png';
             break;
         case '.xml':
             $strType = 'text/xml';
             break;
         case '.htm':
         case '.html':
             $strType = 'text/html';
             break;
         default:
             $strType = false;
             break;
     }
     return $strType;
 }
Exemplo n.º 25
0
<?php

ini_set('error_reporting', E_ALL);
require 'MIME/Type.php';
$type = 'application/x-test-app; foo="bar" (First argument); bar=baz (Second argument)';
$type2 = 'application/vnd.pear.test-type';
print "Checking type: {$type}\n";
if (MIME_Type::isExperimental($type)) {
    print "Type is experimental\n";
} else {
    print "Type is not experimental\n";
}
print "\nChecking type: {$type2}\n";
if (MIME_Type::isVendor($type2)) {
    print "Type is vendor-specific\n";
} else {
    print "Type is not vendor-specific\n";
}
$file = '/www/htdocs/w00acdb0/lib/pear/PEAR/docs/MIME_Type/example.php';
print "\nChecking type of: {$file}\n";
$type = MIME_Type::autoDetect($file);
if (PEAR::isError($type)) {
    print 'Error: ' . $type->getMessage() . "\n";
} else {
    print $type . "\n";
}
Exemplo n.º 26
0
/**
 *	read a file's mimetype
 *
 *	first tries the PHP internal mime_content_type,
 * then falls back to PEAR library, the to unix file
 * to detect mimetype.
 *
 *	@access		public
 *	@param 		string	$file
 *  @param		string	&$mime
 *	@return		bool
 *
 */
function read_mime($file, &$mime, $fallback_extension)
{
    global $file_binary, $ext_to_mime;
    $mime = '';
    if (function_exists('mime_content_type')) {
        $mime = mime_content_type($file);
    }
    if ($mime != '') {
        return true;
    }
    if (function_exists('MIME_TYPE::autoDetect')) {
        $mime = MIME_Type::autoDetect($file);
    }
    if ($mime != '') {
        return true;
    }
    unset($result);
    $cmd = $file_binary . " -b -i \"" . $file . "\"";
    exec($cmd, $result);
    if (isset($result[0])) {
        if (preg_match("/^[a-zA-Z0-9-]+\\/[a-zA-Z0-9-]+\$/", trim($result[0]))) {
            $mime = trim($result[0]);
        }
    } else {
        // probably this version of file is too old to understand "-b", try without
        $cmd = $file_binary . " \"" . $file . "\"";
        exec($cmd, $result);
        // strip path from result
        $result[0] = trim(substr($result[0], strlen($file) + 1));
        // combine the results
        $tmp_result = @explode(" ", $result[0]);
        if (isset($tmp_result[2])) {
            if ($tmp_result[2] == 'file') {
                $mime = $tmp_result[1] . '/' . $tmp_result[0];
            }
        }
    }
    if ($mime != '') {
        return true;
    } else {
        if ($fallback_extension) {
            if (key_exists($fallback_extension, $ext_to_mime)) {
                $mime = @$ext_to_mime[$fallback_extension];
            }
        }
    }
    if ($mime != '') {
        return true;
    } else {
        return false;
    }
}
Exemplo n.º 27
0
<?php

ini_set('error_reporting', E_ALL);
require 'MIME/Type.php';
//require './Type.php';
$type = 'application/x-test-app; foo="bar" (First argument); bar=baz (Second argument)';
$type2 = 'application/vnd.pear.test-type';
print "Checking type: {$type}\n";
if (MIME_Type::isExperimental($type)) {
    print "Type is experimental\n";
} else {
    print "Type is not experimental\n";
}
print "\nChecking type: {$type2}\n";
if (MIME_Type::isVendor($type2)) {
    print "Type is vendor-specific\n";
} else {
    print "Type is not vendor-specific\n";
}
$file = '/home/mini/workspace/Trunk/core/PEAR/docs/MIME_Type/example.php';
print "\nChecking type of: {$file}\n";
print MIME_Type::autoDetect($file) . "\n";
Exemplo n.º 28
0
 /**
  * Attempt to identify the content type of a given file.
  * 
  * @param mixed $f file handle resource, or filesystem path as string
  * @param string $originalFilename (optional) for extension-based detection
  * @return string
  * 
  * @fixme is this an internal or public method? It's called from GetFileAction
  * @fixme this seems to tie a front-end error message in, kinda confusing
  * @fixme this looks like it could return a PEAR_Error in some cases, if
  *        type can't be identified and $config['attachments']['supported'] is true
  * 
  * @throws ClientException if type is known, but not supported for local uploads
  */
 static function getUploadedFileType($f, $originalFilename = false)
 {
     require_once 'MIME/Type.php';
     require_once 'MIME/Type/Extension.php';
     // We have to disable auto handling of PEAR errors
     PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
     $mte = new MIME_Type_Extension();
     $cmd =& PEAR::getStaticProperty('MIME_Type', 'fileCmd');
     $cmd = common_config('attachments', 'filecommand');
     $filetype = null;
     // If we couldn't get a clear type from the file extension,
     // we'll go ahead and try checking the content. Content checks
     // are unambiguous for most image files, but nearly useless
     // for office document formats.
     if (is_string($f)) {
         // assuming a filename
         $filetype = MIME_Type::autoDetect($f);
     } else {
         // assuming a filehandle
         $stream = stream_get_meta_data($f);
         $filetype = MIME_Type::autoDetect($stream['uri']);
     }
     // The content-based sources for MIME_Type::autoDetect()
     // are wildly unreliable for office-type documents. If we've
     // gotten an unclear reponse back or just couldn't identify it,
     // we'll try detecting a type from its extension...
     $unclearTypes = array('application/octet-stream', 'application/vnd.ms-office', 'application/zip', 'text/xml');
     if ($originalFilename && (!$filetype || in_array($filetype, $unclearTypes))) {
         $type = $mte->getMIMEType($originalFilename);
         if (is_string($type)) {
             $filetype = $type;
         }
     }
     $supported = common_config('attachments', 'supported');
     if (is_array($supported)) {
         // Normalize extensions to mime types
         foreach ($supported as $i => $entry) {
             if (strpos($entry, '/') === false) {
                 common_log(LOG_INFO, "sample.{$entry}");
                 $supported[$i] = $mte->getMIMEType("sample.{$entry}");
             }
         }
     }
     if ($supported === true || in_array($filetype, $supported)) {
         // Restore PEAR error handlers for our DB code...
         PEAR::staticPopErrorHandling();
         return $filetype;
     }
     $media = MIME_Type::getMedia($filetype);
     if ('application' !== $media) {
         // TRANS: Client exception thrown trying to upload a forbidden MIME type.
         // TRANS: %1$s is the file type that was denied, %2$s is the application part of
         // TRANS: the MIME type that was denied.
         $hint = sprintf(_('"%1$s" is not a supported file type on this server. ' . 'Try using another %2$s format.'), $filetype, $media);
     } else {
         // TRANS: Client exception thrown trying to upload a forbidden MIME type.
         // TRANS: %s is the file type that was denied.
         $hint = sprintf(_('"%s" is not a supported file type on this server.'), $filetype);
     }
     // Restore PEAR error handlers for our DB code...
     PEAR::staticPopErrorHandling();
     throw new ClientException($hint);
 }
Exemplo n.º 29
0
 /**
  * @see File_Archive_Reader::getMime
  */
 function getMime()
 {
     if ($this->mime === null) {
         PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
         $this->mime = MIME_Type::autoDetect($this->getDataFilename());
         PEAR::popErrorHandling();
         if (PEAR::isError($this->mime)) {
             $this->mime = parent::getMime();
         }
     }
     return $this->mime;
 }
 /**
  * Returns mime type from the actual file using a detection library
  * @access protected
  * @return string or boolean
  */
 protected function autoDetectMIMETypeFromFile($filename)
 {
     $settings = sfConfig::get('app_sfImageTransformPlugin_mime_type', 'GD');
     $support_libraries = array('fileinfo', 'mime_type');
     if (false === $settings['auto_detect']) {
         return false;
     }
     if (in_array(strtolower($settings['library']), $support_libraries) && '' !== $filename) {
         if ('fileinfo' === strtolower($settings["library"])) {
             if (function_exists('finfo_file')) {
                 $finfo = finfo_open(FILEINFO_MIME);
                 return finfo_file($finfo, $filename);
             }
         }
         if ('mime_type' === strtolower($settings["library"])) {
             // Supressing warning as PEAR is not strict compliant
             @(require_once 'MIME/Type.php');
             if (method_exists('MIME_Type', 'autoDetect')) {
                 return @MIME_Type::autoDetect($filename);
             }
         }
     }
     return false;
 }