/** * Test all methods * * @param string $zipClass * @covers ::<public> */ public function testZipArchive($zipClass = 'ZipArchive') { // Preparation $existingFile = __DIR__ . '/../_files/documents/sheet.xls'; $zipFile = __DIR__ . '/../_files/documents/ziptest.zip'; $destination1 = __DIR__ . '/../_files/documents/extract1'; $destination2 = __DIR__ . '/../_files/documents/extract2'; @mkdir($destination1); @mkdir($destination2); Settings::setZipClass($zipClass); $object = new ZipArchive(); $object->open($zipFile, ZipArchive::CREATE); $object->addFile($existingFile, 'xls/new.xls'); $object->addFromString('content/string.txt', 'Test'); $object->close(); $object->open($zipFile); // Run tests $this->assertEquals(0, $object->locateName('xls/new.xls')); $this->assertFalse($object->locateName('blablabla')); $this->assertEquals('Test', $object->getFromName('content/string.txt')); $this->assertEquals('Test', $object->getFromName('/content/string.txt')); $this->assertFalse($object->getNameIndex(-1)); $this->assertEquals('content/string.txt', $object->getNameIndex(1)); $this->assertFalse($object->extractTo('blablabla')); $this->assertTrue($object->extractTo($destination1)); $this->assertTrue($object->extractTo($destination2, 'xls/new.xls')); $this->assertFalse($object->extractTo($destination2, 'blablabla')); // Cleanup $this->deleteDir($destination1); $this->deleteDir($destination2); @unlink($zipFile); }
/** * Extract metadata from document * * @param \ZipArchive $package ZipArchive AbstractOpenXML package * @return array Key-value pairs containing document meta data */ protected function extractMetaData(\ZipArchive $package) { // Data holders $coreProperties = array(); // Prevent php from loading remote resources $loadEntities = libxml_disable_entity_loader(true); // Read relations and search for core properties $relations = simplexml_load_string($package->getFromName("_rels/.rels")); // Restore entity loader state libxml_disable_entity_loader($loadEntities); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == self::SCHEMA_COREPROPERTIES) { // Found core properties! Read in contents... $contents = simplexml_load_string($package->getFromName(dirname($rel["Target"]) . "/" . basename($rel["Target"]))); foreach ($contents->children(self::SCHEMA_DUBLINCORE) as $child) { $coreProperties[$child->getName()] = (string) $child; } foreach ($contents->children(self::SCHEMA_COREPROPERTIES) as $child) { $coreProperties[$child->getName()] = (string) $child; } foreach ($contents->children(self::SCHEMA_DUBLINCORETERMS) as $child) { $coreProperties[$child->getName()] = (string) $child; } } } return $coreProperties; }
/** * Object constructor * * @param string $fileName * @param boolean $storeContent */ private function __construct($fileName, $storeContent) { // Document data holders $documentBody = array(); $coreProperties = array(); // Open OpenXML package $package = new ZipArchive(); $package->open($fileName); // Read relations and search for officeDocument $relations = simplexml_load_string($package->getFromName('_rels/.rels')); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) { // Found office document! Read in contents... $contents = simplexml_load_string($package->getFromName($this->absoluteZipPath(dirname($rel['Target']) . '/' . basename($rel['Target'])))); $contents->registerXPathNamespace('w', Zend_Search_Lucene_Document_Docx::SCHEMA_WORDPROCESSINGML); $paragraphs = $contents->xpath('//w:body/w:p'); foreach ($paragraphs as $paragraph) { $runs = $paragraph->xpath('.//w:r/*[name() = "w:t" or name() = "w:br"]'); if ($runs === false) { // Paragraph doesn't contain any text or breaks continue; } foreach ($runs as $run) { if ($run->getName() == 'br') { // Break element $documentBody[] = ' '; } else { $documentBody[] = (string) $run; } } // Add space after each paragraph. So they are not bound together. $documentBody[] = ' '; } break; } } // Read core properties $coreProperties = $this->extractMetaData($package); // Close file $package->close(); // Store filename $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName, 'UTF-8')); // Store contents if ($storeContent) { $this->addField(Zend_Search_Lucene_Field::Text('body', implode('', $documentBody), 'UTF-8')); } else { $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode('', $documentBody), 'UTF-8')); } // Store meta data properties foreach ($coreProperties as $key => $value) { $this->addField(Zend_Search_Lucene_Field::Text($key, $value, 'UTF-8')); } // Store title (if not present in meta data) if (!isset($coreProperties['title'])) { $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName, 'UTF-8')); } }
/** * Create a new Template Object * * @param string $strFilename */ public function __construct($strFilename) { $path = dirname($strFilename); $this->_tempFileName = $path . DIRECTORY_SEPARATOR . time() . '.docx'; copy($strFilename, $this->_tempFileName); // Copy the source File to the temp File $this->_objZip = new ZipArchive(); $this->_objZip->open($this->_tempFileName); $this->_documentXML = $this->_objZip->getFromName('word/document.xml'); }
protected function retrieveResponse() { $response = $this->initResponse(); if (strpos($this->fileStem, '.zip') !== false) { if (!class_exists('ZipArchive')) { throw new KurogoException("class ZipArchive (php-zip) not available"); } $response->setContext('zipped', true); $zip = new ZipArchive(); if (strpos($this->fileStem, 'http') === 0 || strpos($this->fileStem, 'ftp') === 0) { $tmpFile = Kurogo::tempFile(); copy($this->fileStem, $tmpFile); $zip->open($tmpFile); } else { $zip->open($this->fileStem); } // locate valid shapefile components $shapeNames = array(); for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match('/(.+)\\.(shp|dbf|prj)$/', $zip->getNameIndex($i), $matches)) { $shapeName = $matches[1]; $extension = $matches[2]; if (!isset($shapeNames[$shapeName])) { $shapeNames[$shapeName] = array(); } $shapeNames[$shapeName][] = $extension; } } $responseData = array(); foreach ($shapeNames as $shapeName => $extensions) { if (in_array('dbf', $extensions) && in_array('shp', $extensions)) { $fileData = array('dbf' => $zip->getFromName("{$shapeName}.dbf"), 'shp' => $zip->getFromName("{$shapeName}.shp")); if (in_array('prj', $extensions)) { $prjData = $zip->getFromName("{$shapeName}.prj"); $fileData['projection'] = new MapProjection($prjData); } $responseData[$shapeName] = $fileData; } } $response->setResponse($responseData); } elseif (realpath_exists("{$this->fileStem}.shp") && realpath_exists("{$this->fileStem}.dbf")) { $response->setContext('zipped', false); $response->setContext('shp', "{$this->fileStem}.shp"); $response->setContext('dbf', "{$this->fileStem}.dbf"); if (realpath_exists("{$this->fileStem}.prj")) { $prjData = file_get_contents("{$this->fileStem}.prj"); $response->setContext('projection', new MapProjection($prjData)); } } else { throw new KurogoDataException("Cannot find {$this->fileStem}"); } return $response; }
public function parseFile($filename) { if (strpos($filename, '.zip') !== false) { if (!class_exists('ZipArchive')) { throw new KurogoException("class ZipArchive (php-zip) not available"); } $zip = new ZipArchive(); $zip->open($filename); // locate valid shapefile components $shapeNames = array(); for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match('/(.+)\\.(shp|dbf|prj)$/', $zip->getNameIndex($i), $matches)) { $shapeName = $matches[1]; $extension = $matches[2]; if (!isset($shapeNames[$shapeName])) { $shapeNames[$shapeName] = array(); } $shapeNames[$shapeName][] = $extension; } } $this->dbfParser = new DBase3FileParser(); foreach ($shapeNames as $shapeName => $extensions) { if (in_array('dbf', $extensions) && in_array('shp', $extensions)) { $this->setContents($zip->getFromName("{$shapeName}.shp")); $contents = $zip->getFromName("{$shapeName}.dbf"); if (!$contents) { throw new KurogoDataException("could not read {$shapeName}.dbf"); } $this->dbfParser->setContents($zip->getFromName("{$shapeName}.dbf")); $this->dbfParser->setup(); if (in_array('prj', $extensions)) { $prjData = $zip->getFromName("{$shapeName}.prj"); $this->mapProjection = new MapProjection($prjData); } $this->doParse(); } } } elseif (realpath_exists("{$filename}.shp") && realpath_exists("{$filename}.dbf")) { $this->setFilename("{$filename}.shp"); $this->dbfParser = new DBase3FileParser(); $this->dbfParser->setFilename("{$filename}.dbf"); $this->dbfParser->setup(); $prjFile = $filename . '.prj'; if (realpath_exists($prjFile)) { $prjData = file_get_contents($prjFile); $this->mapProjection = new MapProjection($prjData); } $this->doParse(); } else { throw new KurogoDataException("Cannot find {$filename}"); } return $this->features; }
/** * Create a new Template Object * * @param string $strFilename */ public function __construct($strFilename) { $this->_tempFileName = tempnam(sys_get_temp_dir(), ''); if ($this->_tempFileName !== false) { // Copy the source File to the temp File if (!copy($strFilename, $this->_tempFileName)) { throw new PHPWord_Exception('Could not copy the template from ' . $strFilename . ' to ' . $this->_tempFileName . '.'); } $this->_objZip = new ZipArchive(); $this->_objZip->open($this->_tempFileName); $this->_documentXML = $this->_objZip->getFromName('word/document.xml'); } else { throw new PHPWord_Exception('Could not create temporary file with unique name in the default temporary directory.'); } }
/** * @return string */ public function getMimeType() { if (!CommonFile::fileExists($this->getZipFileOut())) { throw new \Exception('File ' . $this->getZipFileOut() . ' does not exist'); } $oArchive = new \ZipArchive(); $oArchive->open($this->getZipFileOut()); if (!function_exists('getimagesizefromstring')) { $uri = 'data://application/octet-stream;base64,' . base64_encode($oArchive->getFromName($this->getZipFileIn())); $image = getimagesize($uri); } else { $image = getimagesizefromstring($oArchive->getFromName($this->getZipFileIn())); } return image_type_to_mime_type($image[2]); }
/** * Read Shape Drawing * * @param \DOMElement $oNodeFrame */ protected function loadShapeDrawing(\DOMElement $oNodeFrame) { // Core $oShape = new Gd(); $oShape->getShadow()->setVisible(false); $oNodeImage = $this->oXMLReader->getElement('draw:image', $oNodeFrame); if ($oNodeImage) { if ($oNodeImage->hasAttribute('xlink:href')) { $sFilename = $oNodeImage->getAttribute('xlink:href'); // svm = StarView Metafile if (pathinfo($sFilename, PATHINFO_EXTENSION) == 'svm') { return; } $imageFile = $this->oZip->getFromName($sFilename); if (!empty($imageFile)) { $oShape->setImageResource(imagecreatefromstring($imageFile)); } } } $oShape->setName($oNodeFrame->hasAttribute('draw:name') ? $oNodeFrame->getAttribute('draw:name') : ''); $oShape->setDescription($oNodeFrame->hasAttribute('draw:name') ? $oNodeFrame->getAttribute('draw:name') : ''); $oShape->setResizeProportional(false); $oShape->setWidth($oNodeFrame->hasAttribute('svg:width') ? (int) round(CommonDrawing::centimetersToPixels(substr($oNodeFrame->getAttribute('svg:width'), 0, -2))) : ''); $oShape->setHeight($oNodeFrame->hasAttribute('svg:height') ? (int) round(CommonDrawing::centimetersToPixels(substr($oNodeFrame->getAttribute('svg:height'), 0, -2))) : ''); $oShape->setResizeProportional(true); $oShape->setOffsetX($oNodeFrame->hasAttribute('svg:x') ? (int) round(CommonDrawing::centimetersToPixels(substr($oNodeFrame->getAttribute('svg:x'), 0, -2))) : ''); $oShape->setOffsetY($oNodeFrame->hasAttribute('svg:y') ? (int) round(CommonDrawing::centimetersToPixels(substr($oNodeFrame->getAttribute('svg:y'), 0, -2))) : ''); if ($oNodeFrame->hasAttribute('draw:style-name')) { $keyStyle = $oNodeFrame->getAttribute('draw:style-name'); if (isset($this->arrayStyles[$keyStyle])) { $oShape->setShadow($this->arrayStyles[$keyStyle]['shadow']); } } $this->oPhpPresentation->getActiveSlide()->addShape($oShape); }
/** * Create a new Template Object * * @param string $strFilename */ public function __construct($strFilename) { $path = dirname($strFilename); $i = 0; do { $this->_tempFileName = $path . "/" . time() . $i++ . '.docx'; } while (file_exists($this->_tempFileName)); copy($strFilename, $this->_tempFileName); // Copy the source File to the temp File $this->_objZip = new ZipArchive(); $this->_objZip->open($this->_tempFileName); $this->_documentXML = $this->_objZip->getFromName('word/document.xml'); /**FIX: 2011-06-11 Anthon S Litvinenko <*****@*****.**> Replace tags between Values names */ $this->_documentXML = preg_replace_callback('|\\$\\{[^}]*}|', create_function('$matches', 'return strip_tags($matches[0]);'), $this->_documentXML); }
function reload($user) { $lastfacts = DB::get()->val("SELECT value FROM options WHERE name='facts' and grouping = 'misc'"); if ($lastfacts < mktime(0, 0, 0)) { DB::get()->query("SELECT * FROM drawers WHERE indexed = 'facts'"); $users = DB::get()->col("SELECT id FROM users"); $zip = new ZipArchive(); if ($zip->open(dirname(__FILE__) . '/facts.zip') === TRUE) { $facts = explode("\n", $zip->getFromName('facts.txt')); $zip->close(); $fact = '<div class="factoidtext">' . $facts[date('z')] . '</div>'; } else { $content = file_get_contents('http://www.mentalfloss.com/amazingfactgenerator/?p=' . date('z')); $content = SimpleHTML::str_get_html($content); $fact = '<div class="factoidtext">FAIL:' . $content->find('.amazing_fact_body p', 0)->innertext . '</div>'; } $msg = '<a href="#" class="close" onclick="return closedrawer({$drawer_id});">close this drawer</a>' . $fact; foreach ($users as $user_id) { DB::get()->query("INSERT INTO drawers (user_id, message, indexed, cssclass) VALUES (:user_id, :msg, 'facts', 'factoid');", array('user_id' => $user_id, 'msg' => $msg)); } DB::get()->query("DELETE FROM options WHERE name = 'facts' AND grouping = 'misc'"); DB::get()->query("INSERT INTO options (name, grouping, value) VALUES ('facts', 'misc', :value);", array('value' => mktime(0, 0, 0))); } return $user; }
/** * Retrieves the "content.xml" from the ODS file * * @return string The XML from "content.xml" */ public function getContentXml() { if (!$this->odsResource instanceof \ZipArchive) { throw new \Exception('No ODS file opened!'); } return $this->odsResource->getFromName('content.xml'); }
public function docxTemplate($filepath = false, $templates = false, $output = false) { if ($filepath === false || $templates === false || $output === false) { return false; } if (file_exists($output)) { unlink($output); } copy($filepath, $output); if (!file_exists($output)) { die('File not found.'); } $zip = new ZipArchive(); if (!$zip->open($output)) { die('File not open.'); } $documentXml = $zip->getFromName('word/document.xml'); $rekeys = array_keys($templates); for ($i = 0; $i < count($templates); $i++) { $reg = ''; $reg .= substr($rekeys[$i], 0, 1); for ($i2 = 1; $i2 < strlen($rekeys[$i]); $i2++) { $reg .= '(<.*?>)*+' . substr($rekeys[$i], $i2, 1); } $reg = '#' . str_replace(array('#', '{', '[', ']', '}'), array('#', '{', '[', ']', '}'), $reg) . '#'; $documentXml = preg_replace($reg, $templates[$rekeys[$i]], $documentXml); print '->' . $reg . '<br/>'; } $zip->deleteName('word/document.xml'); $zip->addFromString('word/document.xml', $documentXml); $zip->close(); }
/** * @return \PhpOffice\Common\Adapter\Zip\ZipInterface */ public function render() { for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { $shape = $this->getDrawingHashTable()->getByIndex($i); if ($shape instanceof Drawing) { $imagePath = $shape->getPath(); if (strpos($imagePath, 'zip://') !== false) { $imagePath = substr($imagePath, 6); $imagePathSplitted = explode('#', $imagePath); $imageZip = new \ZipArchive(); $imageZip->open($imagePathSplitted[0]); $imageContents = $imageZip->getFromName($imagePathSplitted[1]); $imageZip->close(); unset($imageZip); } else { $imageContents = file_get_contents($imagePath); } $this->getZip()->addFromString('ppt/media/' . str_replace(' ', '_', $shape->getIndexedFilename()), $imageContents); } elseif ($shape instanceof MemoryDrawing) { ob_start(); call_user_func($shape->getRenderingFunction(), $shape->getImageResource()); $imageContents = ob_get_contents(); ob_end_clean(); $this->getZip()->addFromString('ppt/media/' . str_replace(' ', '_', $shape->getIndexedFilename()), $imageContents); } } return $this->getZip(); }
/** * Extract metadata from document * * @param ZipArchive $package ZipArchive OpenXML package * @return array Key-value pairs containing document meta data */ protected function extractMetaData(ZipArchive $package) { // Data holders $coreProperties = array(); // Read relations and search for core properties $relations = simplexml_load_string($package->getFromName("_rels/.rels")); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) { // Found core properties! Read in contents... $contents = simplexml_load_string( $package->getFromName(dirname($rel["Target"]) . "/" . basename($rel["Target"])) ); foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORE) as $child) { $coreProperties[$child->getName()] = (string)$child; } foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_COREPROPERTIES) as $child) { $coreProperties[$child->getName()] = (string)$child; } foreach ($contents->children(Zend_Search_Lucene_Document_OpenXml::SCHEMA_DUBLINCORETERMS) as $child) { $coreProperties[$child->getName()] = (string)$child; } } } return $coreProperties; }
/** * Give it a schema, get back a path(s) that points to a resource * * @param string $schema * @param string $id * @return string */ protected function getTargetPath($schema, $id = '') { $path = ''; // The subfolder name "_rels", the file extension ".rels" are // reserved names in an OPC package if (empty($id)) { $path_to_rel_doc = '_rels/.rels'; } else { $path_to_rel_doc = 'word/_rels/document.xml.rels'; } $relations = simplexml_load_string($this->zip->getFromName($path_to_rel_doc)); foreach ($relations->Relationship as $rel) { if ($rel['Type'] == $schema) { switch ($id) { // must be cast as a string to avoid returning SimpleXml Object. case 'footnotes': $path = 'word/' . (string) $rel['Target']; break; case 'endnotes': $path = 'word/' . (string) $rel['Target']; break; case 'hyperlink': $path["{$rel['Id']}"] = (string) $rel['Target']; break; default: $path = (string) $rel['Target']; break; } } } return $path; }
/** * Upload a new module from ZIP archive * * @param file $module_archive the module archive file (.zip) * @return string the module name uploaded */ public static function uploadModule($module_archive, $scope = null) { $zip = new ZipArchive(); if ($zip->open($module_archive['tmp_name']) === false) { throw new Exception('Can not open module archive ' . $module_archive['name']); } else { $module_name = preg_replace('/(\\w*)\\.zip$/i', '$1', $module_archive['name']); $module_info = $zip->getFromName('module'); $module_details = explode('|', $zip->getFromName('class')); list($module_classname, $module_version) = $module_details; $module_basepath = THEBUGGENIE_MODULES_PATH . $module_name; if (($module_info & $module_details) === false) { throw new Exception('Invalid module archive ' . $module_archive['name']); } $modules = TBGContext::getModules(); foreach ($modules as $module) { if ($module->getName() == $module_name || $module->getClassname() == $module_classname) { throw new Exception('Conflict with the module ' . $module->getLongName() . ' that is already installed with version ' . $module->getVersion()); } } if (is_dir($module_basepath) === false) { if (mkdir($module_basepath) === false) { TBGLogging::log('Try to upload module archive ' . $module_archive['name'] . ': unable to create module directory ' . $module_basepath); throw new Exception('Unable to create module directory ' . $module_basepath); } if ($zip->extractTo($module_basepath) === false) { TBGLogging::log('Try to upload module archive ' . $module_archive['name'] . ': unable to extract archive into ' . $module_basepath); throw new Exception('Unable to extract module into ' . $module_basepath); } } return $module_name; } return null; }
protected function getDocumentContents() { if (!isset($this->contents)) { $this->contents = $this->joinVariables($this->zip->getFromName('word/document.xml')); } return $this->contents; }
public function parse($ipaFile, $infoFile = self::INFO_PLIST) { $zipObj = new ZipArchive(); if ($zipObj->open($ipaFile) !== true) { throw new PListException("unable to open {$ipaFile} file!"); } //scan plist file $plistFile = null; for ($i = 0; $i < $zipObj->numFiles; $i++) { $name = $zipObj->getNameIndex($i); if (preg_match('/Payload\\/(.+)?\\.app\\/' . preg_quote($infoFile) . '$/i', $name)) { $plistFile = $name; break; } } //parse plist file if (!$plistFile) { throw new PListException("unable to parse plist file!"); } //deal in memory $plistHandle = fopen('php://memory', 'wb'); fwrite($plistHandle, $zipObj->getFromName($plistFile)); rewind($plistHandle); $zipObj->close(); $plist = new CFPropertyList($plistHandle, CFPropertyList::FORMAT_AUTO); $this->plistContent = $plist->toArray(); return true; }
/** * Returns the entry contents using its name. * * @param string $name The name of the entry. * * @return mixed The contents of the entry on success or false on failure. * @throws Exception */ public function getFileContents($name) { if (!$this->open) { throw new \Exception('No archive has been opened'); } return $this->zip->getFromName($name); }
public static function doImport() { $db = new DatabaseManager(); RTBAddonManager::verifyTable($db); $dir = realpath(dirname(__DIR__) . '/../local/rtb/'); $files = scandir($dir); $data = array(); foreach ($files as $file) { if (strpos($file, ".zip") === false) { continue; } //echo($file . "<br />"); $dat = new stdClass(); $dat->filename = $file; $zip = new ZipArchive(); $res = $zip->open($dir . '/' . $file); if ($res === TRUE) { $rtbInfo = $zip->getFromName("rtbInfo.txt"); //echo "<pre>$rtbInfo</pre><hr />"; $lines = explode("\n", $rtbInfo); foreach ($lines as $l) { $words = explode(": ", $l); if (sizeof($words) == 2) { $dat->{$words}[0] = trim($words[1]); } } } $data[] = $dat; $db->query("INSERT INTO `rtb_addons` (`id`, `icon`, `type`, `title`, `filename`, `glass_id`) VALUES (" . "'" . $db->sanitize($dat->id) . "'," . "'" . $db->sanitize($dat->icon) . "'," . "'" . $db->sanitize($dat->type) . "'," . "'" . $db->sanitize($dat->title) . "'," . "'" . $db->sanitize($dat->filename) . "', '')"); echo $db->error(); } //var_dump($data); }
public function extractFile($fileName) { $zip = new ZipArchive(); $zip->open($this->zip); $contentFile = $zip->getFromName($fileName); $zip->close(); return $contentFile; }
/** * Object constructor * * @param string $fileName * @param boolean $storeContent */ private function __construct($fileName, $storeContent) { // Document data holders $documentBody = array(); $coreProperties = array(); // Open OpenXML package $package = new ZipArchive(); $package->open($fileName); // Read relations and search for officeDocument $relations = simplexml_load_string($package->getFromName("_rels/.rels")); foreach ($relations->Relationship as $rel) { if ($rel["Type"] == Zend_Search_Lucene_Document_OpenXml::SCHEMA_OFFICEDOCUMENT) { // Found office document! Read in contents... $contents = simplexml_load_string($package->getFromName($this->absoluteZipPath(dirname($rel["Target"]) . "/" . basename($rel["Target"])))); $contents->registerXPathNamespace("w", Zend_Search_Lucene_Document_Docx::SCHEMA_WORDPROCESSINGML); $paragraphs = $contents->xpath('//w:body/w:p'); foreach ($paragraphs as $paragraph) { $runs = $paragraph->xpath('//w:r/w:t'); foreach ($runs as $run) { $documentBody[] = (string) $run; } } break; } } // Read core properties $coreProperties = $this->extractMetaData($package); // Close file $package->close(); // Store filename $this->addField(Zend_Search_Lucene_Field::Text('filename', $fileName)); // Store contents if ($storeContent) { $this->addField(Zend_Search_Lucene_Field::Text('body', implode(' ', $documentBody))); } else { $this->addField(Zend_Search_Lucene_Field::UnStored('body', implode(' ', $documentBody))); } // Store meta data properties foreach ($coreProperties as $key => $value) { $this->addField(Zend_Search_Lucene_Field::Text($key, $value)); } // Store title (if not present in meta data) if (!isset($coreProperties['title'])) { $this->addField(Zend_Search_Lucene_Field::Text('title', $fileName)); } }
public function loadFromFile($fileName, $publicKey) { $this->archive->open($fileName); $this->metaData = json_decode($this->archive->getFromName('update.json'), true); if (isset($publicKey)) { $this->verifySignature($publicKey); } }
protected function getDocxContents($file) { $zip = new \ZipArchive(); $zip->open($file); $contents = $zip->getFromName('word/document.xml'); $zip->close(); return $contents; }
/** * Imports data into the database based on an uploaded zip file. */ public function import() { JSession::checkToken(); $app = JFactory::getApplication(); // form submit $file = $_FILES['importfile']; $dryrun = JRequest::getBool('dryrun', false); // check if the file does exist if ($file['error'] != 0) { $msg = JText::_('COM_EVENTGALLERY_IMPEX_IMPORT_ERROR_INVALID_FILE'); $app->enqueueMessage($msg, 'error'); return $this->display(); } // try to open the zip archive $zip = new ZipArchive(); if ($zip->open($file['tmp_name']) !== true) { $msg = JText::_('COM_EVENTGALLERY_IMPEX_IMPORT_ERROR_INVALID_ZIP'); $app->enqueueMessage($msg, 'error'); return $this->display(); } $db = JFactory::getDbo(); $tableList = $this->getTables(); $msg = ""; foreach ($tableList as $tableName) { $content = $zip->getFromName($tableName . '.txt'); if ($content === false) { continue; } $data = json_decode($content); if (json_last_error() != 0) { $msg .= JText::sprintf('COM_EVENTGALLERY_IMPEX_IMPORT_ERROR_JSON', $tableName, json_last_error()) . "<br>"; continue; } if ($data == null || count($data) == 0) { $msg .= JText::sprintf('COM_EVENTGALLERY_IMPEX_IMPORT_ERROR_EMPTY', $tableName) . "<br>"; continue; } if ($dryrun) { $msg .= JText::sprintf('COM_EVENTGALLERY_IMPEX_IMPORT_DRYRUN_INFO', count($data), $tableName) . "<br>"; continue; } foreach ($data as $row) { $query = $db->getQuery(true); $query = "replace into " . $db->quoteName($tableName) . " SET "; $values = array(); foreach ($row as $key => $value) { array_push($values, $db->quoteName($key) . '=' . $db->quote($value)); } $query .= implode(',', $values); $db->setQuery($query); $db->execute(); set_time_limit(10); } $msg .= JText::sprintf('COM_EVENTGALLERY_IMPEX_IMPORT_SUCCESS_INFO', count($data), $tableName) . "<br>"; } $app->enqueueMessage($msg); return $this->display(); }
function zipfile_sha256($filename) { $zip = new ZipArchive(); $res = $zip->open($filename); $filename = basename($filename, ".zip"); $sha256_hash = $zip->getFromName($filename . ".sha256"); $zip->close(); return $sha256_hash; }
/** * Get a file from apk Archive by name. * * @param string $name * @param int $length * @param int $flags * @return mixed */ public function getFromName($name, $length = NULL, $flags = NULL) { if (strtolower(substr($name, -4)) == '.xml') { $xmlParser = new XmlParser(new Stream($this->getStream($name))); return $xmlParser->getXmlString(); } else { return parent::getFromName($name, $length, $flags); } }
/** * Implements support for fopen(). * * @param string $path resource name including scheme, e.g. * @param string $mode only "r" is supported * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH * @param string &$openedPath absolute path of the opened stream (out parameter) * @return bool true on success */ public function stream_open($path, $mode, $options, &$opened_path) { // Check for mode if ($mode[0] != 'r') { throw new PHPExcel_Reader_Exception('Mode ' . $mode . ' is not supported. Only read mode is supported.'); } $pos = strrpos($path, '#'); $url['host'] = substr($path, 6, $pos - 6); // 6: strlen('zip://') $url['fragment'] = substr($path, $pos + 1); // Open archive $this->archive = new ZipArchive(); $this->archive->open($url['host']); $this->fileNameInArchive = $url['fragment']; $this->position = 0; $this->data = $this->archive->getFromName($this->fileNameInArchive); return true; }
/** * @covers XLSXWriter::writeToFile */ public function testWriteToFile() { $filename = tempnam("/tmp", "xlsx_writer"); $header = array('0' => 'string', '1' => 'string', '2' => 'string', '3' => 'string'); $sheet = array(array('55', '66', '77', '88'), array('10', '11', '12', '13')); $xlsx_writer = new XLSXWriter(); $xlsx_writer->writeSheet($sheet, 'mysheet', $header); $xlsx_writer->writeToFile($filename); $zip = new ZipArchive(); $r = $zip->open($filename); $this->assertTrue($r); $r = $zip->numFiles > 0 ? true : false; $this->assertTrue($r); $out_sheet = array(); for ($z = 0; $z < $zip->numFiles; $z++) { $inside_zip_filename = $zip->getNameIndex($z); if (preg_match("/sheet(\\d+).xml/", basename($inside_zip_filename))) { $out_sheet = $this->stripCellsFromSheetXML($zip->getFromName($inside_zip_filename)); array_shift($out_sheet); $out_sheet = array_values($out_sheet); } } $zip->close(); @unlink($filename); $r1 = self::array_diff_assoc_recursive($out_sheet, $sheet); $r2 = self::array_diff_assoc_recursive($sheet, $out_sheet); $this->assertEmpty($r1); $this->assertEmpty($r2); }