function docx_getTextFromZippedXML($archiveFile, $contentFile, $cacheFolder, $debug) { // Создаёт "реинкарнацию" zip-архива... $zip = new \ZipArchive(); // И пытаемся открыть переданный zip-файл if ($zip->open($archiveFile)) { @mkdir($cacheFolder); $zip->extractTo($cacheFolder); // В случае успеха ищем в архиве файл с данными $xml = false; $xml2 = false; $file = $contentFile; if (($index = $zip->locateName($file)) !== false) { // Если находим, то читаем его в строку $content = $zip->getFromIndex($index); // После этого подгружаем все entity и по возможности include'ы других файлов $xml = \DOMDocument::loadXML($content, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING); } $file = 'word/_rels/document.xml.rels'; if (($index = $zip->locateName($file)) !== false) { // Если находим, то читаем его в строку $content = $zip->getFromIndex($index); $xml2 = \DOMDocument::loadXML($content, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING); //@ - https://bugs.php.net/bug.php?id=41398 Strict Standards: Non-static method DOMDocument::loadXML() should not be called statically } $zip->close(); return array($xml, $xml2); } }
/** * Extract headers and readme.txt data from a ZIP archive that contains a plugin or theme. * * Returns an associative array with these keys: * 'type' - Detected package type. This can be either "plugin" or "theme". * 'header' - An array of plugin or theme headers. See get_plugin_data() or WP_Theme for details. * 'readme' - An array of metadata extracted from readme.txt. @see self::parseReadme() * 'pluginFile' - The name of the PHP file where the plugin headers were found relative to the root directory of the ZIP archive. * 'stylesheet' - The relative path to the style.css file that contains theme headers, if any. * * The 'readme' key will only be present if the input archive contains a readme.txt file * formatted according to WordPress.org readme standards. Similarly, 'pluginFile' and * 'stylesheet' will only be present if the archive contains a plugin or a theme, respectively. * * @param string $packageFilename The path to the ZIP package. * @param bool $applyMarkdown Whether to transform markup used in readme.txt to HTML. Defaults to false. * @return array Either an associative array or FALSE if the input file is not a valid ZIP archive or doesn't contain a WP plugin or theme. */ public static function parsePackage($packageFilename, $applyMarkdown = false) { if (!file_exists($packageFilename) || !is_readable($packageFilename)) { return false; } //Open the .zip $zip = new ZipArchive(); if ($zip->open($packageFilename) !== true) { return false; } //Find and parse the plugin or theme file and (optionally) readme.txt. $header = null; $readme = null; $pluginFile = null; $stylesheet = null; $type = null; for ($fileIndex = 0; $fileIndex < $zip->numFiles && (empty($readme) || empty($header)); $fileIndex++) { $info = $zip->statIndex($fileIndex); //Normalize filename: convert backslashes to slashes, remove leading slashes. $fileName = trim(str_replace('\\', '/', $info['name']), '/'); $fileName = ltrim($fileName, '/'); $fileNameParts = explode('.', $fileName); $extension = strtolower(end($fileNameParts)); $depth = substr_count($fileName, '/'); //Skip empty files, directories and everything that's more than 1 sub-directory deep. if ($depth > 1 || $info['size'] == 0) { continue; } //readme.txt (for plugins)? if (empty($readme) && strtolower(basename($fileName)) == 'readme.txt') { //Try to parse the readme. $readme = self::parseReadme($zip->getFromIndex($fileIndex), $applyMarkdown); } //Theme stylesheet? if (empty($header) && strtolower(basename($fileName)) == 'style.css') { $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024); $header = self::getThemeHeaders($fileContents); if (!empty($header)) { $stylesheet = $fileName; $type = 'theme'; } } //Main plugin file? if (empty($header) && $extension === 'php') { $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024); $header = self::getPluginHeaders($fileContents); if (!empty($header)) { $pluginFile = $fileName; $type = 'plugin'; } } } if (empty($type)) { return false; } else { return compact('header', 'readme', 'pluginFile', 'stylesheet', 'type'); } }
/** * Tim Hodson: renamed functions to avoid collisions. * * Extract plugin headers and readme.txt data from a plugin's ZIP archive. * * Returns an associative array with these keys: * 'headers' - An array of plugin headers. See get_plugin_data() for details. * 'readme' - An array of metadata extracted from readme.txt. See parsePluginReadme() for details. * 'pluginFile' - The name of the PHP file where the plugin headers were found; relative to the root directory of the ZIP archive. * * The 'readme' key will only be present if the input archive contains a readme.txt file * formatted according to WordPress.org readme standards. * * @uses parsePluginReadme() * @uses get_plugin_data() * * @param string $packageFilename The path to the plugin's ZIP package. * @param bool $applyMarkdown Whether to transform markup used in readme.txt to HTML. Defaults to false. * @return array Associative array containing 'headers', 'readme' and 'pluginFile'. Returns FALSE if the input file is not a valid ZIP archive or doesn't contain a WP plugin. */ function pm_analysePluginPackage($packageFilename, $applyMarkdown = false) { if (!file_exists($packageFilename) || !is_readable($packageFilename)) { return false; } //Open the .zip $zip = new ZipArchive(); if ($zip->open($packageFilename) !== true) { return false; } //Find and parse the plugin file and readme.txt $header = null; $readme = null; $pluginFile = null; for ($fileIndex = 0; $fileIndex < $zip->numFiles && (empty($readme) || empty($header)); $fileIndex++) { $info = $zip->statIndex($fileIndex); $fileName = trim(str_replace('\\', '/', $info['name']), '/'); //Backslashes to slashes, kill leading slashes. //readme.txt? if (empty($readme) && strtolower(basename($fileName)) == 'readme.txt') { //Try to parse the readme $readme = pm_parsePluginReadme($zip->getFromIndex($fileIndex), $applyMarkdown); continue; //Skip the rest of the checks. } //Plugin header? if (empty($header)) { //Skip directories and empty files if ($info['size'] == 0) { continue; } //We're only interested in PHP files $extension = end(explode('.', $fileName)); if (strtolower($extension) != 'php') { continue; } //WordPress only looks for plugin files in the top or second level //of the directory tree, so we do the same. if (substr_count($fileName, '/') > 1) { continue; } //Try to read the header. WP only scans the first 8kiB, so we do the same. $fileContents = substr($zip->getFromIndex($fileIndex), 0, 8 * 1024); $header = pm_getPluginHeader($fileContents); if (!empty($header)) { $pluginFile = $fileName; } } } if (empty($pluginFile)) { return false; } else { return compact('header', 'readme', 'pluginFile'); } }
private function load($file) { if (file_exists($file)) { $zip = new ZipArchive(); if ($zip->open($file) === true) { //attempt to load styles: if (($styleIndex = $zip->locateName('word/styles.xml')) !== false) { $stylesXml = $zip->getFromIndex($styleIndex); $xml = simplexml_load_string($stylesXml); $namespaces = $xml->getNamespaces(true); $children = $xml->children($namespaces['w']); foreach ($children->style as $s) { $attr = $s->attributes('w', true); if (isset($attr['styleId'])) { $tags = array(); $attrs = array(); foreach (get_object_vars($s->rPr) as $tag => $style) { $att = $style->attributes('w', true); switch ($tag) { case "b": $tags[] = 'strong'; break; case "i": $tags[] = 'em'; break; case "color": //echo (String) $att['val']; $attrs[] = 'color:#' . $att['val']; break; case "sz": $attrs[] = 'font-size:' . $att['val'] . 'px'; break; } } $styles[(string) $attr['styleId']] = array('tags' => $tags, 'attrs' => $attrs); } } $this->styles = $styles; } if (($index = $zip->locateName('word/document.xml')) !== false) { // If found, read it to the string $data = $zip->getFromIndex($index); // Close archive file $zip->close(); return $data; } $zip->close(); } else { $this->errors[] = 'Could not open file.'; } } else { $this->errors[] = 'File does not exist.'; } }
/** * Sets the hash that is used to uniquely identify this plugin */ public function setHash() { $archiveName = $this->getFilenameOnFilestore(); $zip = new ZipArchive(); $result = $zip->open($archiveName); if ($result !== true) { return false; } for ($i = 0; $i < $zip->numFiles; $i++) { $filename = $zip->getNameIndex($i); if (stripos($filename, 'manifest.xml') !== false) { $manifest = $zip->getFromIndex($i); $id = substr($filename, 0, strpos($filename, '/')); break; } } $zip->close(); if (!isset($manifest)) { return false; } try { $manifest = new ElggPluginManifest($manifest); $author = $manifest->getAuthor(); $version = $manifest->getVersion(); $this->hash = md5($id . $version . $author); } catch (Exception $e) { // skip invalid manifests } }
/** * grabs formatting for list styles from a related internal data file * * @param SimpleXMLElement $numPr the list object element * @return array wrapping tags for ordered and unordered lists */ private function getListFormatting($numPr) { $id = $numPr->numId->attributes('w', TRUE)['val']; $level = $numPr->ilvl->attributes('w', TRUE)['val']; if (FALSE !== ($index = $this->zip->locateName('word/numbering.xml'))) { $xml = $this->zip->getFromIndex($index); $doc = new DOMDocument(); $doc->preserveWhiteSpace = FALSE; $doc->loadXML($xml); $xpath = new DOMXPath($doc); $nodes = $xpath->query('/w:numbering/w:num[@w:numId=' . $id . ']/w:abstractNumId'); if ($nodes->length) { $id = $nodes->item(0)->getAttribute('w:val'); $nodes = $xpath->query('/w:numbering/w:abstractNum[@w:abstractNumId=' . $id . ']/w:lvl[@w:ilvl=' . $level . ']/w:numFmt'); if ($nodes->length) { $listFormat = $nodes->item(0)->getAttribute('w:val'); if ($listFormat === 'bullet') { return ['<ul>', '</ul>']; } else { if ($listFormat === 'decimal') { return ['<ol>', '</ol>']; } } } } } return ['<ul class="list-unstyled">', '</ul>']; }
function readZippedXML($archiveFile, $dataFile) { if (!class_exists('ZipArchive', false)) { return "ZipArchive Class Doesn't Exist."; } // Create new ZIP archive $zip = new ZipArchive(); // Open received archive file if (true === $zip->open($archiveFile)) { // If done, search for the data file in the archive if (($index = $zip->locateName($dataFile)) !== false) { // If found, read it to the string $data = $zip->getFromIndex($index); // Close archive file $zip->close(); // Load XML from a string // Skip errors and warnings return $data; // $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING); // // Return data without XML formatting tags // return strip_tags($xml->saveXML()); } $zip->close(); } // In case of failure return empty string return $zip->getStatusString(); }
private function locateFile(\ZipArchive $zip, $filename) { $indexOfShortestMatch = false; $lengthOfShortestMatch = -1; for ($i = 0; $i < $zip->numFiles; $i++) { $stat = $zip->statIndex($i); if (strcmp(basename($stat['name']), $filename) === 0) { $directoryName = dirname($stat['name']); if ($directoryName == '.') { return $i; } if (strpos($directoryName, '\\') !== false || strpos($directoryName, '/') !== false) { continue; } $length = strlen($stat['name']); if ($indexOfShortestMatch == false || $length < $lengthOfShortestMatch) { $contents = $zip->getFromIndex($i); if ($contents !== false) { $indexOfShortestMatch = $i; $lengthOfShortestMatch = $length; } } } } return $indexOfShortestMatch; }
protected function retrieveResponse() { if (!class_exists('ZipArchive')) { throw new KurogoException("class ZipArchive (php-zip) not available"); } $tmpFile = Kurogo::tempFile(); // this is the same as parent if (!($this->requestURL = $this->url())) { throw new KurogoDataException("URL could not be determined"); } $this->requestParameters = $this->parameters(); // the following are private functions in URLDataRetriever //$this->requestMethod = $this->setContextMethod(); //$this->requestHeaders = $this->setContextHeaders(); //$this->requestData = $this->setContextData(); Kurogo::log(LOG_INFO, "Retrieving {$this->requestURL}", 'url_retriever'); // the creation of $data is different from parent copy($this->requestURL, $tmpFile); $zip = new ZipArchive(); $zip->open($tmpFile); $data = $zip->getFromIndex(0); unlink($tmpFile); // this is the same as parent $http_response_header = isset($http_response_header) ? $http_response_header : array(); $response = $this->initResponse(); $response->setRequest($this->requestMethod, $this->requestURL, $this->requestParameters, $this->requestHeaders, null); $response->setResponse($data); $response->setResponseHeaders($http_response_header); Kurogo::log(LOG_DEBUG, sprintf("Returned status %d and %d bytes", $response->getCode(), strlen($data)), 'url_retriever'); return $response; }
/** * Retrieve plugin info from meta.json in zip * @param $zipPath * @return bool|mixed * @throws CakeException */ public function getPluginMeta($zipPath) { $Zip = new \ZipArchive(); if ($Zip->open($zipPath) === true) { $search = 'config/meta.json'; $indexJson = $Zip->locateName('meta.json', \ZipArchive::FL_NODIR); if ($indexJson === false) { throw new Exception(__d('spider', 'Invalid meta information in archive')); } else { $fileName = $Zip->getNameIndex($indexJson); $fileJson = json_decode($Zip->getFromIndex($indexJson)); if (empty($fileJson->name)) { throw new Exception(__d('spider', 'Invalid meta.json or missing plugin name')); } else { $pluginRootPath = str_replace($search, '', $fileName); $fileJson->rootPath = $pluginRootPath; } } $Zip->close(); if (!isset($fileJson) || empty($fileJson)) { throw new Exception(__d('spider', 'Invali meta.json')); } return $fileJson; } else { throw new CakeException(__d('spider', 'Invalid zip archive')); } return false; }
/** * Give it a path to a file and it will return * the contents of that file, either as xml or html * * @param string $file * @param bool $as_xml (optional) * * @return boolean|\DOMDocument */ protected function getZipContent($file, $as_xml = true) { // Locates an entry using its name $index = $this->zip->locateName($file); if (false === $index) { return false; } // returns the contents using its index $content = $this->zip->getFromIndex($index); // if it's not xml, return if (!$as_xml) { return $content; } $collapsed = preg_replace('/\\s+/', '', $content); if (preg_match('/<!DOCTYPE/i', $collapsed)) { // Invalid XML: Detected use of illegal DOCTYPE return false; } // trouble with simplexmlelement and elements with dashes // (ODT's are ripe with dashes), so giving it to the DOM $old_value = libxml_disable_entity_loader(true); $xml = new \DOMDocument(); $xml->loadXML($content, LIBXML_NOBLANKS | LIBXML_NOENT | LIBXML_NONET | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING); libxml_disable_entity_loader($old_value); return $xml; }
public function loadFromFile($loc, $loadAllVars = false) { $this->source = $loc; $this->loadAllVars = $loadAllVars; if (file_exists($loc)) { if (preg_match('/\\.(gz|zip)$/i', $loc, $ext)) { switch (strtolower($ext[1])) { case 'gz': $loc = 'compress.zlib://' . $loc; break; case 'zip': $zip = new ZipArchive(); if ($zip->open($loc) === true && $zip->numFiles == 1) { return $this->loadFromString($zip->getFromIndex(0), $loadAllVars); } else { $loc = 'zip://' . $loc; } break; } } libxml_use_internal_errors(true); $xmlObj = @simplexml_load_file($loc); if ($this->isValidNzb($xmlObj)) { $this->parseNzb($xmlObj); } unset($xmlObj); } return $this->isLoaded; }
/** * @return bool */ public function getBootstrap() { if ($this->hasBootstrap()) { return $this->_zip->getFromIndex($this->_getBootstrapIndex()); } return null; }
function extracttext($filename) { //Check for extension //$ext = end(explode('.', $filename)); //if its docx file //if($ext == 'docx') $dataFile = "word/document.xml"; //else it must be odt file //else //$dataFile = "content.xml"; //Create a new ZIP archive object $zip = new ZipArchive(); // Open the archive file if (true === $zip->open($filename)) { // If successful, search for the data file in the archive if (($index = $zip->locateName($dataFile)) !== false) { // Index found! Now read it to a string $text = $zip->getFromIndex($index); // Load XML from a string // Ignore errors and warnings $xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING); // Remove XML formatting tags and return the text return strip_tags($xml->saveXML()); } //Close the archive file $zip->close(); } // In case of failure return a message return "File not found"; }
/** * READS The Document and Relationships into separated XML files * * @param String $filename The filename * @return void */ private function readZipPart($filename) { $zip = new ZipArchive(); $_xml = 'word/document.xml'; $_xml_rels = 'word/_rels/document.xml.rels'; if (true === $zip->open($filename)) { if (($index = $zip->locateName($_xml)) !== false) { $xml = $zip->getFromIndex($index); } $zip->close(); } else { die('non zip file'); } if (true === $zip->open($filename)) { if (($index = $zip->locateName($_xml_rels)) !== false) { $xml_rels = $zip->getFromIndex($index); } $zip->close(); } else { die('non zip file'); } $this->doc_xml = new DOMDocument(); $this->doc_xml->encoding = mb_detect_encoding($xml); $this->doc_xml->preserveWhiteSpace = false; $this->doc_xml->formatOutput = true; $this->doc_xml->loadXML($xml); $this->doc_xml->saveXML(); $this->rels_xml = new DOMDocument(); $this->rels_xml->encoding = mb_detect_encoding($xml); $this->rels_xml->preserveWhiteSpace = false; $this->rels_xml->formatOutput = true; $this->rels_xml->loadXML($xml_rels); $this->rels_xml->saveXML(); if ($this->debug) { echo "<textarea style='width:100%; height: 200px;'>"; echo $this->doc_xml->saveXML(); echo "</textarea>"; echo "<textarea style='width:100%; height: 200px;'>"; echo $this->rels_xml->saveXML(); echo "</textarea>"; } }
private function assertZipContains(array $contents, $file) { $zip = new \ZipArchive(); $zip->open($file); $actual = array(); for ($i = 0; $i < $zip->numFiles; $i++) { $actual[$zip->getNameIndex($i)] = $zip->getFromIndex($i); } $zip->close(); $this->assertEquals($contents, $actual); }
function fromCompressed() { $tf3 = tempnam("/tmp", ""); file_put_contents($tf3, $this->dataCompressed); $zip = new \ZipArchive(); if ($zip->open($tf3) === TRUE) { $this->dataXmlSigned = $zip->getFromIndex(0); $zip->close(); } else { throw new \Exception('failed to read compressed data'); } }
public function install_font($post_title, $post) { if ($post->post_type == 'font' && isset($_REQUEST['family'])) { $family = $_REQUEST['family']; $r = wp_remote_get($this->apiurl . "familyinfo/{$family}"); if (!is_wp_error($r)) { $details = json_decode($r['body']); $post_title = $details[0]->family_name; //$dir = WP_CONTENT_DIR . "/fonts/$family"; $dir = $this->root_font_dir . "/{$family}"; //$subdir_name = strtolower(str_replace($details[0]->style_name, '', $details[0]->fontface_name)); // save family add_post_meta($post->ID, 'font-family', $family); if (!is_dir($dir)) { mkdir($dir); // download font-face kit wp_remote_get("http://www.fontsquirrel.com/fontfacekit/{$family}", array('stream' => true, 'filename' => $dir . "/font-face-kit.zip")); // look at font files $zip = new ZipArchive(); $res = $zip->open($dir . "/font-face-kit.zip"); if ($res === TRUE) { // get the stylesheet $stylesheet = $zip->getFromIndex($zip->locateName('stylesheet.css', ZipArchive::FL_NODIR)); $fp = fopen("{$dir}/stylesheet.css", 'w'); fwrite($fp, $stylesheet); fclose($fp); // get the font files preg_match_all("/([^']+webfont\\.(?:eot|woff|ttf|svg))/", $stylesheet, $matches); $fontfiles = array(); foreach (array_unique($matches[1]) as $fontfile) { $i = $zip->locateName($fontfile, ZipArchive::FL_NODIR); $fp = fopen("{$dir}/{$fontfile}", 'w'); fwrite($fp, $zip->getFromIndex($i)); fclose($fp); } // get the font name preg_match("/font-family: '([^']+)';/", $stylesheet, $matches); add_post_meta($post->ID, 'font-name', $matches[1]); $zip->close(); } // download samples wp_remote_get($details[0]->listing_image, array('stream' => true, 'filename' => $dir . "/listing_image.png")); wp_remote_get($details[0]->sample_image, array('stream' => true, 'filename' => $dir . "/sample_image.png")); wp_remote_get(str_replace('sp-720', 'sa-720x300', $details[0]->sample_image), array('stream' => true, 'filename' => $dir . "/sample_alphabet.png")); wp_remote_get(str_replace('sp-720', 'para-128x200-9', $details[0]->sample_image), array('stream' => true, 'filename' => $dir . "/sample_paragraph_9.png")); wp_remote_get(str_replace('sp-720', 'para-128x200-10', $details[0]->sample_image), array('stream' => true, 'filename' => $dir . "/sample_paragraph_10.png")); wp_remote_get(str_replace('sp-720', 'para-202x200-12', $details[0]->sample_image), array('stream' => true, 'filename' => $dir . "/sample_paragraph_12.png")); wp_remote_get(str_replace('sp-720', 'para-202x200-16', $details[0]->sample_image), array('stream' => true, 'filename' => $dir . "/sample_paragraph_16.png")); } } } return $post_title; }
function getPackageInfo($inFile) { $zip = new ZipArchive(); if ($zip->open($inFile)) { for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match("/info.json\$/", $zip->getNameIndex($i))) { $json = new Services_JSON(); return $json->decode($zip->getFromIndex($i)); } } $zip->close(); } }
function saveAllImages() { if (count($this->indexes) == 0) { echo 'No images found'; } foreach ($this->indexes as $key => $index) { $zip = new ZipArchive(); if (true === $zip->open($this->file)) { file_put_contents(dirname(__FILE__) . '/' . $this->savepath . '/' . $key, $zip->getFromIndex($index)); } $zip->close(); } }
/** * @return string Request body content */ public function getContent() { $content = $this->wrappedGetter->getContent(); $tempFile = tempnam(sys_get_temp_dir(), __CLASS__); file_put_contents($tempFile, $content); $zip = new \ZipArchive(); if ($zip->open($tempFile) !== TRUE) { throw new \RuntimeException('ZipArchive::open failed.'); } $content = $zip->getFromIndex(0); $zip->close(); unlink($tempFile); return $content; }
private function docxtotext($filename) { // docx path to the body content of the document $dataFile = "word/document.xml"; $zip = new ZipArchive(); if (true === $zip->open($filename)) { if (($index = $zip->locateName($dataFile)) !== false) { $text = $zip->getFromIndex($index); $xml = DOMDocument::loadXML($text, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING); return trim(strip_tags($xml->saveXML())); } $zip->close(); } }
public function getDataForSigning() { $count = $this->archive->numFiles; $hashes = []; for ($i = 0; $i < $count; $i++) { $fileName = $this->archive->getNameIndex($i); $hashes[$fileName] = $this->gitHash($this->archive->getFromIndex($i)); } ksort($hashes); unset($hashes['update.json']); // echo sha1(json_encode($hashes)); // die(); return sha1(json_encode($hashes)); }
public static function render_page_process($PATH) { $main = null; if (isset($PATH[0])) { if ($PATH[0] == 'context' && isset($PATH[1])) { $attribs = explode(',', $PATH[1]); $stmt = phoromatic_server::$db->prepare('SELECT UserContextStep, UserContextLog FROM phoromatic_system_context_logs WHERE AccountID = :account_id AND ScheduleID = :schedule_id AND SystemID = :system_id AND TriggerID = :trigger_id ORDER BY UploadTime ASC'); $stmt->bindValue(':account_id', $_SESSION['AccountID']); $stmt->bindValue(':system_id', $attribs[0]); $stmt->bindValue(':schedule_id', $attribs[1]); $stmt->bindValue(':trigger_id', base64_decode($attribs[2])); $result = $stmt->execute(); while ($row = $result->fetchArray()) { $main .= '<h2>' . $row['UserContextStep'] . '</h2><p>' . str_replace(PHP_EOL, '<br />', $row['UserContextLog']) . '</p><hr />'; } } else { if ($PATH[0] == 'system' && isset($PATH[1])) { $zip_file = phoromatic_server::phoromatic_account_result_path($_SESSION['AccountID'], $PATH[1]) . 'system-logs.zip'; if (is_file($zip_file)) { $zip = new ZipArchive(); $res = $zip->open($zip_file); if ($res === true) { for ($i = 0; $i < $zip->numFiles; $i++) { if ($zip->getFromIndex($i) != null) { $main .= '<h2>' . basename($zip->getNameIndex($i)) . '</h2><p>' . str_replace(PHP_EOL, '<br />', $zip->getFromIndex($i)) . '</p><hr />'; } } $zip->close(); } } } } } echo phoromatic_webui_header_logged_in(); echo phoromatic_webui_main($main, phoromatic_webui_right_panel_logged_in(null)); echo phoromatic_webui_footer(); }
protected function download() { $this->output->write('<comment>Downloading manifest version (' . $this->version . ') ... </comment>'); $tmp = storage_path("{$this->version}.zip"); \File::put($tmp, file_get_contents($this->url)); $zip = new \ZipArchive(); if (!$zip->open($tmp)) { throw new \Exception('Unable to open Destiny Manifest from Bungie'); } \File::put($this->versionDb, $zip->getFromIndex(0)); \File::put($this->versionFile, $this->version); $zip->close(); \File::delete($tmp); $this->comment('Done!'); }
/** * Locates an entry using its name, returns the entry contents * * @param $file * @param bool $as_xml * * @return string|\SimpleXMLElement */ protected function getZipContent($file, $as_xml = true) { // Locates an entry using its name $index = $this->zip->locateName(urldecode($file)); if ($index === false) { return ''; } // returns the contents using its index $content = $this->zip->getFromIndex($index); // if it's not xml, return if (!$as_xml) { return $content; } // if it is xml, then instantiate and return a simplexml object return new \SimpleXMLElement($content); }
public function testStreamRead() { $archive = new Archive(); $archive = (new Archive())->withContent(new StringContent('test.txt', 'content')); $filename = tempnam(sys_get_temp_dir(), 'zip'); $fileStream = fopen($filename, 'r+'); $psr7Stream = new Psr7Stream(new ZipReader($archive)); while (!$psr7Stream->eof()) { fwrite($fileStream, $psr7Stream->read(1)); } fclose($fileStream); $zip = new \ZipArchive(); $result = $zip->open($filename); $this->assertTrue($result); $this->assertEquals(1, $zip->numFiles); $this->assertEquals('test.txt', $zip->getNameIndex(0)); $this->assertEquals('content', $zip->getFromIndex(0)); }
protected function retrieveData($url) { if (strpos($url, 'kmz') !== false) { if (!class_exists('ZipArchive')) { die("class ZipArchive (php-zip) not supported"); } $tmpDir = $GLOBALS['siteConfig']->getVar('TMP_DIR'); $tmpFile = $tmpDir.'/tmp.kmz'; copy($url, $tmpFile); $zip = new ZipArchive(); $zip->open($tmpFile); $contents = $zip->getFromIndex(0); unlink($tmpFile); return $contents; // this is false on failure, same as file_get_contents } else { return parent::retrieveData($url); } }
public function get_zip_contents($path) { $files = array(); $zip = new ZipArchive(); $zip_ret = $zip->open($path); if (false === $zip_ret) { $this->add_error('invalid-zip', sprintf('Can\'t open: %s', $path), 'blocker', $path); return; } for ($i = 0; $i < $zip->numFiles; $i++) { $file_name = $zip->getNameIndex($i); // Skip directories - seemingly the only way, since php's zip // wrapper doesn't support stat() calls. if (substr($file_name, -1) == '/') { continue; } $files[$file_name] = $zip->getFromIndex($i); } return $files; }
private function getTextFromZippedXML($contentFile) { $archiveFile = $this->filename; // Создаёт "реинкарнацию" zip-архива... $zip = new \ZipArchive(); // И пытаемся открыть переданный zip-файл if ($zip->open($archiveFile)) { // В случае успеха ищем в архиве файл с данными if (($index = $zip->locateName($contentFile)) !== false) { // Если находим, то читаем его в строку $content = $zip->getFromIndex($index); return $content; } else { throw new \ErrorException('error read document'); } $zip->close(); } else { throw new \ErrorException('error open file ' . $archiveFile); } return ''; }