Exemplo n.º 1
1
 /**
  * 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);
 }
Exemplo n.º 2
0
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);
    }
}
Exemplo n.º 3
0
 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.';
     }
 }
 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;
 }
Exemplo n.º 5
0
 public function testCompressFolder()
 {
     $files = array('releases-noNewPatch.xml', 'releases-patchsOnly.xml', 'releases.xml', 'folder/', 'folder/emptyFile', 'emptyFolder/');
     $dest = dirname(__FILE__) . '/backup/test.zip';
     $src = dirname(__FILE__) . '/sample';
     taoUpdate_helpers_Zip::compressFolder($src, $dest);
     $this->assertTrue(is_file($dest));
     $zip = new ZipArchive();
     $zip->open($dest);
     foreach ($files as $file) {
         $this->assertFalse($zip->locateName($file) === false, $file . ' not found');
     }
     $this->assertFalse($zip->locateName('.svn'));
     helpers_File::remove($dest);
     $dest = dirname(__FILE__) . '/backup/test2.zip';
     taoUpdate_helpers_Zip::compressFolder($src, $dest, true);
     $files = array('sample/releases-noNewPatch.xml', 'sample/releases-patchsOnly.xml', 'sample/releases.xml', 'sample/folder/', 'sample/folder/emptyFile', 'sample/emptyFolder/');
     $this->assertTrue(is_file($dest));
     $zip = new ZipArchive();
     $zip->open($dest);
     for ($i = 0; $i < $zip->numFiles; $i++) {
         $stat = $zip->statIndex($i);
         //cehck no .svn added in zip
         $this->assertFalse(strpos($stat['name'], '.svn') > 0);
     }
     foreach ($files as $file) {
         $this->assertFalse($zip->locateName($file) === false);
     }
     helpers_File::remove($dest);
 }
 /**
  * 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>'];
 }
Exemplo n.º 7
0
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";
}
Exemplo n.º 8
0
 public function url_stat($path, $flags)
 {
     $ret = [];
     $zippath = preg_replace('/^myzip:\\/\\//', "", $path);
     $parts = explode('#', $zippath, 2);
     if (count($parts) != 2) {
         return false;
     }
     list($zippath, $subfile) = $parts;
     $za = new \ZipArchive();
     if ($za->open($zippath) !== true) {
         return false;
     }
     $i = $za->locateName($subfile);
     if ($i === false) {
         return false;
     }
     $zst = $za->statIndex($i);
     $za->close();
     unset($za);
     foreach ([7 => 'size', 8 => 'mtime', 9 => 'mtime', 10 => 'mtime'] as $a => $b) {
         if (!isset($zst[$b])) {
             continue;
         }
         $ret[$a] = $zst[$b];
     }
     return $ret;
 }
Exemplo n.º 9
0
 /**
  * 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;
 }
Exemplo n.º 10
0
 /**
  * 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;
 }
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();
}
 /**
  * Create a new entry with a name
  * @param   string          $name
  * @param   \ZipArchive     $archive
  * @return  ZipArchiveEntry
  */
 public static function fromName($name, \ZipArchive $archive)
 {
     $index = $archive->locateName($name);
     if ($index === false) {
         throw new \InvalidArgumentException('Entry does not exist in the archive.');
     }
     return self::fromIndex($index, $archive);
 }
 /**
  * @inheritdoc
  */
 public function offsetUnset($offset)
 {
     if ($this->archive->locateName($offset) !== false) {
         $this->archive->deleteName($offset);
     } else {
         return null;
     }
 }
Exemplo n.º 14
0
 public function postInstall()
 {
     User::onlyHas("template-install");
     $extract_path = Files::fullDir("upload/tmp/tpl/");
     if (file_exists($extract_path) === FALSE) {
         mkdir($extract_path, 0777, true);
     }
     $returnData = [];
     if (isset($_FILES['template'])) {
         $zip = new ZipArchive();
         $result = $zip->open($_FILES['template']['tmp_name']);
         if ($result === TRUE) {
             if ($zip->locateName('install.php') !== false) {
                 // extract files
                 $zip->extractTo($extract_path);
                 //rename($_SERVER['DOCUMENT_ROOT'] . "/tmp/zip/backend/", $_SERVER['DOCUMENT_ROOT'] . "/apps/backend/modules/");
                 //rename($_SERVER['DOCUMENT_ROOT'] . "/tmp/zip/frontend/", $_SERVER['DOCUMENT_ROOT'] . "/apps/frontend/modules/");
                 // get template settings
                 $config = (require_once $extract_path . 'install.php');
                 if (isset($config['app']) && file_exists(Files::fullDir('apps/' . $config['app'] . '/'))) {
                     $template_newfolder = Files::fullDir('apps/' . $config['app'] . '/views/templates/' . $config['name'] . '/');
                     if (isset($config['name']) && file_exists($template_newfolder) === FALSE) {
                         $template_folder = $extract_path . $config['name'] . '/';
                         if (file_exists($template_folder)) {
                             mkdir($template_newfolder);
                             rename($template_folder, $template_newfolder);
                             $returnData['message'] = varlang('tpl-succeful');
                             $returnData['message_type'] = 'alert-success';
                         } else {
                             $returnData['message'] = varlang('template-not-found-in-zip');
                             $returnData['message_type'] = 'alert-danger';
                         }
                     } else {
                         $returnData['message'] = varlang('undefined-template-name-or-already-exists');
                         $returnData['message_type'] = 'alert-danger';
                     }
                 } else {
                     $returnData['message'] = varlang('undefined-app-name');
                     $returnData['message_type'] = 'alert-danger';
                 }
                 File::deleteDirectory($extract_path);
             } else {
                 $returnData['message'] = varlang('installphp-is-required');
                 $returnData['message_type'] = 'alert-danger';
             }
             $zip->close();
         } else {
             $returnData['message'] = varlang('invalid-zip');
             $returnData['message_type'] = 'alert-danger';
         }
     } else {
         $returnData['message'] = varlang('invalid-file');
         $returnData['message_type'] = 'alert-danger';
     }
     return Redirect::to('template')->with($returnData);
 }
Exemplo n.º 15
0
 /**
  * Returns whether the XLSX file contains a shared strings XML file
  *
  * @return bool
  */
 public function hasSharedStrings()
 {
     $hasSharedStrings = false;
     $zip = new \ZipArchive();
     if ($zip->open($this->filePath) === true) {
         $hasSharedStrings = $zip->locateName(self::SHARED_STRINGS_XML_FILE_PATH) !== false;
         $zip->close();
     }
     return $hasSharedStrings;
 }
Exemplo n.º 16
0
 function install($diff)
 {
     if (!file_exists($diff)) {
         return;
     }
     gc_enable();
     $root = __DIR__ . "/../../";
     $archive = new ZipArchive();
     $archive->open($diff);
     $bower = $archive->locateName("bower.json");
     $webDir = $root . "web";
     if (!file_exists($webDir)) {
         mkdir($webDir);
     }
     $privateDir = $root . "private";
     if (!file_exists($privateDir)) {
         mkdir($privateDir);
     }
     if ($bower) {
         $bowerDir = $root . "web/vendor";
         if (file_exists($bowerDir)) {
             $this->rrmdir($bowerDir);
         }
         mkdir($bowerDir);
     }
     $composer = $archive->locateName("composer.json");
     if ($composer) {
         $composerDir = $root . "private/vendor";
         if (file_exists($composerDir)) {
             $this->rrmdir($composerDir);
         }
         mkdir($composerDir);
     }
     $tempDir = $root . "private/temp";
     $this->rrmdir($tempDir);
     mkdir($tempDir);
     $archive->extractTo($root);
     @unlink($diff);
     unset($archive);
     gc_collect_cycles();
     gc_disable();
 }
Exemplo n.º 17
0
 /**
  * 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>";
     }
 }
Exemplo n.º 18
0
 public static function getPackageVersion($zipFileName)
 {
     $zip = new ZipArchive();
     if ($zip->open($zipFileName) !== TRUE) {
         throw new Zend_Exception('Error opening ' . $zipFileName);
     }
     if (!($zip->locateName('info.xml', ZIPARCHIVE::FL_NOCASE) === FALSE)) {
         return '09';
     } else {
         $xml = simplexml_load_string($zip->getFromName('data.xml'));
         $zip->close();
         return str_replace('.', '', $xml->info->version);
     }
 }
Exemplo n.º 19
0
 public static function write($archive, $filename, $content)
 {
     $zip = new ZipArchive();
     if (file_exists($archive)) {
         $zip->open(realpath($archive));
     } else {
         $zip->open(getcwd() . '/' . $archive, ZipArchive::CREATE);
     }
     if ($zip->locateName($filename) !== false) {
         $zip->deleteName($filename);
     }
     $error = $zip->addFromString($filename, $content);
     return $error;
 }
 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();
     }
 }
Exemplo n.º 21
0
 public function checkPackage($zipFileName)
 {
     $zip = new ZipArchive();
     if ($zip->open($zipFileName) !== TRUE) {
         throw new Zend_Exception('Error open ' . $zipFileName);
     }
     $res = $zip->locateName('data.xml', ZIPARCHIVE::FL_NOCASE);
     if ($res === FALSE) {
         throw new Zend_Exception('File data.xml not exists in this package');
     }
     $xml = simplexml_load_string($zip->getFromName('data.xml'));
     $zip->close();
     if (strcmp($xml->info->packagetype, 'Request (for UMAN Statistics)') !== 0) {
         throw new Zend_Exception("packagetype not 'Request (for UMAN Statistics)' ");
     }
     $info = array();
     $info_reports = array();
     foreach ($xml->info->children() as $inf) {
         $info[$inf->getName()] = (string) $inf;
     }
     $validreports = '';
     foreach ($xml->reports->children() as $report) {
         $log = '';
         $isReportValid = 0;
         $ee = $this->checkReportExist((string) $report->info->reportid, $info['orgcode'], $log);
         if ($ee != 1) {
             $sql_guides = array();
             foreach ($xml->guides->children() as $guide) {
                 $sql_guides[(string) $guide['name']] = (string) $guide->sql->uman;
             }
             if ($this->checkReportValid($report, $log, $sql_guides)) {
                 $log .= 'Даний звіт буде завантажено.';
                 $isReportValid = 1;
                 $validreports .= ($validreports ? ',' : '') . (string) $report->info->reportid;
             } else {
                 $log .= ' Неможливо завантажити звіт.';
             }
         }
         $reportKey = 'rep_' . $report->info->reportid;
         foreach ($report->info->children() as $key => $value) {
             $info_reports[$reportKey][$key] = $value;
         }
         $info_reports[$reportKey]['errors'] = $log;
         $info_reports[$reportKey]['isReportValid'] = $isReportValid;
     }
     $info['info_reports'] = $info_reports;
     $info['validreports'] = $validreports;
     return $info;
 }
Exemplo n.º 22
0
 /**
  * Returns whether the file at the given location exists
  *
  * @param string $zipStreamURI URI of a zip stream, e.g. "zip://file.zip#path/inside.xml"
  * @return bool TRUE if the file exists, FALSE otherwise
  */
 protected function fileExistsWithinZip($zipStreamURI)
 {
     $doesFileExists = false;
     $pattern = '/zip:\\/\\/([^#]+)#(.*)/';
     if (preg_match($pattern, $zipStreamURI, $matches)) {
         $zipFilePath = $matches[1];
         $innerFilePath = $matches[2];
         $zip = new \ZipArchive();
         if ($zip->open($zipFilePath) === true) {
             $doesFileExists = $zip->locateName($innerFilePath) !== false;
             $zip->close();
         }
     }
     return $doesFileExists;
 }
Exemplo n.º 23
0
 public function getJsonFromFile($fileName, $pathName)
 {
     $zip = new \ZipArchive();
     $zip->open($pathName);
     if (0 == $zip->numFiles) {
         return false;
     }
     $foundFileIndex = $zip->locateName($fileName, \ZipArchive::FL_NODIR);
     if (false === $foundFileIndex) {
         return false;
     }
     $updateFileName = $zip->getNameIndex($foundFileIndex);
     $updateFile = "zip://{$pathName}#{$updateFileName}";
     $json = file_get_contents($updateFile);
     return $json;
 }
Exemplo n.º 24
0
 /**
  * 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);
 }
Exemplo n.º 25
0
 private function getComposerInformation(\SplFileInfo $file)
 {
     $zip = new \ZipArchive();
     $zip->open($file->getPathname());
     if (0 == $zip->numFiles) {
         return false;
     }
     $foundFileIndex = $zip->locateName('composer.json', \ZipArchive::FL_NODIR);
     if (false === $foundFileIndex) {
         return false;
     }
     $configurationFileName = $zip->getNameIndex($foundFileIndex);
     $composerFile = "zip://{$file->getPathname()}#{$configurationFileName}";
     $json = file_get_contents($composerFile);
     $package = JsonFile::parseJson($json, $composerFile);
     $package['dist'] = array('type' => 'zip', 'url' => $file->getRealPath(), 'reference' => $file->getBasename(), 'shasum' => sha1_file($file->getRealPath()));
     $package = $this->loader->load($package);
     return $package;
 }
Exemplo n.º 26
0
 /**
  * Gets the JSON file content from the package.
  *
  * @param string $jsonFileName JSON file name
  *
  * @return string JSON string
  */
 public function getJsonFromFile($jsonFileName = null)
 {
     $zip = new \ZipArchive();
     $zip->open($this->getFilePath());
     if (0 == $zip->numFiles) {
         return false;
     }
     $foundFileIndex = $zip->locateName(is_null($jsonFileName) ? $this->getFileName() : $jsonFileName, \ZipArchive::FL_NODIR);
     if (false === $foundFileIndex) {
         return false;
     }
     $updateFileName = $zip->getNameIndex($foundFileIndex);
     $updateFile = "zip://{$this->getFilePath()}#{$updateFileName}";
     $json = file_get_contents($updateFile);
     if (!is_string($json)) {
         throw new \Exception(sprintf('Could not fetch content from "%s" file inside "%s"', $this->getFilename(), $this->getFilePath()));
     }
     return $json;
 }
Exemplo n.º 27
0
 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 '';
 }
Exemplo n.º 28
0
function XML($archiveFile, $dataFile)
{
    $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);
            //  return $data;
            // Close archive file
            $zip->close();
            $xml = DOMDocument::loadXML($data, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            $xmldata = $xml->saveXML();
            $xmldata = str_replace("</w:p>", "\r\n", $xmldata);
            return strip_tags($xmldata);
        }
        $zip->close();
    }
    return "";
}
Exemplo n.º 29
0
 function pptx_to_text($input_file = "")
 {
     $zip_handle = new ZipArchive();
     $output_text = "";
     if (true === $zip_handle->open($input_file)) {
         $slide_number = 1;
         //loop through slide files
         while (($xml_index = $zip_handle->locateName("ppt/slides/slide" . $slide_number . ".xml")) !== false) {
             $xml_datas = $zip_handle->getFromIndex($xml_index);
             $xml_handle = DOMDocument::loadXML($xml_datas, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
             $output_text .= strip_tags($xml_handle->saveXML());
             $slide_number++;
         }
         if ($slide_number == 1) {
             $output_text .= "";
         }
         $zip_handle->close();
     } else {
         $output_text .= "";
     }
     return $output_text;
 }
Exemplo n.º 30
0
function getTextFromZippedXML($archiveFile, $contentFile)
{
    // Создаёт "реинкарнацию" zip-архива...
    $zip = new ZipArchive();
    // И пытаемся открыть переданный zip-файл
    if ($zip->open($archiveFile)) {
        // В случае успеха ищем в архиве файл с данными
        if (($index = $zip->locateName($contentFile)) !== false) {
            // Если находим, то читаем его в строку
            $content = $zip->getFromIndex($index);
            // Закрываем zip-архив, он нам больше не нужен
            $zip->close();
            // После этого подгружаем все entity и по возможности include'ы других файлов
            // Проглатываем ошибки и предупреждения
            $xml = DOMDocument::loadXML($content, LIBXML_NOENT | LIBXML_XINCLUDE | LIBXML_NOERROR | LIBXML_NOWARNING);
            // После чего возвращаем данные без XML-тегов форматирования
            return iconv("utf-8", "windows-1250", strip_tags($xml->saveXML()));
        }
        $zip->close();
    }
    // Если что-то пошло не так, возвращаем пустую строку
    return "";
}