public static function sendFileAbs($sAbsFilePath, $bEval = false) { if (file_exists($sAbsFilePath)) { global $MimeTypes; self::$_sCurrentFileName = $sAbsFilePath; $sExt = strtolower(pathinfo($sAbsFilePath, PATHINFO_EXTENSION)); $sType = MimeType::guess($sExt); if ($sType && !isset(self::$_aHeaders['Content-Type'])) { self::setContentType($sType); if (!MimeType::canEval($sExt)) { $bEval = false; } } if ($bEval) { return self::send(file_get_contents($sAbsFilePath), $bEval); } else { self::$_bReadyToSend = true; self::_sendHeaders(); readfile($sAbsFilePath); exit; } } else { debug('File does not exist: ' . $sAbsFilePath); } return false; }
public function testNoFinfoFallback() { global $passthru; $passthru = false; $this->assertNull(MimeType::detectByContent('string')); $passthru = true; }
/** * Sets validator options * * @param string|array|\Zend\Config\Config $mimetype * @return void */ public function __construct($mimetype = array()) { if ($mimetype instanceof \Zend\Config\Config) { $mimetype = $mimetype->toArray(); } $temp = array(); // http://de.wikipedia.org/wiki/Liste_von_Dateiendungen // http://www.iana.org/assignments/media-types/image/ $default = array('application/cdf', 'application/dicom', 'application/fractals', 'application/postscript', 'application/vnd.hp-hpgl', 'application/vnd.oasis.opendocument.graphics', 'application/x-cdf', 'application/x-cmu-raster', 'application/x-ima', 'application/x-inventor', 'application/x-koan', 'application/x-portable-anymap', 'application/x-world-x-3dmf', 'image/bmp', 'image/c', 'image/cgm', 'image/fif', 'image/gif', 'image/jpeg', 'image/jpm', 'image/jpx', 'image/jp2', 'image/naplps', 'image/pjpeg', 'image/png', 'image/svg', 'image/svg+xml', 'image/tiff', 'image/vnd.adobe.photoshop', 'image/vnd.djvu', 'image/vnd.fpx', 'image/vnd.net-fpx', 'image/x-cmu-raster', 'image/x-cmx', 'image/x-coreldraw', 'image/x-cpi', 'image/x-emf', 'image/x-ico', 'image/x-icon', 'image/x-jg', 'image/x-ms-bmp', 'image/x-niff', 'image/x-pict', 'image/x-pcx', 'image/x-portable-anymap', 'image/x-portable-bitmap', 'image/x-portable-greymap', 'image/x-portable-pixmap', 'image/x-quicktime', 'image/x-rgb', 'image/x-tiff', 'image/x-unknown', 'image/x-windows-bmp', 'image/x-xpmi'); if (is_array($mimetype)) { $temp = $mimetype; if (array_key_exists('magicfile', $temp)) { unset($temp['magicfile']); } if (array_key_exists('headerCheck', $temp)) { unset($temp['headerCheck']); } if (empty($temp)) { $mimetype += $default; } } if (empty($mimetype)) { $mimetype = $default; } parent::__construct($mimetype); }
static function &getInstance() { if (self::$instance === false) { self::$instance = new self(); } return self::$instance; }
/** * Sets validator options * * @param string|array|\Zend\Config\Config $compression * @return void */ public function __construct($mimetype = array()) { if ($mimetype instanceof \Zend\Config\Config) { $mimetype = $mimetype->toArray(); } $temp = array(); // http://de.wikipedia.org/wiki/Liste_von_Dateiendungen $default = array('application/arj', 'application/gnutar', 'application/lha', 'application/lzx', 'application/vnd.ms-cab-compressed', 'application/x-ace-compressed', 'application/x-arc', 'application/x-archive', 'application/x-arj', 'application/x-bzip', 'application/x-bzip2', 'application/x-cab-compressed', 'application/x-compress', 'application/x-compressed', 'application/x-cpio', 'application/x-debian-package', 'application/x-eet', 'application/x-gzip', 'application/x-java-pack200', 'application/x-lha', 'application/x-lharc', 'application/x-lzh', 'application/x-lzma', 'application/x-lzx', 'application/x-rar', 'application/x-sit', 'application/x-stuffit', 'application/x-tar', 'application/zip', 'application/zoo', 'multipart/x-gzip'); if (is_array($mimetype)) { $temp = $mimetype; if (array_key_exists('magicfile', $temp)) { unset($temp['magicfile']); } if (array_key_exists('headerCheck', $temp)) { unset($temp['headerCheck']); } if (empty($temp)) { $mimetype += $default; } } if (empty($mimetype)) { $mimetype = $default; } parent::__construct($mimetype); }
public function testGetList() { $primitive = Primitive::enum('enum')->of('MimeType'); $enum = MimeType::wrap(1); $this->assertEquals($primitive->getList(), MimeType::getObjectList()); $primitive->setDefault($enum); $this->assertEquals($primitive->getList(), MimeType::getObjectList()); $primitive->import(array('enum' => MimeType::getAnyId())); $this->assertEquals($primitive->getList(), MimeType::getObjectList()); }
/** * Factory method * * @param var arg either an InputStream, File, or IOElement * @return self * @throws lang.IllegalArgumentException */ public static function of($arg) { if ($arg instanceof InputStream) { return new self($arg); } else { if ($arg instanceof File) { return create(new self($arg->getInputStream()))->withMediaType(MimeType::getByFileName($arg->getFileName()))->withContentLength($arg->getSize())->withLastModified(new Date($arg->lastModified())); } else { if ($arg instanceof IOElement) { return create(new self($arg->getInputStream()))->withMediaType(MimeType::getByFileName($arg->getURI()))->withContentLength($arg->getSize())->withLastModified($arg->lastModified()); } else { throw new IllegalArgumentException('Expected either an InputStream, File, or IOElement, have ' . xp::typeOf($arg)); } } } }
/** * Loads and parses the xml file * @return void */ private static function loadXmlFile() { if (is_null(self::$file)) { self::setXmlFile(dirname(__FILE__) . '/MimeType/mimetypes.xml'); } $xml = simplexml_load_file(self::$file); $mimetypes = array(); // loop through data foreach ($xml as $type) { $mimetypes[(string) $type->extension] = array('extension' => (string) $type->extension, 'mimetype' => (string) $type->mime); } // Cache data self::$data = $mimetypes; // Clear xml instance unset($xml, $mimetypes, $type); }
function testTransitions() { exec('which gs 2>&1', $output, $return); $this->skipUnless($return === 0, 'gs command not available'); $Medium = new DocumentMedium($this->TestData->getFile('application-pdf.pdf')); $Medium = $Medium->convert('image/png'); if ($this->assertIsA($Medium, 'ImageMedium')) { $tmpFile = $Medium->store(TMP . uniqid('test_suite_')); $this->assertEqual(MimeType::guessType($tmpFile), 'image/png'); unlink($tmpFile); } $Medium = new DocumentMedium($this->TestData->getFile('application-pdf.pdf')); $Medium = $Medium->convert('image/png'); if ($this->assertIsA($Medium, 'ImageMedium')) { $result = $Medium->fit(10, 10); $this->assertTrue($result); $this->assertTrue($Medium->width() <= 10); $this->assertTrue($Medium->height() <= 10); } }
/** * Sets validator options * * @param string|array|\Zend\Config\Config $compression * @return void */ public function __construct($options = array()) { // http://de.wikipedia.org/wiki/Liste_von_Dateiendungen $default = array('application/arj', 'application/gnutar', 'application/lha', 'application/lzx', 'application/vnd.ms-cab-compressed', 'application/x-ace-compressed', 'application/x-arc', 'application/x-archive', 'application/x-arj', 'application/x-bzip', 'application/x-bzip2', 'application/x-cab-compressed', 'application/x-compress', 'application/x-compressed', 'application/x-cpio', 'application/x-debian-package', 'application/x-eet', 'application/x-gzip', 'application/x-java-pack200', 'application/x-lha', 'application/x-lharc', 'application/x-lzh', 'application/x-lzma', 'application/x-lzx', 'application/x-rar', 'application/x-sit', 'application/x-stuffit', 'application/x-tar', 'application/zip', 'application/zoo', 'multipart/x-gzip'); if (is_array($options) && array_key_exists('magicFile', $options)) { $this->setMagicFile($options['magicFile']); unset($options['magicFile']); } if (is_array($options) && array_key_exists('enableHeaderCheck', $options)) { $this->enableHeaderCheck($options['enableHeaderCheck']); unset($options['enableHeaderCheck']); } if (is_array($options) && !array_key_exists('mimeType', $options)) { $options['mimeType'] = $options; } if (empty($options)) { $options = array('mimeType' => $default); } if (!is_array($options)) { $options = array('mimeType' => $options); } parent::__construct($options); }
/** * Sets validator options * * @param string|array|\Zend\Config\Config $mimetype * @return void */ public function __construct($options = array()) { // http://de.wikipedia.org/wiki/Liste_von_Dateiendungen // http://www.iana.org/assignments/media-types/image/ $default = array('application/cdf', 'application/dicom', 'application/fractals', 'application/postscript', 'application/vnd.hp-hpgl', 'application/vnd.oasis.opendocument.graphics', 'application/x-cdf', 'application/x-cmu-raster', 'application/x-ima', 'application/x-inventor', 'application/x-koan', 'application/x-portable-anymap', 'application/x-world-x-3dmf', 'image/bmp', 'image/c', 'image/cgm', 'image/fif', 'image/gif', 'image/jpeg', 'image/jpm', 'image/jpx', 'image/jp2', 'image/naplps', 'image/pjpeg', 'image/png', 'image/svg', 'image/svg+xml', 'image/tiff', 'image/vnd.adobe.photoshop', 'image/vnd.djvu', 'image/vnd.fpx', 'image/vnd.net-fpx', 'image/x-cmu-raster', 'image/x-cmx', 'image/x-coreldraw', 'image/x-cpi', 'image/x-emf', 'image/x-ico', 'image/x-icon', 'image/x-jg', 'image/x-ms-bmp', 'image/x-niff', 'image/x-pict', 'image/x-pcx', 'image/x-png', 'image/x-portable-anymap', 'image/x-portable-bitmap', 'image/x-portable-greymap', 'image/x-portable-pixmap', 'image/x-quicktime', 'image/x-rgb', 'image/x-tiff', 'image/x-unknown', 'image/x-windows-bmp', 'image/x-xpmi'); if (is_array($options) && array_key_exists('magicFile', $options)) { $this->setMagicFile($options['magicFile']); unset($options['magicFile']); } if (is_array($options) && array_key_exists('enableHeaderCheck', $options)) { $this->enableHeaderCheck($options['enableHeaderCheck']); unset($options['enableHeaderCheck']); } if (is_array($options) && !array_key_exists('mimeType', $options)) { $options['mimeType'] = $options; } if (empty($options)) { $options = array('mimeType' => $default); } if (!is_array($options)) { $options = array('mimeType' => $options); } parent::__construct($options); }
public function insert_data_object($row, $parameters) { self::debug_iterations("Inserting DataObject"); $this->commit_iterations("DataObject", 20); if ($this->archive_validator->has_error_by_line('http://eol.org/schema/media/document', $parameters['archive_table_definition']->location, $parameters['archive_line_number'])) { write_to_resource_harvesting_log("ERROR: insert_data_object: has_error_by_line" . ",file_location:" . $parameters['archive_table_definition']->location . ",line_number:" . $parameters['archive_line_number']); return false; } $object_taxon_ids = self::get_foreign_keys_from_row($row, 'http://rs.tdwg.org/dwc/terms/taxonID'); $object_taxon_info = array(); if ($object_taxon_ids) { foreach ($object_taxon_ids as $taxon_id) { if ($taxon_info = @$this->taxon_ids_inserted[$taxon_id]) { self::uncompress_array($taxon_info); $object_taxon_info[] = $taxon_info; } } } if (!$object_taxon_info) { return false; } if ($this->harvest_event->resource->is_eol_flickr_group() && self::is_this_flickr_image_in_inaturalist($row)) { return false; } $data_object = new DataObject(); $data_object->identifier = @self::field_decode($row['http://purl.org/dc/terms/identifier']); if (isset($this->media_ids_inserted[$data_object->identifier])) { return false; } $data_object->data_type = DataType::find_or_create_by_schema_value(@self::field_decode($row['http://purl.org/dc/terms/type'])); if ($dt = DataType::find_or_create_by_schema_value(@self::field_decode($row['http://rs.tdwg.org/audubon_core/subtype']))) { $data_object->data_subtype_id = $dt->id; } $data_object->mime_type = MimeType::find_or_create_by_translated_label(@self::field_decode($row['http://purl.org/dc/terms/format'])); $data_object->object_created_at = @self::field_decode($row['http://ns.adobe.com/xap/1.0/CreateDate']); $data_object->object_modified_at = @self::field_decode($row['http://purl.org/dc/terms/modified']); $data_object->available_at = @self::field_decode($row['http://purl.org/dc/terms/available']); $data_object->object_title = @self::field_decode($row['http://purl.org/dc/terms/title']); $data_object->language = Language::find_or_create_for_parser(@self::field_decode($row['http://purl.org/dc/terms/language'])); // check multiple fields for a value of license if (isset($row['http://purl.org/dc/terms/license'])) { $license_string = @self::field_decode($row['http://purl.org/dc/terms/license']); } else { $license_string = @self::field_decode($row['http://ns.adobe.com/xap/1.0/rights/UsageTerms']); } // convert British licences to American licenses $license_string = str_replace("creativecommons.org/licences/", "creativecommons.org/licenses/", $license_string); if (!$license_string && $this->harvest_event->resource->license && $this->harvest_event->resource->license->source_url) { $license_string = $this->harvest_event->resource->license->source_url; } if (!$license_string || !\eol_schema\MediaResource::valid_license($license_string)) { return false; } $data_object->license = License::find_or_create_for_parser($license_string); $data_object->rights_statement = @self::field_decode($row['http://purl.org/dc/terms/rights']); $data_object->rights_holder = @self::field_decode($row['http://ns.adobe.com/xap/1.0/rights/Owner']); $data_object->bibliographic_citation = @self::field_decode($row['http://purl.org/dc/terms/bibliographicCitation']); $data_object->source_url = @self::field_decode($row['http://rs.tdwg.org/ac/terms/furtherInformationURL']); $data_object->derived_from = @self::field_decode($row['http://rs.tdwg.org/ac/terms/derivedFrom']); $data_object->description = @self::field_decode($row['http://purl.org/dc/terms/description']); // Turn newlines into paragraphs $data_object->description = str_replace("\n", "</p><p>", $data_object->description); $data_object->object_url = @self::field_decode($row['http://rs.tdwg.org/ac/terms/accessURI']); $data_object->thumbnail_url = @self::field_decode($row['http://eol.org/schema/media/thumbnailURL']); $data_object->location = @self::field_decode($row['http://iptc.org/std/Iptc4xmpExt/1.0/xmlns/LocationCreated']); $data_object->spatial_location = @self::field_decode($row['http://purl.org/dc/terms/spatial']); $data_object->latitude = @self::field_decode($row['http://www.w3.org/2003/01/geo/wgs84_pos#lat']); $data_object->longitude = @self::field_decode($row['http://www.w3.org/2003/01/geo/wgs84_pos#long']); $data_object->altitude = @self::field_decode($row['http://www.w3.org/2003/01/geo/wgs84_pos#alt']); $rating = @self::field_decode($row['http://ns.adobe.com/xap/1.0/Rating']); // ratings may be 0 to 5 // TODO: technically 0 means untrusted, and then anywhere from 1-5 is OK. // 0.5 for example isn't really valid acording to the schema if (is_numeric($rating) && $rating > 0 && $rating <= 5) { $data_object->data_rating = $rating; } //TODO - update this if ($data_object->mime_type && $data_object->mime_type->equals(MimeType::flash()) && $data_object->is_video()) { $data_object->data_type = DataType::youtube(); $data_object->data_type_id = DataType::youtube()->id; } // //take the first available source_url of one of this object's taxa if (!@$data_object->source_url && @$taxon_parameters["source_url"]) { foreach ($object_taxon_info as $taxon_info) { if ($source_url = $taxon_info['source_url']) { $data_object->source_url = $source_url; break; } } } /* Checking requirements */ // if text: must have description if ($data_object->data_type->equals(DataType::text()) && !$data_object->description) { return false; } // if image, movie or sound: must have object_url if (($data_object->data_type->equals(DataType::video()) || $data_object->data_type->equals(DataType::sound()) || $data_object->data_type->equals(DataType::image())) && !$data_object->object_url) { return false; } /* ADDING THE DATA OBJECT */ list($data_object, $status) = DataObject::find_and_compare($this->harvest_event->resource, $data_object, $this->content_manager); if (@(!$data_object->id)) { return false; } $this->media_ids_inserted[$data_object->identifier] = $data_object->id; $this->harvest_event->add_data_object($data_object, $status); $data_object->delete_hierarchy_entries(); $vetted_id = Vetted::unknown()->id; $visibility_id = Visibility::preview()->id; foreach ($object_taxon_info as $taxon_info) { $he_id = $taxon_info['hierarchy_entry_id']; $tc_id = $taxon_info['taxon_concept_id']; $this->mysqli->insert("INSERT IGNORE INTO data_objects_hierarchy_entries (hierarchy_entry_id, data_object_id, vetted_id, visibility_id) VALUES ({$he_id}, {$data_object->id}, {$vetted_id}, {$visibility_id})"); $this->mysqli->insert("INSERT IGNORE INTO data_objects_taxon_concepts (taxon_concept_id, data_object_id) VALUES ({$tc_id}, {$data_object->id})"); } // a few things to add after the DataObject is inserted // keep track of reference foreign keys self::append_foreign_keys_from_row($row, 'http://eol.org/schema/reference/referenceID', $this->media_reference_ids, $data_object->id, $data_object->guid); // keep track of agent foreign keys self::append_foreign_keys_from_row($row, 'http://eol.org/schema/agent/agentID', $this->media_agent_ids, $data_object->id); $data_object->delete_info_items(); $data_object->delete_table_of_contents(); if ($s = @self::field_decode($row['http://iptc.org/std/Iptc4xmpExt/1.0/xmlns/CVterm'])) { $ii = InfoItem::find_or_create_by_schema_value($s); $data_object->add_info_item($ii->id); unset($ii); } if ($a = @self::field_decode($row['http://purl.org/dc/terms/audience'])) { $a = Audience::find_or_create_by_translated_label(trim((string) $a)); $data_object->add_audience($a->id); unset($a); } $data_object_parameters["agents"] = array(); self::append_agents($row, $data_object_parameters, 'http://purl.org/dc/terms/creator', 'Creator'); self::append_agents($row, $data_object_parameters, 'http://purl.org/dc/terms/publisher', 'Publisher'); self::append_agents($row, $data_object_parameters, 'http://purl.org/dc/terms/contributor', 'Contributor'); $data_object->delete_agents(); $i = 0; foreach ($data_object_parameters['agents'] as &$a) { $agent = Agent::find_or_create($a); if ($agent->logo_url && !$agent->logo_cache_url) { if ($logo_cache_url = $this->content_manager->grab_file($agent->logo_url, "partner")) { $agent->logo_cache_url = $logo_cache_url; $agent->save(); } } $data_object->add_agent($agent->id, @$a['agent_role']->id ?: 0, $i); unset($a); $i++; } if (!isset($this->object_references_deleted[$data_object->id])) { $data_object->delete_refs(); $this->object_references_deleted[$data_object->id] = true; } // add data object info to resource contribution if ($status != "Unchanged") { $result = $this->mysqli->query("SELECT id, source_url, taxon_concept_id, hierarchy_id, identifier FROM hierarchy_entries inner join data_objects_hierarchy_entries on hierarchy_entries.id = data_objects_hierarchy_entries.hierarchy_entry_id where data_object_id =" . $data_object->id); if ($result && ($row = $result->fetch_assoc())) { $hierarchy_entry_id = $row["id"]; $source = "'" . $this->get_hierarchy_entry_outlink($row["hierarchy_id"], $row["identifier"], preg_replace('/\'/', "\\'", $row["source_url"])) . "'"; $identifier = "'" . $row["identifier"] . "'"; $taxon_concept_id = $row["taxon_concept_id"]; } $resource_id = $this->harvest_event->resource_id; $this->mysqli->insert("INSERT IGNORE INTO resource_contributions (resource_id, data_object_id, data_point_uri_id, hierarchy_entry_id, taxon_concept_id, source, object_type, identifier, data_object_type) VALUES ({$resource_id}, {$data_object->id}, NULL, {$hierarchy_entry_id}, {$taxon_concept_id}, {$source}, 'data_object', {$identifier}, {$data_object->data_type_id})"); } }
/** * Get MIME type for a path * * @param string|array $path Absolute or partial path to a file * @return string|boolean */ function mimeType($path) { if ($file = $this->file($path)) { return MimeType::guessType($file); } return false; }
/** * Get a file * * @param string filename * @return org.webdav.WebdavObject * @throws lang.ElementNotFoundException * @throws org.webdav.OperationNotAllowedException */ public function get($filename, $token = NULL) { $this->c->debug('FILENAME', $filename); $this->c->debug('TOKEN', $token); $filename = $this->_normalizePath($filename); // check for lock $lockinfo = $this->getLockInfo($filename); if ($lockinfo and $lockinfo['type'] == 'exclusive' and 'opaquelocktoken:' . $lockinfo['token'] != $token) { throw new IllegalArgumentException($filename . ' is locked exclusive'); } if (is_dir($this->base . $filename)) { $this->c->debug(get_class($this), '::GET Dir', $filename); $f = new Folder($this->base . $filename); if (!$f->exists()) { throw new ElementNotFoundException($filename . ' not found'); } while ($maxdepth >= 0 && ($entry = $f->getEntry())) { $isdir = is_dir($this->base . $filename . '/' . $entry); $atime = date('H:i:s d.m.y', fileatime($this->base . $filename . '/' . $entry)); if ($isdir) { $flist[0][$entry] .= sprintf(' <tr> <td><a href="%s/">%s</a></td> <td><DIR></td> <td>%s</td> <td> </td> </tr> ', rawurlencode($entry), $entry, $atime); } else { $flist[1][$entry] .= sprintf(' <tr> <td><a href="%s">%s</a></td> <td> </td> <td>%s</td> <td>%s Bytes</td> </tr> ', rawurlencode($entry), $entry, $atime, filesize($this->base . $filename . '/' . $entry)); } } asort($flist[0]); $html = '<table cellpadding=3>' . (strlen($filename) > 2 ? '<tr><td><a href="../">..</a></td><td><DIR></tr>' : '') . implode('', $flist[0]); asort($flist[1]); $flist = $html . implode('', $flist[1]) . '</table>'; $o = new WebdavObject($f->uri, NULL, strlen($flist), 'text/html', new Date(filectime($f->uri)), new Date(filemtime($f->uri))); $o->setData($flist); $f->close(); return $o; } $this->c->debug(get_class($this), '::GET filename', $filename); $this->c->debug(get_class($this), '::GET base', $this->base); // Open file and read contents // contentype if (!file_exists($this->base . $filename)) { throw new ElementNotFoundException($filename . ' not found'); } $f = new File($this->base . $filename); $contentType = ''; $this->c->debug(get_class($this), '::get ', $this->base . filename); $eProps = $this->propStorage->getProperties($f->uri); if (!empty($eProps['getcontenttype'])) { $contentType = $eProps['getcontenttype'][0]; } if (empty($contentType)) { $contentType = MimeType::getByFilename($f->uri, 'text/plain'); } $o = new WebdavObject($f->uri, NULL, $f->size(), $contentType, new Date($f->createdAt()), new Date($f->lastModified())); try { $f->open(FILE_MODE_READ); $o->setData($f->read($f->size())); $f->close(); } catch (FileFoundException $e) { throw new ElementNotFoundException($filename . ' not found'); } $this->c->debug('OBJ', $o->properties); return $o; }
function testGuessTypeParanoid() { $this->skipUnless(extension_loaded('fileinfo'), '%s. Fileinfo extension not loaded.'); MimeType::config('magic', array('engine' => 'fileinfo')); MimeType::config('glob', array('engine' => 'core', 'file' => dirname(dirname(dirname(dirname(__FILE__)))) . DS . 'vendors' . DS . 'mime_glob.db')); $file = $this->TestData->getFile(array('image-png.png' => TMP . 'image-png.jpg')); $this->assertEqual(MimeType::guessType($file, array('paranoid' => true)), 'image/png'); $this->assertEqual(MimeType::guessType($file, array('paranoid' => false)), 'image/jpeg'); }
function testTransitions() { $Media = new DocumentMedia($this->TestData->getFile('application-pdf.pdf')); $Media->Adapters->detach(array_diff($Media->adapters, array('ImagickShell'))); $Media = $Media->convert('image/png'); $Media->Adapters->detach(array_diff($Media->adapters, array('ImagickShell'))); $this->assertIsA($Media, 'ImageMedia'); $tmpFile = $Media->store(TMP . uniqid('test_suite_')); $this->assertEqual(MimeType::guessType($tmpFile), 'image/png'); unlink($tmpFile); $Media = new DocumentMedia($this->TestData->getFile('application-pdf.pdf')); $Media->Adapters->detach(array_diff($Media->adapters, array('ImagickShell'))); $Media = $Media->convert('image/png'); $Media->Adapters->detach(array_diff($Media->adapters, array('ImagickShell'))); $result = $Media->fit(10, 10); $this->assertTrue($result); $this->assertTrue($Media->width() <= 10); $this->assertTrue($Media->height() <= 10); }
public function getMimeTypes() { return $this->hasMany(MimeType::className(), ['id' => 'mime_type_id'])->viaTable('posts_settings_mime_types', ['posts_settings_id' => 'id']); }
/** * Method for checking if the adapter is going to work with the provided $Media * * Called before the adapter is going to be initialized * May be overridden * * @param object $Media * @return boolean */ function compatible($Media) { $default = array('mimeTypes' => array(), 'extensions' => array(), 'functions' => array(), 'imports' => array(), 'commands' => array()); $require = array_merge($default, $this->require); if (!empty($require['mimeTypes'])) { if (!in_array(MimeType::simplify($Media->mimeType), $require['mimeTypes'])) { return false; } } foreach ($require['extensions'] as $check) { if (!extension_loaded($check)) { return false; } } foreach ($require['functions'] as $check) { if (!function_exists($check)) { return false; } } foreach ($require['commands'] as $check) { if (!$this->_which($check)) { return false; } } foreach ($require['imports'] as $import) { if (!App::import($import)) { return false; } } return true; }
/** * Do a Put on Webdav server * * @param io.File file * @param string uri, filename or directory * @return peer.http.HttpResponse response object * @see rfc://2518 */ public function put($file, $uri = NULL) { // If no uri or filename is specified, take the original filename if ($uri === NULL) { $uri = $file->getFilename(); } // Encode uri to handle files/directories containing spaces $uri = rawurlencode($uri); if (!$file->isOpen()) { $file->open(FILE_MODE_READ); } return $this->getConnection($uri)->put(new RequestData($file->read($file->size())), array(new Header('Content-Type', MimeType::getByFilename($uri)))); }
/** * Retrieve (cached) metadata of a file * * @param Model $Model * @param string $file An absolute path to a file * @param integer $level level of amount of info to add, `0` disable, `1` for basic, `2` for detailed info * @return mixed Array with results or false if file is not readable */ function metadata(&$Model, $file, $level = 1) { if ($level < 1) { return array(); } extract($this->settings[$Model->alias]); $File = new File($file); if (!$File->readable()) { return false; } $checksum = $File->md5(true); if (isset($this->__cached[$Model->alias][$checksum])) { $data = $this->__cached[$Model->alias][$checksum]; } if ($level > 0 && !isset($data[1])) { $data[1] = array('size' => $File->size(), 'mime_type' => MimeType::guessType($File->pwd()), 'checksum' => $checksum); } if ($level > 1 && !isset($data[2])) { $Media = Media::factory($File->pwd()); if ($Media->name === 'Audio') { $data[2] = array('artist' => $Media->artist(), 'album' => $Media->album(), 'title' => $Media->title(), 'track' => $Media->track(), 'year' => $Media->year(), 'length' => $Media->duration(), 'quality' => $Media->quality(), 'sampling_rate' => $Media->samplingRate(), 'bit_rate' => $Media->bitRate()); } elseif ($Media->name === 'Image') { $data[2] = array('width' => $Media->width(), 'height' => $Media->height(), 'ratio' => $Media->ratio(), 'quality' => $Media->quality(), 'megapixel' => $Media->megapixel()); } elseif ($Media->name === 'Text') { $data[2] = array('characters' => $Media->characters(), 'syllables' => $Media->syllables(), 'sentences' => $Media->sentences(), 'words' => $Media->words(), 'flesch_score' => $Media->fleschScore(), 'lexical_density' => $Media->lexicalDensity()); } elseif ($Media->name === 'Video') { $data[2] = array('title' => $Media->title(), 'year' => $Media->year(), 'length' => $Media->duration(), 'width' => $Media->width(), 'height' => $Media->height(), 'ratio' => $Media->ratio(), 'quality' => $Media->quality(), 'bit_rate' => $Media->bitRate()); } else { $data[2] = array(); } } for ($i = $level, $result = array(); $i > 0; $i--) { $result = array_merge($result, $data[$i]); } $this->__cached[$Model->alias][$checksum] = $data; return Set::filter($result); }
/** * Gets the MIME type of the embedded or inline image * @param string File extension * @access public * @return string MIME type of ext * @static */ public static function _mime_types($ext = '') { $mimeType = MimeType::getMimeType($ext); return ($mimeType === null) ? 'application/octet-stream' : $mimeType; }
public function allow() { $args = func_get_args(); for ($a = 0, $len = count($args); $a < $len; $a++) { $extension = Sanitize::variable($args[$a]); if (!in_array($extension, $this->allowedExtensions)) { $this->allowedExtensions[] = $extension; $mimeTypes = MimeType::get($extension); foreach ($mimeTypes as $value) { $value = Sanitize::variable($value, "./-"); if (!in_array($value, $this->allowedMimes)) { $this->allowedMimes[] = $value; } } } } }
public function render($options = array()) { $this->save_session(); if ($this->render_called === false) { $this->view = new View($this->request_uri, $this->params, $this->view_params); $this->view->controller = $this->controller; // Figure out the template to use: if (!empty($options["action"]) && strpos("/", $options["action"])) { $this->view->template = $options["action"]; } else { if (!empty($options["action"])) { $this->view->template = $this->params["controller"] . "/" . $options["action"]; } } if (!empty($options["template"])) { $parts = explode("/", $options["template"]); if (count($parts) === 0) { $this->view->template = $this->params["controller"] . "/" . $options["template"]; } } if (!empty($options["ext"])) { $this->view->ext = $options["ext"]; } if (!empty($options["format"])) { $this->format = $options["format"]; } // Figure out the layout to use: if (!empty($options["layout"])) { $this->view->layout = "layouts/" . $options["layout"]; } $this->view->content_type = MimeType::lookup_by_extension($this->format); $this->view->format = MimeType::extension_by_mime_type($this->view->content_type); $this->render_called = true; $this->view->render(); } }
/** * 获取内容后缀 */ public function getContentFormat() { if (!$this->contentFormat) { $this->contentFormat = MimeType::getSuffix($this->contentType); } return $this->contentFormat; }
/** * Guesses the MIME type of the file * * Empty results are currently not handled: * application/x-empty * application/x-not-regular-file * * @param string $file * @param options $options Valid options are: * - `'paranoid'` If set to true only then content for the file is used for detection * - `'properties'` Used for simplification, defaults to false * - `'experimental'` Used for simplification, defaults to false * @return mixed string with MIME type on success * @access public */ function guessType($file, $options = array()) { $_this =& MimeType::getInstance(); $defaults = array('paranoid' => false, 'properties' => false, 'experimental' => true); extract($options + $defaults); $magicMatch = $globMatch = array(); if (!$paranoid) { if (is_a($_this->__glob, 'MimeGlob')) { $globMatch = $_this->__glob->analyze($file); } if (count($globMatch) === 1) { return MimeType::simplify(array_shift($globMatch), $properties, $experimental); } } if (!is_readable($file)) { return null; } if (is_a($_this->__magic, 'finfo')) { $magicMatch = $_this->__magic->file($file); } elseif ($_this->__magic === 'mime_magic') { $magicMatch = mime_content_type($file); } elseif (is_a($_this->__magic, 'MimeMagic')) { $magicMatch = $_this->__magic->analyze($file); } $magicMatch = empty($magicMatch) ? array() : array($magicMatch); if (empty($magicMatch)) { $File =& new File($file); if (preg_match('/[\\t\\n\\r]+/', $File->read(32))) { return 'text/plain'; } return 'application/octet-stream'; } if (count($magicMatch) === 1) { return MimeType::simplify(array_shift($magicMatch), $properties, $experimental); } if ($globMatch && $magicMatch) { $combinedMatch = array_intersect($globMatch, $magicMatch); if (count($combinedMatch) === 1) { return MimeType::simplify(array_shift($combinedMatch), $properties, $experimental); } } return null; }
protected function handleStatic($path, $currentInfo) { $mimetype = MimeType::getMimeType($path); header('Content-Type: ' . $mimetype); readfile($currentInfo); }
/** * Gather/Return information about a resource * * @param mixed $resource Path to file in local FS, URL or file-upload array * @param string $what scheme, host, port, file, MIME type, size, permission, * dirname, basename, filename, extension or type * @return mixed */ function info(&$Model, $resource, $what = null) { extract($this->settings[$Model->alias], EXTR_SKIP); $defaultResource = array('scheme' => null, 'host' => null, 'port' => null, 'file' => null, 'mimeType' => null, 'size' => null, 'pixels' => null, 'permisssion' => null, 'dirname' => null, 'basename' => null, 'filename' => null, 'extension' => null, 'type' => null); /* Currently HTTP is supported only */ if (TransferValidation::url($resource, array('scheme' => 'http'))) { $resource = array_merge($defaultResource, pathinfo(parse_url($resource, PHP_URL_PATH)), array('scheme' => parse_url($resource, PHP_URL_SCHEME), 'host' => parse_url($resource, PHP_URL_HOST), 'port' => parse_url($resource, PHP_URL_PORT), 'file' => $resource, 'type' => 'http-url-remote')); if (!class_exists('HttpSocket')) { App::import('Core', 'HttpSocket'); } $Socket =& new HttpSocket(array('timeout' => 5)); $Socket->request(array('method' => 'HEAD', 'uri' => $resource['file'])); if (empty($Socket->error) && $Socket->response['status']['code'] == 200) { $resource = array_merge($resource, array('size' => $Socket->response['header']['Content-Length'], 'mimeType' => $trustClient ? $Socket->response['header']['Content-Type'] : null, 'permission' => '0004')); } } elseif (MediaValidation::file($resource, false)) { $resource = array_merge($defaultResource, pathinfo($resource), array('file' => $resource, 'host' => 'localhost', 'mimeType' => MimeType::guessType($resource, array('paranoid' => !$trustClient)))); if (TransferValidation::uploadedFile($resource['file'])) { $resource['type'] = 'uploaded-file-local'; } else { $resource['type'] = 'file-local'; } if (is_readable($resource['file'])) { /* * Because there is not better way to determine if resource is an image * first, we suppress a warning that would be thrown here otherwise. */ list($width, $height) = @getimagesize($resource['file']); $resource = array_merge($resource, array('size' => filesize($resource['file']), 'permission' => substr(sprintf('%o', fileperms($resource['file'])), -4), 'pixels' => $width * $height)); } } elseif (TransferValidation::fileUpload($resource)) { $resource = array_merge($defaultResource, pathinfo($resource['name']), array('file' => $resource['name'], 'host' => env('REMOTE_ADDR'), 'size' => $resource['size'], 'mimeType' => $trustClient ? $resource['type'] : null, 'permission' => '0004', 'type' => 'file-upload-remote')); } else { return null; } if (!isset($resource['filename'])) { /* PHP < 5.2.0 */ $length = isset($resource['extension']) ? strlen($resource['extension']) + 1 : 0; $resource['filename'] = substr($resource['basename'], 0, -$length); } if (is_null($what)) { return $resource; } elseif (array_key_exists($what, $resource)) { return $resource[$what]; } return null; }
protected function _dispatch() { file_put_contents('/tmp/smtp.log', "\ndispatched started for filename: {$this->messageFilename}", FILE_APPEND); $contents = file($this->messageFilename); file_put_contents('/tmp/smtp.log', "\ncontents: " . print_r($contents, true), FILE_APPEND); $boundary = null; $boundaryLen = 0; $boundaryStarted = false; $data = array(); $tmpData = array(); $headers = array('subject' => '', 'from' => '', 'to' => '', 'date' => '', 'messageId' => ''); $contentsCtr = count($contents); $subjectStarted = false; for ($i = 0; $i < $contentsCtr; $i++) { $line = trim($contents[$i]); $nextI = $i + 1; if (isset($contents[$nextI]) && preg_match('/^Content-(.*):/i', $line) && ($contents[$nextI][0] == "\t" || $contents[$nextI][0] == ' ')) { $contents[$nextI][0] = ' '; $line .= $contents[$nextI]; $i = $nextI; } if (!$boundaryStarted) { if ($boundary !== null && '--' . $boundary == substr($line, 0, $boundaryLen + 2)) { $boundaryStarted = true; continue; } if (preg_match('/^Subject:(.*)/i', $line, $matches)) { $headers['subject'] = ltrim($matches[1]); $subjectStarted = true; } else { if (preg_match('/^From:(.*)/i', $line, $matches)) { $headers['from'] = ltrim($matches[1]); } else { if (preg_match('/^To:(.*)/i', $line, $matches)) { $headers['to'] = ltrim($matches[1]); } else { if (preg_match('/^Content-Type:(.*)/i', $line, $matches)) { $contentType = ltrim($matches[1]); if (preg_match('/boundary=(.*)/i', $contentType, $matches)) { $boundary = $matches[1]; if (preg_match('/^"(.*)"/', $boundary, $matches)) { // some boundaries are enclosed in "" $boundary = $matches[1]; } $boundaryLen = strlen($boundary); } } else { if (preg_match('/^Date:(.*)/i', $line, $matches)) { $headers['date'] = ltrim($matches[1]); } else { if (preg_match('/^Message-Id:(.*)/i', $line, $matches)) { $headers['messageId'] = ltrim($matches[1]); } else { if (preg_match('/^X-Mailer:(.*)/i', $line, $matches)) { $headers['mailer'] = ltrim($matches[1]); } else { if ($subjectStarted) { $tmpData[] = $line; } } } } } } } } } else { if (substr($line, 0, $boundaryLen + 2) == '--' . $boundary) { if (isset($tmpData[0])) { $data[] = $tmpData; $tmpData = array(); } } else { $tmpData[] = $line; } } } if (isset($tmpData[0])) { $data[] = $tmpData; $tmpData = array(); } $dataContents = array(); $i = 0; foreach ($data as $lines) { $content = ''; $contentTypes = array(); foreach ($lines as $line) { if (preg_match('/^Content-(.*):(.*)/i', $line, $matches)) { $contentTypes['content-' . strtolower($matches[1])] = ltrim($matches[2]); } else { if ($line == '') { $lineStart = true; $lineEnd = true; } else { $content .= $line; } } } if (isset($contentTypes['content-disposition']) && (isset($contentTypes['content-transfer-encoding']) && strtolower($contentTypes['content-transfer-encoding']) == 'base64')) { // temporarily accept base64 encoding that serves as an attachment $tmpData[] = array('contentTypes' => $contentTypes, 'content' => $content); continue; } $dataContents[] = array('contentTypes' => $contentTypes, 'content' => $content); } if (isset($tmpData[0])) { $dataContents = $tmpData; } $recipients = array(); $addresses = explode(',', $headers['to']); $db = Zend_Registry::get('dbAdapter'); foreach ($addresses as $address) { if (preg_match('/<(.*)>/', $address, $matches)) { $address = $matches[1]; } $x = explode('@', $address); $username = $x[0]; $domain = $x[1]; $sqlSelect = $db->select()->from('patient', 'person_id')->where('record_number = ?', $username); $personId = 0; if ($row = $db->fetchRow($sqlSelect)) { $personId = $row['person_id']; } $recipients[] = array('personId' => $personId, 'address' => $address, 'username' => $username, 'domain' => $domain); } file_put_contents('/tmp/smtp.log', "\ndata contents: " . print_r($dataContents, true), FILE_APPEND); foreach ($dataContents as $content) { $contentTypes = $content['contentTypes']; $filename = null; // email has an attachments if (isset($contentTypes['content-disposition']) && (isset($contentTypes['content-transfer-encoding']) && strtolower($contentTypes['content-transfer-encoding']) == 'base64')) { // temporarily accept base64 encoding that serves as an attachment $contentType = $contentTypes['content-type']; // image/jpeg; name="sample-signature.jpeg" $types = explode(';', $contentType); $mimeType = array_shift($types); foreach ($types as $type) { $type = ltrim($type); if (preg_match('/^name="(.*)"/', $type, $matches)) { $filename = '/tmp/' . $matches[1]; break; } } if ($filename === null) { // try to create a random filename with specific extension based on mime type $extension = MimeType::extension($mimeType); $tmpFile = tempnam('/tmp', 'ch30_attach_'); $filename = $tmpFile . '.' . $extension; //rename($tmpFile,$filename); unlink($tmpFile); } $content['content'] = base64_decode($content['content']); // decode the base64 encoded file } foreach ($recipients as $recipient) { $personId = $recipient['personId']; $messagingId = WebVista_Model_ORM::nextSequenceId(); $messaging = array(); $messaging['note'] = 'Email message: ' . $content['content']; $attachmentId = 0; if ($filename !== null) { $attachmentId = WebVista_Model_ORM::nextSequenceId(); $attachment = array(); $attachment['attachmentId'] = $attachmentId; $attachment['attachmentReferenceId'] = md5($headers['messageId']); $attachment['name'] = basename($filename); $attachment['dateTime'] = date('Y-m-d H:i:s', strtotime($headers['date'])); $attachment['mimeType'] = $mimeType; $attachment['md5sum'] = md5($content['content']); $db->insert('attachments', $attachment); $audit = array(); $audit['objectClass'] = 'Attachment'; $audit['objectId'] = $attachment['attachmentId']; $audit['auditValues'] = $attachment; Audit::persistManualAuditArray($audit); $attachmentBlob = array(); $attachmentBlob['attachmentId'] = $attachment['attachmentId']; $attachmentBlob['data'] = $content['content']; $db->insert('attachmentBlobs', $attachmentBlob); $messaging['note'] = 'Scanned document for ' . $recipient['address']; } $messaging['messagingId'] = $messagingId; $messaging['objectType'] = Messaging::TYPE_INBOUND_FAX; $messaging['status'] = 'Fax/Email Received'; $messaging['dateStatus'] = date('Y-m-d H:i:s'); $db->insert('messaging', $messaging); $messagingInboundFax = array(); $messagingInboundFax['messagingId'] = $messaging['messagingId']; $messagingInboundFax['personId'] = $personId; $messagingInboundFax['mrn'] = $recipient['username']; $messagingInboundFax['subject'] = $headers['subject']; $messagingInboundFax['from'] = $headers['from']; $messagingInboundFax['to'] = $recipient['address']; $messagingInboundFax['messageId'] = $headers['messageId']; $messagingInboundFax['attachmentId'] = $attachmentId; $db->insert('messagingInboundFaxes', $messagingInboundFax); $audit = array(); $audit['objectClass'] = 'MessagingInboundFax'; $audit['objectId'] = $messagingInboundFax['messagingId']; $audit['auditValues'] = $messagingInboundFax; Audit::persistManualAuditArray($audit); } } unlink($this->messageFilename); return $this; }
function testManipulation() { $Medium = new TestImagickImageMedium($this->TestData->getFile('image-jpg.jpg')); $Medium->fit(10, 10); $this->assertTrue($Medium->width() <= 10); $this->assertTrue($Medium->height() <= 10); $Medium = new TestImagickImageMedium($this->TestData->getFile('image-jpg.jpg')); $Medium = $Medium->convert('image/png'); if ($this->assertIsA($Medium, 'ImageMedium')) { $result = $Medium->mimeType; $this->assertEqual($result, 'image/png'); } $Medium = new TestImagickImageMedium($this->TestData->getFile('image-jpg.jpg')); $Medium = $Medium->convert('image/png'); if ($this->assertIsA($Medium, 'ImageMedium')) { $tmpFile = TMP . uniqid('test_suite_'); $tmpFile = $Medium->store($tmpFile); $this->assertEqual(MimeType::guessType($tmpFile), 'image/png'); unlink($tmpFile); } }
static function is_type($type, $name) { $_this = new MimeType(); $main_mimetype = $_this->main_mimetype_of($name); return $type == $main_mimetype; }