Exemple #1
0
 public function testLongLinkAndFileName()
 {
     $dir = $this->getTempDir();
     $filename = $this->createTempFile('linktest.tar');
     $archive = ezcArchive::open($filename);
     foreach ($archive as $entry) {
         $archive->extractCurrent($dir);
     }
     self::assertEquals(true, file_exists("{$dir}/var/ezwebin_site/storage/images/eu/biofoul/lobster-plant/galleri-3-bilder/photo-1/1225-1-eng-GB/Photo-1_sidebar_large.jpg"));
     self::assertEquals(true, file_exists("{$dir}/var/ezwebin_site/storage/images/eu/lobster-plant/galleri-3-bilder/photo-1/1225-1-eng-GB/Photo-1_sidebar_large.jpg"));
 }
 /**
  *
  * Test function to test if the extract function of ezcArchive works on files
  * with long name.
  *
  * Due to '\0' at the end of the filename, file_exists fatal error is being caught.
  *
  */
 public function test_entry_path()
 {
     $this->createTempDir("entryPath-", sys_get_temp_dir());
     $dir = $this->getTempDir();
     $archive = ezcArchive::open(dirname(__FILE__) . "/data/images.tar.gz");
     try {
         $archive->extract($dir);
     } catch (Exception $e) {
         // ignore any type of exception, including fatal exception file_exists
     }
     clearstatcache();
     $this->assertTrue(file_exists("{$dir}/testing/naming/including/inner/module/files/purpose/helper/jquery-ui-bootstrap/images/ui-bg_flat_0_aaaaaa_40x100.png"));
     $this->assertTrue(file_exists("{$dir}/testing/naming/including/inner/module/files/purpose/helper/jquery-ui-bootstrap/images/ui-bg_highlight-soft_75_cccccc_1x100.png"));
     $this->assertTrue(file_exists("{$dir}/testing/naming/including/inner/module/files/purpose/helper/jquery-ui-bootstrap/images/ui-bg_inset-soft_95_fef1ec_1x100.png"));
     $this->removeTempDir();
 }
Exemple #3
0
 public function testCreateBzip2TarWithTwoFiles()
 {
     if (!ezcBaseFeatures::hasExtensionSupport('bz2')) {
         $this->markTestSkipped();
     }
     $dir = $this->getTempDir();
     $archive = ezcArchive::open("compress.bzip2://{$dir}/mytar.tar.bz2", ezcArchive::TAR_USTAR);
     file_put_contents("{$dir}/a.txt", "Hello world!");
     file_put_contents("{$dir}/b.txt", "BBBBBBBBBBBB");
     $archive->append("{$dir}/a.txt", $dir);
     $archive->append("{$dir}/b.txt", $dir);
     $archive->close();
     exec("tar -cf {$dir}/gnutar.tar --format=ustar -C {$dir} a.txt b.txt");
     exec("bunzip2 {$dir}/mytar.tar.bz2");
     $this->assertEquals(file_get_contents("{$dir}/gnutar.tar"), file_get_contents("{$dir}/mytar.tar"));
 }
 /**
  * Creates a new content or updates an existing one based on $file
  *
  * @param string $file the file to import
  * @param int $placeNodeID the node id where to place the new document or
  *        the node of the document to update
  * @param string $originalFileName
  * @param string $importType "import" or "replace"
  * @param eZContentUpload|null $upload (not used in this method)
  * @param string|false $locale the locale to use while creating/updating
  *        the content
  * @return array|false false if something went wrong
  */
 function import($file, $placeNodeID, $originalFileName, $importType = "import", $upload = null, $locale = false)
 {
     $ooINI = eZINI::instance('odf.ini');
     //$tmpDir = $ooINI->variable( 'ODFSettings', 'TmpDir' );
     // Use var-directory as temporary directory
     $tmpDir = getcwd() . "/" . eZSys::cacheDirectory();
     $allowedTypes = $ooINI->variable('DocumentType', 'AllowedTypes');
     $convertTypes = $ooINI->variable('DocumentType', 'ConvertTypes');
     $originalFileType = array_slice(explode('.', $originalFileName), -1, 1);
     $originalFileType = strtolower($originalFileType[0]);
     if (!in_array($originalFileType, $allowedTypes, false) and !in_array($originalFileType, $convertTypes, false)) {
         $this->setError(self::ERROR_UNSUPPORTEDTYPE, ezpI18n::tr('extension/ezodf/import/error', "Filetype: ") . $originalFileType);
         return false;
     }
     // If replacing/updating the document we need the ID.
     if ($importType == "replace") {
         $GLOBALS["OOImportObjectID"] = $placeNodeID;
     }
     // Check if we have access to node
     $place_node = eZContentObjectTreeNode::fetch($placeNodeID);
     $importClassIdentifier = $ooINI->variable('ODFImport', 'DefaultImportClass');
     // Check if class exist
     $class = eZContentClass::fetchByIdentifier($importClassIdentifier);
     if (!is_object($class)) {
         eZDebug::writeError("Content class <strong>{$importClassIdentifier}</strong> specified in odf.ini does not exist.");
         $this->setError(self::ERROR_UNKNOWNCLASS, $importClassIdentifier);
         return false;
     }
     if (!is_object($place_node)) {
         $locationOK = false;
         if ($upload !== null) {
             $parentNodes = false;
             $parentMainNode = false;
             $locationOK = $upload->detectLocations($importClassIdentifier, $class, $placeNodeID, $parentNodes, $parentMainNode);
         }
         if ($locationOK === false || $locationOK === null) {
             $this->setError(self::ERROR_UNKNOWNNODE, ezpI18n::tr('extension/ezodf/import/error', "Unable to fetch node with id ") . $placeNodeID);
             return false;
         }
         $placeNodeID = $parentMainNode;
         $place_node = eZContentObjectTreeNode::fetch($placeNodeID);
     }
     // Check if document conversion is needed
     //
     // Alex 2008/04/21 - added !== false
     if (in_array($originalFileType, $convertTypes, false) !== false) {
         $uniqueStamp = md5(time());
         $tmpFromFile = $tmpDir . "/convert_from_{$uniqueStamp}.doc";
         $tmpToFile = $tmpDir . "/ooo_converted_{$uniqueStamp}.odt";
         copy(realpath($file), $tmpFromFile);
         /// Convert document using the eZ Publish document conversion daemon
         if (!$this->daemonConvert($tmpFromFile, $tmpToFile)) {
             if ($this->getErrorNumber() == 0) {
                 $this->setError(self::ERROR_CONVERT);
             }
             return false;
         }
         // At this point we can unlink the sourcefile for conversion
         unlink($tmpFromFile);
         // Overwrite the file location
         $file = $tmpToFile;
     }
     $importResult = array();
     $unzipResult = "";
     $uniqueImportDir = $this->ImportDir;
     eZDir::mkdir($uniqueImportDir, false, true);
     $http = eZHTTPTool::instance();
     $archiveOptions = new ezcArchiveOptions(array('readOnly' => true));
     $archive = ezcArchive::open($file, null, $archiveOptions);
     $archive->extract($uniqueImportDir);
     $fileName = $uniqueImportDir . "content.xml";
     $dom = new DOMDocument('1.0', 'UTF-8');
     $success = $dom->load($fileName);
     $sectionNodeHash = array();
     // At this point we could unlink the destination file from the conversion, if conversion was used
     if (isset($tmpToFile)) {
         unlink($tmpToFile);
     }
     if (!$success) {
         $this->setError(self::ERROR_PARSEXML);
         return false;
     }
     // Fetch the automatic document styles
     $automaticStyleArray = $dom->getElementsByTagNameNS(self::NAMESPACE_OFFICE, 'automatic-styles');
     if ($automaticStyleArray->length == 1) {
         $this->AutomaticStyles = $automaticStyleArray->item(0)->childNodes;
     }
     // Fetch the body section content
     $sectionNodeArray = $dom->getElementsByTagNameNS(self::NAMESPACE_TEXT, 'section');
     $customClassFound = false;
     if ($sectionNodeArray->length > 0) {
         $registeredClassArray = $ooINI->variable('ODFImport', 'RegisteredClassArray');
         // Check the defined sections in OO document
         $sectionNameArray = array();
         foreach ($sectionNodeArray as $sectionNode) {
             $sectionNameArray[] = strtolower($sectionNode->getAttributeNS(self::NAMESPACE_TEXT, "name"));
         }
         // Check if there is a coresponding eZ Publish class for this document
         foreach ($registeredClassArray as $className) {
             $attributeArray = $ooINI->variable($className, 'Attribute');
             if (!empty($attributeArray)) {
                 // Convert space to _ in section names
                 foreach ($sectionNameArray as $key => $value) {
                     $sectionNameArray[$key] = str_replace(" ", "_", $value);
                 }
                 sort($attributeArray);
                 sort($sectionNameArray);
                 $diff = array_diff($attributeArray, $sectionNameArray);
                 if (empty($diff)) {
                     $importClassIdentifier = $className;
                     $customClassFound = true;
                     break;
                 }
             }
         }
         if ($customClassFound == true) {
             foreach ($sectionNodeArray as $sectionNode) {
                 $sectionName = str_replace(" ", "_", strtolower($sectionNode->getAttributeNS(self::NAMESPACE_TEXT, 'name')));
                 $xmlText = "";
                 $level = 1;
                 $childArray = $sectionNode->childNodes;
                 $nodeCount = 1;
                 foreach ($childArray as $childNode) {
                     if ($childNode->nodeType === XML_ELEMENT_NODE) {
                         $isLastTag = $nodeCount == $childArray->length;
                         $xmlText .= self::handleNode($childNode, $level, $isLastTag);
                     }
                     $nodeCount++;
                 }
                 $endSectionPart = "";
                 $levelDiff = 1 - $level;
                 if ($levelDiff < 0) {
                     $endSectionPart = str_repeat("</section>", abs($levelDiff));
                 }
                 $charset = eZTextCodec::internalCharset();
                 // Store the original XML for each section, since some datatypes needs to handle the XML specially
                 $sectionNodeHash[$sectionName] = $sectionNode;
                 $xmlTextArray[$sectionName] = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . "  xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>";
             }
         }
     }
     if ($customClassFound == false) {
         // No defined sections. Do default import.
         $bodyNodeArray = $dom->getElementsByTagNameNS(self::NAMESPACE_OFFICE, 'text');
         // Added by Soushi
         // check the parent-style-name [ eZSectionDefinition ]
         $eZSectionDefinitionStyleName = array();
         foreach ($automaticStyleArray->item(0)->childNodes as $child) {
             if ($child->nodeType === XML_ELEMENT_NODE && $child->getAttributeNS(self::NAMESPACE_STYLE, 'parent-style-name') === 'eZSectionDefinition') {
                 $eZSectionDefinitionStyleName[] = $child->getAttributeNS(self::NAMESPACE_STYLE, 'name');
             }
         }
         $sectionNameArray = array();
         $sectionNodeArray = array();
         $paragraphSectionName = NULL;
         $firstChildFlag = false;
         $paragraphSectionNodeArray = array();
         foreach ($bodyNodeArray->item(0)->childNodes as $childNode) {
             $firstChildFlag = true;
             if ($childNode->nodeType === XML_ELEMENT_NODE && (in_array($childNode->getAttributeNS(self::NAMESPACE_TEXT, 'style-name'), $eZSectionDefinitionStyleName) || $childNode->getAttributeNS(self::NAMESPACE_TEXT, 'style-name') === 'eZSectionDefinition')) {
                 $firstChildFlag = false;
                 $childNodeChildren = $childNode->childNodes;
                 $paragraphSectionName = trim($childNodeChildren->item(0)->textContent);
                 $sectionNameArray[] = $paragraphSectionName;
             }
             if ($paragraphSectionName && $firstChildFlag) {
                 $paragraphSectionNodeArray[$paragraphSectionName][] = $childNode;
             }
         }
         $sectionNodeArray = array();
         foreach ($paragraphSectionNodeArray as $key => $childNodes) {
             $sectionNode = $dom->createElement('section');
             foreach ($childNodes as $childNode) {
                 $sectionNode->appendChild($childNode);
             }
             $sectionNodeArray[$key] = $sectionNode;
         }
         $customClassFound = false;
         if ($sectionNameArray) {
             $registeredClassArray = $ooINI->variable('ODFImport', 'RegisteredClassArray');
             // Check if there is a coresponding eZ Publish class for this document
             foreach ($registeredClassArray as $className) {
                 $attributeArray = $ooINI->variable($className, 'Attribute');
                 if (!empty($attributeArray)) {
                     // Convert space to _ in section names
                     foreach ($sectionNameArray as $key => $value) {
                         $sectionNameArray[$key] = str_replace(" ", "_", $value);
                     }
                     sort($attributeArray);
                     sort($sectionNameArray);
                     $diff = array_diff($attributeArray, $sectionNameArray);
                     if (empty($diff)) {
                         $importClassIdentifier = $className;
                         $customClassFound = true;
                         break;
                     }
                 }
             }
         }
         if ($sectionNameArray && $customClassFound == true) {
             foreach ($sectionNodeArray as $key => $sectionNode) {
                 $sectionName = str_replace(" ", "_", $key);
                 $xmlText = "";
                 $level = 1;
                 foreach ($sectionNode->childNodes as $childNode) {
                     $isLastTag = !isset($childNode->nextSibling);
                     $xmlText .= self::handleNode($childNode, $level, $isLastTag);
                 }
                 $endSectionPart = "";
                 $levelDiff = 1 - $level;
                 if ($levelDiff < 0) {
                     $endSectionPart = str_repeat("</section>", abs($levelDiff));
                 }
                 $charset = eZTextCodec::internalCharset();
                 // Store the original XML for each section, since some datatypes needs to handle the XML specially
                 $sectionNodeHash[$sectionName] = $sectionNode;
                 $xmlTextArray[$sectionName] = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . "  xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>";
             }
         } else {
             if ($bodyNodeArray->length === 1) {
                 $xmlText = "";
                 $level = 1;
                 foreach ($bodyNodeArray->item(0)->childNodes as $childNode) {
                     $xmlText .= self::handleNode($childNode, $level);
                 }
                 $endSectionPart = "";
                 $levelDiff = 1 - $level;
                 if ($levelDiff < 0) {
                     $endSectionPart = str_repeat("</section>", abs($levelDiff));
                 }
                 $charset = eZTextCodec::internalCharset();
                 $xmlTextBody = "<?xml version='1.0' encoding='{$charset}' ?>" . "<section xmlns:image='http://ez.no/namespaces/ezpublish3/image/' " . "  xmlns:xhtml='http://ez.no/namespaces/ezpublish3/xhtml/'><section>" . $xmlText . $endSectionPart . "</section></section>";
             }
         }
     }
     if ($importType == "replace") {
         // Check if we are allowed to edit the node
         $functionCollection = new eZContentFunctionCollection();
         $access = $functionCollection->checkAccess('edit', $place_node, false, false, $locale);
     } else {
         // Check if we are allowed to create a node under the node
         $functionCollection = new eZContentFunctionCollection();
         $access = $functionCollection->checkAccess('create', $place_node, $importClassIdentifier, $place_node->attribute('class_identifier'), $locale);
     }
     if ($access['result']) {
         // Check if we should replace the current object or import a new
         if ($importType !== "replace") {
             $class = eZContentClass::fetchByIdentifier($importClassIdentifier);
             $place_object = $place_node->attribute('object');
             $sectionID = $place_object->attribute('section_id');
             $creatorID = $this->currentUserID;
             $parentNodeID = $placeNodeID;
             if (!is_object($class)) {
                 eZDebug::writeError("Content class <strong>{$importClassIdentifier}</strong> specified in odf.ini does not exist.");
                 $this->setError(self::ERROR_UNKNOWNCLASS, $importClassIdentifier);
                 return false;
             }
             $object = $class->instantiate($creatorID, $sectionID, false, $locale);
             $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $object->attribute('id'), 'contentobject_version' => $object->attribute('current_version'), 'parent_node' => $parentNodeID, 'is_main' => 1));
             $nodeAssignment->store();
             $version = $object->version(1);
             $version->setAttribute('modified', eZDateTime::currentTimeStamp());
             $version->setAttribute('status', eZContentObjectVersion::STATUS_DRAFT);
             $version->store();
             $dataMap = $object->dataMap();
         } else {
             // Check if class is supported before we start changing anything
             $placeClassIdentifier = $place_node->attribute('class_identifier');
             if ($ooINI->hasVariable($placeClassIdentifier, 'DefaultImportTitleAttribute') && $ooINI->hasVariable($placeClassIdentifier, 'DefaultImportBodyAttribute')) {
                 $titleAttribute = $ooINI->variable($placeClassIdentifier, 'DefaultImportTitleAttribute');
                 $bodyAttribute = $ooINI->variable($placeClassIdentifier, 'DefaultImportBodyAttribute');
                 // Extra check to see if attributes exist in dataMap (config is not wrong)
                 $dataMap = $place_node->attribute('data_map');
                 if (!isset($dataMap[$titleAttribute]) || !isset($dataMap[$bodyAttribute])) {
                     $this->setError(self::ERROR_IMPORTING, "Error in configuration for {$placeClassIdentifier}, please check configuration file.");
                     return false;
                 }
                 unset($dataMap);
             } else {
                 $this->setError(self::ERROR_IMPORTING, "No settings for replacing node of type {$placeClassIdentifier}. Stopping.");
                 return false;
             }
             // Change class for importing
             $importClassIdentifier = $placeClassIdentifier;
             // already fetched: $node = eZContentObjectTreeNode::fetch( $placeNodeID );
             $object = $place_node->attribute('object');
             $version = $object->createNewVersionIn($locale);
             $dataMap = $version->dataMap();
         }
         $contentObjectID = $object->attribute('id');
         if ($customClassFound == true) {
             // Initialize the actual object attributes
             $attributeArray = $ooINI->variable($importClassIdentifier, 'Attribute');
             foreach ($attributeArray as $attributeIdentifier => $sectionName) {
                 switch ($dataMap[$attributeIdentifier]->DataTypeString) {
                     case "ezstring":
                     case "eztext":
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $eztextDom = new DOMDOcument('1.0', 'UTF-8');
                         $eztextDom->loadXML($xmlTextArray[$sectionName]);
                         $text = $eztextDom->documentElement->textContent;
                         $dataMap[$attributeIdentifier]->setAttribute('data_text', trim($text));
                         $dataMap[$attributeIdentifier]->store();
                         break;
                     case "ezxmltext":
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $dataMap[$attributeIdentifier]->setAttribute('data_text', $xmlTextArray[$sectionName]);
                         $dataMap[$attributeIdentifier]->store();
                         break;
                     case "ezdate":
                         // Only support date formats as a single paragraph in a section with the format:
                         // day/month/year
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $dateString = strip_tags($xmlTextArray[$sectionName]);
                         $dateArray = explode("/", $dateString);
                         if (count($dateArray) == 3) {
                             $year = $dateArray[2];
                             $month = $dateArray[1];
                             $day = $dateArray[0];
                             $date = new eZDate();
                             $contentClassAttribute = $dataMap[$attributeIdentifier];
                             $date->setMDY($month, $day, $year);
                             $dataMap[$attributeIdentifier]->setAttribute('data_int', $date->timeStamp());
                             $dataMap[$attributeIdentifier]->store();
                         }
                         break;
                     case "ezdatetime":
                         // Only support date formats as a single paragraph in a section with the format:
                         // day/month/year 14:00
                         if (!isset($xmlTextArray[$sectionName])) {
                             continue;
                         }
                         $dateString = trim(strip_tags($xmlTextArray[$sectionName]));
                         $dateTimeArray = explode(" ", $dateString);
                         $dateArray = explode("/", $dateTimeArray[0]);
                         $timeArray = explode(":", $dateTimeArray[1]);
                         if (count($dateArray) == 3 and count($timeArray) == 2) {
                             $year = $dateArray[2];
                             $month = $dateArray[1];
                             $day = $dateArray[0];
                             $hour = $timeArray[0];
                             $minute = $timeArray[1];
                             $dateTime = new eZDateTime();
                             $contentClassAttribute = $dataMap[$attributeIdentifier];
                             $dateTime->setMDYHMS($month, $day, $year, $hour, $minute, 0);
                             $dataMap[$attributeIdentifier]->setAttribute('data_int', $dateTime->timeStamp());
                             $dataMap[$attributeIdentifier]->store();
                         }
                         break;
                     case "ezimage":
                         $hasImage = false;
                         // Images are treated as an image object inside a paragrah.
                         // We fetch the first image object if there are multiple and ignore the rest
                         if (is_object($sectionNodeHash[$sectionName])) {
                             // Look for paragraphs in the section
                             foreach ($sectionNodeHash[$sectionName]->childNodes as $paragraph) {
                                 if (!$paragraph->hasChildNodes()) {
                                     continue;
                                 }
                                 // Look for frame node
                                 foreach ($paragraph->childNodes as $frame) {
                                     // finally look for the image node
                                     $children = $frame->childNodes;
                                     $imageNode = $children->item(0);
                                     if ($imageNode && $imageNode->localName == "image") {
                                         $fileName = ltrim($imageNode->getAttributeNS(self::NAMESPACE_XLINK, 'href'), '#');
                                         $filePath = $this->ImportDir . $fileName;
                                         if (file_exists($filePath)) {
                                             $imageContent = $dataMap[$attributeIdentifier]->attribute('content');
                                             $imageContent->initializeFromFile($filePath, false, basename($filePath));
                                             $imageContent->store($dataMap[$attributeIdentifier]);
                                             $dataMap[$attributeIdentifier]->store();
                                         }
                                         $hasImage = true;
                                     }
                                 }
                             }
                         }
                         if (!$hasImage) {
                             $imageHandler = $dataMap[$attributeIdentifier]->attribute('content');
                             if ($imageHandler) {
                                 $imageHandler->removeAliases($dataMap[$attributeIdentifier]);
                             }
                         }
                         break;
                     case "ezmatrix":
                         $matrixHeaderArray = array();
                         // Fetch the current defined columns in the matrix
                         $matrix = $dataMap[$attributeIdentifier]->content();
                         $columns = $matrix->attribute("columns");
                         foreach ($columns['sequential'] as $column) {
                             $matrixHeaderArray[] = $column['name'];
                         }
                         $headersValid = true;
                         $originalHeaderCount = count($matrixHeaderArray);
                         $headerCount = 0;
                         $rowCount = 0;
                         $cellArray = array();
                         // A matrix is supported as a table inside sections. If multiple tables are present we take the first.
                         if (is_object($sectionNodeHash[$sectionName])) {
                             // Look for paragraphs in the section
                             foreach ($sectionNodeHash[$sectionName]->childNodes as $table) {
                                 if ($table->localName == "table") {
                                     // Loop the rows in the table
                                     foreach ($table->childNodes as $row) {
                                         // Check the headers and compare with the defined matrix
                                         if ($row->localName == "table-header-rows") {
                                             $rowArray = $row->childNodes;
                                             if ($rowArray->length == 1) {
                                                 foreach ($rowArray->item(0)->childNodes as $headerCell) {
                                                     if ($headerCell->localName == "table-cell") {
                                                         $paragraphArray = $headerCell->childNodes;
                                                         if ($paragraphArray->length == 1) {
                                                             $headerName = $paragraphArray->item(0)->textContent;
                                                             if ($matrixHeaderArray[$headerCount] != $headerName) {
                                                                 $headersValid = false;
                                                             }
                                                             $headerCount++;
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                         // Check the rows
                                         if ($row->localName == "table-row") {
                                             foreach ($row->childNodes as $cell) {
                                                 if ($cell->childNodes->length >= 1) {
                                                     $firstParagraph = $cell->childNodes->item(0);
                                                     $cellArray[] = $firstParagraph->textContent;
                                                 }
                                             }
                                             $rowCount++;
                                         }
                                     }
                                 }
                             }
                         }
                         if ($headerCount == $originalHeaderCount and $headersValid == true) {
                             // Remove all existing rows
                             for ($i = 0; $i < $matrix->attribute("rowCount"); $i++) {
                                 $matrix->removeRow($i);
                             }
                             // Insert new rows
                             $matrix->addRow(false, $rowCount);
                             $matrix->Cells = $cellArray;
                             $dataMap[$attributeIdentifier]->setAttribute('data_text', $matrix->xmlString());
                             $matrix->decodeXML($dataMap[$attributeIdentifier]->attribute('data_text'));
                             $dataMap[$attributeIdentifier]->setContent($matrix);
                             $dataMap[$attributeIdentifier]->store();
                         }
                         break;
                     default:
                         eZDebug::writeError("Unsupported datatype for OpenOffice.org import: " . $dataMap[$attributeIdentifier]->DataTypeString);
                         break;
                 }
             }
         } else {
             // Check if attributes are already fetched
             if (!isset($titleAttribute) || !isset($bodyAttribute)) {
                 // Set attributes accorring to import class
                 $titleAttribute = $ooINI->variable($importClassIdentifier, 'DefaultImportTitleAttribute');
                 $bodyAttribute = $ooINI->variable($importClassIdentifier, 'DefaultImportBodyAttribute');
             }
             $objectName = basename($originalFileName);
             // Remove extension from name
             $objectName = preg_replace("/(\\....)\$/", "", $objectName);
             // Convert _ to spaces and upcase the first character
             $objectName = ucfirst(str_replace("_", " ", $objectName));
             $dataMap[$titleAttribute]->setAttribute('data_text', $objectName);
             $dataMap[$titleAttribute]->store();
             $dataMap[$bodyAttribute]->setAttribute('data_text', $xmlTextBody);
             $dataMap[$bodyAttribute]->store();
         }
         $operationResult = eZOperationHandler::execute('content', 'publish', array('object_id' => $contentObjectID, 'version' => $version->attribute('version')));
         $storeImagesInMedia = $ooINI->variable("ODFImport", "PlaceImagesInMedia") == "true";
         if ($storeImagesInMedia == true) {
             // Fetch object to get correct name
             $object = eZContentObject::fetch($contentObjectID);
             $contentINI = eZINI::instance('content.ini');
             $mediaRootNodeID = $contentINI->variable("NodeSettings", "MediaRootNode");
             $node = eZContentObjectTreeNode::fetch($mediaRootNodeID);
             $articleFolderName = $object->attribute('name');
             $importFolderName = $ooINI->variable('ODFImport', 'ImportedImagesMediaNodeName');
             $importNode = self::createSubNode($node, $importFolderName);
             $articleNode = self::createSubNode($importNode, $articleFolderName);
             $imageRootNode = $articleNode->attribute("node_id");
         } else {
             $imageRootNode = $object->attribute("main_node_id");
         }
         // Publish all embedded images as related objects
         foreach ($this->RelatedImageArray as $image) {
             // Publish related images
             $nodeAssignment = eZNodeAssignment::create(array('contentobject_id' => $image['ID'], 'contentobject_version' => 1, 'parent_node' => $imageRootNode, 'is_main' => 1));
             $nodeAssignment->store();
             eZOperationHandler::execute('content', 'publish', array('object_id' => $image['ID'], 'version' => 1));
             $object->addContentObjectRelation($image['ID'], 1);
         }
         $mainNode = $object->attribute('main_node');
         // Create object stop.
         $importResult['Object'] = $object;
         $importResult['Published'] = $operationResult['status'] == eZModuleOperationInfo::STATUS_CONTINUE;
         if ($mainNode instanceof eZContentObjectTreeNode) {
             $importResult['MainNode'] = $mainNode;
             $importResult['URLAlias'] = $mainNode->attribute('url_alias');
             $importResult['NodeName'] = $mainNode->attribute('name');
         } else {
             $importResult['MainNode'] = false;
             $importResult['URLAlias'] = false;
             $importResult['NodeName'] = false;
         }
         $importResult['ClassIdentifier'] = $importClassIdentifier;
     } else {
         $this->setError(self::ERROR_ACCESSDENIED);
         return false;
     }
     // Clean up
     eZDir::recursiveDelete($uniqueImportDir);
     return $importResult;
 }
Exemple #5
0
 public function testAppendArchiveAtOnce()
 {
     if (!$this->canWrite) {
         try {
             $this->complexArchive->truncate();
             $this->fail("Cannot write exception expected");
         } catch (ezcBaseFilePermissionException $e) {
             // Okay, some exception thrown.
         }
         return;
     }
     $dir = $this->getTempDir();
     $src = $dir . "/src";
     mkdir($src);
     $files = array();
     do {
         $this->complexArchive->extractCurrent($src);
         $files[] = $src . '/' . $this->complexArchive->current()->getPath();
     } while ($this->complexArchive->next());
     $mytar = "{$dir}/my_archive.tar";
     $bf = new ezcArchiveBlockFile($mytar, true);
     $archive = ezcArchive::getTarInstance($bf, $this->tarMimeFormat);
     $archive->appendToCurrent($files, $src);
     $archive->close();
     exec("tar -cf {$dir}/gnutar.tar --format=" . $this->tarFormat . " -C {$src} files");
     $this->assertEquals(file_get_contents("{$dir}/gnutar.tar"), file_get_contents($mytar));
     unset($archive);
     unset($bf);
 }
Exemple #6
0
 public function testAppendToArchive()
 {
     try {
         $name = $this->getTempDir() . DIRECTORY_SEPARATOR . 'my_archive.zip';
         $archive = ezcArchive::open($name, ezcArchive::ZIP);
         $dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'testfiles';
         $files = array("{$dir}/test2.php", "{$dir}/test1.php", "{$dir}/test7.php", "{$dir}/unicode.php");
         $archive->append($files, '');
         $archive->close();
     } catch (Exception $e) {
         echo $e->__toString();
     }
 }
<?php

require_once 'tutorial_autoload.php';
date_default_timezone_set("UTC");
class ArchiveContext extends ezcBaseFileFindContext
{
    public $archive;
    public $prefix;
}
function findRecursiveCallback(ezcBaseFileFindContext $context, $sourceDir, $fileName, $fileInfo)
{
    $path = "{$sourceDir}/{$fileName}";
    if (is_dir($path)) {
        $path .= '/';
    }
    $context->archive->append(array($path), $context->prefix);
}
function appendRecursive($archive, $sourceDir, $prefix)
{
    $context = new ArchiveContext();
    $context->archive = $archive;
    $context->prefix = $prefix;
    ezcBaseFile::walkRecursive($sourceDir, array(), array(), 'findRecursiveCallback', $context);
}
$archive = ezcArchive::open("my_archive.zip", ezcArchive::ZIP);
$archive->truncate();
// the 2nd parameter is the directory, the 3rd parameter is the prefix
appendRecursive($archive, '/tmp/directory/', '/tmp/directory/');
 public function extract($archive, $target, $check_minimum_directory = true)
 {
     if (!file_exists($archive)) {
         trigger_error(sprintf(phpbb::$user->lang['FILE_NOT_EXIST'], basename($archive)));
     }
     // Some simple file protection to prevent getting out of the titania root
     if ($check_minimum_directory) {
         if (!$this->check_filesystem_path($archive)) {
             return false;
         }
         if (!$this->check_filesystem_path($target)) {
             return false;
         }
     }
     // Clear out old stuff if there is anything here...
     $this->rmdir_recursive($target);
     // Using the phpBB ezcomponents loader
     titania::_include('library/ezcomponents/loader', false, 'phpbb_ezcomponents_loader');
     phpbb_ezcomponents_loader::load_component('archive');
     // ezcomponents archive handler
     $ezcarchive = ezcArchive::open($archive, ezcArchive::ZIP);
     $ezcarchive->extract($target);
     $ezcarchive->close();
 }
 /**
  * Imports a package from a gzip compressed tarball file
  *
  * @param string $archiveName Path to the archive file
  * @param string $packageName Package name
  * @param bool $dbAvailable
  * @param bool $repositoryID
  *
  * @return eZPackage The eZPackage object if successfull, or one of the
  *         STATUS_* class constants if an error occurs
  */
 static function import($archiveName, &$packageName, $dbAvailable = true, $repositoryID = false)
 {
     if (is_dir($archiveName)) {
         eZDebug::writeError("Importing from directory is not supported.");
         $retValue = false;
         return $retValue;
     } else {
         $tempDirPath = eZPackage::temporaryImportPath();
         // make a temporary directory to extract the package file to
         do {
             $archivePath = eZDir::path(array($tempDirPath, mt_rand()));
         } while (file_exists($archivePath));
         eZDir::mkdir($archivePath, false, true);
         $archiveOptions = new ezcArchiveOptions(array('readOnly' => true));
         // Fix for issue #15891: ezjscore - file names are cutted
         // Force the type of the archive as ezcArchive::TAR_GNU so that long file names are supported on Windows
         // The previous value for the second parameter was null which meant the type was guessed from the
         // archive, but on Windows it was detected as TAR_USTAR and this lead to filenames being limited
         // to 100 characters
         $archive = ezcArchive::open("compress.zlib://{$archiveName}", ezcArchive::TAR_GNU, $archiveOptions);
         $fileList = array();
         $fileList[] = eZPackage::definitionFilename();
         // Search for the files we want to extract
         foreach ($archive as $entry) {
             if (in_array($entry->getPath(), $fileList)) {
                 if (!$archive->extractCurrent($archivePath)) {
                     eZDebug::writeError("Failed extracting package definition file from {$archivePath}");
                     return false;
                 }
             }
         }
         $definitionFileName = eZDir::path(array($archivePath, self::definitionFilename()));
         $package = eZPackage::fetchFromFile($definitionFileName);
         eZPackage::removeFiles($archivePath);
         if ($package) {
             $packageName = $package->attribute('name');
             if (!self::isValidName($packageName)) {
                 return eZPackage::STATUS_INVALID_NAME;
             }
             if (!$repositoryID) {
                 $repositoryID = $package->attribute('vendor-dir');
             }
             $existingPackage = eZPackage::fetch($packageName, false, false, $dbAvailable);
             if ($existingPackage) {
                 return eZPackage::STATUS_ALREADY_EXISTS;
             }
             unset($package);
             $fullRepositoryPath = eZPackage::repositoryPath() . '/' . $repositoryID;
             $packagePath = $fullRepositoryPath . '/' . $packageName;
             if (!file_exists($packagePath)) {
                 eZDir::mkdir($packagePath, false, true);
             }
             $archive->extract($packagePath);
             $package = eZPackage::fetch($packageName, $fullRepositoryPath, false, $dbAvailable);
             if (!$package) {
                 eZDebug::writeError("Failed loading imported package {$packageName} from {$fullRepositoryPath}");
             }
         } else {
             eZDebug::writeError("Failed loading temporary package {$packageName}");
         }
         return $package;
     }
 }
 /**
  * Creates a tarball of all extensions in the build/ directory
  *
  * @todo add locking support
  */
 static function run_fat_dist($task = null, $args = array(), $cliopts = array())
 {
     $opts = self::getOpts(@$args[0], @$args[1], $cliopts);
     pake_mkdirs($opts['dist']['dir']);
     $files = pakeFinder::type('any')->in(self::getBuildDir($opts));
     // get absolute path to build dir
     $rootpath = pakeFinder::type('directory')->name($opts['extension']['name'])->in(self::getBuildDir($opts));
     $rootpath = dirname($rootpath[0]);
     $target = $opts['dist']['dir'] . '/' . $opts['extension']['name'] . '-' . $opts['version']['alias'] . '.' . $opts['version']['release'] . '-bundle.tar';
     // we do not rely on this, not to depend on phar extension and also because it's slightly buggy if there are dots in archive file name
     //pakeArchive::createArchive( $files, $opts['build']['dir'], $target, true );
     $tar = ezcArchive::open($target, ezcArchive::TAR);
     $tar->appendToCurrent($files, $rootpath);
     $tar->close();
     $fp = fopen('compress.zlib://' . $target . '.gz', 'wb9');
     /// @todo read file by small chunks to avoid memory exhaustion
     fwrite($fp, file_get_contents($target));
     fclose($fp);
     unlink($target);
     pake_echo_action('file+', $target . '.gz');
 }
Exemple #11
0
 public function testListing()
 {
     $dir = $this->getTempDir();
     $archive = ezcArchive::open("compress.zlib://{$dir}/mytar.tar.gz", ezcArchive::TAR_USTAR);
     file_put_contents("{$dir}/a.txt", "AAAAAAAAAAA");
     $archive->append("{$dir}/a.txt", $dir);
     file_put_contents("{$dir}/a.txt", "AAAAAAAAAAA");
     $archive->append("{$dir}/a.txt", $dir);
     $a = $archive->getListing();
     $this->assertEquals(2, sizeof($a));
 }
<?php

require_once 'tutorial_autoload.php';
$options = new ezcArchiveOptions(array('readOnly' => true));
$archive = ezcArchive::open("compress.zlib:///tmp/my_archive.tar.gz", null, $options);
// The foreach method calls internally the iterator methods.
foreach ($archive as $entry) {
    echo $entry, "\n";
    $archive->extractCurrent("/tmp/target_location/");
}
Exemple #13
0
<?php

require 'ezc-setup.php';
$archive = ezcArchive::open(dirname(__FILE__) . '/test-archive.zip');
foreach ($archive as $entry) {
    if ($entry->getPath() == 'archive-logo.jpg') {
        $dir = dirname(__FILE__);
        echo "Extracting {$entry->getPath()} to {$dir}.<br/><br/>\n";
        $archive->extractCurrent($dir);
    }
    echo $entry, "\n";
}
Exemple #14
0
 /**
  * Returns the content DOMDocument object from the .odt file
  *
  * @param string $file
  * @return DOMDocument|null
  */
 protected function getDOMDocument($file)
 {
     $archive = ezcArchive::open($file, null, new ezcArchiveOptions(array('readOnly' => true)));
     eZDir::mkdir($this->ImportDir, false, true);
     $archive->extract($this->ImportDir);
     $fileName = $this->ImportDir . "content.xml";
     $dom = new DOMDocument('1.0', 'UTF-8');
     $success = $dom->load($fileName);
     return !$success ? null : $dom;
 }
Exemple #15
0
 public function testReadOnlyModifyFileTime()
 {
     $dir = $this->getTempDir();
     copy(dirname(__FILE__) . "/data/gzip-test.tar.gz", "{$dir}/mytar.tar.gz");
     $before = stat("{$dir}/mytar.tar.gz");
     clearstatcache();
     sleep(2);
     $options = new ezcArchiveOptions(array('readOnly' => true));
     $archive = ezcArchive::open("{$dir}/mytar.tar.gz", null, $options);
     mkdir($dir . '/extract');
     foreach ($archive as $file) {
         $archive->extractCurrent('extract');
     }
     $after = stat("{$dir}/mytar.tar.gz");
     self::assertEquals($before['ctime'], $after['ctime']);
     self::assertEquals($before['mtime'], $after['mtime']);
 }
Exemple #16
0
 /**
  * Test for issue ZETACOMP-8: Double extraction causes empty file
  *
  * The failure happens only with some tarballs. The easiest way to create
  * such failing one is to remove some of the nul characters which are
  * appended to the file's content to continue the block.
  */
 public function testDoubleExtraction()
 {
     $archive = ezcArchive::open(dirname(dirname(__FILE__)) . "/data/tar_v7_truncated_block.tar");
     $dir = $this->getTempDir();
     foreach ($archive as $entry) {
         if ($entry->getPath() === "file1") {
             $archive->extractCurrent($dir);
             // break intentionally omitted.
         }
     }
     $archive->extract($dir);
     $this->assertEquals(13, filesize("{$dir}/file1"));
 }
Exemple #17
0
 public function testExtractLongLinkName()
 {
     $dir = $this->getTempDir();
     if ($this->isWindows()) {
         $dirname = "aaaaabbbbbaaaaabbbbbaaaaabbbbb";
         // 30 char. max paths shorter in Windows
         $filename = "cccccdddddcccccdddddcccccddddd";
         // 30 char. max paths shorter in Windows
         mkdir("{$dir}\\{$dirname}\\{$dirname}\\{$dirname}", 0777, true);
         touch("{$dir}\\{$dirname}\\{$dirname}\\{$dirname}\\{$filename}");
         copy("{$dir}\\{$dirname}\\{$dirname}\\{$dirname}\\{$filename}", "{$dir}/mylink");
     } else {
         $dirname = "aaaaaaaaaabbbbbbbbbbaaaaaaaaaabbbbbbbbbbaaaaaaaaaabbbbbbbbbb";
         // 60 char.
         mkdir("{$dir}/{$dirname}/{$dirname}/{$dirname}", 0777, true);
         $filename = "ccccccccccddddddddddccccccccccddddddddddccccccccccdddddddddd";
         // 60 char.
         touch("{$dir}/{$dirname}/{$dirname}/{$dirname}/{$filename}");
         symlink("{$dirname}/{$dirname}/{$dirname}/{$filename}", "{$dir}/mylink");
     }
     exec("tar -cf {$dir}/gnutar.tar --format=" . $this->tarFormat . " -C {$dir} mylink");
     unlink("{$dir}/{$dirname}/{$dirname}/{$dirname}/{$filename}");
     rmdir("{$dir}/{$dirname}/{$dirname}/{$dirname}");
     rmdir("{$dir}/{$dirname}/{$dirname}");
     rmdir("{$dir}/{$dirname}");
     // Extract it:
     $bf = new ezcArchiveBlockFile("{$dir}/gnutar.tar");
     $archive = ezcArchive::getTarInstance($bf, $this->tarMimeFormat);
     foreach ($archive as $entry) {
         $archive->extractCurrent($dir);
     }
     $this->assertTrue(is_link("{$dir}/mylink"));
     $this->assertEquals("{$dirname}/{$dirname}/{$dirname}/{$filename}", readlink("{$dir}/mylink"));
     unset($bf);
 }
 function writeDocument()
 {
     $ooINI = eZINI::instance('odf.ini');
     // Initalize directories
     eZDir::mkdir($this->OORootDir);
     eZDir::mkdir($this->OOExportDir . "META-INF", false, true);
     eZDir::mkdir($this->OOTemplateDir);
     $metaXML = "<?xml version='1.0' encoding='UTF-8'?>" . "<office:document-meta xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0' xmlns:ooo='http://openoffice.org/2004/office' office:version='1.0' xmlns:ezpublish='http://www.ez.no/ezpublish/oasis'>" . "<office:meta>" . "<meta:generator>eZ Publish</meta:generator>" . " <meta:creation-date>2004-11-10T11:39:50</meta:creation-date>" . "  <dc:date>2004-11-10T11:40:15</dc:date>" . "  <dc:language>en-US</dc:language>" . "  <meta:editing-cycles>3</meta:editing-cycles>" . "  <meta:editing-duration>PT26S</meta:editing-duration>" . "  <meta:user-defined meta:name='Info 1'/>" . "  <meta:user-defined meta:name='Info 2'/>" . "  <meta:user-defined meta:name='Info 3'/>" . "  <meta:user-defined meta:name='Info 4'/>" . " <meta:document-statistic meta:table-count='0' meta:image-count='0' meta:object-count='0' meta:page-count='1' meta:paragraph-count='1' meta:word-count='2' meta:character-count='10'/>" . " </office:meta>" . "</office:document-meta>";
     file_put_contents($this->OOExportDir . "meta.xml", $metaXML);
     $settingsXML = "<?xml version='1.0' encoding='UTF-8'?>" . "<office:document-settings xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:config='urn:oasis:names:tc:opendocument:xmlns:config:1.0' xmlns:ooo='http://openoffice.org/2004/office' office:version='1.0'>" . "  <office:settings>" . " </office:settings>" . "</office:document-settings>";
     file_put_contents($this->OOExportDir . "settings.xml", $settingsXML);
     $useTemplate = $ooINI->variable('ODFExport', 'UseTemplate') == "true";
     $templateName = $ooINI->variable('ODFExport', 'TemplateName');
     if ($useTemplate) {
         $templateFile = "extension/ezodf/templates/" . $templateName;
         $archiveOptions = new ezcArchiveOptions(array('readOnly' => true));
         $archive = ezcArchive::open($templateFile, null, $archiveOptions);
         $archive->extract($this->OOTemplateDir);
         // Copy styles.xml and images, if any to the document being generated
         if (!copy($this->OOTemplateDir . "styles.xml", $this->OOExportDir . "styles.xml")) {
             return array(self::ERROR_COULD_NOT_COPY, "Could not copy the styles.xml file.");
         }
         $sourceDir = $this->OOTemplateDir . "Pictures";
         $destDir = $this->OOExportDir . "Pictures";
         eZDir::mkdir($destDir, false, true);
         eZDir::copy($sourceDir, $destDir, false, true);
     } else {
         // Generate a default empty styles.xml file
         $stylesXML = "<?xml version='1.0' encoding='UTF-8'?>" . "<office:document-styles xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0' xmlns:style='urn:oasis:names:tc:opendocument:xmlns:style:1.0' xmlns:text='urn:oasis:names:tc:opendocument:xmlns:text:1.0' xmlns:table='urn:oasis:names:tc:opendocument:xmlns:table:1.0' xmlns:draw='urn:oasis:names:tc:opendocument:xmlns:drawing:1.0' xmlns:fo='urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0' xmlns:xlink='http://www.w3.org/1999/xlink' xmlns:dc='http://purl.org/dc/elements/1.1/' xmlns:meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0' xmlns:number='urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0' xmlns:svg='urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0' xmlns:chart='urn:oasis:names:tc:opendocument:xmlns:chart:1.0' xmlns:dr3d='urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0' xmlns:math='http://www.w3.org/1998/Math/MathML' xmlns:form='urn:oasis:names:tc:opendocument:xmlns:form:1.0' xmlns:script='urn:oasis:names:tc:opendocument:xmlns:script:1.0' xmlns:ooo='http://openoffice.org/2004/office' xmlns:ooow='http://openoffice.org/2004/writer' xmlns:oooc='http://openoffice.org/2004/calc' xmlns:dom='http://www.w3.org/2001/xml-events' office:version='1.0'>" . "  <office:font-face-decls>" . "  </office:font-face-decls>" . "   <office:styles>" . "     <style:style style:name='Table_20_Heading' style:display-name='Table Heading' style:family='paragraph' style:parent-style-name='Table_20_Contents' style:class='extra'>" . " <style:paragraph-properties fo:text-align='center' style:justify-single-word='false' text:number-lines='false' text:line-number='0'/>" . "  <style:text-properties fo:font-style='italic' fo:font-weight='bold' style:font-style-asian='italic' style:font-weight-asian='bold' style:font-style-complex='italic' style:font-weight-complex='bold'/>" . " </style:style>" . " <style:style style:name='Preformatted_20_Text' style:display-name='Preformatted Text' style:family='paragraph' style:parent-style-name='Standard' style:class='html'>" . "   <style:paragraph-properties fo:margin-top='0in' fo:margin-bottom='0in'/>" . "   <style:text-properties style:font-name='Courier New' fo:font-size='10pt' style:font-name-asian='Courier New' style:font-size-asian='10pt' style:font-name-complex='Courier New' style:font-size-complex='10pt'/>" . "  </style:style>" . " <style:style style:name='eZCustom_20_factbox' style:display-name='eZCustom_20_factbox' style:family='paragraph' style:parent-style-name='Standard' style:class='text'>" . "   <style:paragraph-properties fo:margin-top='0in' fo:margin-bottom='0in'/>" . "   <style:text-properties style:font-name='Helvetica' fo:font-size='10pt' style:font-name-asian='Helvetica' style:font-size-asian='10pt' style:font-name-complex='Helvetica' style:font-size-complex='10pt'/>" . "  </style:style>" . " <style:style style:name='eZCustom_20_quote' style:display-name='eZCustom_20_quote' style:family='paragraph' style:parent-style-name='Standard' style:class='text'>" . "   <style:paragraph-properties fo:margin-top='0in' fo:margin-bottom='0in'/>" . "   <style:text-properties style:font-name='Helvetica' fo:font-size='10pt' style:font-name-asian='Helvetica' style:font-size-asian='10pt' style:font-name-complex='Helvetica' style:font-size-complex='10pt'/>" . "  </style:style>" . "  </office:styles>" . "</office:document-styles>";
         file_put_contents($this->OOExportDir . "styles.xml", $stylesXML);
     }
     $mimeType = "application/vnd.oasis.opendocument.text";
     file_put_contents($this->OOExportDir . "mimetype", $mimeType);
     // Write content XML file
     $contentXML = "<?xml version='1.0' encoding='UTF-8'?>" . "<!DOCTYPE office:document-content PUBLIC '-//OpenOffice.org//DTD OfficeDocument1.0//EN' 'office.dtd'>" . "<office:document-content xmlns:office='urn:oasis:names:tc:opendocument:xmlns:office:1.0'" . "                          xmlns:meta='urn:oasis:names:tc:opendocument:xmlns:meta:1.0'" . "                          xmlns:config='urn:oasis:names:tc:opendocument:xmlns:config:1.0'" . "                          xmlns:text='urn:oasis:names:tc:opendocument:xmlns:text:1.0'" . "                          xmlns:table='urn:oasis:names:tc:opendocument:xmlns:table:1.0'" . "                          xmlns:draw='urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'" . "                          xmlns:presentation='urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'" . "                          xmlns:dr3d='urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'" . "                          xmlns:chart='urn:oasis:names:tc:opendocument:xmlns:chart:1.0'" . "                          xmlns:form='urn:oasis:names:tc:opendocument:xmlns:form:1.0'" . "                          xmlns:script='urn:oasis:names:tc:opendocument:xmlns:script:1.0'" . "                          xmlns:style='urn:oasis:names:tc:opendocument:xmlns:style:1.0'" . "                          xmlns:number='urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'" . "                          xmlns:math='http://www.w3.org/1998/Math/MathML'" . "                          xmlns:svg='urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'" . "                          xmlns:fo='urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'" . "                          xmlns:koffice='http://www.koffice.org/2005/'" . "                          xmlns:dc='http://purl.org/dc/elements/1.1/'" . "                          xmlns:xlink='http://www.w3.org/1999/xlink'>" . " <office:script/>" . " <office:font-face-decls/>" . " <office:automatic-styles>" . "  <text:list-style style:name='bulletlist'>" . "   <text:list-level-style-bullet text:level='1' text:style-name='Bullet_20_Symbols' style:num-suffix='.' text:bullet-char='●'>" . "      <style:list-level-properties text:space-before='0.25in' text:min-label-width='0.25in'/>" . "       <style:text-properties style:font-name='StarSymbol'/>" . "   </text:list-level-style-bullet>" . "   <text:list-level-style-bullet text:level='2' text:style-name='Bullet_20_Symbols' style:num-suffix='.' text:bullet-char='○'>" . "      <style:list-level-properties text:space-before='0.5in' text:min-label-width='0.25in'/>" . "       <style:text-properties style:font-name='StarSymbol'/>" . "   </text:list-level-style-bullet>" . "   <text:list-level-style-bullet text:level='3' text:style-name='Bullet_20_Symbols' style:num-suffix='.' text:bullet-char='■'>" . "      <style:list-level-properties text:space-before='0.75in' text:min-label-width='0.25in'/>" . "       <style:text-properties style:font-name='StarSymbol'/>" . "   </text:list-level-style-bullet>" . "  </text:list-style>" . "  <text:list-style style:name='numberedlist'>" . "   <text:list-level-style-number text:level='1' text:style-name='Numbering_20_Symbols' style:num-suffix='.' style:num-format='1'>" . "      <style:list-level-properties text:space-before='0.25in' text:min-label-width='0.25in'/>" . "   </text:list-level-style-number>" . "  </text:list-style>" . " <style:style style:name='imagecentered' style:family='graphic' style:parent-style-name='Graphics'>" . "  <style:graphic-properties style:horizontal-pos='center' style:horizontal-rel='paragraph' style:mirror='none' fo:clip='rect(0in 0in 0in 0in)' draw:luminance='0%' draw:contrast='0%' draw:red='0%' draw:green='0%' draw:blue='0%' draw:gamma='100%' draw:color-inversion='false' draw:image-opacity='100%' draw:color-mode='standard'/>" . " </style:style>" . " <style:style style:name='imageleft' style:family='graphic' style:parent-style-name='Graphics'>" . "   <style:graphic-properties style:wrap='right' style:horizontal-pos='left' style:horizontal-rel='paragraph' style:mirror='none' fo:clip='rect(0in 0in 0in 0in)' draw:luminance='0%' draw:contrast='0%' draw:red='0%' draw:green='0%' draw:blue='0%' draw:gamma='100%' draw:color-inversion='false' draw:image-opacity='100%' draw:color-mode='standard'/>" . "  </style:style>" . "  <style:style style:name='imageright' style:family='graphic' style:parent-style-name='Graphics'>" . "   <style:graphic-properties style:wrap='left' style:horizontal-pos='right' style:horizontal-rel='paragraph' style:mirror='none' fo:clip='rect(0in 0in 0in 0in)' draw:luminance='0%' draw:contrast='0%' draw:red='0%' draw:green='0%' draw:blue='0%' draw:gamma='100%' draw:color-inversion='false' draw:image-opacity='100%' draw:color-mode='standard'/>" . "  </style:style>" . " <style:style style:name='T1' style:family='text'>" . "   <style:text-properties fo:font-weight='bold' style:font-weight-asian='bold' style:font-weight-complex='bold'/>" . "   </style:style>" . " <style:style style:name='T2' style:family='text'>" . "  <style:text-properties fo:font-style='italic' style:font-style-asian='italic' style:font-style-complex='italic'/>" . " </style:style>" . " </office:automatic-styles>" . " <office:body>" . " <office:text>";
     $bodyXML = "";
     // Add body contents
     foreach ($this->DocumentArray as $element) {
         $bodyXML .= $this->handleElement($element);
     }
     // Handle charset conversion if needed
     $charset = 'UTF-8';
     $codec = eZTextCodec::instance(false, $charset);
     $bodyXML = $codec->convertString($bodyXML);
     $contentXML .= $bodyXML;
     // Add the content end
     $contentXML .= "</office:text></office:body></office:document-content>";
     file_put_contents($this->OOExportDir . "content.xml", $contentXML);
     // Write the manifest file
     $manifestXML = "<?xml version='1.0' encoding='UTF-8'?>" . "<!DOCTYPE manifest:manifest PUBLIC '-//OpenOffice.org//DTD Manifest 1.0//EN' 'Manifest.dtd'>" . "<manifest:manifest xmlns:manifest='urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'>" . "<manifest:file-entry manifest:media-type='application/vnd.oasis.opendocument.text' manifest:full-path='/'/>" . "<manifest:file-entry manifest:media-type='application/vnd.sun.xml.ui.configuration' manifest:full-path='Configurations2/'/>" . "<manifest:file-entry manifest:media-type='' manifest:full-path='Pictures/'/>" . "<manifest:file-entry manifest:media-type='text/xml' manifest:full-path='content.xml'/>" . "<manifest:file-entry manifest:media-type='text/xml' manifest:full-path='styles.xml'/>" . "<manifest:file-entry manifest:media-type='text/xml' manifest:full-path='meta.xml'/>" . "<manifest:file-entry manifest:media-type='' manifest:full-path='Thumbnails/'/>" . "<manifest:file-entry manifest:media-type='text/xml' manifest:full-path='settings.xml'/>";
     // Do not include the thumnail file.
     // "<manifest:file-entry manifest:media-type='' manifest:full-path='Thumbnails/thumbnail.png'/>" .
     foreach ($this->ImageFileArray as $imageFile) {
         $manifestXML .= "<manifest:file-entry manifest:media-type='' manifest:full-path='{$imageFile}'/>\n";
     }
     $manifestXML .= "</manifest:manifest>";
     file_put_contents($this->OOExportDir . "META-INF/manifest.xml", $manifestXML);
     $fileName = $this->OORootDir . "ootest.odt";
     $zipArchive = ezcArchive::open($fileName, ezcArchive::ZIP);
     $zipArchive->truncate();
     $prefix = $this->OOExportDir;
     $fileList = array();
     eZDir::recursiveList($this->OOExportDir, $this->OOExportDir, $fileList);
     foreach ($fileList as $fileInfo) {
         $path = $fileInfo['type'] === 'dir' ? $fileInfo['path'] . '/' . $fileInfo['name'] . '/' : $fileInfo['path'] . '/' . $fileInfo['name'];
         $zipArchive->append(array($path), $prefix);
     }
     $zipArchive->close();
     // Clean up
     eZDir::recursiveDelete($this->OOExportDir);
     eZDir::recursiveDelete($this->OOTemplateDir);
     // Clean up temporary image files if any
     $fileHandler = eZClusterFileHandler::instance();
     foreach ($this->SourceImageArray as $sourceImageFile) {
         $fileHandler->fileDeleteLocal($sourceImageFile);
     }
     return $fileName;
 }
Exemple #19
0
 public function testAppendToCurrentFifo()
 {
     if (!$this->canWrite) {
         return;
     }
     if (!ezcBaseFeatures::hasFunction('posix_mknod')) {
         return;
     }
     $dir = $this->getTempDir();
     posix_mknod("{$dir}/myfifo", POSIX_S_IFIFO);
     $fifo = "{$dir}/my_fifo.tar";
     $bf = new ezcArchiveBlockFile($fifo, true);
     $archive = ezcArchive::getTarInstance($bf, $this->tarMimeFormat);
     $archive->appendToCurrent("{$dir}/myfifo", "{$dir}");
     $archive->close();
     // Do the same with gnu tar.
     exec("tar -cf {$dir}/gnutar.tar --format=" . $this->tarFormat . " -C {$dir}/ myfifo");
     $this->assertEquals(file_get_contents("{$dir}/gnutar.tar"), file_get_contents($fifo));
     unlink("{$dir}/myfifo");
 }
<?php

require_once 'tutorial_autoload.php';
$archive = ezcArchive::open("compress.zlib:///tmp/my_archive.tar.gz");
// The foreach method calls internally the iterator methods.
foreach ($archive as $entry) {
    echo $entry, "\n";
    $archive->extractCurrent("/tmp/target_location/");
}
<?php

require_once 'tutorial_autoload.php';
date_default_timezone_set("UTC");
$archive = ezcArchive::open("/tmp/my_archive.zip");
$archive->truncate();
$filesToAppend[] = "/tmp/directory/";
$filesToAppend[] = "/tmp/file.txt";
// The second parameter specifies prefix. The prefix is normally not included
// in the archive.
$archive->appendToCurrent($filesToAppend, "/tmp/");